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}
66pub struct Response {
67    pub status: u16,
68    pub body: Pin<Box<dyn AsyncRead + Send>>,
69}
70#[async_trait::async_trait]
71pub trait Transport: Send + Sync {
72    async fn send(&self, request: Request) -> Result<Response, HttpError>;
73}
74pub struct NativeTransport {
75    client: reqwest::Client,
76}
77impl NativeTransport {
78    pub fn new() -> Result<Self, HttpError> {
79        let addresses = [
80            std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
81            std::net::SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 1], 0)),
82        ];
83        let client = reqwest::Client::builder()
84            .redirect(reqwest::redirect::Policy::none())
85            .no_proxy()
86            .resolve_to_addrs("localhost", &addresses)
87            .connect_timeout(Duration::from_secs(5))
88            .timeout(Duration::from_secs(1800))
89            .build()
90            .map_err(|_| HttpError::Transport)?;
91        Ok(Self { client })
92    }
93}
94#[async_trait::async_trait]
95impl Transport for NativeTransport {
96    async fn send(&self, request: Request) -> Result<Response, HttpError> {
97        crate::state::loopback(request.url.as_str()).map_err(|_| HttpError::Invalid)?;
98        let mut builder = if let Some(body) = request.body {
99            self.client.post(request.url).json(&body)
100        } else {
101            self.client.get(request.url)
102        };
103        if let Some(token) = request.token {
104            builder = builder.bearer_auth(token);
105        }
106        let response = builder.send().await.map_err(|_| HttpError::Transport)?;
107        let status = response.status().as_u16();
108        Ok(Response {
109            status,
110            body: Box::pin(StreamReader::new(
111                response.bytes_stream().map_err(std::io::Error::other),
112            )),
113        })
114    }
115}
116pub async fn read_json(
117    transport: &dyn Transport,
118    request: Request,
119    cancel: &CancellationToken,
120    maximum: usize,
121) -> Result<Value, HttpError> {
122    if maximum == 0 || maximum > 16 * 1024 * 1024 {
123        return Err(HttpError::Limit);
124    }
125    if cancel.is_cancelled() {
126        return Err(HttpError::Cancelled);
127    }
128    let operation = async {
129        let response = transport.send(request).await?;
130        if !(200..300).contains(&response.status) {
131            return Err(HttpError::Status(response.status));
132        }
133        let mut bytes = Vec::new();
134        response
135            .body
136            .take(maximum as u64 + 1)
137            .read_to_end(&mut bytes)
138            .await
139            .map_err(|_| HttpError::Transport)?;
140        if bytes.len() > maximum {
141            return Err(HttpError::Limit);
142        }
143        serde_json::from_slice(&bytes).map_err(|_| HttpError::Response)
144    };
145    tokio::select! { biased; _=cancel.cancelled()=>Err(HttpError::Cancelled),result=tokio::time::timeout(Duration::from_secs(120),operation)=>result.map_err(|_|HttpError::Timeout)? }
146}