mkt-cli-core 0.2.0

Core traits, models, config, and output for the mkt marketing CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Unified error types for the `mkt` workspace.
//!
//! All provider crates convert their specific errors into [`MktError`]
//! variants. The CLI boundary uses `anyhow` for final error reporting.

use thiserror::Error;

/// The unified error type for the `mkt` workspace.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum MktError {
    /// The requested provider is not registered or not available.
    #[error("Provider '{provider}' not found. Available: {available}")]
    ProviderNotFound {
        /// The provider name that was requested.
        provider: String,
        /// Comma-separated list of available provider names.
        available: String,
    },

    /// An API request returned an error response.
    #[error("API error from {provider}: {status} — {message}")]
    ApiError {
        /// Which provider returned the error.
        provider: String,
        /// HTTP status code.
        status: u16,
        /// Human-readable error message from the API.
        message: String,
        /// Optional retry-after hint in seconds.
        retry_after: Option<u64>,
    },

    /// Authentication failed for a provider.
    #[error("Authentication failed for {provider}: {reason}")]
    AuthError {
        /// Which provider failed authentication.
        provider: String,
        /// Human-readable reason for the failure.
        reason: String,
    },

    /// A configuration error occurred.
    #[error("Configuration error: {0}")]
    ConfigError(String),

    /// The provider's rate limit has been exceeded.
    #[error("Rate limit exceeded for {provider}. Retry after {retry_after_secs}s")]
    RateLimited {
        /// Which provider hit the rate limit.
        provider: String,
        /// How many seconds to wait before retrying.
        retry_after_secs: u64,
    },

    /// A validation error on user input.
    #[error("Validation error: {field} — {message}")]
    ValidationError {
        /// The field that failed validation.
        field: String,
        /// What went wrong.
        message: String,
    },

    /// The provider does not support the requested feature.
    #[error("{provider} does not support '{feature}'")]
    NotSupported {
        /// Which provider lacks the feature.
        provider: String,
        /// The feature that is not supported.
        feature: String,
    },

    /// An HTTP transport error from `reqwest`.
    #[error(transparent)]
    Http(#[from] reqwest::Error),

    /// A filesystem I/O error.
    #[error(transparent)]
    Io(#[from] std::io::Error),

    /// A JSON serialization/deserialization error.
    #[error(transparent)]
    SerdeJson(#[from] serde_json::Error),

    /// A TOML parsing error.
    #[error(transparent)]
    Toml(#[from] toml::de::Error),

    /// A CSV writing error.
    #[error(transparent)]
    Csv(#[from] csv::Error),
}

impl MktError {
    /// Convenience constructor for `NotSupported` errors.
    pub fn not_supported(provider: &str, feature: &str) -> Self {
        Self::NotSupported {
            provider: provider.to_string(),
            feature: feature.to_string(),
        }
    }

    /// Convenience constructor for `AuthError`.
    pub fn auth_error(provider: &str, reason: &str) -> Self {
        Self::AuthError {
            provider: provider.to_string(),
            reason: reason.to_string(),
        }
    }

    /// Process exit code for this error.
    ///
    /// The contract is stable and documented in `AGENTS.md` so scripts and
    /// coding agents can branch on it:
    ///
    /// | Code | Meaning                                  |
    /// |------|------------------------------------------|
    /// | 0    | success                                  |
    /// | 1    | unexpected error (I/O, transport, bug)   |
    /// | 2    | invalid input or configuration           |
    /// | 3    | authentication failed                    |
    /// | 4    | resource or provider not found           |
    /// | 5    | rate limited (transient — retry)         |
    /// | 6    | feature not supported by the provider    |
    /// | 7    | provider API rejected the request        |
    #[must_use]
    pub const fn exit_code(&self) -> u8 {
        match self {
            Self::ValidationError { .. } | Self::ConfigError(_) => 2,
            Self::AuthError { .. } => 3,
            Self::ProviderNotFound { .. } => 4,
            Self::RateLimited { .. } => 5,
            Self::NotSupported { .. } => 6,
            Self::ApiError { status, .. } => match status {
                401 | 403 => 3,
                404 => 4,
                429 => 5,
                _ => 7,
            },
            _ => 1,
        }
    }

    /// Stable machine-readable error identifier (`snake_case`).
    ///
    /// Emitted in structured error output so agents can match on the kind
    /// of failure without parsing human-readable messages.
    #[must_use]
    pub const fn error_type(&self) -> &'static str {
        match self {
            Self::ProviderNotFound { .. } => "provider_not_found",
            Self::ApiError { .. } => "api_error",
            Self::AuthError { .. } => "auth_error",
            Self::ConfigError(_) => "config_error",
            Self::RateLimited { .. } => "rate_limited",
            Self::ValidationError { .. } => "validation_error",
            Self::NotSupported { .. } => "not_supported",
            Self::Http(_) => "http_error",
            Self::Io(_) => "io_error",
            Self::SerdeJson(_) => "serde_error",
            Self::Toml(_) => "toml_error",
            Self::Csv(_) => "csv_error",
        }
    }

    /// Whether retrying the same request later may succeed.
    #[must_use]
    pub const fn is_transient(&self) -> bool {
        match self {
            Self::RateLimited { .. } | Self::Http(_) => true,
            Self::ApiError { status, .. } => *status == 429 || *status >= 500,
            _ => false,
        }
    }

    /// A recovery hint for the user or agent, when one exists.
    #[must_use]
    pub fn suggestion(&self) -> Option<String> {
        match self {
            Self::AuthError { provider, .. } => Some(format!(
                "Run 'mkt doctor' and check the MKT_{}_ACCESS_TOKEN environment \
                 variable or the profile config.",
                provider.to_uppercase()
            )),
            Self::ApiError { status, .. } if *status == 401 || *status == 403 => {
                Some("Run 'mkt doctor' to verify credentials and permissions.".to_string())
            }
            Self::NotSupported { .. } => {
                Some("Run 'mkt providers' to see each provider's capabilities.".to_string())
            }
            Self::RateLimited {
                retry_after_secs, ..
            } => Some(format!("Retry after {retry_after_secs} seconds.")),
            Self::ApiError {
                retry_after: Some(secs),
                ..
            } => Some(format!("Retry after {secs} seconds.")),
            Self::ProviderNotFound { available, .. } => {
                Some(format!("Available providers: {available}."))
            }
            Self::ConfigError(_) => {
                Some("Run 'mkt doctor' to validate the configuration.".to_string())
            }
            _ => None,
        }
    }
}

/// A `Result` type alias that uses [`MktError`].
pub type Result<T> = std::result::Result<T, MktError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn display_provider_not_found() {
        let err = MktError::ProviderNotFound {
            provider: "twitter".into(),
            available: "meta, google".into(),
        };
        assert_eq!(
            err.to_string(),
            "Provider 'twitter' not found. Available: meta, google"
        );
    }

    #[test]
    fn display_api_error() {
        let err = MktError::ApiError {
            provider: "meta".into(),
            status: 400,
            message: "Invalid objective".into(),
            retry_after: None,
        };
        assert_eq!(
            err.to_string(),
            "API error from meta: 400 — Invalid objective"
        );
    }

    #[test]
    fn display_not_supported() {
        let err = MktError::not_supported("tiktok", "dark_posts");
        assert_eq!(err.to_string(), "tiktok does not support 'dark_posts'");
    }

    #[test]
    fn display_rate_limited() {
        let err = MktError::RateLimited {
            provider: "meta".into(),
            retry_after_secs: 30,
        };
        assert_eq!(
            err.to_string(),
            "Rate limit exceeded for meta. Retry after 30s"
        );
    }

    #[test]
    fn display_auth_error() {
        let err = MktError::auth_error("google", "token expired");
        assert_eq!(
            err.to_string(),
            "Authentication failed for google: token expired"
        );
    }

    #[test]
    fn from_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
        let mkt_err: MktError = io_err.into();
        assert!(matches!(mkt_err, MktError::Io(_)));
    }

    #[test]
    #[allow(clippy::panic)]
    fn from_serde_json_error() {
        let Err(json_err) = serde_json::from_str::<serde_json::Value>("not json") else {
            panic!("expected JSON parse error");
        };
        let mkt_err: MktError = json_err.into();
        assert!(matches!(mkt_err, MktError::SerdeJson(_)));
    }

    #[test]
    fn display_config_error() {
        let err = MktError::ConfigError("missing profile".into());
        assert_eq!(err.to_string(), "Configuration error: missing profile");
    }

    #[test]
    fn display_validation_error() {
        let err = MktError::ValidationError {
            field: "budget".into(),
            message: "must be positive".into(),
        };
        assert_eq!(
            err.to_string(),
            "Validation error: budget — must be positive"
        );
    }

    // ── Exit code contract (stable, documented in AGENTS.md) ──

    #[test]
    fn exit_codes_follow_documented_contract() {
        assert_eq!(
            MktError::ValidationError {
                field: "x".into(),
                message: "y".into()
            }
            .exit_code(),
            2
        );
        assert_eq!(MktError::ConfigError("bad".into()).exit_code(), 2);
        assert_eq!(MktError::auth_error("meta", "expired").exit_code(), 3);
        assert_eq!(
            MktError::ProviderNotFound {
                provider: "x".into(),
                available: "meta".into()
            }
            .exit_code(),
            4
        );
        assert_eq!(
            MktError::RateLimited {
                provider: "meta".into(),
                retry_after_secs: 10
            }
            .exit_code(),
            5
        );
        assert_eq!(MktError::not_supported("meta", "x").exit_code(), 6);
    }

    #[test]
    fn api_error_exit_code_depends_on_status() {
        let not_found = MktError::ApiError {
            provider: "meta".into(),
            status: 404,
            message: "missing".into(),
            retry_after: None,
        };
        assert_eq!(not_found.exit_code(), 4);

        let rate_limited = MktError::ApiError {
            provider: "meta".into(),
            status: 429,
            message: "slow down".into(),
            retry_after: Some(30),
        };
        assert_eq!(rate_limited.exit_code(), 5);

        let auth = MktError::ApiError {
            provider: "meta".into(),
            status: 401,
            message: "bad token".into(),
            retry_after: None,
        };
        assert_eq!(auth.exit_code(), 3);

        let other = MktError::ApiError {
            provider: "meta".into(),
            status: 400,
            message: "bad request".into(),
            retry_after: None,
        };
        assert_eq!(other.exit_code(), 7);
    }

    #[test]
    fn generic_errors_exit_code_is_one() {
        let io_err: MktError =
            std::io::Error::new(std::io::ErrorKind::NotFound, "file missing").into();
        assert_eq!(io_err.exit_code(), 1);
    }

    #[test]
    fn error_type_is_stable_snake_case() {
        assert_eq!(
            MktError::ValidationError {
                field: "x".into(),
                message: "y".into()
            }
            .error_type(),
            "validation_error"
        );
        assert_eq!(MktError::auth_error("m", "r").error_type(), "auth_error");
        assert_eq!(
            MktError::RateLimited {
                provider: "m".into(),
                retry_after_secs: 1
            }
            .error_type(),
            "rate_limited"
        );
        assert_eq!(
            MktError::not_supported("m", "f").error_type(),
            "not_supported"
        );
    }

    #[test]
    fn transient_errors_are_flagged_for_retry() {
        assert!(
            MktError::RateLimited {
                provider: "m".into(),
                retry_after_secs: 1
            }
            .is_transient()
        );
        let server_err = MktError::ApiError {
            provider: "m".into(),
            status: 503,
            message: "unavailable".into(),
            retry_after: None,
        };
        assert!(server_err.is_transient());
        assert!(
            !MktError::ValidationError {
                field: "x".into(),
                message: "y".into()
            }
            .is_transient()
        );
    }

    #[test]
    #[allow(clippy::expect_used)]
    fn suggestions_guide_recovery() {
        let auth = MktError::auth_error("meta", "expired");
        let suggestion = auth.suggestion().expect("auth errors carry a suggestion");
        assert!(suggestion.contains("doctor"), "got: {suggestion}");

        let unsupported = MktError::not_supported("meta", "x");
        assert!(
            unsupported
                .suggestion()
                .expect("not_supported carries a suggestion")
                .contains("providers")
        );
    }
}