Skip to main content

gadk_model/
http.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 pluggable HTTP transport used by model backends.
17
18use bytes::{Bytes, BytesMut};
19use futures::StreamExt;
20use futures::stream::BoxStream;
21
22use crate::error::ModelError;
23
24/// A streaming response body.
25pub type BodyStream = BoxStream<'static, Result<Bytes, ModelError>>;
26
27/// An HTTP transport. Backends send every request through this trait so tests can
28/// substitute a recorder/replayer.
29#[async_trait::async_trait]
30pub trait HttpClient: Send + Sync {
31    /// Sends `req` and returns the response with a streaming body.
32    async fn send(
33        &self,
34        req: http::Request<Bytes>,
35    ) -> Result<http::Response<BodyStream>, ModelError>;
36}
37
38/// [`HttpClient`] backed by `reqwest`.
39#[derive(Debug, Clone, Default)]
40pub struct ReqwestClient(reqwest::Client);
41
42impl ReqwestClient {
43    /// Wraps an existing `reqwest::Client`.
44    pub fn new(client: reqwest::Client) -> Self {
45        Self(client)
46    }
47}
48
49#[async_trait::async_trait]
50impl HttpClient for ReqwestClient {
51    async fn send(
52        &self,
53        req: http::Request<Bytes>,
54    ) -> Result<http::Response<BodyStream>, ModelError> {
55        let req =
56            reqwest::Request::try_from(req).map_err(|e| ModelError::Transport(Box::new(e)))?;
57        let resp = self
58            .0
59            .execute(req)
60            .await
61            .map_err(|e| ModelError::Transport(Box::new(e)))?;
62        let status = resp.status();
63        let version = resp.version();
64        let headers = resp.headers().clone();
65        let body: BodyStream = resp
66            .bytes_stream()
67            .map(|r| r.map_err(|e| ModelError::Transport(Box::new(e))))
68            .boxed();
69        let mut out = http::Response::new(body);
70        *out.status_mut() = status;
71        *out.version_mut() = version;
72        *out.headers_mut() = headers;
73        Ok(out)
74    }
75}
76
77/// Reads a [`BodyStream`] to the end, concatenating all chunks.
78pub async fn collect_body(mut body: BodyStream) -> Result<Bytes, ModelError> {
79    let mut buf = BytesMut::new();
80    while let Some(chunk) = body.next().await {
81        buf.extend_from_slice(&chunk?);
82    }
83    Ok(buf.freeze())
84}
85
86/// `err` and its sources, joined with `": "` (moved from gadk-anthropic so every REST
87/// provider renders a cause chain the same way).
88pub fn error_chain(err: &(dyn std::error::Error + 'static)) -> String {
89    let mut out = err.to_string();
90    let mut cur = err.source();
91    while let Some(e) = cur {
92        out.push_str(": ");
93        out.push_str(&e.to_string());
94        cur = e.source();
95    }
96    out
97}
98
99/// The text of a [`ModelError::Transport`] cause: a `reqwest::Error` loses its URL, then the
100/// source chain is joined with `": "` ([`error_chain`]).
101pub fn transport_error_detail(err: Box<dyn std::error::Error + Send + Sync>) -> String {
102    match err.downcast::<reqwest::Error>() {
103        Ok(e) => error_chain(&e.without_url()),
104        Err(other) => error_chain(other.as_ref()),
105    }
106}
107
108/// `url` for `Debug` output: credentials embedded in it (`https://user:secret@host`) are
109/// removed; a URL without user info is returned as it is, and one that does not parse, has no
110/// host but contains `@`, or whose user info cannot be removed becomes `<redacted>`.
111pub fn redact_url(url: &str) -> String {
112    let Ok(mut parsed) = reqwest::Url::parse(url) else {
113        return "<redacted>".to_string();
114    };
115    // Without an authority, an `@` may be user info the parser did not recognise (e.g.
116    // `user:secret@host` parses as scheme `user`), so the whole value is withheld.
117    if !parsed.has_host() && url.contains('@') {
118        return "<redacted>".to_string();
119    }
120    if parsed.username().is_empty() && parsed.password().is_none() {
121        return url.to_string();
122    }
123    if parsed.set_username("").is_err() || parsed.set_password(None).is_err() {
124        return "<redacted>".to_string();
125    }
126    parsed.to_string()
127}
128
129#[cfg(test)]
130mod tests {
131    use super::redact_url;
132
133    #[test]
134    fn redact_url_removes_user_info() {
135        assert_eq!(
136            redact_url("https://user:secret@proxy.example/v1"),
137            "https://proxy.example/v1"
138        );
139        assert_eq!(
140            redact_url("https://token@proxy.example"),
141            "https://proxy.example/"
142        );
143        assert_eq!(
144            redact_url("https://:secret@proxy.example/"),
145            "https://proxy.example/"
146        );
147        // No user info: unchanged (not normalized).
148        assert_eq!(redact_url("https://proxy.example"), "https://proxy.example");
149        assert_eq!(redact_url("not a url user:secret@"), "<redacted>");
150        // Scheme-less user info parses as scheme `user` with no authority.
151        assert_eq!(redact_url("user:secret@proxy.example:8080"), "<redacted>");
152        assert_eq!(redact_url("user:secret@proxy.example/v1"), "<redacted>");
153    }
154}