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