1#[cfg(feature = "native-http")]
7use crate::shared::errors::NetworkError;
8use crate::shared::errors::{HttpError, Result, StreamError};
9use async_stream::try_stream;
10use bytes::Bytes;
11use futures::Stream;
12use futures::StreamExt;
13
14pub const MAX_DOWNLOAD_SIZE: usize = 50 * 1024 * 1024;
20pub const MAX_ERROR_BODY_SIZE: usize = 1024 * 1024;
22pub const MAX_SSE_LINE_SIZE: usize = 1024 * 1024;
24pub const MODEL_CACHE_TTL_MS: u64 = 5 * 60 * 1000;
26pub const DEFAULT_JSON_TIMEOUT_MS: u64 = 30_000;
28pub const CHAT_REQUEST_TIMEOUT_MS: u64 = 11 * 60 * 1000;
31pub const COEF_CACHE_TTL_MS: u64 = 8 * 1000;
33
34pub fn parse_http_error(status_code: u16, body: &str) -> HttpError {
43 parse_http_error_with_retry_after(status_code, body, 0)
44}
45
46pub fn parse_http_error_with_retry_after(
48 status_code: u16,
49 body: &str,
50 retry_after: i64,
51) -> HttpError {
52 if body.is_empty() {
53 return HttpError::new(status_code, "", "", retry_after, "");
54 }
55
56 let mut type_ = String::new();
57 let mut message = String::new();
58 if let Ok(obj) = serde_json::from_str::<serde_json::Value>(body) {
59 if let Some(err_obj) = obj.get("error").filter(|v| v.is_object()) {
60 if let Some(m) = err_obj.get("message").and_then(|v| v.as_str()) {
61 message = m.to_string();
62 }
63 if let Some(t) = err_obj.get("type").and_then(|v| v.as_str()) {
64 type_ = t.to_string();
65 }
66 }
67 }
68 HttpError::new(status_code, type_, message, retry_after, body)
70}
71
72#[cfg(feature = "native-http")]
82pub fn classify_transport(op: &str, url: &str, err: &reqwest::Error) -> NetworkError {
83 let mut ne = NetworkError::new(op, url, err.to_string());
84 if err.is_timeout() {
85 ne.timeout = true;
86 return ne;
87 }
88 if err.is_connect() {
89 ne.eof = true;
90 return ne;
91 }
92 let msg = err.to_string().to_lowercase();
93 if msg.contains("connection reset")
94 || msg.contains("eof")
95 || msg.contains("broken pipe")
96 || msg.contains("connection closed")
97 {
98 ne.eof = true;
99 }
100 ne
101}
102
103pub fn parse_stream_error(data: &str) -> StreamError {
110 let payload: serde_json::Value = match serde_json::from_str(data) {
111 Ok(v) => v,
112 Err(_) => {
113 return StreamError {
114 raw_error: data.to_string(),
115 ..Default::default()
116 }
117 }
118 };
119
120 let mut code = payload
121 .get("errorCode")
122 .and_then(|v| v.as_str())
123 .unwrap_or("")
124 .to_string();
125 let stage = payload
126 .get("stage")
127 .and_then(|v| v.as_str())
128 .unwrap_or("")
129 .to_string();
130 let mut message = payload
131 .get("message")
132 .and_then(|v| v.as_str())
133 .unwrap_or("")
134 .to_string();
135 let retryable = payload
136 .get("retryable")
137 .and_then(|v| v.as_bool())
138 .unwrap_or(false);
139 let mut raw_error = String::new();
140
141 if let Some(err_val) = payload.get("error") {
142 if let Some(s) = err_val.as_str() {
143 raw_error = s.to_string();
144 } else if err_val.is_object() {
145 raw_error = err_val.to_string();
146 if message.is_empty() {
148 if let Some(m) = err_val.get("message").and_then(|v| v.as_str()) {
149 message = m.to_string();
150 }
151 }
152 if code.is_empty() {
154 if let Some(t) = err_val.get("type").and_then(|v| v.as_str()) {
155 code = t.to_string();
156 }
157 }
158 }
159 }
160
161 StreamError {
162 code,
163 stage,
164 user_message: message,
165 raw_error,
166 retryable,
167 }
168}
169
170pub fn is_order_success(status: &str) -> bool {
176 matches!(status, "PAID" | "SUCCESS" | "COMPLETED")
177}
178
179pub fn is_order_terminal(status: &str) -> bool {
181 matches!(
182 status,
183 "PAID"
184 | "SUCCESS"
185 | "COMPLETED"
186 | "FAILED"
187 | "CANCELLED"
188 | "CLOSED"
189 | "EXPIRED"
190 | "REFUNDED"
191 )
192}
193
194#[cfg(feature = "native-http")]
204pub fn iter_sse_lines<S>(body: S) -> impl Stream<Item = Result<String>>
205where
206 S: Stream<Item = reqwest::Result<Bytes>>,
207{
208 iter_sse_lines_with_cap(body, MAX_SSE_LINE_SIZE)
209}
210
211#[cfg(feature = "native-http")]
213pub fn iter_sse_lines_with_cap<S>(
214 body: S,
215 max_line_bytes: usize,
216) -> impl Stream<Item = Result<String>>
217where
218 S: Stream<Item = reqwest::Result<Bytes>>,
219{
220 iter_sse_lines_result_with_cap(body.map(|v| v.map_err(Into::into)), max_line_bytes)
221}
222
223pub fn iter_sse_lines_result<S>(body: S) -> impl Stream<Item = Result<String>>
224where
225 S: Stream<Item = Result<Bytes>>,
226{
227 iter_sse_lines_result_with_cap(body, MAX_SSE_LINE_SIZE)
228}
229
230pub fn iter_sse_lines_result_with_cap<S>(
231 body: S,
232 max_line_bytes: usize,
233) -> impl Stream<Item = Result<String>>
234where
235 S: Stream<Item = Result<Bytes>>,
236{
237 try_stream! {
238 futures::pin_mut!(body);
239 let mut buf: Vec<u8> = Vec::new();
240 while let Some(chunk) = body.next().await {
241 let chunk = chunk?;
242 let mut remaining = chunk.as_ref();
245 while !remaining.is_empty() {
246 let nl = remaining.iter().position(|&b| b == b'\n');
247 let end = nl.unwrap_or(remaining.len());
248 let part = &remaining[..end];
249 let trailing_cr = part.last().or_else(|| buf.last()) == Some(&b'\r');
250 let size = buf.len().checked_add(part.len())
251 .ok_or_else(|| crate::shared::errors::Error::other("SSE line size overflow"))?;
252 let content_size = size.saturating_sub(usize::from(trailing_cr));
253 if content_size > max_line_bytes {
254 Err(crate::shared::errors::Error::other(format!(
255 "SSE line exceeds {max_line_bytes} bytes"
256 )))?;
257 }
258 buf.extend_from_slice(part);
259 if let Some(nl) = nl {
260 if buf.last() == Some(&b'\r') { buf.pop(); }
261 let line = String::from_utf8(std::mem::take(&mut buf))
262 .map_err(|_| crate::shared::errors::Error::other("SSE line contains invalid UTF-8"))?;
263 yield line;
264 remaining = &remaining[nl + 1..];
265 } else {
266 break;
267 }
268 }
269 }
270 if !buf.is_empty() {
272 if buf.last() == Some(&b'\r') {
273 buf.pop();
274 }
275 if !buf.is_empty() {
276 yield String::from_utf8(buf).map_err(|_| crate::shared::errors::Error::other("SSE line contains invalid UTF-8"))?;
277 }
278 }
279 }
280}
281
282#[cfg(feature = "native-http")]
288pub async fn read_limited<S>(body: S, max_bytes: usize) -> Result<Vec<u8>>
289where
290 S: Stream<Item = reqwest::Result<Bytes>>,
291{
292 read_limited_result(body.map(|v| v.map_err(Into::into)), max_bytes).await
293}
294
295pub async fn read_limited_result<S>(body: S, max_bytes: usize) -> Result<Vec<u8>>
296where
297 S: Stream<Item = Result<Bytes>>,
298{
299 futures::pin_mut!(body);
300 let mut out: Vec<u8> = Vec::new();
301 while let Some(chunk) = body.next().await {
302 let chunk = chunk?;
303 if out.len() + chunk.len() > max_bytes {
304 let remain = max_bytes - out.len();
305 if remain > 0 {
306 out.extend_from_slice(&chunk[..remain]);
307 }
308 break;
309 }
310 out.extend_from_slice(&chunk);
311 }
312 Ok(out)
313}
314
315#[cfg(feature = "native-http")]
317pub async fn read_limited_text<S>(body: S, max_bytes: usize) -> Result<String>
318where
319 S: Stream<Item = reqwest::Result<Bytes>>,
320{
321 let buf = read_limited(body, max_bytes).await?;
322 Ok(String::from_utf8_lossy(&buf).into_owned())
323}
324
325pub async fn read_limited_text_result<S>(body: S, max_bytes: usize) -> Result<String>
326where
327 S: Stream<Item = Result<Bytes>>,
328{
329 Ok(String::from_utf8_lossy(&read_limited_result(body, max_bytes).await?).into_owned())
330}