vakya 0.1.0-alpha.1

Completion-native HTTP building blocks for the Karmaio runtime
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
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
use super::{Body, Frame, SizeHint, TrailerHint};
use karmaio::buf::IoBuf;

/// One of two statically dispatched body types.
///
/// The variants may have different data and error types; their outputs use
/// `Either` too. This adds no allocation or dynamic dispatch. Recovered data
/// returns to its originating variant, or is dropped if that variant has been
/// replaced while the frame was outstanding.
#[derive(Clone, Copy, Debug)]
pub enum Either<A, B> {
    /// The first body variant.
    Left(A),
    /// The second body variant.
    Right(B),
}

impl<A> Either<A, A> {
    /// Removes the `Either` wrapper when both variants have the same type.
    #[inline]
    pub fn into_inner(self) -> A {
        match self {
            Self::Left(body) | Self::Right(body) => body,
        }
    }
}

impl<A, B> Body for Either<A, B>
where
    A: Body,
    B: Body,
{
    type Data = Either<A::Data, B::Data>;
    type Error = Either<A::Error, B::Error>;

    async fn next_frame(&mut self) -> Result<Option<Frame<Self::Data>>, Self::Error> {
        match self {
            Self::Left(body) => body
                .next_frame()
                .await
                .map(|frame| map_frame(frame, Either::Left))
                .map_err(Either::Left),
            Self::Right(body) => body
                .next_frame()
                .await
                .map(|frame| map_frame(frame, Either::Right))
                .map_err(Either::Right),
        }
    }

    #[inline]
    fn size_hint(&self) -> SizeHint {
        match self {
            Self::Left(body) => body.size_hint(),
            Self::Right(body) => body.size_hint(),
        }
    }

    #[inline]
    fn trailer_hint(&self) -> TrailerHint {
        match self {
            Self::Left(body) => body.trailer_hint(),
            Self::Right(body) => body.trailer_hint(),
        }
    }

    #[inline]
    fn is_end_stream(&self) -> bool {
        match self {
            Self::Left(body) => body.is_end_stream(),
            Self::Right(body) => body.is_end_stream(),
        }
    }

    #[inline]
    fn recycle(&mut self, data: Self::Data) {
        match (self, data) {
            (Self::Left(body), Either::Left(data)) => body.recycle(data),
            (Self::Right(body), Either::Right(data)) => body.recycle(data),
            (_, data) => drop(data),
        }
    }
}

fn map_frame<A, B>(frame: Option<Frame<A>>, map: impl FnOnce(A) -> B) -> Option<Frame<B>> {
    frame.map(|frame| frame.map_data(map))
}

impl<A: IoBuf, B: IoBuf> IoBuf for Either<A, B> {
    #[inline]
    fn as_init(&self) -> &[u8] {
        match self {
            Self::Left(data) => data.as_init(),
            Self::Right(data) => data.as_init(),
        }
    }
}

impl<A: std::fmt::Display, B: std::fmt::Display> std::fmt::Display for Either<A, B> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Left(error) => error.fmt(formatter),
            Self::Right(error) => error.fmt(formatter),
        }
    }
}

impl<A: std::error::Error + 'static, B: std::error::Error + 'static> std::error::Error for Either<A, B> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(match self {
            Self::Left(error) => error,
            Self::Right(error) => error,
        })
    }
}

/// A body that transforms errors from an inner body.
///
/// Frames and recovered data pass through unchanged. The mapping function runs
/// only when the inner body returns an error.
#[derive(Clone, Copy, Debug)]
pub struct MapError<B, F> {
    body: B,
    map: F,
}

impl<B, F> MapError<B, F> {
    /// Creates an error-mapping body wrapper.
    #[inline]
    pub const fn new(body: B, map: F) -> Self {
        Self { body, map }
    }

    /// Returns a shared reference to the inner body.
    #[inline]
    pub const fn get_ref(&self) -> &B {
        &self.body
    }

    /// Returns an exclusive reference to the inner body.
    #[inline]
    pub const fn get_mut(&mut self) -> &mut B {
        &mut self.body
    }

    /// Removes this wrapper and returns the inner body.
    #[inline]
    pub fn into_inner(self) -> B {
        self.body
    }
}

impl<B, F, E> Body for MapError<B, F>
where
    B: Body,
    F: FnMut(B::Error) -> E,
{
    type Data = B::Data;
    type Error = E;

    async fn next_frame(&mut self) -> Result<Option<Frame<Self::Data>>, Self::Error> {
        self.body.next_frame().await.map_err(&mut self.map)
    }

    #[inline]
    fn size_hint(&self) -> SizeHint {
        self.body.size_hint()
    }

    #[inline]
    fn trailer_hint(&self) -> TrailerHint {
        self.body.trailer_hint()
    }

    #[inline]
    fn is_end_stream(&self) -> bool {
        self.body.is_end_stream()
    }

    #[inline]
    fn recycle(&mut self, data: Self::Data) {
        self.body.recycle(data);
    }
}

/// A body that observes frames without changing payloads or metadata.
///
/// The observer is called once for each yielded frame. Recycling is forwarded
/// to the original producer. Errors pass through without calling the observer.
#[derive(Debug)]
pub struct InspectFrame<B, F> {
    body: B,
    inspect: F,
}

impl<B, F> InspectFrame<B, F> {
    /// Wraps a body with a synchronous frame observer.
    #[inline]
    pub const fn new(body: B, inspect: F) -> Self {
        Self { body, inspect }
    }
}

impl<B: Body, F: FnMut(&Frame<B::Data>)> Body for InspectFrame<B, F> {
    type Data = B::Data;
    type Error = B::Error;

    async fn next_frame(&mut self) -> Result<Option<Frame<Self::Data>>, Self::Error> {
        let frame = self.body.next_frame().await?;
        if let Some(frame) = &frame {
            (self.inspect)(frame);
        }
        Ok(frame)
    }

    #[inline]
    fn size_hint(&self) -> SizeHint {
        self.body.size_hint()
    }
    #[inline]
    fn trailer_hint(&self) -> TrailerHint {
        self.body.trailer_hint()
    }
    #[inline]
    fn is_end_stream(&self) -> bool {
        self.body.is_end_stream()
    }
    #[inline]
    fn recycle(&mut self, data: Self::Data) {
        self.body.recycle(data);
    }
}

/// A body that transforms each frame and invalidates its original metadata.
///
/// The mapping function must preserve valid data/trailer ordering. Size is
/// unknown and trailers are possible until termination. Recovered output is
/// dropped: arbitrary transformations do not retain a route to the original
/// producer's buffer. Use error mapping or inspection to preserve recycling.
#[derive(Debug)]
pub struct MapFrame<B, F> {
    body: B,
    map: F,
    done: bool,
}

impl<B, F> MapFrame<B, F> {
    /// Wraps a body with a synchronous frame transformation.
    #[inline]
    pub const fn new(body: B, map: F) -> Self {
        Self { body, map, done: false }
    }
}

impl<B, F, D> Body for MapFrame<B, F>
where
    B: Body,
    F: FnMut(Frame<B::Data>) -> Frame<D>,
    D: IoBuf,
{
    type Data = D;
    type Error = B::Error;

    async fn next_frame(&mut self) -> Result<Option<Frame<D>>, Self::Error> {
        if self.done {
            return Ok(None);
        }
        match self.body.next_frame().await {
            Ok(Some(frame)) => Ok(Some((self.map)(frame))),
            result => {
                self.done = true;
                result.map(|_| None)
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> SizeHint {
        if self.done {
            SizeHint::with_exact(0)
        } else {
            SizeHint::new()
        }
    }
    #[inline]
    fn trailer_hint(&self) -> TrailerHint {
        if self.done {
            TrailerHint::None
        } else {
            TrailerHint::MayHave
        }
    }
    #[inline]
    fn is_end_stream(&self) -> bool {
        self.done
    }
}

/// A body that appends supplied fields to its trailing headers.
///
/// Existing trailer values are preserved, including duplicate names. If the
/// source has no trailers, one frame is emitted after successful completion.
/// Producer errors are preserved, even after an existing trailers frame. On
/// error, fields not yet attached are discarded. Payload metadata and recycling
/// are forwarded; pending trailers prevent an early end-of-stream hint.
#[derive(Debug)]
pub struct WithTrailers<B> {
    body: B,
    pending: Option<http::HeaderMap>,
    done: bool,
}

impl<B> WithTrailers<B> {
    /// Attaches fields without copying their values or allocating another map.
    ///
    /// Merging into existing trailers can grow that map. HTTP execution is
    /// responsible for validating trailer fields and wire-size limits.
    #[inline]
    pub fn new(body: B, trailers: http::HeaderMap) -> Self {
        Self {
            body,
            pending: Some(trailers),
            done: false,
        }
    }
}

impl<B: Body> Body for WithTrailers<B> {
    type Data = B::Data;
    type Error = B::Error;

    async fn next_frame(&mut self) -> Result<Option<Frame<Self::Data>>, Self::Error> {
        if self.done {
            return Ok(None);
        }
        match self.body.next_frame().await {
            Ok(Some(mut frame)) => {
                if let super::frame::Kind::Trailers(fields) = &mut frame.kind
                    && let Some(pending) = self.pending.take()
                {
                    let mut name = None;
                    for (next_name, value) in pending {
                        if next_name.is_some() {
                            name = next_name;
                        }
                        // HeaderMap's owned iterator uses None only for
                        // subsequent values of the preceding field name.
                        fields.append(name.as_ref().expect("trailer value has a field name"), value);
                    }
                }
                Ok(Some(frame))
            }
            Ok(None) => {
                self.done = true;
                Ok(self.pending.take().map(Frame::trailers))
            }
            Err(error) => {
                self.done = true;
                self.pending = None;
                Err(error)
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> SizeHint {
        if self.done {
            SizeHint::with_exact(0)
        } else {
            self.body.size_hint()
        }
    }
    #[inline]
    fn trailer_hint(&self) -> TrailerHint {
        if self.done {
            TrailerHint::None
        } else if self.pending.is_some() {
            TrailerHint::MayHave
        } else {
            self.body.trailer_hint()
        }
    }
    #[inline]
    fn is_end_stream(&self) -> bool {
        self.done
    }
    #[inline]
    fn recycle(&mut self, data: Self::Data) {
        self.body.recycle(data);
    }
}

#[cfg(test)]
mod tests {
    use super::{Body, Either, Frame, MapError, SizeHint};
    use crate::body::{Empty, Full};
    use karmaio::buf::IoBuf;
    use std::{
        cell::Cell,
        future::Future,
        pin::pin,
        rc::Rc,
        task::{Context, Poll, Waker},
    };

    fn complete<F>(future: F) -> F::Output
    where
        F: Future,
    {
        let mut future = pin!(future);
        let mut context = Context::from_waker(Waker::noop());

        match future.as_mut().poll(&mut context) {
            Poll::Ready(output) => output,
            Poll::Pending => panic!("test body unexpectedly returned pending"),
        }
    }

    struct TestBody {
        state: TestState,
        length: SizeHint,
        recycled: Rc<Cell<usize>>,
    }

    enum TestState {
        Data(Vec<u8>),
        Error(&'static str),
        Done,
    }

    impl TestBody {
        fn data(data: &'static [u8], recycled: Rc<Cell<usize>>) -> Self {
            Self {
                state: TestState::Data(data.to_vec()),
                length: SizeHint::with_exact(data.len() as u64),
                recycled,
            }
        }

        fn error(error: &'static str) -> Self {
            Self {
                state: TestState::Error(error),
                length: SizeHint::new(),
                recycled: Rc::new(Cell::new(0)),
            }
        }
    }

    impl Body for TestBody {
        type Data = Vec<u8>;
        type Error = &'static str;

        async fn next_frame(&mut self) -> Result<Option<Frame<Self::Data>>, Self::Error> {
            self.length = SizeHint::with_exact(0);
            match std::mem::replace(&mut self.state, TestState::Done) {
                TestState::Data(data) => Ok(Some(Frame::data(data))),
                TestState::Error(error) => Err(error),
                TestState::Done => Ok(None),
            }
        }

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

        fn recycle(&mut self, data: Self::Data) {
            assert!(!data.as_init().is_empty());
            self.recycled.set(self.recycled.get() + 1);
        }
    }

    struct OtherBody(TestBody);

    impl Body for OtherBody {
        type Data = Vec<u8>;
        type Error = &'static str;

        async fn next_frame(&mut self) -> Result<Option<Frame<Self::Data>>, Self::Error> {
            self.0.next_frame().await
        }

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

        fn recycle(&mut self, data: Self::Data) {
            self.0.recycle(data);
        }
    }

    #[test]
    fn either_supports_different_buffer_and_error_types() {
        let recycled = Rc::new(Cell::new(0));
        let mut left: Either<TestBody, Full<bytes::Bytes>> =
            Either::Left(TestBody::data(b"left", Rc::clone(&recycled)));
        let data = complete(left.next_frame())
            .unwrap()
            .expect("missing frame")
            .into_data()
            .expect("missing data");
        assert_eq!(data.as_init(), b"left");
        left.recycle(data);
        assert_eq!(recycled.get(), 1);
        let mut right: Either<TestBody, Full<bytes::Bytes>> =
            Either::Right(Full::new(bytes::Bytes::from_static(b"right")));
        let data = complete(right.next_frame())
            .unwrap()
            .expect("missing frame")
            .into_data()
            .expect("missing data");
        assert_eq!(data.as_init(), b"right");
        right.recycle(data);
        let mut failed: Either<TestBody, Empty> = Either::Left(TestBody::error("failure"));
        assert!(matches!(complete(failed.next_frame()), Err(Either::Left("failure"))));
    }

    #[test]
    fn either_left_forwards_frames_length_and_recycling() {
        let recycled = Rc::new(Cell::new(0));
        let mut body: Either<TestBody, OtherBody> = Either::Left(TestBody::data(b"left", Rc::clone(&recycled)));

        assert_eq!(body.size_hint(), SizeHint::with_exact(4));
        let data = complete(body.next_frame())
            .unwrap()
            .expect("missing frame")
            .into_data()
            .expect("missing data");
        body.recycle(data);
        assert_eq!(recycled.get(), 1);
    }

    #[test]
    fn either_right_forwards_frames_length_and_recycling() {
        let recycled = Rc::new(Cell::new(0));
        let mut body: Either<TestBody, OtherBody> =
            Either::Right(OtherBody(TestBody::data(b"right", Rc::clone(&recycled))));

        assert_eq!(body.size_hint(), SizeHint::with_exact(5));
        let data = complete(body.next_frame())
            .unwrap()
            .expect("missing frame")
            .into_data()
            .expect("missing data");
        body.recycle(data);
        assert_eq!(recycled.get(), 1);
    }

    #[test]
    fn map_error_changes_only_the_error() {
        let mut body = MapError::new(TestBody::error("body failed"), |error: &'static str| error.len());

        assert_eq!(body.size_hint(), SizeHint::new());
        assert!(matches!(
            complete(body.next_frame()),
            Err(length) if length == "body failed".len()
        ));
    }

    #[test]
    fn map_error_forwards_recycling() {
        let recycled = Rc::new(Cell::new(0));
        let mut body = MapError::new(TestBody::data(b"data", Rc::clone(&recycled)), |error: &'static str| {
            error
        });

        let data = complete(body.next_frame())
            .unwrap()
            .expect("missing frame")
            .into_data()
            .expect("missing data");
        body.recycle(data);
        assert_eq!(recycled.get(), 1);
    }

    #[test]
    fn composition_preserves_metadata_and_empty_data_is_not_end_of_stream() {
        use crate::body::{Empty, Full, TrailerHint};

        let body: Either<Full<Vec<u8>>, Empty> = Either::Left(Full::new(Vec::new()));
        let mut mapped = MapError::new(body, |error| error);
        let mut borrowed = &mut mapped;
        assert_eq!(borrowed.size_hint().exact(), Some(0));
        assert_eq!(borrowed.trailer_hint(), TrailerHint::None);
        assert!(!borrowed.is_end_stream());
        let frame = complete(Body::next_frame(&mut borrowed)).unwrap().unwrap();
        let data = frame.into_data().unwrap();
        assert!(data.as_init().is_empty());
        borrowed.recycle(data);
        assert!(borrowed.is_end_stream());
        assert!(complete(borrowed.next_frame()).unwrap().is_none());
    }
}