1
//! The reader task of an eval channel.
2
//!
3
//! It never stops listening: while a request waits for room in its stream's
4
//! queue, new chunks are still decoded, an `(:interrupt n)` reaches the mux at
5
//! once. Requests and `(:close n)` frames wait in a short FIFO, so their order
6
//! holds. A framing error stops the input; the frames already taken are still
7
//! answered before the `parse` reply. A client close aborts through the mux's [`rpc::mux::AbortHandle`].
8

            
9
use std::collections::VecDeque;
10

            
11
use rpc::envelope::{Frame, read_frame};
12
use rpc::mux::{Mux, QUEUE_CAPACITY, reject_input};
13
use rpc::{FrameDecoder, FrameError};
14
use tokio::sync::mpsc;
15

            
16
30
pub(super) async fn read_input(mut mux: Mux, mut chunks: mpsc::Receiver<Vec<u8>>) {
17
30
    let replies = mux.replies();
18
30
    let mut decoder = FrameDecoder::new();
19
30
    let mut held: VecDeque<String> = VecDeque::new();
20
30
    let mut input_open = true;
21
30
    let mut failed = None;
22
20950
    while input_open || !held.is_empty() {
23
20930
        tokio::select! {
24
            biased;
25
20930
            () = ready_front(&mux, held.front()), if !held.is_empty() => {
26
20546
                let Some(frame) = held.pop_front() else { continue };
27
20546
                if let Some(refusal) = mux.frame(&frame) {
28
130
                    replies.send(refusal).await.ok();
29
20416
                }
30
            }
31
20930
            chunk = chunks.recv(), if input_open && held.len() < QUEUE_CAPACITY => {
32
374
                let Some(bytes) = chunk else {
33
17
                    input_open = false;
34
17
                    continue;
35
                };
36
357
                if let Err(err) = take_chunk(&mut decoder, &mut mux, &mut held, &bytes) {
37
3
                    failed = Some(err);
38
3
                    input_open = false;
39
354
                }
40
            }
41
        }
42
    }
43
20
    if let Some(err) = failed {
44
3
        replies.send(reject_input(&err)).await.ok();
45
17
    }
46
20
}
47

            
48
20930
async fn ready_front(mux: &Mux, front: Option<&String>) {
49
20589
    if let Some(frame) = front {
50
20589
        mux.ready(frame).await;
51
    }
52
20546
}
53

            
54
/// Interrupts go to the mux now; everything else waits its turn.
55
357
fn take_chunk(
56
357
    decoder: &mut FrameDecoder,
57
357
    mux: &mut Mux,
58
357
    held: &mut VecDeque<String>,
59
357
    bytes: &[u8],
60
357
) -> Result<(), FrameError> {
61
357
    decoder.feed(bytes)?;
62
20909
    while let Some(frame) = decoder.next_frame() {
63
20555
        let frame = frame?;
64
20552
        match read_frame(&frame) {
65
3
            Ok(Frame::Interrupt(stream)) => mux.interrupt(stream),
66
20549
            _ => held.push_back(frame),
67
        }
68
    }
69
354
    Ok(())
70
357
}