Skip to main content

docsrs_cli/
render.rs

1//! Markdown and JSON rendering with output truncation.
2
3use serde::Serialize;
4
5use crate::config::{Config, HOST_DOCS_RS, SCHEMA_VERSION, SCHEME_HTTPS};
6use crate::crates_io::SearchCratesData;
7use crate::docs_rs::{GetItemData, ReadmeData, SearchInCrateData};
8use crate::error::{AppError, ErrorKind};
9
10/// JSON success envelope for agents (`schema_version`, `ok`, `command`, `data`, `duration_ms`).
11///
12/// Typed wire shape — serializes directly without an intermediate `serde_json::Value`.
13/// Optional fields use omit-on-`None` (`skip_serializing_if`), not JSON `null`.
14#[derive(Debug, Serialize)]
15pub struct SuccessEnvelope<'a, T: Serialize> {
16    /// Envelope schema version.
17    pub schema_version: u32,
18    /// Always `true` for success envelopes.
19    pub ok: bool,
20    /// Command name that produced this payload.
21    pub command: &'a str,
22    /// Command-specific typed data payload.
23    pub data: T,
24    /// Wall-clock duration of the command in milliseconds.
25    pub duration_ms: u64,
26    /// Final source URL when the command fetched remote content.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub source_url: Option<&'a str>,
29}
30
31/// JSON dry-run success envelope with planned URL and params.
32///
33/// `P` is a typed per-command params struct (`Serialize`). No intermediate
34/// `serde_json::Value` on the agent write path.
35#[derive(Debug, Serialize)]
36pub struct DryRunEnvelope<'a, P: Serialize> {
37    /// Envelope schema version.
38    pub schema_version: u32,
39    /// Always `true` for dry-run envelopes.
40    pub ok: bool,
41    /// Command name that would have run.
42    pub command: &'a str,
43    /// Always `true` — marks the response as a dry-run plan.
44    pub dry_run: bool,
45    /// Planned request details.
46    pub data: DryRunData<'a, P>,
47    /// Wall-clock duration until the plan was emitted.
48    pub duration_ms: u64,
49}
50
51/// Dry-run `data` object (`planned_url` + typed `planned_params`).
52#[derive(Debug, Serialize)]
53pub struct DryRunData<'a, P: Serialize> {
54    /// Absolute URL that would be requested.
55    pub planned_url: &'a str,
56    /// Command-specific planned query/body parameters (typed struct).
57    pub planned_params: P,
58}
59
60/// JSON error envelope for agents.
61///
62/// Parity with success envelopes: agents always get `command` + `duration_ms`
63/// (Camada Y / GAP-X-004) so failures correlate with the attempted wire command.
64#[derive(Debug, Serialize)]
65pub struct ErrorEnvelope<'a> {
66    /// Envelope schema version.
67    pub schema_version: u32,
68    /// Always `false` for error envelopes.
69    pub ok: bool,
70    /// Wire command name (`get-item`, `usage`, `cache-path`, …).
71    pub command: &'a str,
72    /// Wall-clock duration of the attempt in milliseconds.
73    pub duration_ms: u64,
74    /// Structured error body.
75    pub error: ErrorBody,
76}
77
78/// Error body fields inside the envelope.
79#[derive(Debug, Serialize)]
80pub struct ErrorBody {
81    /// Process exit code as an integer.
82    pub code: u8,
83    /// Snake_case error kind.
84    pub kind: String,
85    /// Technical English message.
86    pub message: String,
87    /// Whether an agent may retry after backoff.
88    pub retryable: bool,
89    /// Optional Retry-After seconds.
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub retry_after_secs: Option<u64>,
92}
93
94/// Render a human-readable markdown document for an embedded JSON Schema.
95///
96/// Includes title, description, required fields, a property table, and the
97/// raw JSON Schema fenced for agents that still want the machine schema.
98///
99/// # Errors
100///
101/// Returns [`ErrorKind::Internal`] when pretty-printing the embedded schema fails
102/// (should not happen for valid `serde_json::Value` trees).
103pub fn render_schema_markdown(cmd: &str, schema: &serde_json::Value) -> crate::error::AppResult<String> {
104    use crate::error::{AppError, ErrorKind};
105    // Schema markdown is small but non-trivial; avoid repeated small reallocs.
106    let mut out = String::with_capacity(1024);
107    let title = schema.get("title").and_then(|v| v.as_str()).unwrap_or(cmd);
108    out.push_str(&format!("# Schema: `{cmd}`\n\n"));
109    out.push_str(&format!("**Title:** {title}\n\n"));
110    if let Some(desc) = schema.get("description").and_then(|v| v.as_str()) {
111        out.push_str(&format!("{desc}\n\n"));
112    }
113    if let Some(req) = schema.get("required").and_then(|v| v.as_array()) {
114        out.push_str("## Required fields\n\n");
115        for r in req {
116            if let Some(name) = r.as_str() {
117                out.push_str(&format!("- `{name}`\n"));
118            }
119        }
120        out.push('\n');
121    }
122    out.push_str("## Properties\n\n");
123    out.push_str("| property | type | required | description |\n");
124    out.push_str("| --- | --- | --- | --- |\n");
125    let required: std::collections::HashSet<&str> = schema
126        .get("required")
127        .and_then(|v| v.as_array())
128        .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
129        .unwrap_or_default();
130    if let Some(props) = schema.get("properties").and_then(|v| v.as_object()) {
131        for (name, prop) in props {
132            let ty = schema_type_label(prop);
133            let is_req = if required.contains(name.as_str()) {
134                "yes"
135            } else {
136                "no"
137            };
138            let desc = prop
139                .get("description")
140                .and_then(|v| v.as_str())
141                .unwrap_or("")
142                .replace('|', "\\|");
143            out.push_str(&format!("| `{name}` | {ty} | {is_req} | {desc} |\n"));
144        }
145    } else {
146        out.push_str("| _(none)_ | | | |\n");
147    }
148    out.push_str("\n## JSON Schema\n\n");
149    out.push_str("```json\n");
150    let pretty = serde_json::to_string_pretty(schema).map_err(|e| {
151        AppError::with_source(ErrorKind::Internal, "json pretty-print failed", e)
152    })?;
153    out.push_str(&pretty);
154    out.push_str("\n```\n");
155    Ok(out)
156}
157
158fn schema_type_label(prop: &serde_json::Value) -> String {
159    if let Some(t) = prop.get("type") {
160        if let Some(s) = t.as_str() {
161            return s.to_string();
162        }
163        if let Some(arr) = t.as_array() {
164            let parts: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
165            if !parts.is_empty() {
166                return parts.join(" | ");
167            }
168        }
169    }
170    if prop.get("properties").is_some() {
171        return "object".into();
172    }
173    if prop.get("items").is_some() {
174        return "array".into();
175    }
176    "any".into()
177}
178
179/// Build a typed success envelope (`schema_version`, `ok`, `command`, `data`, `duration_ms`).
180pub fn success_envelope<'a, T: Serialize>(
181    command: &'a str,
182    data: T,
183    duration_ms: u64,
184    source_url: Option<&'a str>,
185) -> SuccessEnvelope<'a, T> {
186    success_envelope_with_ok(command, data, duration_ms, source_url, true)
187}
188
189/// Build a success-shaped envelope with an explicit top-level `ok` (used by `doctor`).
190pub fn success_envelope_with_ok<'a, T: Serialize>(
191    command: &'a str,
192    data: T,
193    duration_ms: u64,
194    source_url: Option<&'a str>,
195    ok: bool,
196) -> SuccessEnvelope<'a, T> {
197    SuccessEnvelope {
198        schema_version: SCHEMA_VERSION,
199        ok,
200        command,
201        data,
202        duration_ms,
203        source_url,
204    }
205}
206
207/// Build a typed dry-run success envelope with planned URL/params.
208pub fn dry_run_envelope<'a, P: Serialize>(
209    command: &'a str,
210    planned_url: &'a str,
211    planned_params: P,
212    duration_ms: u64,
213) -> DryRunEnvelope<'a, P> {
214    DryRunEnvelope {
215        schema_version: SCHEMA_VERSION,
216        ok: true,
217        command,
218        dry_run: true,
219        data: DryRunData {
220            planned_url,
221            planned_params,
222        },
223        duration_ms,
224    }
225}
226
227/// Build an error envelope. SIGINT/SIGTERM surface as kind `canceled` with exit 130/143.
228///
229/// `command` is the wire name of the attempted command (`usage` when clap fails
230/// before dispatch). `duration_ms` is wall time since process start for that
231/// attempt (may be `0` for early parse failures).
232pub fn error_envelope<'a>(err: &AppError, command: &'a str, duration_ms: u64) -> ErrorEnvelope<'a> {
233    let kind = err.kind();
234    let kind_str = match kind {
235        ErrorKind::Interrupted | ErrorKind::Terminated => "canceled",
236        ErrorKind::BrokenPipe => "broken_pipe",
237        other => other.as_str(),
238    };
239    ErrorEnvelope {
240        schema_version: SCHEMA_VERSION,
241        ok: false,
242        command,
243        duration_ms,
244        error: ErrorBody {
245            code: kind.exit_code(),
246            kind: kind_str.to_string(),
247            message: err.message().to_string(),
248            retryable: kind.retryable(),
249            retry_after_secs: err.retry_after_secs(),
250        },
251    }
252}
253
254/// Truncate UTF-8 text on a char boundary; returns (text, truncated).
255pub fn truncate_output(text: &str, max_bytes: u64) -> (String, bool) {
256    if max_bytes == 0 {
257        return (String::new(), true);
258    }
259    let max = max_bytes as usize;
260    if text.len() <= max {
261        return (text.to_string(), false);
262    }
263    let mut end = max;
264    while end > 0 && !text.is_char_boundary(end) {
265        end -= 1;
266    }
267    (text[..end].to_string(), true)
268}
269
270/// Reduce `search-crates` hits until the success envelope fits `max_output_bytes`.
271///
272/// Preserves JSON parseability (never mid-string cuts). Sets `truncated=true` when
273/// any hit is dropped for budget. If even zero hits exceeds the budget, returns
274/// the zero-hit payload with `truncated=true` (agents should raise the cap).
275pub fn apply_output_budget_search_crates(
276    mut data: SearchCratesData,
277    max_bytes: u64,
278    duration_ms: u64,
279    source_url: Option<&str>,
280) -> SearchCratesData {
281    if max_bytes == 0 {
282        data.hits.clear();
283        data.truncated = true;
284        return data;
285    }
286    loop {
287        let env = success_envelope("search-crates", &data, duration_ms, source_url);
288        let len = match serde_json::to_vec(&env) {
289            Ok(buf) => buf.len() as u64,
290            Err(_) => return data,
291        };
292        if len <= max_bytes {
293            return data;
294        }
295        if data.hits.is_empty() {
296            data.truncated = true;
297            return data;
298        }
299        data.hits.pop();
300        data.truncated = true;
301    }
302}
303
304/// Reduce `search-in-crate` hits until the success envelope fits `max_output_bytes`.
305///
306/// `truncated` becomes true when budget (or a prior limit) cuts the list.
307pub fn apply_output_budget_search_in_crate(
308    mut data: SearchInCrateData,
309    max_bytes: u64,
310    duration_ms: u64,
311    source_url: Option<&str>,
312) -> SearchInCrateData {
313    if max_bytes == 0 {
314        data.hits.clear();
315        data.emitted = 0;
316        data.truncated = true;
317        return data;
318    }
319    loop {
320        let env = success_envelope("search-in-crate", &data, duration_ms, source_url);
321        let len = match serde_json::to_vec(&env) {
322            Ok(buf) => buf.len() as u64,
323            Err(_) => return data,
324        };
325        if len <= max_bytes {
326            return data;
327        }
328        if data.hits.is_empty() {
329            data.emitted = 0;
330            data.truncated = true;
331            return data;
332        }
333        data.hits.pop();
334        data.emitted = data.hits.len();
335        data.truncated = true;
336    }
337}
338
339/// Human Markdown for search-crates.
340pub fn render_search_markdown(data: &SearchCratesData) -> String {
341    let mut out = format!(
342        "# Crate Search Results for \"{}\" (page {})\n\n",
343        data.query, data.page
344    );
345    if data.hits.is_empty() {
346        out.push_str("No crates found.\n");
347        return out;
348    }
349    for h in &data.hits {
350        out.push_str(&format!("## {} ({})\n\n", h.name, h.version));
351        out.push_str(&format!("**Description:** {}\n\n", h.description));
352        out.push_str(&format!("**Downloads:** {}\n\n", h.downloads));
353        let docs = h
354            .documentation
355            .clone()
356            .filter(|s| !s.is_empty())
357            .unwrap_or_else(|| format!("{SCHEME_HTTPS}://{HOST_DOCS_RS}/{}", h.name));
358        out.push_str(&format!("**Documentation:** {docs}\n\n---\n\n"));
359    }
360    out
361}
362
363/// Human Markdown for readme.
364pub fn render_readme_markdown(data: &ReadmeData) -> String {
365    let mut out = format!("# {} Documentation\n\n", data.crate_name);
366    if data.empty {
367        out.push_str("No documentation content found.\n");
368    } else {
369        out.push_str(&data.markdown);
370        out.push('\n');
371    }
372    out
373}
374
375/// Human Markdown for get-item.
376pub fn render_item_markdown(data: &GetItemData) -> String {
377    let mut out = format!("# {}\n\n", data.title);
378    out.push_str(&format!("**Documentation URL:** {}\n\n", data.source_url));
379    if data.empty {
380        out.push_str("No documentation content found.\n");
381    } else {
382        out.push_str(&data.markdown);
383        out.push('\n');
384    }
385    out
386}
387
388/// Human Markdown for search-in-crate.
389pub fn render_search_in_crate_markdown(data: &SearchInCrateData) -> String {
390    // Borrow query text — no String clone for the heading.
391    let term = if data.query.is_empty() {
392        "all items"
393    } else {
394        data.query.as_str()
395    };
396    let mut out = format!(
397        "# Search Results for \"{}\" in {}\n\nFound {} items (emitted {})\n\n",
398        term, data.crate_name, data.total, data.emitted
399    );
400    if data.hits.is_empty() {
401        out.push_str("No matching items found.\n");
402        return out;
403    }
404    for h in &data.hits {
405        out.push_str(&format!("## {} ({})\n\n", h.name, h.kind));
406        out.push_str(&format!("**Link:** {}\n\n---\n\n", h.url));
407    }
408    out
409}
410
411/// Apply max_output_bytes truncation to readme payload.
412pub fn apply_truncation_to_readme(mut data: ReadmeData, cfg: &Config) -> ReadmeData {
413    let (md, trunc) = truncate_output(&data.markdown, cfg.max_output_bytes);
414    data.markdown = md;
415    data.truncated = trunc;
416    data
417}
418
419/// Apply max_output_bytes truncation to get-item payload.
420pub fn apply_truncation_to_item(mut data: GetItemData, cfg: &Config) -> GetItemData {
421    let (md, trunc) = truncate_output(&data.markdown, cfg.max_output_bytes);
422    data.markdown = md;
423    data.truncated = trunc;
424    data
425}
426
427/// Map clap parse failures to usage errors.
428pub fn usage_error(msg: impl Into<String>) -> AppError {
429    AppError::new(ErrorKind::Usage, msg)
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435    use crate::crates_io::{CrateSearchHit, SearchCratesData, SearchMeta};
436    use crate::docs_rs::{GetItemData, ReadmeData};
437    use crate::error::AppError;
438
439    #[test]
440    fn truncate_marks_flag() {
441        let (out, trunc) = truncate_output("abcdef", 3);
442        assert!(trunc);
443        assert_eq!(out, "abc");
444    }
445
446    #[test]
447    fn cancel_kinds_in_envelope() {
448        let e = error_envelope(&AppError::terminated(), "get-item", 0);
449        assert_eq!(e.error.code, 143);
450        assert_eq!(e.command, "get-item");
451        assert_eq!(e.duration_ms, 0);
452        assert_eq!(e.error.kind, "canceled");
453        let e = error_envelope(&AppError::interrupted(), "get-item", 1);
454        assert_eq!(e.error.code, 130);
455        assert_eq!(e.error.kind, "canceled");
456    }
457
458    #[test]
459    fn empty_search_markdown() {
460        let data = SearchCratesData {
461            query: "z".into(),
462            page: 1,
463            per_page: 10,
464            sort: "relevance".into(),
465            hits: vec![],
466            meta: SearchMeta {
467                total: 0,
468                next_page: None,
469                prev_page: None,
470            },
471            cache_hit: false,
472            truncated: false,
473        };
474        let md = render_search_markdown(&data);
475        assert!(md.contains("No crates found"));
476    }
477
478    #[test]
479    fn empty_readme_and_item() {
480        let r = ReadmeData {
481            crate_name: "c".into(),
482            version: "latest".into(),
483            resolved_version: None,
484            markdown: String::new(),
485            empty: true,
486            truncated: false,
487            source_url: "u".into(),
488            cache_hit: false,
489        };
490        assert!(render_readme_markdown(&r).contains("No documentation"));
491        let i = GetItemData {
492            crate_name: "c".into(),
493            item_type: "fn".into(),
494            item_path: "c::f".into(),
495            item_name: "f".into(),
496            version: "latest".into(),
497            resolved_version: None,
498            markdown: String::new(),
499            empty: true,
500            truncated: false,
501            source_url: "u".into(),
502            title: "c::f (fn)".into(),
503            cache_hit: false,
504            extraction: None,
505            resolved_item_path: None,
506        };
507        assert!(render_item_markdown(&i).contains("No documentation"));
508    }
509
510    #[test]
511    fn success_and_dry_run_envelopes() {
512        let payload = serde_json::json!({"n": 1});
513        let v = success_envelope("version", &payload, 3, Some("https://x"));
514        let v = serde_json::to_value(&v).expect("serialize success envelope");
515        assert_eq!(v["ok"], true);
516        assert_eq!(v["source_url"], "https://x");
517        assert_eq!(v["schema_version"], SCHEMA_VERSION);
518        // Optional source_url omitted when None (not JSON null).
519        let no_url = success_envelope("version", &payload, 1, None);
520        let no_url = serde_json::to_value(&no_url).expect("serialize");
521        assert!(no_url.get("source_url").is_none());
522        #[derive(serde::Serialize)]
523        struct EmptyParams {}
524        let d = dry_run_envelope("readme", "https://u", EmptyParams {}, 1);
525        let d = serde_json::to_value(&d).expect("serialize dry-run envelope");
526        assert_eq!(d["dry_run"], true);
527        assert_eq!(d["data"]["planned_url"], "https://u");
528        assert_eq!(d["data"]["planned_params"], serde_json::json!({}));
529        assert!(usage_error("x").kind() == ErrorKind::Usage);
530    }
531
532    #[test]
533    fn optional_fields_omitted_not_null() {
534        let hit = CrateSearchHit {
535            name: "x".into(),
536            description: "d".into(),
537            downloads: 1,
538            version: "1.0.0".into(),
539            documentation: None,
540            max_version: None,
541            max_stable_version: None,
542            default_version: None,
543            recent_downloads: None,
544            exact_match: None,
545            yanked: None,
546            repository: None,
547            homepage: None,
548        };
549        let v = serde_json::to_value(&hit).expect("serialize hit");
550        assert!(v.get("documentation").is_none());
551        assert!(v.get("repository").is_none());
552        assert!(!v.as_object().expect("object").values().any(|x| x.is_null()));
553
554        let readme = ReadmeData {
555            crate_name: "c".into(),
556            version: "latest".into(),
557            resolved_version: None,
558            markdown: "m".into(),
559            empty: false,
560            truncated: false,
561            source_url: "https://example.com".into(),
562            cache_hit: false,
563        };
564        let r = serde_json::to_value(&readme).expect("serialize readme");
565        assert!(r.get("resolved_version").is_none());
566        assert!(!r.as_object().expect("object").values().any(|x| x.is_null()));
567    }
568
569    #[test]
570    fn apply_truncation_sets_flags() {
571        let cfg = Config {
572            max_output_bytes: 4,
573            ..Config::default()
574        };
575        let r = apply_truncation_to_readme(
576            ReadmeData {
577                crate_name: "c".into(),
578                version: "1".into(),
579                resolved_version: None,
580                markdown: "hello world".into(),
581                empty: false,
582                truncated: false,
583                source_url: "u".into(),
584                cache_hit: false,
585            },
586            &cfg,
587        );
588        assert!(r.truncated);
589        assert!(r.markdown.len() <= 4);
590        let i = apply_truncation_to_item(
591            GetItemData {
592                crate_name: "c".into(),
593                item_type: "fn".into(),
594                item_path: "c::f".into(),
595                item_name: "f".into(),
596                version: "1".into(),
597                resolved_version: None,
598                markdown: "abcdef".into(),
599                empty: false,
600                truncated: false,
601                source_url: "u".into(),
602                title: "t".into(),
603                cache_hit: false,
604                extraction: None,
605                resolved_item_path: None,
606            },
607            &cfg,
608        );
609        assert!(i.truncated);
610        assert_eq!(i.markdown, "abcd");
611    }
612
613    #[test]
614    fn truncate_zero_and_utf8_boundary() {
615        let (out, trunc) = truncate_output("abc", 0);
616        assert!(trunc);
617        assert!(out.is_empty());
618        let s = "áéí"; // multi-byte
619        let (out, trunc) = truncate_output(s, 2);
620        assert!(trunc);
621        assert!(out.is_char_boundary(out.len()));
622    }
623
624    #[test]
625    fn empty_search_in_crate_markdown() {
626        use crate::docs_rs::SearchInCrateData;
627        let data = SearchInCrateData {
628            crate_name: "c".into(),
629            query: String::new(),
630            version: "1".into(),
631            item_type: None,
632            match_mode: "prefix".into(),
633            total: 0,
634            emitted: 0,
635            hits: vec![],
636            truncated: false,
637            source_url: "u".into(),
638            cache_hit: false,
639        };
640        let md = render_search_in_crate_markdown(&data);
641        assert!(md.contains("all items"));
642        assert!(md.contains("No matching items"));
643    }
644
645    #[test]
646    fn search_docs_fallback_docs_rs_url() {
647        let data = SearchCratesData {
648            query: "x".into(),
649            page: 1,
650            per_page: 10,
651            sort: "relevance".into(),
652            hits: vec![CrateSearchHit {
653                name: "foo".into(),
654                description: "d".into(),
655                downloads: 1,
656                version: "1.0.0".into(),
657                documentation: None,
658                max_version: None,
659                max_stable_version: None,
660                default_version: None,
661                recent_downloads: None,
662                exact_match: None,
663                yanked: None,
664                repository: None,
665                homepage: None,
666            }],
667            meta: SearchMeta {
668                total: 1,
669                next_page: None,
670                prev_page: None,
671            },
672            cache_hit: false,
673            truncated: false,
674        };
675        let md = render_search_markdown(&data);
676        assert!(md.contains("https://docs.rs/foo"));
677        assert!(!md.contains("N/A"));
678    }
679
680    #[test]
681    fn output_budget_reduces_search_hits() {
682        let mut hits = Vec::new();
683        for i in 0..20 {
684            hits.push(CrateSearchHit {
685                name: format!("crate-{i}"),
686                description: "A".repeat(80),
687                downloads: i as u64,
688                version: "1.0.0".into(),
689                documentation: Some(format!("https://docs.rs/crate-{i}")),
690                max_version: None,
691                max_stable_version: None,
692                default_version: None,
693                recent_downloads: None,
694                exact_match: None,
695                yanked: None,
696                repository: None,
697                homepage: None,
698            });
699        }
700        let data = SearchCratesData {
701            query: "crate".into(),
702            page: 1,
703            per_page: 20,
704            sort: "relevance".into(),
705            hits,
706            meta: SearchMeta {
707                total: 20,
708                next_page: None,
709                prev_page: None,
710            },
711            cache_hit: false,
712            truncated: false,
713        };
714        let budgeted = apply_output_budget_search_crates(data, 800, 1, Some("https://crates.io"));
715        assert!(budgeted.truncated);
716        assert!(budgeted.hits.len() < 20);
717        let env = success_envelope("search-crates", &budgeted, 1, Some("https://crates.io"));
718        let len = serde_json::to_vec(&env).unwrap().len() as u64;
719        assert!(len <= 800, "envelope len {len} > 800");
720    }
721
722    #[test]
723    fn budget_error_is_not_retryable() {
724        let e = AppError::new(ErrorKind::Budget, "body too large");
725        let env = error_envelope(&e, "get-item", 12);
726        assert_eq!(env.command, "get-item");
727        assert_eq!(env.duration_ms, 12);
728        assert_eq!(env.error.kind, "budget");
729        assert_eq!(env.error.code, 74);
730        assert!(!env.error.retryable);
731    }
732}