1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/*******************************************************************************
*
* Copyright (c) 2025 - 2026 Haixing Hu.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0.
*
******************************************************************************/
//! Unified HTTP response type and helpers.
use std::time::Duration;
use async_stream::stream;
use bytes::Bytes;
use futures_util::{
stream as futures_stream,
StreamExt,
};
use http::header::{
CONTENT_LENGTH,
CONTENT_TYPE,
};
use http::{
HeaderMap,
Method,
StatusCode,
};
use serde::de::DeserializeOwned;
use tokio_util::sync::CancellationToken;
use url::Url;
use crate::error::{
backend_error_mapper::map_reqwest_error,
ReqwestErrorPhase,
};
use crate::sse::{
DoneMarkerPolicy,
SseChunkStream,
SseEventStream,
SseJsonMode,
};
use crate::{
HttpByteStream,
HttpError,
HttpErrorKind,
HttpResult,
};
use super::{
HttpResponseMeta,
HttpResponseOptions,
};
/// Runtime state bound to one response instance.
#[derive(Debug, Clone)]
struct HttpResponseRuntime {
/// Per-response read timeout inherited from request/client.
read_timeout: Duration,
/// Optional cancellation token inherited from request.
cancellation_token: Option<CancellationToken>,
/// Request URL used in read/cancellation error context.
request_url: Url,
}
impl HttpResponseRuntime {
fn new(
read_timeout: Duration,
cancellation_token: Option<CancellationToken>,
request_url: Url,
) -> Self {
Self {
read_timeout,
cancellation_token,
request_url,
}
}
}
/// Unified HTTP response with lazily consumed body.
#[derive(Debug)]
pub struct HttpResponse {
/// Response metadata (status, headers, final URL, request method).
pub meta: HttpResponseMeta,
/// Raw backend response until consumed.
backend: Option<reqwest::Response>,
/// Cached full body bytes after eager or lazy read.
buffered_body: Option<Bytes>,
/// Runtime state inherited from request/client.
runtime: HttpResponseRuntime,
/// Decode and error-preview options inherited from client options.
options: HttpResponseOptions,
}
impl HttpResponse {
/// Creates a buffered response.
pub fn new(
status: StatusCode,
headers: HeaderMap,
body: Bytes,
url: Url,
method: Method,
) -> Self {
Self {
meta: HttpResponseMeta::new(status, headers, url.clone(), method),
backend: None,
buffered_body: Some(body),
runtime: HttpResponseRuntime::new(Duration::from_secs(30), None, url),
options: HttpResponseOptions::default(),
}
}
/// Creates a response from backend response and request-scoped options.
pub(crate) fn from_backend(
meta: HttpResponseMeta,
backend: reqwest::Response,
read_timeout: Duration,
cancellation_token: Option<CancellationToken>,
request_url: Url,
options: HttpResponseOptions,
) -> Self {
Self {
meta,
backend: Some(backend),
buffered_body: None,
runtime: HttpResponseRuntime::new(read_timeout, cancellation_token, request_url),
options,
}
}
/// Returns shared response metadata.
#[inline]
pub fn meta(&self) -> &HttpResponseMeta {
&self.meta
}
/// Returns response status code.
#[inline]
pub fn status(&self) -> StatusCode {
self.meta.status
}
/// Returns response headers.
#[inline]
pub fn headers(&self) -> &HeaderMap {
&self.meta.headers
}
/// Returns final response URL.
#[inline]
pub fn url(&self) -> &Url {
&self.meta.url
}
/// Returns request URL used in response read context.
#[inline]
pub fn request_url(&self) -> &Url {
&self.runtime.request_url
}
/// Returns whether status is success.
#[inline]
pub fn is_success(&self) -> bool {
self.status().is_success()
}
/// Returns parsed `Retry-After` hint when status and headers provide one.
#[inline]
pub fn retry_after_hint(&self) -> Option<Duration> {
self.meta.retry_after_hint()
}
/// Returns `Ok(self)` for success statuses, otherwise maps a status error
/// with `Retry-After` and response-body preview context.
pub(crate) async fn into_success_or_status_error(
self,
message_prefix: &str,
) -> HttpResult<Self> {
let status = self.status();
if status.is_success() {
return Ok(self);
}
let retry_after = self.retry_after_hint();
let method = self.meta.method.clone();
let url = self.request_url().clone();
let error_preview_limit = self.options.error_response_preview_limit;
let body_preview = self.into_error_body_preview(error_preview_limit).await?;
let message = format!(
"{} with status {} for {} {}; response body preview: {}",
message_prefix, status, method, url, body_preview
);
let mut mapped = HttpError::status(status, message)
.with_method(&method)
.with_url(&url)
.with_response_body_preview(body_preview);
if let Some(retry_after) = retry_after {
mapped = mapped.with_retry_after(retry_after);
}
Err(mapped)
}
/// Consumes this response and returns a bounded body preview for status errors.
///
/// # Errors
/// Returns [`HttpErrorKind::Cancelled`](crate::HttpErrorKind::Cancelled)
/// when the request cancellation token fires while preview bytes are being
/// read.
pub(crate) async fn into_error_body_preview(mut self, max_bytes: usize) -> HttpResult<String> {
let limit = max_bytes.max(1);
if let Some(error) = self.cancelled_error_if_needed(
"Request cancelled while reading status error response body preview",
) {
return Err(error);
}
if let Some(body) = self.buffered_body.take() {
let end = body.len().min(limit);
return Ok(Self::render_error_body_preview(
&body[..end],
body.len() > limit,
));
}
let Some(backend) = self.backend.take() else {
return Ok("<empty>".to_string());
};
Self::read_error_body_preview(
backend,
self.runtime.read_timeout,
self.runtime.cancellation_token.clone(),
self.meta.method.clone(),
self.runtime.request_url.clone(),
limit,
)
.await
}
/// Returns full body bytes, consuming backend stream lazily on first call.
pub async fn bytes(&mut self) -> HttpResult<Bytes> {
if let Some(body) = &self.buffered_body {
return Ok(body.clone());
}
let Some(mut backend) = self.backend.take() else {
self.buffered_body = Some(Bytes::new());
return Ok(Bytes::new());
};
let method = self.meta.method.clone();
let url = self.runtime.request_url.clone();
let read_timeout = self.runtime.read_timeout;
let cancellation_token = self.runtime.cancellation_token.clone();
let mut body = bytes::BytesMut::new();
loop {
let next = if let Some(token) = &cancellation_token {
tokio::select! {
_ = token.cancelled() => {
return Err(HttpError::cancelled("Request cancelled while reading response body")
.with_method(&method)
.with_url(&url));
}
item = tokio::time::timeout(read_timeout, backend.chunk()) => item,
}
} else {
tokio::time::timeout(read_timeout, backend.chunk()).await
};
match next {
Ok(Ok(Some(chunk))) => body.extend_from_slice(&chunk),
Ok(Ok(None)) => {
let body = body.freeze();
self.buffered_body = Some(body.clone());
return Ok(body);
}
Ok(Err(error)) => {
return Err(map_reqwest_error(
error,
HttpErrorKind::Decode,
ReqwestErrorPhase::Read,
Some(method),
Some(url),
));
}
Err(_) => {
return Err(HttpError::read_timeout(format!(
"Read timeout after {:?} while reading response body",
read_timeout
))
.with_method(&self.meta.method)
.with_url(&self.runtime.request_url));
}
}
}
}
/// Returns body as stream; if already buffered, returns stream backed by cached bytes.
pub fn stream(&mut self) -> HttpResult<HttpByteStream> {
if let Some(body) = self.buffered_body.as_ref() {
let bytes = body.clone();
return Ok(Box::pin(futures_stream::once(async move { Ok(bytes) })));
}
if let Some(error) = self
.cancelled_error_if_needed("Streaming response cancelled before reading response body")
{
return Err(error);
}
let Some(backend) = self.backend.take() else {
return Ok(Box::pin(futures_stream::empty()));
};
let method = self.meta.method.clone();
let url = self.runtime.request_url.clone();
let read_timeout = self.runtime.read_timeout;
let cancellation_token = self.runtime.cancellation_token.clone();
let mut stream = backend.bytes_stream();
let wrapped = stream! {
loop {
let next = if let Some(token) = &cancellation_token {
tokio::select! {
_ = token.cancelled() => {
yield Err(HttpError::cancelled("Streaming response cancelled while reading body")
.with_method(&method)
.with_url(&url));
break;
}
item = tokio::time::timeout(read_timeout, stream.next()) => item,
}
} else {
tokio::time::timeout(read_timeout, stream.next()).await
};
match next {
Ok(Some(Ok(bytes))) => yield Ok(bytes),
Ok(Some(Err(error))) => {
let mapped = map_reqwest_error(
error,
HttpErrorKind::Transport,
ReqwestErrorPhase::Read,
Some(method.clone()),
Some(url.clone()),
);
yield Err(mapped);
break;
}
Ok(None) => break,
Err(_) => {
let error = HttpError::read_timeout(format!(
"Read timeout after {:?} while streaming response",
read_timeout
))
.with_method(&method)
.with_url(&url);
yield Err(error);
break;
}
}
}
};
Ok(Box::pin(wrapped))
}
/// Interprets response body as UTF-8 text.
pub async fn text(&mut self) -> HttpResult<String> {
let body = self.bytes().await?;
String::from_utf8(body.to_vec()).map_err(|error| {
HttpError::decode(format!(
"Failed to decode response body as UTF-8: {}",
error
))
.with_status(self.meta.status)
.with_url(&self.meta.url)
})
}
/// Deserializes response body as JSON.
pub async fn json<T>(&mut self) -> HttpResult<T>
where
T: DeserializeOwned,
{
let body = self.bytes().await?;
serde_json::from_slice(&body).map_err(|error| {
HttpError::decode(format!("Failed to decode response JSON: {}", error))
.with_status(self.meta.status)
.with_url(&self.meta.url)
})
}
/// Overrides the maximum allowed size (in bytes) for one SSE line on this response.
///
/// Values below 1 are clamped to 1. Returns `self` so callers can chain configuration
/// before consuming the body with [`Self::sse_events`] or [`Self::sse_chunks`]
/// (together with [`Self::sse_json_mode`], [`Self::sse_done_marker_policy`], etc.).
#[inline]
pub fn sse_max_line_bytes(mut self, max_line_bytes: usize) -> Self {
self.options.sse_max_line_bytes = max_line_bytes.max(1);
self
}
/// Overrides the maximum allowed size (in bytes) for one SSE frame on this response.
///
/// Values below 1 are clamped to 1. Returns `self` for chained configuration.
#[inline]
pub fn sse_max_frame_bytes(mut self, max_frame_bytes: usize) -> Self {
self.options.sse_max_frame_bytes = max_frame_bytes.max(1);
self
}
/// Overrides the JSON decoding mode used by [`Self::sse_chunks`] on this response.
#[inline]
pub fn sse_json_mode(mut self, mode: SseJsonMode) -> Self {
self.options.sse_json_mode = mode;
self
}
/// Overrides how [`Self::sse_chunks`] detects end-of-stream from trimmed `data:` payloads.
#[inline]
pub fn sse_done_marker_policy(mut self, policy: DoneMarkerPolicy) -> Self {
self.options.sse_done_marker_policy = policy;
self
}
/// Decodes body stream as SSE events using this response's SSE line/frame byte limits (from
/// client defaults unless overridden via [`Self::sse_max_line_bytes`] /
/// [`Self::sse_max_frame_bytes`]).
pub fn sse_events(mut self) -> SseEventStream {
let max_line_bytes = self.options.sse_max_line_bytes;
let max_frame_bytes = self.options.sse_max_frame_bytes;
match self.stream() {
Ok(stream) => crate::sse::decode_events_from_stream_with_limits(
stream,
max_line_bytes,
max_frame_bytes,
),
Err(error) => Box::pin(futures_stream::once(async move { Err(error) })),
}
}
/// Decodes SSE `data:` lines as JSON chunks using this response's SSE JSON mode, done-marker
/// policy, and line/frame limits (see [`Self::sse_json_mode`], [`Self::sse_done_marker_policy`],
/// [`Self::sse_max_line_bytes`], [`Self::sse_max_frame_bytes`]).
pub fn sse_chunks<T>(mut self) -> SseChunkStream<T>
where
T: DeserializeOwned + Send + 'static,
{
let done_policy = self.options.sse_done_marker_policy.clone();
let mode = self.options.sse_json_mode;
let max_line_bytes = self.options.sse_max_line_bytes;
let max_frame_bytes = self.options.sse_max_frame_bytes;
match self.stream() {
Ok(stream) => crate::sse::decode_json_chunks_from_stream_with_limits(
stream,
done_policy,
mode,
max_line_bytes,
max_frame_bytes,
),
Err(error) => Box::pin(futures_stream::once(async move { Err(error) })),
}
}
/// Returns a buffered body reference for response logging if available.
///
/// # Returns
/// `Some(&Bytes)` when response body has already been buffered.
pub(crate) fn buffered_body_for_logging(&self) -> Option<&Bytes> {
self.buffered_body.as_ref()
}
/// Returns whether logger may safely buffer the full body for logging.
///
/// # Parameters
/// - `body_log_limit`: Configured logging body preview limit in bytes.
///
/// # Returns
/// `true` only when this response is not SSE, has an explicit `Content-Length`,
/// and declared length is within `body_log_limit`.
pub(crate) fn can_buffer_body_for_logging(&self, body_log_limit: usize) -> bool {
if self.backend.is_none() {
return false;
}
if self.is_sse_response() {
return false;
}
self.content_length_hint()
.is_some_and(|content_length| content_length <= body_log_limit as u64)
}
/// Reads bounded preview bytes from a response body for status error messages.
///
/// # Errors
/// Returns [`HttpErrorKind::Cancelled`](crate::HttpErrorKind::Cancelled)
/// when the supplied cancellation token fires while waiting for preview
/// bytes.
async fn read_error_body_preview(
mut response: reqwest::Response,
read_timeout: Duration,
cancellation_token: Option<CancellationToken>,
method: Method,
url: Url,
max_bytes: usize,
) -> HttpResult<String> {
let limit = max_bytes.max(1);
let mut preview = Vec::new();
let mut truncated = false;
loop {
let next = if let Some(token) = cancellation_token.as_ref() {
tokio::select! {
_ = token.cancelled() => {
return Err(HttpError::cancelled(
"Request cancelled while reading status error response body preview",
)
.with_method(&method)
.with_url(&url));
}
item = tokio::time::timeout(read_timeout, response.chunk()) => item,
}
} else {
tokio::time::timeout(read_timeout, response.chunk()).await
};
match next {
Ok(Ok(Some(chunk))) => {
if preview.len() >= limit {
truncated = true;
break;
}
let remaining = limit - preview.len();
if chunk.len() > remaining {
preview.extend_from_slice(&chunk[..remaining]);
truncated = true;
break;
}
preview.extend_from_slice(&chunk);
}
Ok(Ok(None)) => break,
Ok(Err(error)) => {
return Ok(format!(
"<error body unavailable: failed to read response body: {}>",
error
));
}
Err(_) => {
return Ok(format!(
"<error body unavailable: read timeout after {:?}>",
read_timeout
));
}
}
}
Ok(Self::render_error_body_preview(&preview, truncated))
}
/// Returns a cancellation error with response read context when cancelled.
///
/// # Parameters
/// - `message`: Cancellation message to include in the error.
///
/// # Returns
/// `Some(HttpError)` when this response has a cancelled token; otherwise
/// `None`.
fn cancelled_error_if_needed(&self, message: &str) -> Option<HttpError> {
if self
.runtime
.cancellation_token
.as_ref()
.is_some_and(CancellationToken::is_cancelled)
{
Some(
HttpError::cancelled(message.to_string())
.with_method(&self.meta.method)
.with_url(&self.runtime.request_url),
)
} else {
None
}
}
/// Returns `Content-Length` parsed from response headers when present and valid.
fn content_length_hint(&self) -> Option<u64> {
self.meta
.headers
.get(CONTENT_LENGTH)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<u64>().ok())
}
/// Returns whether response content-type is SSE (`text/event-stream`).
fn is_sse_response(&self) -> bool {
self.meta
.headers
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|content_type| {
content_type
.to_ascii_lowercase()
.starts_with("text/event-stream")
})
}
fn render_error_body_preview(bytes: &[u8], truncated: bool) -> String {
if bytes.is_empty() {
return "<empty>".to_string();
}
let suffix = if truncated { "...<truncated>" } else { "" };
match std::str::from_utf8(bytes) {
Ok(text) => format!("{text}{suffix}"),
Err(_) => format!("<binary {} bytes>{suffix}", bytes.len()),
}
}
}