tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
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
use std::{
    fmt,
    pin::Pin,
    task::{Context, Poll},
};

use bytes::Bytes;
use futures_util::Stream;
use http_body::Body as _;
use http_body::{Frame, SizeHint};
use serde::de::DeserializeOwned;

mod json;
mod sse;

pub(crate) use json::{
    CONTENT_TYPE as NDJSON_CONTENT_TYPE, DOCUMENT_CONTENT_TYPE as JSON_CONTENT_TYPE,
    encode as ndjson_body, encode_array as json_array_body,
};
pub(crate) use sse::{CONTENT_TYPE as SSE_CONTENT_TYPE, encode as sse_body};

use crate::{Body, Error, Event, Result};

const TERMINAL_DATA: &str = "[DONE]";

enum Item {
    Json(Bytes),
    Event(Event),
}

struct Decoder {
    framing: Framing,
}

enum Framing {
    Json(json::Document),
    Ndjson(json::Lines),
    Sse(sse::Decoder),
}

impl Decoder {
    fn json(limit: usize) -> Self {
        Self {
            framing: Framing::Json(json::Document::new(limit)),
        }
    }

    fn ndjson(limit: usize) -> Self {
        Self {
            framing: Framing::Ndjson(json::Lines::new(limit)),
        }
    }

    fn sse(limit: usize) -> Self {
        Self {
            framing: Framing::Sse(sse::Decoder::new(limit)),
        }
    }

    fn push_one(&mut self, bytes: &[u8], offset: &mut usize) -> Result<Option<Item>> {
        match &mut self.framing {
            Framing::Json(decoder) => decoder
                .push_one(bytes, offset)
                .map(|item| item.map(Item::Json)),
            Framing::Ndjson(decoder) => decoder
                .push_one(bytes, offset)
                .map(|item| item.map(Item::Json)),
            Framing::Sse(decoder) => decoder
                .push_one(bytes, offset)
                .map(|item| item.map(Item::Event)),
        }
    }

    fn finish(&mut self) -> Result<Option<Item>> {
        match &mut self.framing {
            Framing::Json(decoder) => Ok(decoder.finish().map(Item::Json)),
            Framing::Ndjson(decoder) => decoder.finish().map(|item| item.map(Item::Json)),
            Framing::Sse(decoder) => decoder.finish().map(|item| item.map(Item::Event)),
        }
    }
}

/// A one-shot response body consumed as backpressured byte chunks.
///
/// This type also implements [`http_body::Body`] when callers need trailers.
/// Use [`ResponseStream::json`], [`ResponseStream::ndjson`], or
/// [`ResponseStream::sse`] to select the body's framing.
pub struct ResponseStream {
    body: Body,
    item_limit: usize,
}

impl ResponseStream {
    pub(crate) fn new(body: Body, item_limit: usize) -> Self {
        Self { body, item_limit }
    }

    /// Decodes one complete JSON document from the stream.
    #[must_use]
    pub fn json<T>(self) -> JsonStream<T>
    where
        T: DeserializeOwned,
    {
        JsonStream::new(self.body, Decoder::json(self.item_limit), decode_json)
    }

    /// Decodes newline-delimited JSON records as they arrive.
    #[must_use]
    pub fn ndjson<T>(self) -> JsonStream<T>
    where
        T: DeserializeOwned,
    {
        JsonStream::new(self.body, Decoder::ndjson(self.item_limit), decode_json)
    }

    /// Decodes a server-sent event stream.
    #[must_use]
    pub fn sse(self) -> EventStream {
        EventStream {
            inner: FramedStream::new(self.body, Decoder::sse(self.item_limit), keep_event),
        }
    }

    /// Consumes this stream and returns the underlying Tez body.
    #[must_use]
    pub fn into_body(self) -> Body {
        self.body
    }

    /// Reads the next non-empty data chunk.
    pub async fn next(&mut self) -> Result<Option<Bytes>> {
        std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context))
            .await
            .transpose()
    }
}

impl Stream for ResponseStream {
    type Item = Result<Bytes>;

    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            match Pin::new(&mut self.body).poll_frame(context) {
                Poll::Ready(Some(Ok(frame))) => {
                    if let Ok(data) = frame.into_data()
                        && !data.is_empty()
                    {
                        return Poll::Ready(Some(Ok(data)));
                    }
                }
                Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))),
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

impl http_body::Body for ResponseStream {
    type Data = Bytes;
    type Error = Error;

    fn poll_frame(
        self: Pin<&mut Self>,
        context: &mut Context<'_>,
    ) -> Poll<Option<std::result::Result<Frame<Self::Data>, Self::Error>>> {
        Pin::new(&mut self.get_mut().body).poll_frame(context)
    }

    fn is_end_stream(&self) -> bool {
        self.body.is_end_stream()
    }

    fn size_hint(&self) -> SizeHint {
        self.body.size_hint()
    }
}

impl fmt::Debug for ResponseStream {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ResponseStream")
            .field("item_limit", &self.item_limit)
            .finish_non_exhaustive()
    }
}

/// A one-shot stream of server-sent events.
///
/// Call [`EventStream::json`] when each event's data is JSON. Raw events retain
/// their name, identifier, and retry delay.
pub struct EventStream {
    inner: FramedStream<Event>,
}

impl EventStream {
    /// Deserializes each event's data as JSON.
    ///
    /// Every event is decoded. Use [`EventStream::json_until_done`] for APIs
    /// that use `[DONE]` as a non-JSON terminal sentinel.
    #[must_use]
    pub fn json<T>(self) -> JsonStream<T>
    where
        T: DeserializeOwned,
    {
        JsonStream::new_from(self.inner, decode_event_json)
    }

    /// Deserializes event data as JSON until a `[DONE]` sentinel arrives.
    #[must_use]
    pub fn json_until_done<T>(self) -> JsonStream<T>
    where
        T: DeserializeOwned,
    {
        JsonStream::new_from(self.inner, decode_event_json_until_done)
    }

    /// Reads the next server-sent event.
    pub async fn next(&mut self) -> Result<Option<Event>> {
        std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context))
            .await
            .transpose()
    }
}

impl Stream for EventStream {
    type Item = Result<Event>;

    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.inner).poll_next(context)
    }
}

impl fmt::Debug for EventStream {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("EventStream")
            .finish_non_exhaustive()
    }
}

/// A one-shot stream of JSON values.
///
/// Values may come from one JSON document, NDJSON records, or JSON data fields
/// in a server-sent event stream.
pub struct JsonStream<T> {
    inner: FramedStream<T>,
}

impl<T> JsonStream<T> {
    fn new(body: Body, decoder: Decoder, decode: fn(Item) -> Decoded<T>) -> Self {
        Self {
            inner: FramedStream::new(body, decoder, decode),
        }
    }

    fn new_from<U>(inner: FramedStream<U>, decode: fn(Item) -> Decoded<T>) -> Self {
        Self {
            inner: FramedStream {
                body: inner.body,
                decoder: inner.decoder,
                pending_data: inner.pending_data,
                data_offset: inner.data_offset,
                decode,
                finished: inner.finished,
            },
        }
    }

    /// Reads the next JSON value.
    pub async fn next(&mut self) -> Result<Option<T>> {
        std::future::poll_fn(|context| Pin::new(&mut *self).poll_next(context))
            .await
            .transpose()
    }
}

impl<T> Stream for JsonStream<T> {
    type Item = Result<T>;

    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.inner).poll_next(context)
    }
}

impl<T> fmt::Debug for JsonStream<T> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_struct("JsonStream").finish_non_exhaustive()
    }
}

struct FramedStream<T> {
    body: Body,
    decoder: Decoder,
    pending_data: Option<Bytes>,
    data_offset: usize,
    decode: fn(Item) -> Decoded<T>,
    finished: bool,
}

enum Decoded<T> {
    Item(T),
    Finished,
    Error(Error),
}

impl<T> FramedStream<T> {
    fn new(body: Body, decoder: Decoder, decode: fn(Item) -> Decoded<T>) -> Self {
        Self {
            body,
            decoder,
            pending_data: None,
            data_offset: 0,
            decode,
            finished: false,
        }
    }

    fn poll_item(&mut self, context: &mut Context<'_>) -> Poll<Option<Result<Item>>> {
        loop {
            if let Some(data) = self.pending_data.take() {
                let mut offset = self.data_offset;
                let next_item = self.decoder.push_one(&data, &mut offset);

                if offset < data.len() {
                    self.pending_data = Some(data);
                    self.data_offset = offset;
                } else {
                    self.data_offset = 0;
                }

                match next_item {
                    Ok(Some(item)) => return Poll::Ready(Some(Ok(item))),
                    Ok(None) => {}
                    Err(error) => {
                        self.finished = true;
                        self.pending_data = None;
                        return Poll::Ready(Some(Err(error)));
                    }
                }
            }

            if self.finished {
                return Poll::Ready(None);
            }

            match Pin::new(&mut self.body).poll_frame(context) {
                Poll::Ready(Some(Ok(frame))) => {
                    if let Ok(data) = frame.into_data() {
                        self.pending_data = Some(data);
                        self.data_offset = 0;
                    }
                }
                Poll::Ready(Some(Err(error))) => {
                    self.finished = true;
                    return Poll::Ready(Some(Err(error)));
                }
                Poll::Ready(None) => {
                    self.finished = true;
                    return match self.decoder.finish() {
                        Ok(Some(item)) => Poll::Ready(Some(Ok(item))),
                        Ok(None) => Poll::Ready(None),
                        Err(error) => Poll::Ready(Some(Err(error))),
                    };
                }
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

impl<T> Stream for FramedStream<T> {
    type Item = Result<T>;

    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if self.finished {
            return Poll::Ready(None);
        }

        match self.poll_item(context) {
            Poll::Ready(Some(Ok(item))) => match (self.decode)(item) {
                Decoded::Item(item) => Poll::Ready(Some(Ok(item))),
                Decoded::Finished => {
                    self.finished = true;
                    Poll::Ready(None)
                }
                Decoded::Error(error) => {
                    self.finished = true;
                    Poll::Ready(Some(Err(error)))
                }
            },
            Poll::Ready(Some(Err(error))) => {
                self.finished = true;
                Poll::Ready(Some(Err(error)))
            }
            Poll::Ready(None) => {
                self.finished = true;
                Poll::Ready(None)
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

fn keep_event(item: Item) -> Decoded<Event> {
    match item {
        Item::Event(event) => Decoded::Item(event),
        Item::Json(_) => Decoded::Error(Error::decode("stream framing produced an invalid item")),
    }
}

fn decode_json<T>(item: Item) -> Decoded<T>
where
    T: DeserializeOwned,
{
    let Item::Json(data) = item else {
        return Decoded::Error(Error::decode("stream framing produced an invalid item"));
    };
    match crate::content::decode_json(&data, "stream JSON could not be decoded") {
        Ok(value) => Decoded::Item(value),
        Err(error) => Decoded::Error(error),
    }
}

fn decode_event_json<T>(item: Item) -> Decoded<T>
where
    T: DeserializeOwned,
{
    let Item::Event(event) = item else {
        return Decoded::Error(Error::decode("stream framing produced an invalid item"));
    };
    match crate::content::decode_json(event.data().as_bytes(), "event JSON could not be decoded") {
        Ok(value) => Decoded::Item(value),
        Err(error) => Decoded::Error(error),
    }
}

fn decode_event_json_until_done<T>(item: Item) -> Decoded<T>
where
    T: DeserializeOwned,
{
    if matches!(&item, Item::Event(event) if event.data() == TERMINAL_DATA) {
        return Decoded::Finished;
    }
    decode_event_json(item)
}