use crate::shared::errors::{HttpError, NetworkError, Result, StreamError};
use async_stream::try_stream;
use bytes::Bytes;
use futures::Stream;
use futures::StreamExt;
pub const MAX_DOWNLOAD_SIZE: usize = 50 * 1024 * 1024;
pub const MAX_ERROR_BODY_SIZE: usize = 1024 * 1024;
pub const MAX_SSE_LINE_SIZE: usize = 1024 * 1024;
pub const MODEL_CACHE_TTL_MS: u64 = 5 * 60 * 1000;
pub const DEFAULT_JSON_TIMEOUT_MS: u64 = 30_000;
pub const CHAT_REQUEST_TIMEOUT_MS: u64 = 11 * 60 * 1000;
pub const COEF_CACHE_TTL_MS: u64 = 8 * 1000;
pub fn parse_http_error(status_code: u16, body: &str) -> HttpError {
parse_http_error_with_retry_after(status_code, body, 0)
}
pub fn parse_http_error_with_retry_after(
status_code: u16,
body: &str,
retry_after: i64,
) -> HttpError {
if body.is_empty() {
return HttpError::new(status_code, "", "", retry_after, "");
}
let mut type_ = String::new();
let mut message = String::new();
if let Ok(obj) = serde_json::from_str::<serde_json::Value>(body) {
if let Some(err_obj) = obj.get("error").filter(|v| v.is_object()) {
if let Some(m) = err_obj.get("message").and_then(|v| v.as_str()) {
message = m.to_string();
}
if let Some(t) = err_obj.get("type").and_then(|v| v.as_str()) {
type_ = t.to_string();
}
}
}
HttpError::new(status_code, type_, message, retry_after, body)
}
pub fn classify_transport(op: &str, url: &str, err: &reqwest::Error) -> NetworkError {
let mut ne = NetworkError::new(op, url, err.to_string());
if err.is_timeout() {
ne.timeout = true;
return ne;
}
if err.is_connect() {
ne.eof = true;
return ne;
}
let msg = err.to_string().to_lowercase();
if msg.contains("connection reset")
|| msg.contains("eof")
|| msg.contains("broken pipe")
|| msg.contains("connection closed")
{
ne.eof = true;
}
ne
}
pub fn parse_stream_error(data: &str) -> StreamError {
let payload: serde_json::Value = match serde_json::from_str(data) {
Ok(v) => v,
Err(_) => {
return StreamError {
raw_error: data.to_string(),
..Default::default()
}
}
};
let mut code = payload
.get("errorCode")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let stage = payload
.get("stage")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let mut message = payload
.get("message")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let retryable = payload
.get("retryable")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let mut raw_error = String::new();
if let Some(err_val) = payload.get("error") {
if let Some(s) = err_val.as_str() {
raw_error = s.to_string();
} else if err_val.is_object() {
raw_error = err_val.to_string();
if message.is_empty() {
if let Some(m) = err_val.get("message").and_then(|v| v.as_str()) {
message = m.to_string();
}
}
if code.is_empty() {
if let Some(t) = err_val.get("type").and_then(|v| v.as_str()) {
code = t.to_string();
}
}
}
}
StreamError {
code,
stage,
user_message: message,
raw_error,
retryable,
}
}
pub fn is_order_success(status: &str) -> bool {
matches!(status, "PAID" | "SUCCESS" | "COMPLETED")
}
pub fn is_order_terminal(status: &str) -> bool {
matches!(
status,
"PAID"
| "SUCCESS"
| "COMPLETED"
| "FAILED"
| "CANCELLED"
| "CLOSED"
| "EXPIRED"
| "REFUNDED"
)
}
pub fn iter_sse_lines<S>(body: S) -> impl Stream<Item = Result<String>>
where
S: Stream<Item = reqwest::Result<Bytes>>,
{
iter_sse_lines_with_cap(body, MAX_SSE_LINE_SIZE)
}
pub fn iter_sse_lines_with_cap<S>(
body: S,
max_line_bytes: usize,
) -> impl Stream<Item = Result<String>>
where
S: Stream<Item = reqwest::Result<Bytes>>,
{
try_stream! {
futures::pin_mut!(body);
let mut buf: Vec<u8> = Vec::new();
while let Some(chunk) = body.next().await {
let chunk = chunk?;
buf.extend_from_slice(&chunk);
while let Some(nl) = buf.iter().position(|&b| b == b'\n') {
let mut line: Vec<u8> = buf.drain(..=nl).collect();
line.pop(); if line.last() == Some(&b'\r') {
line.pop();
}
yield String::from_utf8_lossy(&line).into_owned();
}
if buf.len() > max_line_bytes {
Err(crate::shared::errors::Error::other(format!(
"SSE line exceeds {max_line_bytes} bytes"
)))?;
}
}
if !buf.is_empty() {
if buf.last() == Some(&b'\r') {
buf.pop();
}
if !buf.is_empty() {
yield String::from_utf8_lossy(&buf).into_owned();
}
}
}
}
pub async fn read_limited<S>(body: S, max_bytes: usize) -> Result<Vec<u8>>
where
S: Stream<Item = reqwest::Result<Bytes>>,
{
futures::pin_mut!(body);
let mut out: Vec<u8> = Vec::new();
while let Some(chunk) = body.next().await {
let chunk = chunk?;
if out.len() + chunk.len() > max_bytes {
let remain = max_bytes - out.len();
if remain > 0 {
out.extend_from_slice(&chunk[..remain]);
}
break;
}
out.extend_from_slice(&chunk);
}
Ok(out)
}
pub async fn read_limited_text<S>(body: S, max_bytes: usize) -> Result<String>
where
S: Stream<Item = reqwest::Result<Bytes>>,
{
let buf = read_limited(body, max_bytes).await?;
Ok(String::from_utf8_lossy(&buf).into_owned())
}