reqwest_streams/lib.rs
1#![allow(unused_parens, clippy::new_without_default)]
2#![forbid(unsafe_code)]
3#![cfg_attr(docsrs, feature(doc_cfg))]
4
5//! HTTP body streaming support for reqwest, in both directions, for different formats:
6//! - JSON array stream format
7//! - JSON Lines (NL/NewLines) format
8//! - CSV stream format
9//! - [Protobuf] len-prefixed stream format
10//! - [Apache Arrow IPC] stream format
11//!
12//! This type of responses are useful when you are reading huge stream of objects from some source (such as database, file, etc)
13//! and want to avoid huge memory allocations to store on the server side.
14//!
15//! # Features
16//!
17//! **Note:** The `default` features do not include any formats.
18//!
19//! - `json`: JSON array and JSON Lines (JSONL) stream formats
20//! - `csv`: CSV stream format
21//! - `protobuf`: [Protobuf] len-prefixed stream format
22//! - `arrow`: [Apache Arrow IPC] stream format
23//! - `tracing`: report progress and errors through [tracing]
24//!
25//! # Example
26//!
27//! ```rust,no_run
28//! use futures::stream::BoxStream as _;
29//! use reqwest_streams::JsonStreamResponse as _;
30//! use serde::Deserialize;
31//!
32//! #[derive(Debug, Clone, Deserialize)]
33//! struct MyTestStructure {
34//! some_test_field: String
35//! }
36//!
37//!#[tokio::main]
38//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
39//!
40//! let _stream = reqwest::get("http://localhost:8080/json-array")
41//! .await?
42//! .json_array_stream::<MyTestStructure>(1024);
43//!
44//! Ok(())
45//! }
46//! ```
47//!
48//! # Streaming uploads
49//!
50//! The same formats work the other way round: give a `POST` or `PUT` a stream of items and it
51//! is encoded into the request body as it is sent, without ever holding the whole thing in
52//! memory.
53//!
54//! ```rust,no_run
55//! use futures::stream;
56//! use reqwest_streams::JsonStreamRequest as _;
57//! use serde::Serialize;
58//!
59//! #[derive(Serialize)]
60//! struct MyTestStructure {
61//! some_test_field: String
62//! }
63//!
64//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
65//! let items = stream::iter(vec![MyTestStructure { some_test_field: "value".into() }]);
66//!
67//! reqwest::Client::new()
68//! .post("http://localhost:8080/ingest")
69//! .json_array_stream_body(items)
70//! .send()
71//! .await?;
72//! # Ok(())
73//! # }
74//! ```
75//!
76//! The `Content-Type` is set from the format. Use [`ReqwestStreamBody`] directly when you need
77//! options, a body for `multipart`, or a request built by hand.
78//!
79//! **Read [`ReqwestStreamBody`]'s caveats before using this in anger.** Streaming a request
80//! body is much less universally supported than streaming a response: the body cannot be
81//! retried, a redirect silently sends an *empty* body, and buffering reverse proxies defeat
82//! the streaming entirely.
83//!
84//! More and complete examples available on the github in the examples directory.
85//!
86//! ## Need server support?
87//! [axum-streams](https://github.com/abdolence/axum-streams-rs) is the other half of the pair,
88//! and covers both directions too. Since its 0.29 it can also *receive* a streamed request
89//! body, so an upload sent with [`JsonStreamRequest`] and friends is decoded on the server by
90//! its `StreamBodyFrom` extractor. Both crates encode and decode through the same
91//! [http-streams-core](https://github.com/abdolence/http-streams-core-rs).
92//!
93//!
94//! # Observing stream errors
95//!
96//! An error that happens mid-stream is yielded as an item, so a consumer that stops at the
97//! first one silently gets a truncated result. Use [`ReqwestStreamOptions::on_error`] to
98//! observe them, or enable the `tracing` feature to have them logged at `ERROR` on the
99//! `reqwest_streams` target.
100//!
101//! # Observing stream progress
102//!
103//! Nothing at the call site can tell you how much of a response actually arrived, because it
104//! is read long after the call returned. With the `tracing` feature every stream reports its
105//! totals once at `INFO` when it ends, on an `http_streams_core::stream` span:
106//!
107//! ```text
108//! INFO http_streams_core::stream{format="json_array" direction="response" side="client" status=200 items=1000 bytes=28001 errors=0 elapsed_ms=11239 outcome="completed"}: Finished streaming an HTTP body
109//! ```
110//!
111//! The `outcome` tells apart the three ways a stream can end: `completed`, `aborted` (the
112//! consumer stopped reading early) and `failed`, which reports at `ERROR` instead. Raise the
113//! filter to `reqwest_streams=debug,http_streams_core=debug` for a progress line about once a
114//! second, and to `http_streams_core=trace` for one per body chunk. Naming both targets keeps
115//! anything this crate logs itself visible alongside the shared accounting.
116//!
117//! The target is `http_streams_core` rather than `reqwest_streams` because the accounting is
118//! shared with `axum-streams`; the `direction` and `side` span fields tell the cases apart.
119//!
120//! The same accounting is available without tracing, for metrics, via
121//! [`ReqwestStreamOptions::on_progress`].
122//!
123//! [tracing]: https://docs.rs/tracing
124//! [Apache Arrow IPC]: https://arrow.apache.org/docs/format/Columnar.html#serialization-and-interprocess-communication-ipc
125//! [Protobuf]: https://protobuf.dev/programming-guides/encoding/
126
127#[macro_use]
128mod macros;
129
130cfg_json! {
131 pub use json_body::JsonStreamRequest;
132 pub use json_stream::JsonStreamResponse;
133 mod json_body;
134 mod json_stream;
135}
136
137cfg_csv! {
138 pub use csv_body::CsvStreamRequest;
139 pub use csv_stream::CsvStreamResponse;
140 mod csv_body;
141 mod csv_stream;
142}
143
144use crate::error::StreamBodyError;
145
146cfg_formats! {
147 pub use stream_body::{ReqwestStreamBody, ReqwestStreamBodyOptions, StreamBodyRequest};
148 mod stream_body;
149}
150
151cfg_formats! {
152 pub use observability::{
153 ReqwestStreamErrorHandler, ReqwestStreamOptions, ReqwestStreamOutcome,
154 ReqwestStreamProgress, ReqwestStreamProgressHandler,
155 };
156 mod observability;
157}
158
159cfg_protobuf! {
160 pub use protobuf_body::ProtobufStreamRequest;
161 pub use protobuf_stream::ProtobufStreamResponse;
162 mod protobuf_body;
163 mod protobuf_stream;
164}
165
166cfg_arrow! {
167 pub use arrow_body::ArrowIpcStreamRequest;
168 pub use arrow_ipc_stream::ArrowIpcStreamResponse;
169 mod arrow_body;
170 mod arrow_ipc_stream;
171}
172
173pub mod error;
174
175/// Alias for the [`Result`] type returned by streaming responses.
176pub type StreamBodyResult<T> = std::result::Result<T, StreamBodyError>;
177
178/// The shared core, re-exported so downstream code can name the types this crate's public API
179/// mentions without adding its own dependency — and so it cannot end up with a second,
180/// incompatible copy of them.
181pub use http_streams_core;
182
183cfg_formats! {
184 // Only the format modules' tests use it, so with no format enabled there is no caller.
185 #[cfg(test)]
186 mod test_client;
187}