Skip to main content

aviso_cli/
lib.rs

1// (C) Copyright 2024- ECMWF and individual contributors.
2//
3// This software is licensed under the terms of the Apache Licence Version 2.0
4// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
5// In applying this licence, ECMWF does not waive the privileges and immunities
6// granted to it by virtue of its status as an intergovernmental organisation nor
7// does it submit to any jurisdiction.
8
9//! Library entry point for the `aviso` command-line client.
10//!
11//! The `aviso` binary (`src/main.rs`) is a thin shim over [`run`], and the
12//! `pyaviso` Python wheel's bundled `aviso` console command calls the same
13//! [`run`] entry point through the `aviso-py` extension. Keeping the whole
14//! CLI in the library (clap parsing, tracing setup, async dispatch, and
15//! exit-code mapping) means both surfaces share one code path. Aside from the
16//! second-Ctrl+C hard-exit escape hatch in the private `cancel` module,
17//! [`std::process::exit`] lives in the binary, not in this library.
18
19#![allow(
20    clippy::doc_markdown,
21    reason = "clap derive doc-comments are operator-facing --help text; backticks render literally in clap output and degrade UX"
22)]
23
24use std::ffi::OsString;
25use std::path::PathBuf;
26
27use anyhow::{Context, Result};
28use clap::{Parser, Subcommand, ValueEnum};
29
30/// Color output mode for the global `--color auto|always|never` flag.
31///
32/// Translated to a per-stream `bool` via [`color_enabled`]: tracing
33/// uses `stderr`'s TTY state; the echo trigger uses `stdout`'s. The
34/// `auto` variant honours the `NO_COLOR` env var; `always` overrides
35/// it (operator-supplied explicit override wins); `never` always
36/// suppresses ANSI escapes.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
38pub(crate) enum ColorMode {
39    /// Emit colors when the target output stream is a TTY and `NO_COLOR`
40    /// is unset.
41    Auto,
42    /// Emit colors regardless of TTY state. Overrides `NO_COLOR`.
43    Always,
44    /// Never emit colors. Default.
45    Never,
46}
47
48/// Pure helper that resolves a `ColorMode` to a `bool` for a specific
49/// output stream.
50///
51/// Inputs are explicit (no env access, no TTY probing) so the function
52/// is unit-testable without `std::env::set_var` (which is `unsafe` in
53/// Rust 2024 and unsound to call after worker threads have spawned).
54/// The CLI computes the inputs once at startup and passes the result
55/// to (a) the tracing subscriber's `.with_ansi(...)` and (b) the lib's
56/// [`aviso::set_echo_color_enabled`] before any listener spawns.
57fn color_enabled(mode: ColorMode, is_terminal: bool, no_color_present: bool) -> bool {
58    match mode {
59        ColorMode::Always => true,
60        ColorMode::Never => false,
61        ColorMode::Auto => !no_color_present && is_terminal,
62    }
63}
64
65#[cfg(test)]
66#[allow(
67    clippy::unwrap_used,
68    reason = "test code: unwrap on pure logic assertions is the expected diagnostic"
69)]
70mod tests {
71    use super::{ColorMode, color_enabled};
72
73    #[test]
74    fn always_emits_color_regardless_of_tty_and_no_color() {
75        assert!(color_enabled(ColorMode::Always, false, false));
76        assert!(color_enabled(ColorMode::Always, false, true));
77        assert!(color_enabled(ColorMode::Always, true, false));
78        assert!(color_enabled(ColorMode::Always, true, true));
79    }
80
81    #[test]
82    fn never_suppresses_color_regardless_of_tty_and_no_color() {
83        assert!(!color_enabled(ColorMode::Never, false, false));
84        assert!(!color_enabled(ColorMode::Never, false, true));
85        assert!(!color_enabled(ColorMode::Never, true, false));
86        assert!(!color_enabled(ColorMode::Never, true, true));
87    }
88
89    #[test]
90    fn auto_emits_color_only_when_tty_and_no_color_unset() {
91        assert!(color_enabled(ColorMode::Auto, true, false));
92        assert!(
93            !color_enabled(ColorMode::Auto, true, true),
94            "NO_COLOR set => suppressed in auto mode"
95        );
96        assert!(
97            !color_enabled(ColorMode::Auto, false, false),
98            "non-TTY => suppressed in auto mode"
99        );
100        assert!(!color_enabled(ColorMode::Auto, false, true));
101    }
102
103    #[test]
104    fn always_overrides_no_color_per_explicit_operator_choice() {
105        assert!(
106            color_enabled(ColorMode::Always, true, true),
107            "--color always must override NO_COLOR (explicit operator override wins)"
108        );
109    }
110}
111
112mod auth;
113mod cancel;
114mod client_builder;
115mod commands;
116mod config;
117mod error;
118mod exit;
119mod from_value;
120mod listener;
121mod listener_file;
122mod output;
123mod paths;
124mod tracing_format;
125
126/// Top-level CLI. Holds the global flags shared across every
127/// subcommand plus the dispatch into [`Commands`].
128#[derive(Debug, Parser)]
129#[command(
130    name = "aviso",
131    version = aviso::VERSION,
132    about = "Command-line client for aviso-server",
133    long_about = "The `aviso` command-line client for ECMWF's aviso-server notification service. \
134                  Configuration lives in ~/.config/aviso/config.yaml by default; flag and env \
135                  overrides take precedence per the documented config-layering rule. See \
136                  `aviso <SUBCOMMAND> --help` for per-command details, or \
137                  https://github.com/ecmwf/aviso-client/tree/main/docs/src/cli for the full \
138                  operator documentation.",
139)]
140pub(crate) struct Cli {
141    /// Path to the YAML config file. Default:
142    /// ~/.config/aviso/config.yaml. Env override:
143    /// AVISO_CLIENT_CONFIG_FILE.
144    #[arg(short = 'c', long, value_name = "PATH", global = true)]
145    config: Option<PathBuf>,
146
147    /// Path to the JsonFileStore state file. Default:
148    /// ~/.config/aviso/state.json. Env override: AVISO_STATE_FILE.
149    #[arg(long, value_name = "PATH", global = true)]
150    state_file: Option<PathBuf>,
151
152    /// Override the aviso-server base URL. Env override:
153    /// AVISO_BASE_URL.
154    #[arg(long, value_name = "URL", global = true)]
155    base_url: Option<String>,
156
157    /// Bearer auth token. Mutually exclusive with --username and
158    /// --password. Env override: AVISO_TOKEN.
159    #[arg(
160        long,
161        value_name = "TOKEN",
162        global = true,
163        conflicts_with_all = ["username", "password"]
164    )]
165    token: Option<String>,
166
167    /// Basic auth username. Requires --password. Mutually exclusive
168    /// with --token. Env override: AVISO_USERNAME.
169    #[arg(long, value_name = "USERNAME", global = true, requires = "password")]
170    username: Option<String>,
171
172    /// Basic auth password. Requires --username. Mutually exclusive
173    /// with --token. Env override: AVISO_PASSWORD.
174    #[arg(long, value_name = "PASSWORD", global = true, requires = "username")]
175    password: Option<String>,
176
177    /// Path to a PEM-encoded CA bundle to trust in addition to the
178    /// system root store. Repeatable: pass --ca-bundle multiple
179    /// times to add multiple certificates.
180    #[arg(
181        long,
182        value_name = "PATH",
183        global = true,
184        long_help = "Path to PEM-encoded CA bundle to trust IN ADDITION TO the system roots. \
185                     Use when the aviso-server is fronted by an internal CA not in the system \
186                     trust store (private deployments behind corporate roots, self-hosted \
187                     clusters with their own ACME setup, similar). The system root store stays \
188                     in effect; --ca-bundle only adds, never replaces. Repeatable: pass \
189                     --ca-bundle multiple times for multiple certificates. The 'TLS' section at \
190                     https://github.com/ecmwf/aviso-client/blob/main/docs/src/cli/configuration.md \
191                     has end-to-end setup steps including how to fetch a PEM cert from a \
192                     running server."
193    )]
194    ca_bundle: Vec<PathBuf>,
195
196    /// Disable TLS certificate validation entirely. Insecure by
197    /// design.
198    #[arg(
199        long,
200        global = true,
201        long_help = "Disable TLS certificate validation entirely. INSECURE; intended only for \
202                     short-lived dev work against a self-signed aviso-server when shipping the \
203                     cert via --ca-bundle is not practical. Logs WARN \
204                     `event.name=cli.tls.insecure_mode` once per invocation so log scrapers can \
205                     flag misuse. The right production move is always --ca-bundle, never this. \
206                     See the 'TLS' section at \
207                     https://github.com/ecmwf/aviso-client/blob/main/docs/src/cli/configuration.md."
208    )]
209    danger_accept_invalid_certs: bool,
210
211    /// Force JSON output (overrides TTY-aware default).
212    #[arg(long, global = true)]
213    json: bool,
214
215    /// Color output mode. `never` (default) disables all ANSI escapes;
216    /// `always` emits colors in the human-readable output paths
217    /// regardless of TTY (overrides NO_COLOR); `auto` emits colors
218    /// in the human-readable paths when the target output stream is
219    /// a TTY and NO_COLOR is unset. A value is REQUIRED:
220    /// `--color auto|always|never`. ANSI is never emitted into JSON
221    /// (machine consumers via pipe/file) regardless of this flag.
222    /// Per-stream: tracing checks stderr, echo trigger checks stdout,
223    /// so `aviso listen --color auto | jq` correctly keeps stderr
224    /// colored (TTY) and stdout JSON (pipe).
225    #[arg(long, value_enum, default_value_t = ColorMode::Never, global = true)]
226    color: ColorMode,
227
228    /// Increase verbosity. Repeatable: -v = DEBUG, -vv = TRACE.
229    /// Affects the aviso crates only; third-party crates (hyper,
230    /// h2, reqwest, rustls) stay at WARN regardless. When the
231    /// AVISO_LOG env var is set, its EnvFilter directive overrides
232    /// this flag (operator-supplied policy is authoritative); use
233    /// AVISO_LOG=h2=debug,hyper=debug,aviso=debug to also see
234    /// transport-level diagnostics.
235    #[arg(short = 'v', long, action = clap::ArgAction::Count, global = true)]
236    verbose: u8,
237
238    #[command(subcommand)]
239    command: Commands,
240}
241
242/// Top-level subcommand enum. Each variant maps to one subcommand
243/// of the `aviso` binary; the handler dispatch lives in [`dispatch`].
244#[derive(Debug, Subcommand)]
245enum Commands {
246    /// Publish one notification to /api/v1/notification.
247    ///
248    /// Parameters are comma-separated. `event=<TYPE>` is required,
249    /// `data=<JSON>` is optional, and all other entries enter the
250    /// identifier map. Use `key:=JSON` for explicitly typed JSON values.
251    Notify {
252        /// Comma-separated parameters, for example
253        /// `event=mars,count:=12,class=od,data={"x":1}`.
254        parameters: String,
255    },
256
257    /// Run one or more listeners against /api/v1/watch.
258    ///
259    /// Listeners come from the positional YAML files (each carrying
260    /// its own top-level `listeners:` list) when supplied, OR from
261    /// the `listeners:` section of the global config when not.
262    /// Spawns every resolved listener concurrently; a single
263    /// listener's error WARNs but does not cancel siblings.
264    Listen {
265        /// Listener YAML files. Each file's `listeners:` list is
266        /// concatenated in argv order; positional files REPLACE
267        /// (not merge with) the global config's `listeners:`
268        /// section for this invocation. Ignored when `--event` and
269        /// `--identifiers` are both supplied (inline mode takes
270        /// precedence, matching `aviso replay`).
271        listener_files: Vec<PathBuf>,
272
273        /// Force MemoryStore for the invocation. Ignores any
274        /// configured `state_file`.
275        #[arg(long)]
276        no_state_store: bool,
277
278        /// Listener-level cursor override applied uniformly to every
279        /// resolved listener. Accepts the same seven forms as
280        /// `aviso replay --from`. When set, the listener's per-YAML
281        /// `from_id` / `from_date` is overridden.
282        #[arg(long, value_name = "VALUE")]
283        from: Option<String>,
284
285        /// Inline ad-hoc listener: event type to listen for, without
286        /// a YAML file. Requires `--identifiers`. The inline pair
287        /// takes precedence over any positional YAML files.
288        #[arg(long, value_name = "TYPE", requires = "identifiers")]
289        event: Option<String>,
290
291        /// Inline ad-hoc listener: identifiers filter as a JSON
292        /// object (e.g. `'{"class":"od"}'`). Requires `--event`.
293        /// The inline listener runs with a single default echo
294        /// trigger; for other triggers, use a YAML file instead.
295        #[arg(long, value_name = "JSON", requires = "event")]
296        identifiers: Option<String>,
297    },
298
299    /// Replay historical notifications from a server-side cursor.
300    Replay {
301        /// Listener name from the resolved listener set. Required
302        /// when more than one listener resolves.
303        #[arg(long, value_name = "NAME")]
304        listener: Option<String>,
305
306        /// Override the listener's `event:` for an ad-hoc replay.
307        /// Requires --identifiers.
308        #[arg(long, value_name = "TYPE", requires = "identifiers")]
309        event: Option<String>,
310
311        /// Override the listener's `identifiers:` for an ad-hoc
312        /// replay (JSON object). Requires --event.
313        #[arg(long, value_name = "JSON", requires = "event")]
314        identifiers: Option<String>,
315
316        /// Required cursor. Accepts a u64 sequence id OR one of
317        /// six date forms; see the '`--from` value formats' section
318        /// at <https://github.com/ecmwf/aviso-client/blob/main/docs/src/cli/configuration.md>
319        /// for the full list and the pure-digit-always-id ambiguity rule.
320        #[arg(long, value_name = "VALUE", required = true)]
321        from: String,
322
323        /// Listener YAML files. Same resolution semantics as
324        /// `aviso listen`.
325        listener_files: Vec<PathBuf>,
326    },
327
328    /// Schema operations.
329    #[command(subcommand)]
330    Schema(SchemaSubcommand),
331
332    /// Destructive admin operations. Each leaf requires --yes.
333    #[command(subcommand)]
334    Admin(AdminSubcommand),
335
336    /// Configuration introspection.
337    #[command(subcommand)]
338    Config(ConfigSubcommand),
339
340    /// Print shell completions for the chosen shell to stdout.
341    Completions {
342        /// Target shell. One of: bash, zsh, fish, powershell,
343        /// elvish.
344        shell: clap_complete::Shell,
345    },
346}
347
348#[derive(Debug, Subcommand)]
349enum SchemaSubcommand {
350    /// List all schemas registered on the server.
351    List,
352    /// Get the schema for one event type.
353    Get {
354        /// Event type whose schema to fetch.
355        event_type: String,
356    },
357}
358
359#[derive(Debug, Subcommand)]
360enum AdminSubcommand {
361    /// Wipe every notification for one event-type stream.
362    WipeStream {
363        /// Event type whose stream to wipe.
364        event_type: String,
365        /// Required confirmation. Without it the command exits 2
366        /// with usage.
367        #[arg(long)]
368        yes: bool,
369    },
370    /// Wipe every notification across every stream.
371    WipeAll {
372        /// Required confirmation. Without it the command exits 2
373        /// with usage.
374        #[arg(long)]
375        yes: bool,
376    },
377    /// Delete a single notification by its CloudEvents id
378    /// (`<event_type>@<sequence>`).
379    Delete {
380        /// CloudEvents id of the notification to delete.
381        notification_id: String,
382        /// Required confirmation. Without it the command exits 2
383        /// with usage.
384        #[arg(long)]
385        yes: bool,
386    },
387}
388
389#[derive(Debug, Subcommand)]
390enum ConfigSubcommand {
391    /// Dump the resolved config (flag-over-env-over-file applied)
392    /// to stdout.
393    Dump {
394        /// Mask tokens and passwords in the output.
395        #[arg(long)]
396        redact: bool,
397    },
398}
399
400fn init_tracing(verbose: u8, ansi: bool) -> Result<()> {
401    use std::io::IsTerminal as _;
402    use tracing_subscriber::EnvFilter;
403    use tracing_subscriber::filter::LevelFilter;
404    use tracing_subscriber::fmt;
405
406    // Filter policy is per-crate. The CLI binary and the core
407    // library both compile under the crate name `aviso` (the
408    // binary's `[[bin]] name = "aviso"` makes its module_path
409    // resolve to `aviso`, same as the lib), so a single `aviso`
410    // directive covers both. Every other crate (hyper, h2,
411    // reqwest, rustls, etc.) stays at WARN regardless of -v so
412    // the operator does not get flooded with HTTP/2 frame logs
413    // when they asked for "a bit more detail from aviso". Power
414    // users who want transport diagnostics set `AVISO_LOG`
415    // explicitly (e.g. `AVISO_LOG=h2=debug,hyper=debug,aviso=debug`),
416    // and that operator-supplied directive overrides -v entirely.
417    let our_level = match verbose {
418        0 => "info",
419        1 => "debug",
420        _ => "trace",
421    };
422    let filter = if let Ok(directives) = std::env::var("AVISO_LOG") {
423        EnvFilter::builder()
424            .with_default_directive(LevelFilter::WARN.into())
425            .parse_lossy(directives)
426    } else {
427        let directive_str = format!("warn,aviso={our_level}");
428        EnvFilter::try_new(directive_str).context("constructing default tracing filter")?
429    };
430
431    // Output format is TTY-aware. Interactive operators see a
432    // compact human-readable line per event (colored only when the
433    // operator opts in via `--color auto|always`, off by default);
434    // headless deployments (piped stderr, systemd, CI) get OTel-JSON
435    // for log aggregators (never colored regardless of the flag).
436    // Detection is on stderr (not stdout) so the common
437    // `aviso listen | tee log.txt` pattern correctly keeps the
438    // operator's terminal human-friendly while the file gets the
439    // operator's chosen trigger output.
440    // `try_init` returns Err only when a global subscriber is already
441    // installed. That happens when `run` is called more than once in a single
442    // process: the test suite calls `_run_cli` repeatedly, and a host program
443    // embedding the extension could too. A failed install is treated as
444    // success there, leaving the first subscriber in place.
445    if std::io::stderr().is_terminal() {
446        let _ = fmt()
447            .with_env_filter(filter)
448            .with_writer(std::io::stderr)
449            .with_target(false)
450            .with_timer(tracing_format::ShortClockTimer)
451            .with_ansi(ansi)
452            .compact()
453            .try_init();
454    } else {
455        let _ = fmt()
456            .with_env_filter(filter)
457            .with_writer(std::io::stderr)
458            .event_format(tracing_format::OtelLogFormat::new())
459            .try_init();
460    }
461
462    Ok(())
463}
464
465async fn dispatch(cli: Cli) -> Result<()> {
466    let resolved = config::resolve(
467        cli.config.as_ref(),
468        cli.state_file.as_ref(),
469        cli.base_url.as_deref(),
470        cli.token.as_deref(),
471        cli.username.as_deref(),
472        cli.password.as_deref(),
473        &cli.ca_bundle,
474        cli.danger_accept_invalid_certs,
475        cli.json,
476        cli.verbose,
477    )?;
478
479    if resolved.tls_danger_accept_invalid_certs.value {
480        tracing::warn!(
481            event.name = "cli.tls.insecure_mode",
482            "TLS certificate validation disabled by --danger-accept-invalid-certs; do not use in production"
483        );
484    }
485
486    tracing::debug!(
487        event.name = "cli.config.resolved",
488        config_path = %resolved.config_path.value.display(),
489        state_path = %resolved.state_path.value.display(),
490        base_url_set = resolved.base_url.is_some(),
491        auth_provider_set = resolved.auth_provider.is_some(),
492        listeners_count = resolved.listeners.len(),
493        "resolved configuration"
494    );
495
496    match cli.command {
497        Commands::Notify { parameters } => commands::notify::run(&resolved, &parameters).await,
498        Commands::Listen {
499            listener_files,
500            no_state_store,
501            from,
502            event,
503            identifiers,
504        } => {
505            commands::listen::run(
506                &resolved,
507                &listener_files,
508                no_state_store,
509                from.as_deref(),
510                event.as_deref(),
511                identifiers.as_deref(),
512            )
513            .await
514        }
515        Commands::Replay {
516            listener,
517            event,
518            identifiers,
519            from,
520            listener_files,
521        } => {
522            commands::replay::run(
523                &resolved,
524                &listener_files,
525                listener.as_deref(),
526                event.as_deref(),
527                identifiers.as_deref(),
528                &from,
529            )
530            .await
531        }
532        Commands::Schema(sub) => match sub {
533            SchemaSubcommand::List => commands::schema::run_list(&resolved).await,
534            SchemaSubcommand::Get { event_type } => {
535                commands::schema::run_get(&resolved, &event_type).await
536            }
537        },
538        Commands::Admin(sub) => match sub {
539            AdminSubcommand::WipeStream { event_type, yes } => {
540                if !yes {
541                    return Err(exit::usage_error("aviso admin wipe-stream requires --yes"));
542                }
543                commands::admin::run_wipe_stream(&resolved, &event_type).await
544            }
545            AdminSubcommand::WipeAll { yes } => {
546                if !yes {
547                    return Err(exit::usage_error("aviso admin wipe-all requires --yes"));
548                }
549                commands::admin::run_wipe_all(&resolved).await
550            }
551            AdminSubcommand::Delete {
552                notification_id,
553                yes,
554            } => {
555                if !yes {
556                    return Err(exit::usage_error("aviso admin delete requires --yes"));
557                }
558                commands::admin::run_delete(&resolved, &notification_id).await
559            }
560        },
561        Commands::Config(ConfigSubcommand::Dump { redact }) => {
562            commands::config_dump::run(&resolved, redact)
563        }
564        Commands::Completions { shell } => commands::completions::run(shell),
565    }
566}
567
568/// Runs the `aviso` command-line client to completion and returns the
569/// process exit code.
570///
571/// This is the single entry point shared by the `aviso` binary
572/// (`src/main.rs`) and the bundled `aviso` console command shipped in the
573/// `pyaviso` Python wheel through the `aviso-py` extension. It owns argument
574/// parsing, tracing setup, the async runtime, and the exit-code mapping, and
575/// it does not call [`std::process::exit`] on its normal paths, so an embedding
576/// process (the Python interpreter) keeps control of its own lifecycle. The one
577/// exception is the second-Ctrl+C hard exit during `listen` / `replay`, which
578/// terminates the process immediately by design.
579///
580/// `args` is the full argument vector including the program name at index 0,
581/// matching [`std::env::args_os`] and `sys.argv`.
582///
583/// Exit codes: `0` success, `1` runtime error, `2` usage error. A clap parse
584/// failure prints its message and returns clap's own exit code (`2`), while
585/// `--help` and `--version` print and return `0`.
586pub fn run<I, T>(args: I) -> i32
587where
588    I: IntoIterator<Item = T>,
589    T: Into<OsString> + Clone,
590{
591    use std::io::IsTerminal as _;
592
593    let cli = match Cli::try_parse_from(args) {
594        Ok(cli) => cli,
595        Err(err) => {
596            let _ = err.print();
597            return err.exit_code();
598        }
599    };
600    let no_color = std::env::var_os("NO_COLOR").is_some();
601    let stderr_color = color_enabled(cli.color, std::io::stderr().is_terminal(), no_color);
602    let stdout_color = color_enabled(cli.color, std::io::stdout().is_terminal(), no_color);
603    aviso::set_echo_color_enabled(stdout_color);
604    if let Err(e) = init_tracing(cli.verbose, stderr_color) {
605        let _ = output::write_stderr_line(&format!("error: failed to initialise tracing: {e:#}"));
606        return exit::RUNTIME_ERROR;
607    }
608    let runtime = match tokio::runtime::Builder::new_multi_thread()
609        .enable_all()
610        .build()
611    {
612        Ok(runtime) => runtime,
613        Err(e) => {
614            let _ =
615                output::write_stderr_line(&format!("error: failed to start async runtime: {e:#}"));
616            return exit::RUNTIME_ERROR;
617        }
618    };
619    match runtime.block_on(dispatch(cli)) {
620        Ok(()) => exit::SUCCESS,
621        Err(e) => {
622            let code = exit::exit_code_for_anyhow(&e);
623            error::format_chain(&e);
624            code
625        }
626    }
627}