Skip to main content

taskfast_cli/
envelope.rs

1// SPDX-License-Identifier: MIT
2//! JSON output envelope — uniform across success/error/dry-run.
3//!
4//! Shape (success):
5//! ```json
6//! { "ok": true, "environment": "production", "dry_run": false, "data": {...} }
7//! ```
8//!
9//! Shape (error):
10//! ```json
11//! {
12//!   "ok": false, "environment": "production", "dry_run": false,
13//!   "error": { "code": "rate_limited", "message": "...", "retry_after_seconds": 30 }
14//! }
15//! ```
16//!
17//! Orchestrators branch on `ok` + `error.code`; `retry_after_seconds` is
18//! populated only when the server supplied a sleep hint (HTTP 429) so callers
19//! don't have to regex-scrape the human message to schedule their next try.
20
21use serde::Serialize;
22
23use crate::cmd::CmdError;
24use crate::Environment;
25
26#[derive(Debug, Serialize)]
27pub struct Envelope {
28    pub ok: bool,
29    pub environment: &'static str,
30    pub dry_run: bool,
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub data: Option<serde_json::Value>,
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub error: Option<ErrorPayload>,
35    /// Server `x-request-id` (gh#91), present whenever the invocation made an
36    /// HTTP call. Lets a consumer reading only stdout JSON join back to the
37    /// server-side `mix taskfast.trace`, without the server's `Error` schema
38    /// having to carry it (`additionalProperties: false`).
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub correlation_id: Option<String>,
41    /// F15: machine-readable non-fatal security signals. Always present
42    /// (possibly empty) so orchestrators can unconditionally `.jq`
43    /// `.security_warnings | length > 0` without needing a null check.
44    /// Populated by command code via [`Self::with_warnings`].
45    pub security_warnings: Vec<SecurityWarning>,
46}
47
48/// One non-fatal security observation surfaced on stderr + envelope.
49///
50/// `code` is a stable identifier orchestrators can gate on (e.g.
51/// `"custom_api_base"`, `"custom_tempo_rpc"`, `"password_env_var"`);
52/// `message` is the human-readable detail. Kept flat rather than nested
53/// so a JSON consumer can key on `.code` directly.
54#[derive(Debug, Clone, Serialize)]
55pub struct SecurityWarning {
56    pub code: &'static str,
57    pub message: String,
58}
59
60#[derive(Debug, Serialize)]
61pub struct ErrorPayload {
62    pub code: &'static str,
63    pub message: String,
64    /// Server-directed sleep hint in whole seconds. Present only for
65    /// rate-limited errors that carried a `Retry-After` header.
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub retry_after_seconds: Option<u64>,
68}
69
70impl Envelope {
71    pub fn success(env: Environment, dry_run: bool, data: serde_json::Value) -> Self {
72        Self {
73            ok: true,
74            environment: env.as_str(),
75            dry_run,
76            data: Some(data),
77            error: None,
78            correlation_id: None,
79            security_warnings: Vec::new(),
80        }
81    }
82
83    pub fn error(env: Environment, dry_run: bool, err: &CmdError) -> Self {
84        Self {
85            ok: false,
86            environment: env.as_str(),
87            dry_run,
88            data: None,
89            error: Some(ErrorPayload {
90                code: err.code(),
91                message: err.to_string(),
92                retry_after_seconds: err.retry_after().map(|d| d.as_secs()),
93            }),
94            correlation_id: None,
95            security_warnings: Vec::new(),
96        }
97    }
98
99    /// Attach non-fatal security warnings to this envelope. Idempotent —
100    /// appends to whatever is already set; callers can accumulate across
101    /// the request pipeline.
102    pub fn with_warnings(mut self, warnings: Vec<SecurityWarning>) -> Self {
103        self.security_warnings.extend(warnings);
104        self
105    }
106
107    /// Attach the server correlation id captured for this invocation
108    /// (gh#91). `None` when no HTTP call was made or none carried the
109    /// header.
110    pub fn with_correlation_id(mut self, id: Option<String>) -> Self {
111        self.correlation_id = id;
112        self
113    }
114
115    pub fn emit(&self) {
116        // Flush is implicit — stdout closes on process exit.
117        let _ = serde_json::to_writer(std::io::stdout().lock(), self);
118        println!();
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use std::time::Duration;
126
127    #[test]
128    fn success_envelope_omits_error_field() {
129        let env = Envelope::success(
130            Environment::Prod,
131            false,
132            serde_json::json!({"agent_id": "ag_1"}),
133        );
134        let v = serde_json::to_value(&env).unwrap();
135        assert_eq!(v["ok"], true);
136        assert_eq!(v["environment"], "production");
137        assert_eq!(v["dry_run"], false);
138        assert_eq!(v["data"]["agent_id"], "ag_1");
139        assert!(v.get("error").is_none(), "error must be omitted on success");
140        // F15: security_warnings is always present (possibly empty).
141        assert_eq!(
142            v["security_warnings"].as_array().map(Vec::len),
143            Some(0),
144            "security_warnings must be an empty array on healthy success"
145        );
146    }
147
148    #[test]
149    fn with_warnings_populates_the_array() {
150        let env =
151            Envelope::success(Environment::Prod, false, serde_json::json!({})).with_warnings(vec![
152                SecurityWarning {
153                    code: "custom_api_base",
154                    message: "api_base overridden via --allow-custom-endpoints".into(),
155                },
156            ]);
157        let v = serde_json::to_value(&env).unwrap();
158        let arr = v["security_warnings"].as_array().unwrap();
159        assert_eq!(arr.len(), 1);
160        assert_eq!(arr[0]["code"], "custom_api_base");
161    }
162
163    #[test]
164    fn error_envelope_omits_data_field_and_carries_code() {
165        let err = CmdError::Auth("401".into());
166        let env = Envelope::error(Environment::Staging, false, &err);
167        let v = serde_json::to_value(&env).unwrap();
168        assert_eq!(v["ok"], false);
169        assert_eq!(v["environment"], "staging");
170        assert_eq!(v["error"]["code"], "auth");
171        assert!(v["error"]["message"].as_str().unwrap().contains("401"));
172        assert!(v.get("data").is_none(), "data must be omitted on error");
173        assert!(
174            v["error"].get("retry_after_seconds").is_none(),
175            "retry_after_seconds must be omitted when absent"
176        );
177    }
178
179    #[test]
180    fn rate_limited_error_surfaces_retry_after_seconds() {
181        let err = CmdError::RateLimited {
182            retry_after: Duration::from_secs(30),
183        };
184        let env = Envelope::error(Environment::Prod, false, &err);
185        let v = serde_json::to_value(&env).unwrap();
186        assert_eq!(v["error"]["code"], "rate_limited");
187        assert_eq!(v["error"]["retry_after_seconds"], 30);
188    }
189
190    #[test]
191    fn dry_run_flag_is_serialized_verbatim() {
192        let env = Envelope::success(Environment::Local, true, serde_json::json!({}));
193        let v = serde_json::to_value(&env).unwrap();
194        assert_eq!(v["dry_run"], true);
195        assert_eq!(v["environment"], "local");
196    }
197
198    #[test]
199    fn correlation_id_omitted_when_absent() {
200        let env = Envelope::success(Environment::Prod, false, serde_json::json!({}));
201        let v = serde_json::to_value(&env).unwrap();
202        assert!(v.get("correlation_id").is_none());
203
204        let err = CmdError::Auth("401".into());
205        let env = Envelope::error(Environment::Staging, false, &err);
206        let v = serde_json::to_value(&env).unwrap();
207        assert!(v.get("correlation_id").is_none());
208    }
209
210    #[test]
211    fn with_correlation_id_populates_the_field_on_success() {
212        let env = Envelope::success(Environment::Prod, false, serde_json::json!({}))
213            .with_correlation_id(Some("req-9".into()));
214        let v = serde_json::to_value(&env).unwrap();
215        assert_eq!(v["correlation_id"], "req-9");
216    }
217
218    #[test]
219    fn with_correlation_id_populates_the_field_on_error() {
220        let err = CmdError::Auth("401".into());
221        let env = Envelope::error(Environment::Staging, false, &err)
222            .with_correlation_id(Some("req-7".into()));
223        let v = serde_json::to_value(&env).unwrap();
224        assert_eq!(v["correlation_id"], "req-7");
225    }
226}