Skip to main content

rigspark_runtime/
http.rs

1use futures_util::TryStreamExt;
2use serde_json::Value;
3use std::{pin::Pin, time::Duration};
4use tokio::io::{AsyncRead, AsyncReadExt};
5use tokio_util::{io::StreamReader, sync::CancellationToken};
6
7#[derive(Debug, thiserror::Error)]
8pub enum HttpError {
9    #[error("invalid loopback HTTP request")]
10    Invalid,
11    #[error("local runtime HTTP {0}")]
12    Status(u16),
13    #[error("local runtime transport failed")]
14    Transport,
15    #[error("local runtime response exceeds limit")]
16    Limit,
17    #[error("invalid local runtime response")]
18    Response,
19    #[error("operation cancelled")]
20    Cancelled,
21    #[error("local runtime request timed out")]
22    Timeout,
23}
24pub struct Request {
25    pub url: url::Url,
26    body: Option<Value>,
27    token: Option<String>,
28}
29impl Request {
30    pub fn new(
31        endpoint: &str,
32        path: &str,
33        body: Option<Value>,
34        token: Option<String>,
35    ) -> Result<Self, HttpError> {
36        let mut url = crate::state::loopback(endpoint).map_err(|_| HttpError::Invalid)?;
37        if !path.starts_with('/')
38            || path.starts_with("//")
39            || path.split('/').any(|part| part == ".." || part == ".")
40            || path
41                .bytes()
42                .any(|byte| byte.is_ascii_control() || b"\\%?#".contains(&byte))
43            || path.len() > 2048
44            || token.as_ref().is_some_and(|value| {
45                value.is_empty()
46                    || value.len() > 4096
47                    || value.bytes().any(|byte| !(0x20..=0x7e).contains(&byte))
48            })
49        {
50            return Err(HttpError::Invalid);
51        }
52        url.set_path(path);
53        url.set_query(None);
54        url.set_fragment(None);
55        if body.as_ref().is_some_and(|value| {
56            serde_json::to_vec(value).map_or(true, |bytes| bytes.len() > 16 * 1024 * 1024)
57        }) {
58            return Err(HttpError::Limit);
59        }
60        Ok(Self { url, body, token })
61    }
62    pub fn body(&self) -> Option<&Value> {
63        self.body.as_ref()
64    }
65    /// Adds percent-encoded query pairs; keys are ASCII identifiers, values bounded text.
66    pub fn with_query(mut self, pairs: &[(&str, &str)]) -> Result<Self, HttpError> {
67        if pairs.is_empty()
68            || pairs.len() > 16
69            || pairs.iter().any(|(key, value)| {
70                key.is_empty()
71                    || key.len() > 64
72                    || !key
73                        .bytes()
74                        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
75                    || value.len() > 1024
76                    || value.chars().any(char::is_control)
77            })
78        {
79            return Err(HttpError::Invalid);
80        }
81        self.url.query_pairs_mut().clear().extend_pairs(pairs);
82        Ok(self)
83    }
84}
85pub struct Response {
86    pub status: u16,
87    pub body: Pin<Box<dyn AsyncRead + Send>>,
88}
89#[async_trait::async_trait]
90pub trait Transport: Send + Sync {
91    async fn send(&self, request: Request) -> Result<Response, HttpError>;
92}
93pub struct NativeTransport {
94    client: reqwest::Client,
95}
96impl NativeTransport {
97    pub fn new() -> Result<Self, HttpError> {
98        let addresses = [
99            std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
100            std::net::SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], 0)),
101        ];
102        let client = reqwest::Client::builder()
103            .redirect(reqwest::redirect::Policy::none())
104            .no_proxy()
105            .resolve_to_addrs("localhost", &addresses)
106            .connect_timeout(Duration::from_secs(5))
107            .timeout(Duration::from_secs(1800))
108            .build()
109            .map_err(|_| HttpError::Transport)?;
110        Ok(Self { client })
111    }
112}
113#[async_trait::async_trait]
114impl Transport for NativeTransport {
115    async fn send(&self, request: Request) -> Result<Response, HttpError> {
116        crate::state::loopback(request.url.as_str()).map_err(|_| HttpError::Invalid)?;
117        let mut builder = if let Some(body) = request.body {
118            self.client.post(request.url).json(&body)
119        } else {
120            self.client.get(request.url)
121        };
122        if let Some(token) = request.token {
123            builder = builder.bearer_auth(token);
124        }
125        let response = builder.send().await.map_err(|_| HttpError::Transport)?;
126        let status = response.status().as_u16();
127        Ok(Response {
128            status,
129            body: Box::pin(StreamReader::new(
130                response.bytes_stream().map_err(std::io::Error::other),
131            )),
132        })
133    }
134}
135pub async fn read_json(
136    transport: &dyn Transport,
137    request: Request,
138    cancel: &CancellationToken,
139    maximum: usize,
140) -> Result<Value, HttpError> {
141    if maximum == 0 || maximum > 16 * 1024 * 1024 {
142        return Err(HttpError::Limit);
143    }
144    if cancel.is_cancelled() {
145        return Err(HttpError::Cancelled);
146    }
147    let operation = async {
148        let response = transport.send(request).await?;
149        if !(200..300).contains(&response.status) {
150            return Err(HttpError::Status(response.status));
151        }
152        let mut bytes = Vec::new();
153        response
154            .body
155            .take(maximum as u64 + 1)
156            .read_to_end(&mut bytes)
157            .await
158            .map_err(|_| HttpError::Transport)?;
159        if bytes.len() > maximum {
160            return Err(HttpError::Limit);
161        }
162        serde_json::from_slice(&bytes).map_err(|_| HttpError::Response)
163    };
164    tokio::select! { biased; _=cancel.cancelled()=>Err(HttpError::Cancelled),result=tokio::time::timeout(Duration::from_secs(120),operation)=>result.map_err(|_|HttpError::Timeout)? }
165}