vibeio-http 0.4.0

High-performance HTTP server primitives for the `vibeio` 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
use super::*;

enum ServicePoll<ResB> {
    /// The stream task is done (response fully handed over).
    Done,
    /// Waiting on a response, early hints, or peer reset.
    Pending,
    /// The final response is ready to be piped to the connection.
    Body(ResB),
}

pin_project! {
    /// Drives one stream task: runs the user's `request_fn`, forwards
    /// interim and final responses to the connection, and pipes the
    /// response body as chunks.
    ///
    /// The task stops when the response is fully handed over, when the
    /// peer resets the stream, or when the connection goes away. On
    /// every exit path it first enqueues [`StreamMsg::Closed`], so the
    /// connection can drop its per-stream state.
    pub(crate) struct StreamDriver<Fut, ResB> {
        msg_tx: kanal::AsyncSender<StreamMsg>,
        reset_rx: kanal::AsyncReceiver<u32>,
        // Pokes the connection's drive loop when a message lands in
        // the channel, so responses are delivered even while the peer
        // idles.
        wake_tx: kanal::AsyncSender<()>,
        #[pin]
        msg_tx_fut: Option<kanal::SendFuture<'static, StreamMsg>>,
        queue: VecDeque<StreamMsg>,
        // Set once the terminal StreamMsg::Closed lands in the queue;
        // the task only drains from then on.
        done: bool,
        #[pin]
        state: StreamDriverState<Fut, ResB>,
    }
}

pin_project! {
    #[project = StreamDriverProj]
    enum StreamDriverState<Fut, ResB> {
        Service {
            #[pin]
            response_fut: Fut,
            #[pin]
            early_hints_rx: EarlyHintsReceiver,
            response_done: bool,
            body: Option<ResB>,
            send_continue: bool,
            send_continue_body: Option<Arc<AtomicBool>>,
            continue_sent: bool,
            early_hints_open: bool,
        },
        Body {
            #[pin]
            body: ResB,
            body_end: bool,
        },
    }
}

impl<Fut, ResB> StreamDriver<Fut, ResB> {
    #[allow(clippy::too_many_arguments)]
    #[inline]
    pub(crate) fn new(
        response_fut: Fut,
        reset_rx: kanal::AsyncReceiver<u32>,
        msg_tx: kanal::AsyncSender<StreamMsg>,
        wake_tx: kanal::AsyncSender<()>,
        early_hints_rx: EarlyHintsReceiver,
        send_continue: bool,
        send_continue_body: Option<Arc<AtomicBool>>,
    ) -> Self {
        Self {
            msg_tx,
            reset_rx,
            wake_tx,
            msg_tx_fut: None,
            queue: VecDeque::with_capacity(8),
            done: false,
            state: StreamDriverState::Service {
                response_fut,
                early_hints_rx,
                response_done: false,
                body: None,
                send_continue,
                send_continue_body,
                continue_sent: false,
                early_hints_open: true,
            },
        }
    }
}

impl<Fut, ResB, ResBE, ResE> Future for StreamDriver<Fut, ResB>
where
    Fut: Future<Output = Result<Response<ResB>, ResE>>,
    ResB: Body<Data = Bytes, Error = ResBE> + Unpin,
    ResBE: std::error::Error + 'static,
    ResE: std::error::Error + 'static,
{
    type Output = ();

    #[inline]
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut this = self.project();
        loop {
            if let Some(msg_tx_fut) = this.msg_tx_fut.as_mut().as_pin_mut() {
                match msg_tx_fut.poll(cx) {
                    Poll::Ready(Ok(_)) => {
                        // SAFETY: Pin is re-borrowed here
                        let uckm = unsafe { this.msg_tx_fut.as_mut().get_unchecked_mut() };
                        uckm.take();
                        let _ = this.wake_tx.try_send(());
                    }
                    Poll::Ready(Err(_)) => {
                        // SAFETY: Pin is re-borrowed here
                        let uckm = unsafe { this.msg_tx_fut.as_mut().get_unchecked_mut() };
                        uckm.take();
                        return Poll::Ready(());
                    }
                    Poll::Pending => return Poll::Pending,
                }
            }
            // Drain the outbound queue first: the states are only
            // driven again once the queue is empty, so a completed
            // response or body frame is never re-read.
            if let Some(msg) = this.queue.pop_front() {
                let msg_tx_fut = this.msg_tx.send(msg);
                // SAFETY: msg_tx_fut lives as long as msg_tx after storing in struct
                let msg_tx_fut = unsafe {
                    std::mem::transmute::<
                        kanal::SendFuture<'_, StreamMsg>,
                        kanal::SendFuture<'static, StreamMsg>,
                    >(msg_tx_fut)
                };
                // SAFETY: Pin is re-borrowed here
                let uckm = unsafe { this.msg_tx_fut.as_mut().get_unchecked_mut() };
                *uckm = Some(msg_tx_fut);
                continue;
            }
            if *this.done {
                return Poll::Ready(());
            }
            match this.state.as_mut().project() {
                StreamDriverProj::Service {
                    response_fut,
                    early_hints_rx,
                    response_done,
                    body,
                    send_continue,
                    send_continue_body,
                    continue_sent,
                    early_hints_open,
                } => {
                    match Self::poll_service(
                        this.msg_tx,
                        this.wake_tx,
                        this.msg_tx_fut.as_mut(),
                        this.reset_rx,
                        response_fut,
                        early_hints_rx,
                        response_done,
                        body,
                        send_continue,
                        send_continue_body,
                        continue_sent,
                        early_hints_open,
                        cx,
                    ) {
                        ServicePoll::Done => {}
                        ServicePoll::Pending => return Poll::Pending,
                        ServicePoll::Body(body) => {
                            this.state.set(StreamDriverState::Body {
                                body,
                                body_end: false,
                            });
                            continue;
                        }
                    }
                }
                StreamDriverProj::Body { body, body_end } => {
                    match Self::poll_body(
                        this.msg_tx,
                        this.msg_tx_fut.as_mut(),
                        this.reset_rx,
                        body,
                        body_end,
                        cx,
                    ) {
                        Poll::Ready(()) => {}
                        Poll::Pending => return Poll::Pending,
                    }
                }
            }
            // Terminal message: the outer drain loop delivers it before
            // the task exits, so the connection always sees Closed.
            this.queue.push_back(StreamMsg::Closed);
            *this.done = true;
            continue;
        }
    }
}

impl<Fut, ResB, ResBE, ResE> StreamDriver<Fut, ResB>
where
    Fut: Future<Output = Result<Response<ResB>, ResE>>,
    ResB: Body<Data = Bytes, Error = ResBE> + Unpin,
    ResBE: std::error::Error + 'static,
    ResE: std::error::Error + 'static,
{
    /// Polls the service state: the response future, peer resets, the
    /// `100 Continue` trigger and early hints. Returns only with the
    /// outbound channel drained.
    #[allow(clippy::too_many_arguments)]
    #[inline]
    fn poll_service(
        msg_tx: &mut kanal::AsyncSender<StreamMsg>,
        wake_tx: &kanal::AsyncSender<()>,
        mut msg_tx_fut: Pin<&mut Option<kanal::SendFuture<'static, StreamMsg>>>,
        reset_rx: &mut kanal::AsyncReceiver<u32>,
        mut response_fut: Pin<&mut Fut>,
        mut early_hints_rx: Pin<&mut EarlyHintsReceiver>,
        response_done: &mut bool,
        body: &mut Option<ResB>,
        send_continue: &bool,
        send_continue_body: &Option<Arc<AtomicBool>>,
        continue_sent: &mut bool,
        early_hints_open: &mut bool,
        cx: &mut Context<'_>,
    ) -> ServicePoll<ResB> {
        loop {
            if *response_done {
                match body.take() {
                    Some(body) => return ServicePoll::Body(body),
                    None => return ServicePoll::Done,
                }
            }
            if let Poll::Ready(result) = response_fut.as_mut().poll(cx) {
                let Ok(response) = result else {
                    // Handler error: the stream ends without a reply.
                    *response_done = true;
                    continue;
                };
                if *send_continue && !*continue_sent {
                    if !response.status().is_client_error() && !response.status().is_server_error()
                    {
                        let mut interim = Response::new(());
                        *interim.status_mut() = StatusCode::CONTINUE;
                        let (parts, _) = interim.into_parts();

                        match Self::send(
                            msg_tx,
                            msg_tx_fut.as_mut(),
                            wake_tx,
                            StreamMsg::Informational { parts },
                            cx,
                        ) {
                            Poll::Ready(()) => {}
                            Poll::Pending => return ServicePoll::Pending,
                        }
                    }
                    *continue_sent = true;
                }
                let response_is_end_stream = response.body().is_end_stream();
                let (parts, response_body) = response.into_parts();

                match Self::send(
                    msg_tx,
                    msg_tx_fut.as_mut(),
                    wake_tx,
                    StreamMsg::Headers {
                        parts,
                        end_stream: response_is_end_stream,
                    },
                    cx,
                ) {
                    Poll::Ready(()) => {}
                    Poll::Pending => return ServicePoll::Pending,
                }
                *body = Some(response_body);
                *response_done = true;
                continue;
            }
            match std::pin::pin!(reset_rx.recv()).poll(cx) {
                Poll::Ready(_) => return ServicePoll::Done,
                Poll::Pending => {}
            }
            if *send_continue
                && !*continue_sent
                && send_continue_body
                    .as_ref()
                    .is_some_and(|flag| flag.load(Ordering::Relaxed))
            {
                let mut interim = Response::new(());
                *interim.status_mut() = StatusCode::CONTINUE;
                let (parts, _) = interim.into_parts();
                match Self::send(
                    msg_tx,
                    msg_tx_fut.as_mut(),
                    wake_tx,
                    StreamMsg::Informational { parts },
                    cx,
                ) {
                    Poll::Ready(()) => {}
                    Poll::Pending => return ServicePoll::Pending,
                }
                *continue_sent = true;
                continue;
            }
            if *early_hints_open {
                match early_hints_rx.poll_recv(cx) {
                    Poll::Ready(Some((headers, sender))) => {
                        let mut interim = Response::new(());
                        *interim.status_mut() = StatusCode::EARLY_HINTS;
                        *interim.headers_mut() = headers;
                        let (parts, _) = interim.into_parts();
                        match Self::send(
                            msg_tx,
                            msg_tx_fut.as_mut(),
                            wake_tx,
                            StreamMsg::Informational { parts },
                            cx,
                        ) {
                            Poll::Ready(()) => {}
                            Poll::Pending => return ServicePoll::Pending,
                        }
                        // The write itself happens later on the
                        // connection task; enqueueing is the failure
                        // surface that matters here.
                        sender.into_inner().send(Ok(())).ok();
                        continue;
                    }
                    Poll::Ready(None) => {
                        *early_hints_open = false;
                        continue;
                    }
                    Poll::Pending => {}
                }
            }
            return ServicePoll::Pending;
        }
    }

    /// Enqueues one outbound message, parking until the channel has
    /// room. `Pending` means the sender is parked (by `poll_ready` it
    /// will be woken when the connection task drains); `Ready(())`
    /// means the message was delivered or the connection is gone.
    #[inline]
    fn send(
        msg_tx: &mut kanal::AsyncSender<StreamMsg>,
        mut msg_tx_fut: Pin<&mut Option<kanal::SendFuture<'static, StreamMsg>>>,
        wake_tx: &kanal::AsyncSender<()>,
        msg: StreamMsg,
        cx: &mut Context<'_>,
    ) -> Poll<()> {
        if let Some(msg_tx_fut2) = msg_tx_fut.as_mut().as_pin_mut() {
            match msg_tx_fut2.poll(cx) {
                Poll::Ready(Ok(_)) => {
                    // SAFETY: Pin is re-borrowed here
                    let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
                    uckm.take();
                    let _ = wake_tx.try_send(());
                }
                Poll::Ready(Err(_)) => {
                    return Poll::Ready(());
                }
                Poll::Pending => return Poll::Pending,
            }
        }

        let msg_tx_fut2 = msg_tx.send(msg);
        // SAFETY: msg_tx_fut lives as long as msg_tx after storing in struct
        let msg_tx_fut2 = unsafe {
            std::mem::transmute::<
                kanal::SendFuture<'_, StreamMsg>,
                kanal::SendFuture<'static, StreamMsg>,
            >(msg_tx_fut2)
        };
        // SAFETY: Pin is re-borrowed here
        let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
        *uckm = Some(msg_tx_fut2);

        if let Some(msg_tx_fut2) = msg_tx_fut.as_mut().as_pin_mut() {
            match msg_tx_fut2.poll(cx) {
                Poll::Ready(Ok(_)) => {
                    // SAFETY: Pin is re-borrowed here
                    let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
                    uckm.take();
                    let _ = wake_tx.try_send(());
                    return Poll::Ready(());
                }
                Poll::Ready(Err(_)) => {
                    // SAFETY: Pin is re-borrowed here
                    let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
                    uckm.take();
                    return Poll::Ready(());
                }
                Poll::Pending => return Poll::Pending,
            }
        }

        Poll::Pending
    }

    /// Pipes the response body to the connection: DATA frames, then an
    /// END_STREAM (empty DATA when the body yields nothing more, or a
    /// HEADERS block carrying trailers).
    #[inline]
    fn poll_body(
        msg_tx: &mut kanal::AsyncSender<StreamMsg>,
        mut msg_tx_fut: Pin<&mut Option<kanal::SendFuture<'static, StreamMsg>>>,
        reset_rx: &mut kanal::AsyncReceiver<u32>,
        mut body: Pin<&mut ResB>,
        end: &mut bool,
        cx: &mut Context<'_>,
    ) -> Poll<()> {
        loop {
            if let Some(msg_tx_fut2) = msg_tx_fut.as_mut().as_pin_mut() {
                match msg_tx_fut2.poll(cx) {
                    Poll::Ready(Ok(_)) => {
                        // SAFETY: Pin is re-borrowed here
                        let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
                        uckm.take();
                    }
                    Poll::Ready(Err(_)) => {
                        // SAFETY: Pin is re-borrowed here
                        let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
                        uckm.take();
                        return Poll::Ready(());
                    }
                    Poll::Pending => return Poll::Pending,
                }
            }

            if *end {
                return Poll::Ready(());
            }

            match std::pin::pin!(reset_rx.recv()).poll(cx) {
                Poll::Ready(_) => return Poll::Ready(()),
                Poll::Pending => {}
            }
            match body.as_mut().poll_frame(cx) {
                Poll::Ready(Some(Ok(frame))) => match frame.into_data() {
                    Ok(data) => {
                        let msg = StreamMsg::Data {
                            data,
                            end_stream: body.is_end_stream(),
                        };

                        let msg_tx_fut2 = msg_tx.send(msg);
                        // SAFETY: msg_tx_fut lives as long as msg_tx after storing in struct
                        let msg_tx_fut2 = unsafe {
                            std::mem::transmute::<
                                kanal::SendFuture<'_, StreamMsg>,
                                kanal::SendFuture<'static, StreamMsg>,
                            >(msg_tx_fut2)
                        };
                        // SAFETY: Pin is re-borrowed here
                        let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
                        *uckm = Some(msg_tx_fut2);
                    }
                    Err(frame) => match frame.into_trailers() {
                        Ok(trailers) => {
                            let msg_tx_fut2 = msg_tx.send(StreamMsg::Trailers { trailers });
                            // SAFETY: msg_tx_fut lives as long as msg_tx after storing in struct
                            let msg_tx_fut2 = unsafe {
                                std::mem::transmute::<
                                    kanal::SendFuture<'_, StreamMsg>,
                                    kanal::SendFuture<'static, StreamMsg>,
                                >(msg_tx_fut2)
                            };
                            // SAFETY: Pin is re-borrowed here
                            let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
                            *uckm = Some(msg_tx_fut2);
                            *end = true;
                        }
                        Err(_) => return Poll::Ready(()),
                    },
                },
                Poll::Ready(Some(Err(_))) => {
                    let msg = StreamMsg::Reset {
                        error_code: crate::h2::error::Reason::InternalError.code(),
                    };
                    let msg_tx_fut2 = msg_tx.send(msg);
                    // SAFETY: msg_tx_fut lives as long as msg_tx after storing in struct
                    let msg_tx_fut2 = unsafe {
                        std::mem::transmute::<
                            kanal::SendFuture<'_, StreamMsg>,
                            kanal::SendFuture<'static, StreamMsg>,
                        >(msg_tx_fut2)
                    };
                    // SAFETY: Pin is re-borrowed here
                    let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
                    *uckm = Some(msg_tx_fut2);
                    *end = true;
                }
                Poll::Ready(None) => {
                    // The body has no more frames: close with an empty
                    // END_STREAM DATA frame.
                    let msg = StreamMsg::Data {
                        data: Bytes::new(),
                        end_stream: true,
                    };
                    let msg_tx_fut2 = msg_tx.send(msg);
                    // SAFETY: msg_tx_fut lives as long as msg_tx after storing in struct
                    let msg_tx_fut2 = unsafe {
                        std::mem::transmute::<
                            kanal::SendFuture<'_, StreamMsg>,
                            kanal::SendFuture<'static, StreamMsg>,
                        >(msg_tx_fut2)
                    };
                    // SAFETY: Pin is re-borrowed here
                    let uckm = unsafe { msg_tx_fut.as_mut().get_unchecked_mut() };
                    *uckm = Some(msg_tx_fut2);
                    *end = true;
                }
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

// Debug-friendly message types for tests that decode wire replies.