Skip to main content

acosmi/core/
http.rs

1//! Client 内部 HTTP 辅助。端口自 `core/http.ts`(其端口自 `acosmi-sdk-go/client.go`)。
2//!
3//! 含:安全限制常量 / `parse_http_error`(Anthropic + OpenAI 错误体)/ `classify_transport`
4//! (NetworkError 分类)/ `parse_stream_error`(三 schema)/ 订单状态判定 / SSE 行扫描器 / 限长读取。
5
6#[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
14// =============================================================================
15// 安全限制常量(端口自 client.go 安全限制常量段)
16// =============================================================================
17
18/// 50MB —— 技能 ZIP 包最大下载体积。
19pub const MAX_DOWNLOAD_SIZE: usize = 50 * 1024 * 1024;
20/// 1MB —— 错误响应体最大读取量。
21pub const MAX_ERROR_BODY_SIZE: usize = 1024 * 1024;
22/// 1MB —— SSE 单行最大长度(大 JSON chunk)。
23pub const MAX_SSE_LINE_SIZE: usize = 1024 * 1024;
24/// 模型列表缓存有效期(毫秒)。
25pub const MODEL_CACHE_TTL_MS: u64 = 5 * 60 * 1000;
26/// 非流式 JSON 子请求默认超时(毫秒),对应 TS `doJSONFull*` 内 `withRequestTimeout(30_000,...)`。
27pub const DEFAULT_JSON_TIMEOUT_MS: u64 = 30_000;
28/// chat / messages / 媒体生成 per-request 超时(毫秒,11min),对应 TS `CHAT_REQUEST_TIMEOUT_MS`。
29/// 容纳 DeepSeek 等上游"首字节前 10min 保活"窗口。
30pub const CHAT_REQUEST_TIMEOUT_MS: u64 = 11 * 60 * 1000;
31/// V29 系数缓存(TTL 8s)。
32pub const COEF_CACHE_TTL_MS: u64 = 8 * 1000;
33
34// =============================================================================
35// HTTP 错误解析
36// =============================================================================
37
38/// 解析 HTTP 错误响应体,兼容 Anthropic 和 OpenAI 错误格式。
39/// - Anthropic:`{"type":"error","error":{"type":"...","message":"..."}}`
40/// - OpenAI:`{"error":{"message":"...","type":"...","code":"..."}}`
41/// - 通用回退:`HTTP {status}: {body}`
42pub fn parse_http_error(status_code: u16, body: &str) -> HttpError {
43    parse_http_error_with_retry_after(status_code, body, 0)
44}
45
46/// 同 [`parse_http_error`],额外携带已从 `Retry-After` 头解析的秒数(0 = 无)。
47pub 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    // 非 JSON → body 原样保留(type/message 空)。
69    HttpError::new(status_code, type_, message, retry_after, body)
70}
71
72// =============================================================================
73// 网络错误分类
74// =============================================================================
75
76/// 包装传输层 `reqwest::Error` 为 `NetworkError`,便于 retry policy 判定。
77///
78/// - 超时(`is_timeout`)→ `timeout=true`
79/// - 连接重置 / EOF / broken pipe / 连接失败 → `eof=true`
80/// - 其它:`timeout`/`eof` 均 false(不重试)
81#[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
103// =============================================================================
104// Stream Error 解析
105// =============================================================================
106
107/// 从 failed/error 事件 JSON 中提取结构化错误(兼容三种 schema,按优先级)。
108/// 对应 TS `parseStreamError`。
109pub 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            // 私有 message 空时,用 Anthropic error.message 兜底。
147            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            // errorCode 空 + Anthropic error.type 非空时,兜底用 type 作 code。
153            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
170// =============================================================================
171// Order 状态判定
172// =============================================================================
173
174/// 订单是否成功终态。对应 TS `isOrderSuccess`。
175pub fn is_order_success(status: &str) -> bool {
176    matches!(status, "PAID" | "SUCCESS" | "COMPLETED")
177}
178
179/// 订单是否到达终态(成功或失败)。对应 TS `isOrderTerminal`。
180pub 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// =============================================================================
195// SSE 行迭代器(替代 Go bufio.Scanner / TS iterSSELines)
196// =============================================================================
197
198/// 把字节流(reqwest `Response::bytes_stream()`)转为按行产出的异步流。
199///
200/// - 单行 1MB 硬上限(与 [`MAX_SSE_LINE_SIZE`] 对齐)—— 超长行报错。
201/// - 去除行尾 `\r`(CRLF)。
202/// - flush 末行(无结尾 `\n`)。
203#[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/// [`iter_sse_lines`] 带自定义单行上限。
212#[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            // Bound before copying, including complete lines contained in one chunk.
243            // One trailing CR is framing, and may be split from its LF.
244            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        // 末行(无结尾 \n)。
271        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// =============================================================================
283// 限长读取(替代 Go io.LimitReader)
284// =============================================================================
285
286/// 读取字节流但限制最大字节数,超限丢弃尾部。对应 TS `readLimited`。
287#[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/// 读取字节流 + UTF-8 解码,限制最大字节数。对应 TS `readLimitedText`。
316#[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}