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
mod bearers;

use std::{
    collections::HashMap,
    io::{Read, Write},
    sync::mpsc::{self, Receiver, Sender, TryRecvError},
    thread::{self, JoinHandle},
    time::{Duration, Instant},
};

use log::{debug, error, trace, warn};

pub trait Bearer: Read + Write + Send + Sync + Sized {
    fn read_segment(&mut self) -> Result<(u16, u32, Payload), std::io::Error>;

    fn write_segment(
        &mut self,
        clock: Instant,
        protocol_id: u16,
        partial_payload: &[u8],
    ) -> Result<(), std::io::Error>;

    fn clone(&self) -> Self;
}

const MAX_SEGMENT_PAYLOAD_LENGTH: usize = 65535;

pub type Payload = Vec<u8>;

fn tx_round<TBearer>(
    bearer: &mut TBearer,
    ingress: &MuxIngress,
    clock: Instant,
) -> Result<u16, std::io::Error>
where
    TBearer: Bearer,
{
    let mut writes = 0u16;

    for (id, rx) in ingress.iter() {
        match rx.try_recv() {
            Ok(payload) => {
                let chunks = payload.chunks(MAX_SEGMENT_PAYLOAD_LENGTH);

                for chunk in chunks {
                    bearer.write_segment(clock, *id, chunk)?;
                    writes += 1;
                }
            }
            Err(TryRecvError::Disconnected) => {
                //TODO: remove handle from list
                trace!("protocol handle {} disconnected", id);
            }
            Err(TryRecvError::Empty) => (),
        };
    }

    Ok(writes)
}

fn tx_loop<TBearer>(bearer: &mut TBearer, ingress: MuxIngress)
where
    TBearer: Bearer,
{
    loop {
        let clock = Instant::now();
        match tx_round(bearer, &ingress, clock) {
            Err(err) => {
                error!("{:?}", err);
                panic!();
            }
            Ok(0) => thread::sleep(Duration::from_millis(10)),
            Ok(_) => (),
        };
    }
}

fn rx_loop<TBearer>(bearer: &mut TBearer, egress: DemuxerEgress)
where
    TBearer: Bearer,
{
    let mut tx_map: HashMap<_, _> = egress.into_iter().collect();

    loop {
        match bearer.read_segment() {
            Err(err) => {
                error!("{:?}", err);
                panic!();
            }
            Ok(segment) => {
                let (id, _ts, payload) = segment;
                match tx_map.get(&id) {
                    Some(tx) => match tx.send(payload) {
                        Err(err) => {
                            error!("error sending egress tx to protocol, removing protocol from egress output. {:?}", err);
                            tx_map.remove(&id);
                        }
                        Ok(_) => {
                            debug!("successful tx to egress protocol");
                        }
                    },
                    None => warn!("received segment for protocol id not being demuxed {}", id),
                }
            }
        }
    }
}

pub struct Channel(pub Sender<Payload>, pub Receiver<Payload>);

type ChannelProtocolHandle = (u16, Channel);
type ChannelIngressHandle = (u16, Receiver<Payload>);
type ChannelEgressHandle = (u16, Sender<Payload>);
type MuxIngress = Vec<ChannelIngressHandle>;
type DemuxerEgress = Vec<ChannelEgressHandle>;

pub struct Multiplexer {
    tx_thread: JoinHandle<()>,
    rx_thread: JoinHandle<()>,
    io_handles: HashMap<u16, Channel>,
}

impl Multiplexer {
    pub fn setup<TBearer>(
        bearer: TBearer,
        protocols: &[u16],
    ) -> Result<Multiplexer, Box<dyn std::error::Error>>
    where
        TBearer: Bearer + 'static,
    {
        let handles = protocols
            .iter()
            .map(|id| {
                let (demux_tx, demux_rx) = mpsc::channel::<Payload>();
                let (mux_tx, mux_rx) = mpsc::channel::<Payload>();

                let channel = Channel(mux_tx, demux_rx);

                let protocol_handle: ChannelProtocolHandle = (*id, channel);
                let ingress_handle: ChannelIngressHandle = (*id, mux_rx);
                let egress_handle: ChannelEgressHandle = (*id, demux_tx);

                (protocol_handle, (ingress_handle, egress_handle))
            })
            .collect::<Vec<_>>();

        let (protocol_handles, multiplex_handles): (Vec<_>, Vec<_>) = handles.into_iter().unzip();

        let (ingress, egress): (Vec<_>, Vec<_>) = multiplex_handles.into_iter().unzip();

        let mut tx_bearer = bearer.clone();
        let tx_thread = thread::spawn(move || tx_loop(&mut tx_bearer, ingress));

        let mut rx_bearer = bearer.clone();
        let rx_thread = thread::spawn(move || rx_loop(&mut rx_bearer, egress));

        let io_handles: HashMap<u16, Channel> = protocol_handles.into_iter().collect();

        Ok(Multiplexer {
            io_handles,
            tx_thread,
            rx_thread,
        })
    }

    pub fn use_channel(&mut self, protocol_id: u16) -> Channel {
        self.io_handles.remove(&protocol_id).unwrap()
    }

    pub fn join(self) {
        self.tx_thread.join().unwrap();
        self.rx_thread.join().unwrap();
    }
}