Skip to main content

faucet_cli/
error.rs

1//! CLI-level error type. Wraps every failure mode the binary surfaces so
2//! `main()` can render a single, user-readable line per failure.
3
4use std::path::PathBuf;
5use thiserror::Error;
6
7/// Convenience alias used by every CLI module.
8pub type CliResult<T> = Result<T, CliError>;
9
10/// Top-level error variants for the `faucet` binary.
11#[derive(Debug, Error)]
12pub enum CliError {
13    /// Failed to read a config file from disk.
14    #[error("failed to read config file '{path}': {source}")]
15    ReadConfig {
16        path: PathBuf,
17        #[source]
18        source: std::io::Error,
19    },
20
21    /// The config file extension is neither `.yaml`/`.yml` nor `.json`.
22    #[error(
23        "unsupported config extension for '{path}' — use .yaml, .yml, or .json (mixed JSON/YAML in a single file is not allowed)"
24    )]
25    UnknownExtension { path: PathBuf },
26
27    /// Failed to parse the raw config text after interpolation.
28    #[error("failed to parse config '{path}': {message}")]
29    ParseConfig { path: PathBuf, message: String },
30
31    /// An `${env:VAR}` reference could not be resolved.
32    #[error("missing environment variable '{var}' referenced in config at '{location}'")]
33    MissingEnvVar { var: String, location: String },
34
35    /// A `${file:PATH}` reference could not be read.
36    #[error("failed to read interpolated file '{}' referenced in config: {source}", path.display())]
37    ReadInterpolatedFile {
38        path: PathBuf,
39        #[source]
40        source: std::io::Error,
41    },
42
43    #[error(
44        "interpolated file '{}' exceeds the {max_bytes}-byte limit for `${{file:...}}` — \
45         this directive is for small token/secret files, not bulk data",
46        path.display()
47    )]
48    InterpolatedFileTooLarge { path: PathBuf, max_bytes: u64 },
49
50    /// A `${row_id.path}` token referenced an unknown matrix row id at
51    /// expand-time (or a typo'd load-time prefix that survived to record-time).
52    #[error(
53        "interpolation '{token}' references unknown id '{id}' (must be a matrix row id, or one of env/file/secret)"
54    )]
55    UnknownInterpolationId { id: String, token: String },
56
57    /// A `${row_id.path}` resolved at record-time, but the dotted path doesn't
58    /// match any field in the parent record.
59    #[error("matrix row '{id}' has no field at path '{path}' in this parent record")]
60    MissingRecordField { id: String, path: String },
61
62    /// The named connector is unknown (or its feature flag is disabled in this build).
63    #[error("unknown {kind} '{name}'. Available: {available}")]
64    UnknownConnector {
65        kind: &'static str,
66        name: String,
67        available: String,
68    },
69
70    /// The state-store type referenced in the config is unknown or not compiled in.
71    #[error("unknown state store '{name}'. Available: {available}")]
72    UnknownStateStore { name: String, available: String },
73
74    /// A transform type referenced in the config is not recognised.
75    #[error("unknown transform '{name}'. Available: {available}")]
76    UnknownTransform { name: String, available: String },
77
78    /// The transform config block could not be deserialized into the expected shape.
79    #[error("invalid transform '{name}': {message}")]
80    InvalidTransform { name: String, message: String },
81
82    /// A connector config object failed to deserialize.
83    #[error("invalid config for {kind} '{name}': {message}")]
84    InvalidConnectorConfig {
85        kind: &'static str,
86        name: String,
87        message: String,
88    },
89
90    /// A scaffold target already exists.
91    #[error("refusing to overwrite existing file '{path}' — pass --force to overwrite")]
92    ScaffoldExists { path: PathBuf },
93
94    /// The CLI was invoked with `--from-env` but the required selector env var
95    /// (`FAUCET_SOURCE` or `FAUCET_SINK`) is unset.
96    #[error(
97        "missing required environment variable '{var}' — set it before invoking `faucet run --from-env`"
98    )]
99    MissingEnvSelector { var: String },
100
101    /// An explicit `--env-file` path does not exist on disk.
102    #[error("--env-file path '{}' does not exist", path.display())]
103    EnvFileNotFound { path: PathBuf },
104
105    /// `faucet run` invoked with neither a config path nor `--from-env`, and
106    /// auto-discovery found no `faucet.{yaml,yml,json}` in cwd.
107    #[error(
108        "no pipeline config: pass a path, --from-env, or create faucet.yaml (or .yml/.json) in the current directory"
109    )]
110    NoConfigOrFromEnv,
111
112    /// Both a scalar env var and its `_JSON` counterpart were set for the same field.
113    #[error(
114        "conflicting environment variables for field '{field}': both '{scalar_var}' and '{json_var}' are set — pick one"
115    )]
116    EnvConflict {
117        field: String,
118        scalar_var: String,
119        json_var: String,
120    },
121
122    /// A `*_JSON` env var did not parse as JSON.
123    #[error("environment variable '{var}' is not valid JSON: {message}")]
124    InvalidEnvJson { var: String, message: String },
125
126    /// `FAUCET_TRANSFORM_<N>` indices are not contiguous starting at 1.
127    #[error(
128        "transform env vars must be contiguous starting at FAUCET_TRANSFORM_1; index {missing} is missing"
129    )]
130    TransformIndexGap { missing: u32 },
131
132    /// A matrix row id collides with a load-time interpolation prefix.
133    #[error("matrix row id '{id}' is reserved (env, file, secret, matrix, pipeline)")]
134    ReservedRowId { id: String },
135
136    /// Two matrix rows declared the same id.
137    #[error("duplicate matrix row id '{id}'")]
138    DuplicateRowId { id: String },
139
140    /// A row's `parent:` field names a row that doesn't exist.
141    #[error("matrix row '{id}' references unknown parent '{parent}'")]
142    UnknownParent { id: String, parent: String },
143
144    /// The parent chain contains a cycle.
145    #[error("matrix has a parent cycle through: {}", ids.join(" -> "))]
146    ParentCycle { ids: Vec<String> },
147
148    /// Two parent records of the same matrix row resolved to the same
149    /// `parent_key` value, producing a colliding state-key suffix.
150    #[error(
151        "duplicate state key '{state_key}' for matrix row '{id}': two parent records resolve to the same `parent_key` value — choose a `parent_key` that is unique per record"
152    )]
153    DuplicateStateKey { id: String, state_key: String },
154
155    /// The state key derived from the pipeline name + row id (+ resolved
156    /// parent-key value) is not a valid state-store key. Caught up front at
157    /// unit construction rather than mid-run.
158    #[error("invalid state key '{state_key}' for row '{id}': {reason}")]
159    InvalidStateKey {
160        id: String,
161        state_key: String,
162        reason: String,
163    },
164
165    /// One or more matrix invocations failed under `on_error: continue`.
166    #[error("{count} pipeline invocation(s) failed (see logs above for details)")]
167    PipelineHadFailures { count: usize },
168
169    /// DLQ sink kind is not registered (not compiled in or feature disabled).
170    #[error("DLQ sink kind `{kind}` is not registered (in {context})")]
171    UnknownDlqSinkKind { kind: String, context: String },
172
173    /// DLQ budget field is set to zero (which is invalid; omit to mean 'unlimited').
174    #[error("DLQ {field} must be > 0 (got 0); omit the field to mean 'unlimited'")]
175    InvalidDlqBudget { field: &'static str },
176
177    /// A matrix row referenced a named template that doesn't exist in
178    /// `pipeline.sources` / `pipeline.sinks` (or the legacy `default`).
179    #[error(
180        "matrix row '{row_id}' references unknown {kind} template '{name}'. Known {kind} templates: {known}",
181        known = if known.is_empty() { String::from("(none defined)") } else { known.join(", ") }
182    )]
183    UnknownTemplate {
184        kind: &'static str,
185        name: String,
186        row_id: String,
187        known: Vec<String>,
188    },
189
190    /// A matrix row supplied no `ref:` and the legacy `default` template
191    /// doesn't exist either.
192    #[error(
193        "matrix row '{row_id}' has no {kind}: either set `{kind}: {{ ref: <name> }}` pointing at a `pipeline.{kind}s` template, or declare a legacy `pipeline.{kind}` block"
194    )]
195    MissingTemplate { kind: &'static str, row_id: String },
196
197    /// Both the legacy `pipeline.source` and `pipeline.sources.default` were
198    /// declared (same for sinks). The `default` slot can only be defined once.
199    #[error(
200        "{kind} template '{name}' is defined twice — declare it either via the singular `pipeline.{kind}` block or in `pipeline.{kind}s`, not both"
201    )]
202    DuplicateTemplate { kind: &'static str, name: String },
203
204    /// A sink template carries a `transforms:` field, which only sources support.
205    #[error(
206        "sink template '{name}' has `transforms:` — sinks cannot carry transforms; \
207         declare transforms on the source template, pipeline, or matrix row instead"
208    )]
209    TransformsOnSink { name: String },
210
211    /// A sink template carries `inherit_transforms:`, which only sources support.
212    #[error(
213        "sink template '{name}' has `inherit_transforms:` — sinks cannot carry the \
214         transform-inheritance flag; remove it"
215    )]
216    InheritTransformsOnSink { name: String },
217
218    /// A cycle was detected resolving `${vars.X}` / `${sources.X.PATH}` /
219    /// `${sinks.X.PATH}` references at load time.
220    #[error("interpolation cycle: {}", chain.join(" -> "))]
221    InterpolationCycle { chain: Vec<String> },
222
223    /// A `${vars.X}` token referenced an undefined var.
224    #[error(
225        "interpolation '{token}' references unknown var '{name}' (define it under top-level `vars:`)"
226    )]
227    UnknownVarsRef { name: String, token: String },
228
229    /// A `${sources.X.PATH}` or `${sinks.X.PATH}` token referenced an
230    /// undefined template, or a dotted path that doesn't resolve inside it.
231    #[error("interpolation '{token}' could not be resolved: {reason}")]
232    UnknownTemplateRef { token: String, reason: String },
233
234    /// A connector's `auth: { ref }` named a provider not declared in the
235    /// top-level `auth:` catalog.
236    #[error(
237        "auth references unknown provider '{name}'. Declared providers: {}",
238        if known.is_empty() { String::from("(none)") } else { known.join(", ") }
239    )]
240    UnknownAuthProvider { name: String, known: Vec<String> },
241
242    /// A top-level `auth:` provider spec failed to build.
243    #[error("failed to build auth provider '{name}': {message}")]
244    AuthProviderBuild { name: String, message: String },
245
246    /// A config-level validation failure that isn't covered by a more specific
247    /// variant (e.g. an invalid `quality:` block, or a quality check that
248    /// requires a DLQ when none is configured).
249    #[error("config error: {0}")]
250    Config(String),
251
252    /// Pass-through for failures bubbling up from `faucet-core` or a connector.
253    #[error(transparent)]
254    Faucet(#[from] faucet_core::FaucetError),
255
256    /// Pass-through I/O error.
257    #[error("io error: {0}")]
258    Io(#[from] std::io::Error),
259
260    /// Observability stack (Prometheus / tracing) failed to install.
261    #[error("observability install failed: {0}")]
262    Observability(String),
263
264    /// An internal invariant was violated (a bug). Surfaced instead of
265    /// silently producing a partial result.
266    #[error("internal error: {0}")]
267    Internal(String),
268
269    /// A secret-manager directive used a scheme whose backend feature was not
270    /// compiled into this binary.
271    #[error(
272        "secret directive uses scheme '{scheme}' but this binary was built without \
273         the `secrets-{scheme}` feature — rebuild with `--features secrets-{scheme}` (or `secrets`)"
274    )]
275    SecretBackendDisabled { scheme: String },
276
277    /// The secrets manager has no secret at the given reference.
278    #[error("secret '{reference}' not found in {scheme}")]
279    SecretNotFound { scheme: String, reference: String },
280
281    /// The secret fetch failed (network / API error).
282    #[error("failed to fetch secret '{reference}' from {scheme}: {source}")]
283    SecretFetchFailed {
284        scheme: String,
285        reference: String,
286        #[source]
287        source: Box<dyn std::error::Error + Send + Sync>,
288    },
289
290    /// No ambient credentials were available for the backend.
291    #[error("could not authenticate to {scheme}: {hint}")]
292    SecretAuthFailed { scheme: String, hint: String },
293
294    /// A `#field` selector was used on a secret that is not JSON.
295    #[error("secret '{reference}' from {scheme} is not JSON, but a '#field' selector was used")]
296    SecretNotJson { scheme: String, reference: String },
297
298    /// A `#field` selector named a key absent from the secret JSON.
299    #[error(
300        "secret '{reference}' from {scheme} has no field '{field}' (available: {})",
301        if available.is_empty() { String::from("(none — secret is an empty object)") } else { available.join(", ") }
302    )]
303    SecretFieldMissing {
304        scheme: String,
305        reference: String,
306        field: String,
307        available: Vec<String>,
308    },
309
310    /// A secret directive was found while loading via the synchronous path.
311    #[error(
312        "config references a secrets manager (${{vault:…}} / ${{aws-sm:…}} / …) which requires \
313         the async load path — load via `faucet run`/`validate`/`preview` rather than the sync API"
314    )]
315    SecretsRequireAsyncLoad,
316
317    /// One or more `faucet doctor` preflight probes failed. The checklist is
318    /// printed by the command; `main` maps this to an exit code equal to the
319    /// failed-probe count (clamped to 255).
320    #[error("{failed} preflight probe(s) failed")]
321    DoctorFailed { failed: usize },
322
323    /// A `faucet serve` startup or runtime failure (bind, auth gate, etc.).
324    #[error("serve error: {0}")]
325    Serve(String),
326
327    /// `overlap_policy: forbid` saw a tick fire while a run was still in flight.
328    #[error("scheduled run overlap with overlap_policy: forbid — previous run still in progress")]
329    ScheduleOverlapForbidden,
330}
331
332impl From<faucet_core::InstallError> for CliError {
333    fn from(e: faucet_core::InstallError) -> Self {
334        CliError::Observability(e.to_string())
335    }
336}
337
338#[cfg(test)]
339mod secrets_error_tests {
340    use super::*;
341
342    #[test]
343    fn secret_errors_render_reference_not_value() {
344        let e = CliError::SecretNotFound {
345            scheme: "vault".into(),
346            reference: "secret/data/app#token".into(),
347        };
348        let msg = e.to_string();
349        assert!(msg.contains("vault"));
350        assert!(msg.contains("secret/data/app#token"));
351
352        let e = CliError::SecretFieldMissing {
353            scheme: "aws-sm".into(),
354            reference: "prod/db".into(),
355            field: "password".into(),
356            available: vec!["username".into(), "host".into()],
357        };
358        let msg = e.to_string();
359        assert!(msg.contains("password"));
360        assert!(msg.contains("username") && msg.contains("host"));
361
362        let e = CliError::SecretBackendDisabled {
363            scheme: "azure-kv".into(),
364        };
365        assert!(e.to_string().contains("secrets-azure-kv"));
366
367        assert!(
368            CliError::SecretsRequireAsyncLoad
369                .to_string()
370                .contains("async")
371        );
372    }
373
374    #[test]
375    fn fetch_auth_notjson_errors_render_safely() {
376        let e = CliError::SecretFetchFailed {
377            scheme: "vault".into(),
378            reference: "secret/data/app#token".into(),
379            source: "connection refused".into(),
380        };
381        let msg = e.to_string();
382        assert!(msg.contains("vault") && msg.contains("secret/data/app#token"));
383
384        let e = CliError::SecretAuthFailed {
385            scheme: "aws-sm".into(),
386            hint: "set AWS_PROFILE".into(),
387        };
388        assert!(e.to_string().contains("aws-sm") && e.to_string().contains("set AWS_PROFILE"));
389
390        let e = CliError::SecretNotJson {
391            scheme: "vault".into(),
392            reference: "secret/raw".into(),
393        };
394        assert!(e.to_string().contains("not JSON"));
395    }
396
397    #[test]
398    fn field_missing_with_empty_available_has_no_dangling_list() {
399        let e = CliError::SecretFieldMissing {
400            scheme: "vault".into(),
401            reference: "secret/data/app".into(),
402            field: "token".into(),
403            available: vec![],
404        };
405        let msg = e.to_string();
406        assert!(!msg.ends_with("(available: )"));
407        assert!(msg.contains("token"));
408    }
409}
410
411#[cfg(test)]
412mod tests {
413    use super::*;
414
415    #[test]
416    fn missing_env_selector_renders() {
417        let e = CliError::MissingEnvSelector {
418            var: "FAUCET_SOURCE".to_owned(),
419        };
420        let msg = e.to_string();
421        assert!(msg.contains("FAUCET_SOURCE"));
422        assert!(msg.contains("--from-env"));
423    }
424
425    #[test]
426    fn env_conflict_names_both_vars() {
427        let e = CliError::EnvConflict {
428            field: "auth".to_owned(),
429            scalar_var: "FAUCET_SOURCE_REST_AUTH".to_owned(),
430            json_var: "FAUCET_SOURCE_REST_AUTH_JSON".to_owned(),
431        };
432        let msg = e.to_string();
433        assert!(msg.contains("FAUCET_SOURCE_REST_AUTH"));
434        assert!(msg.contains("FAUCET_SOURCE_REST_AUTH_JSON"));
435    }
436
437    #[test]
438    fn invalid_env_json_names_var_and_parse_error() {
439        let e = CliError::InvalidEnvJson {
440            var: "FAUCET_SOURCE_REST_AUTH_JSON".to_owned(),
441            message: "expected value at line 1 column 1".to_owned(),
442        };
443        let msg = e.to_string();
444        assert!(msg.contains("FAUCET_SOURCE_REST_AUTH_JSON"));
445        assert!(msg.contains("expected value"));
446    }
447
448    #[test]
449    fn transform_index_gap_reports_missing_index() {
450        let e = CliError::TransformIndexGap { missing: 2 };
451        let msg = e.to_string();
452        assert!(msg.contains('2'));
453        assert!(msg.to_ascii_lowercase().contains("transform"));
454    }
455
456    #[test]
457    fn unknown_template_lists_known_names() {
458        let e = CliError::UnknownTemplate {
459            kind: "source",
460            name: "users_api".into(),
461            row_id: "load_users".into(),
462            known: vec!["customers_api".into(), "orders_api".into()],
463        };
464        let msg = e.to_string();
465        assert!(msg.contains("users_api"));
466        assert!(msg.contains("load_users"));
467        assert!(msg.contains("customers_api"));
468    }
469
470    #[test]
471    fn duplicate_template_names_kind() {
472        let e = CliError::DuplicateTemplate {
473            kind: "sink",
474            name: "default".into(),
475        };
476        let msg = e.to_string();
477        assert!(msg.contains("sink"));
478        assert!(msg.contains("default"));
479    }
480
481    #[test]
482    fn interpolation_cycle_renders_chain() {
483        let e = CliError::InterpolationCycle {
484            chain: vec!["vars.a".into(), "vars.b".into(), "vars.a".into()],
485        };
486        let msg = e.to_string();
487        assert!(msg.contains("vars.a"));
488        assert!(msg.contains("vars.b"));
489    }
490}