Skip to main content

gadk_model/rest/
googleapi.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The Google API HTTP error: [`ApiError`] (its `Display` is the `googleapi: Error {code}: …`
17//! text), [`ErrorItem`], and the response check that builds it ([`check_response`], with
18//! [`api_error_from_response`] as its error branch).
19
20use std::fmt;
21
22use http::HeaderMap;
23use serde::{Deserialize, Deserializer};
24use serde_json::Value;
25
26/// One entry of a Google API error's `errors` list.
27#[derive(Debug, Clone, Default, PartialEq, Eq)]
28pub struct ErrorItem {
29    /// `reason`, e.g. `notFound`.
30    pub reason: String,
31    /// `message`.
32    pub message: String,
33}
34
35/// A Google API HTTP error, built by [`check_response`] from a response with status ≥ 300.
36/// `Display` renders `googleapi: Error {code}: {message}` plus any details and error items.
37#[derive(Debug, Clone, Default)]
38pub struct ApiError {
39    /// The HTTP status code.
40    pub code: u16,
41    /// The JSON error body's `error.message`.
42    pub message: String,
43    /// The JSON error body's `error.details`.
44    pub details: Vec<Value>,
45    /// The raw response body.
46    pub body: String,
47    /// The response headers.
48    pub header: HeaderMap,
49    /// The JSON error body's `error.errors`.
50    pub errors: Vec<ErrorItem>,
51}
52
53impl fmt::Display for ApiError {
54    /// Formats the error as the `googleapi: …` text described on [`ApiError`].
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        if self.errors.is_empty() && self.message.is_empty() {
57            return write!(
58                f,
59                "googleapi: got HTTP response code {} with body: {}",
60                self.code, self.body
61            );
62        }
63        let mut buf = format!("googleapi: Error {}: ", self.code);
64        buf.push_str(&self.message);
65        if !self.details.is_empty()
66            && let Ok(compact) = crate::to_go_json(&self.details)
67        {
68            // Details as pretty-printed JSON with a two-space indent and a trailing newline.
69            buf.push_str("\nDetails:");
70            buf.push('\n');
71            buf.push_str(&go_json_indent(&compact));
72            buf.push('\n');
73        }
74        if self.errors.is_empty() {
75            return f.write_str(buf.trim());
76        }
77        if self.errors.len() == 1 && self.errors[0].message == self.message {
78            buf.push_str(", ");
79            buf.push_str(&self.errors[0].reason);
80            return f.write_str(&buf);
81        }
82        buf.push_str("\nMore details:\n");
83        for e in &self.errors {
84            buf.push_str(&format!("Reason: {}, Message: {}\n", e.reason, e.message));
85        }
86        f.write_str(&buf)
87    }
88}
89
90impl std::error::Error for ApiError {}
91
92/// Re-indents compact JSON (`to_go_json` output) with two spaces per level.
93fn go_json_indent(compact: &[u8]) -> String {
94    let text = String::from_utf8_lossy(compact);
95    let mut out = String::with_capacity(text.len() * 2);
96    let mut depth = 0usize;
97    let mut in_string = false;
98    let mut escaped = false;
99    let mut need_indent = false;
100    let newline = |out: &mut String, depth: usize| {
101        out.push('\n');
102        for _ in 0..depth {
103            out.push_str("  ");
104        }
105    };
106    for c in text.chars() {
107        if in_string {
108            out.push(c);
109            if escaped {
110                escaped = false;
111            } else if c == '\\' {
112                escaped = true;
113            } else if c == '"' {
114                in_string = false;
115            }
116            continue;
117        }
118        match c {
119            '{' | '[' => {
120                if need_indent {
121                    newline(&mut out, depth);
122                }
123                out.push(c);
124                depth += 1;
125                need_indent = true;
126            }
127            '}' | ']' => {
128                depth = depth.saturating_sub(1);
129                if need_indent {
130                    // An empty object or array stays `{}` / `[]`.
131                    need_indent = false;
132                } else {
133                    newline(&mut out, depth);
134                }
135                out.push(c);
136            }
137            ',' => {
138                out.push(c);
139                newline(&mut out, depth);
140            }
141            ':' => out.push_str(": "),
142            _ => {
143                if need_indent {
144                    newline(&mut out, depth);
145                    need_indent = false;
146                }
147                if c == '"' {
148                    in_string = true;
149                }
150                out.push(c);
151            }
152        }
153    }
154    out
155}
156
157/// `Ok` for a 2xx status, else the [`ApiError`] of [`api_error_from_response`].
158pub fn check_response(parts: &http::response::Parts, body: &[u8]) -> Result<(), Box<ApiError>> {
159    if parts.status.is_success() {
160        return Ok(());
161    }
162    Err(Box::new(api_error_from_response(parts, body)))
163}
164
165/// For a response with status ≥ 300: the [`ApiError`] built from the JSON error body
166/// (`error.code` / `message` / `errors` / `details`), the raw body and the headers.
167pub fn api_error_from_response(parts: &http::response::Parts, body: &[u8]) -> ApiError {
168    let status = parts.status.as_u16();
169    let mut err = ApiError {
170        code: status,
171        body: String::from_utf8_lossy(body).into_owned(),
172        header: parts.headers.clone(),
173        ..ApiError::default()
174    };
175    if let Some(reply) = error_reply_from_body(body) {
176        if reply.code != 0 {
177            // The body's `error.code` is kept even when it differs from the HTTP status; a code
178            // outside `u16` (negative or above 65535) keeps the HTTP status instead.
179            err.code = u16::try_from(reply.code).unwrap_or(status);
180        }
181        err.message = reply.message;
182        err.details = reply.details;
183        // A `null` entry becomes a zero `ErrorItem` and is kept.
184        err.errors = reply
185            .errors
186            .into_iter()
187            .map(|i| {
188                let i = i.unwrap_or_default();
189                ErrorItem {
190                    reason: i.reason,
191                    message: i.message,
192                }
193            })
194            .collect();
195    }
196    err
197}
198
199#[derive(Deserialize)]
200struct ErrorReply {
201    error: Option<ErrorReplyBody>,
202}
203
204#[derive(Deserialize)]
205struct ErrorReplyBody {
206    #[serde(default, deserialize_with = "nullable")]
207    code: i64,
208    #[serde(default, deserialize_with = "nullable")]
209    message: String,
210    #[serde(default, deserialize_with = "nullable")]
211    details: Vec<Value>,
212    #[serde(default, deserialize_with = "nullable")]
213    errors: Vec<Option<ErrorItemReply>>,
214}
215
216#[derive(Default, Deserialize)]
217#[serde(default)]
218struct ErrorItemReply {
219    #[serde(deserialize_with = "nullable")]
220    reason: String,
221    #[serde(deserialize_with = "nullable")]
222    message: String,
223}
224
225/// A JSON object `{"error": …}`, or the first element of a JSON array
226/// of them; `None` when the body is neither or has no `error`.
227fn error_reply_from_body(body: &[u8]) -> Option<ErrorReplyBody> {
228    if body.first() == Some(&b'[') {
229        let mut replies: Vec<ErrorReply> = serde_json::from_slice(body).ok()?;
230        if replies.is_empty() {
231            return None;
232        }
233        return replies.swap_remove(0).error;
234    }
235    serde_json::from_slice::<ErrorReply>(body).ok()?.error
236}
237
238/// A JSON `null` (or a missing field) as the type's zero value.
239fn nullable<'de, D, T>(d: D) -> Result<T, D::Error>
240where
241    D: Deserializer<'de>,
242    T: Deserialize<'de> + Default,
243{
244    Ok(Option::<T>::deserialize(d)?.unwrap_or_default())
245}
246
247#[cfg(test)]
248mod tests {
249    #![allow(clippy::unwrap_used)]
250
251    use serde_json::json;
252
253    use super::*;
254
255    fn parts(status: u16) -> http::response::Parts {
256        let (mut parts, ()) = http::Response::new(()).into_parts();
257        parts.status = http::StatusCode::from_u16(status).unwrap();
258        parts
259    }
260
261    #[test]
262    fn display_is_gos_error_text() {
263        let no_message = ApiError {
264            code: 502,
265            body: "bad gateway".into(),
266            ..ApiError::default()
267        };
268        assert_eq!(
269            no_message.to_string(),
270            "googleapi: got HTTP response code 502 with body: bad gateway"
271        );
272        let one_item = ApiError {
273            code: 404,
274            message: "nf".into(),
275            errors: vec![ErrorItem {
276                reason: "notFound".into(),
277                message: "nf".into(),
278            }],
279            ..ApiError::default()
280        };
281        assert_eq!(one_item.to_string(), "googleapi: Error 404: nf, notFound");
282        let many = ApiError {
283            code: 400,
284            message: "bad".into(),
285            errors: vec![
286                ErrorItem {
287                    reason: "invalid".into(),
288                    message: "a".into(),
289                },
290                ErrorItem::default(),
291            ],
292            ..ApiError::default()
293        };
294        assert_eq!(
295            many.to_string(),
296            "googleapi: Error 400: bad\nMore details:\nReason: invalid, Message: a\nReason: , \
297             Message: \n"
298        );
299        let details = ApiError {
300            code: 400,
301            message: "bad".into(),
302            details: vec![json!({"@type": "t<x>", "empty": {}, "list": [1, 2], "none": []})],
303            ..ApiError::default()
304        };
305        assert_eq!(
306            details.to_string(),
307            "googleapi: Error 400: bad\nDetails:\n[\n  {\n    \"@type\": \"t\\u003cx\\u003e\",\n    \
308             \"empty\": {},\n    \"list\": [\n      1,\n      2\n    ],\n    \"none\": []\n  }\n]"
309        );
310    }
311
312    #[test]
313    fn check_response_passes_2xx_and_builds_the_error_otherwise() {
314        for status in [200, 201, 204, 299] {
315            assert!(
316                check_response(&parts(status), b"not json").is_ok(),
317                "{status}"
318            );
319        }
320        let mut p = parts(404);
321        p.headers
322            .insert("x-goog-request-id", http::HeaderValue::from_static("r1"));
323        let body = br#"{"error":{"code":404,"message":"gone","errors":[{"reason":"notFound","message":"gone"}],"details":[{"k":1}]}}"#;
324        let err = check_response(&p, body).unwrap_err();
325        assert_eq!(err.code, 404);
326        assert_eq!(err.message, "gone");
327        assert_eq!(err.details, vec![json!({"k": 1})]);
328        assert_eq!(err.body, String::from_utf8_lossy(body));
329        assert_eq!(err.header.get("x-goog-request-id").unwrap(), "r1");
330        // A 3xx is an error too (Go checks 200..=299).
331        let err = check_response(&parts(304), b"").unwrap_err();
332        assert_eq!(
333            err.to_string(),
334            "googleapi: got HTTP response code 304 with body: "
335        );
336    }
337
338    #[test]
339    fn api_error_from_response_reads_go_error_replies() {
340        // The body's code wins; a JSON array's first element is read.
341        let err =
342            api_error_from_response(&parts(400), br#"[{"error":{"code":409,"message":"dup"}}]"#);
343        assert_eq!((err.code, err.message.as_str()), (409, "dup"));
344        // A zero, negative or too large body code keeps the status.
345        for body in [
346            &br#"{"error":{"code":0,"message":"m"}}"#[..],
347            br#"{"error":{"code":-1,"message":"m"}}"#,
348            br#"{"error":{"code":70000,"message":"m"}}"#,
349        ] {
350            assert_eq!(api_error_from_response(&parts(412), body).code, 412);
351        }
352        // `null` fields are zero values; a `null` item is a zero item.
353        let err = api_error_from_response(
354            &parts(403),
355            br#"{"error":{"code":null,"message":null,"details":null,"errors":[null,{"reason":null,"message":"m"}]}}"#,
356        );
357        assert_eq!(err.code, 403);
358        assert_eq!(
359            err.errors,
360            vec![
361                ErrorItem::default(),
362                ErrorItem {
363                    reason: String::new(),
364                    message: "m".into(),
365                },
366            ]
367        );
368        // Not an error reply: the status and the raw body.
369        for body in [
370            &b"down"[..],
371            b"[]",
372            br#"{"error":null}"#,
373            br#"{"error":"x"}"#,
374        ] {
375            let err = api_error_from_response(&parts(502), body);
376            assert_eq!(err.code, 502);
377            assert!(err.message.is_empty() && err.errors.is_empty());
378            assert_eq!(err.body, String::from_utf8_lossy(body));
379        }
380    }
381}