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
use std::{
    io::{BufRead, Write},
    net::{Shutdown, TcpStream, ToSocketAddrs},
    sync::Arc,
    thread,
    time::Duration,
};

use parking_lot_rt::Mutex;
use rtsc::{
    channel::{Receiver, Sender},
    ops::Operation,
};
use tracing::trace;

use crate::{
    Direction, Error, API_VERSION, DEFAULT_INCOMING_QUEUE_SIZE, DEFAULT_TIMEOUT, GREETING,
    HEADERS_TRANSMISSION_END,
};

#[derive(Clone)]
pub struct Client {
    stream: Arc<Mutex<TcpStream>>,
}

#[derive(Clone)]
pub struct ConnectionOptions {
    timeout: Duration,
    incoming_queue_size: usize,
}

impl Default for ConnectionOptions {
    fn default() -> Self {
        Self {
            timeout: DEFAULT_TIMEOUT,
            incoming_queue_size: DEFAULT_INCOMING_QUEUE_SIZE,
        }
    }
}

impl ConnectionOptions {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }
    pub fn incoming_queue_size(mut self, size: usize) -> Self {
        self.incoming_queue_size = size;
        self
    }
}

impl Client {
    /// Connect to a server and create a client instance
    pub fn connect(
        addr: impl ToSocketAddrs,
    ) -> Result<(Self, Receiver<(Direction, String)>), Error> {
        Self::connect_with_options(addr, &ConnectionOptions::default())
    }
    /// Connect to a server and create a client instance with the defined options
    pub fn connect_with_options(
        addr: impl ToSocketAddrs,
        options: &ConnectionOptions,
    ) -> Result<(Self, Receiver<(Direction, String)>), Error> {
        let timeout = options.timeout;
        let op = Operation::new(timeout);
        let stream = TcpStream::connect_timeout(
            &addr
                .to_socket_addrs()?
                .next()
                .ok_or(Error::InvalidAddress)?,
            timeout,
        )?;
        stream.set_read_timeout(Some(timeout))?;
        stream.set_write_timeout(Some(timeout))?;
        stream.set_nodelay(true)?;
        let reader = &mut std::io::BufReader::new(&stream);
        let mut lines = reader.lines();
        trace!("reading greeting");
        let line = lines.next().ok_or(Error::InvalidData)??;
        let mut sp = line.split('/');
        if sp.next() != Some(GREETING) {
            return Err(Error::InvalidData);
        }
        let api_version: u8 = sp
            .next()
            .ok_or_else(|| {
                trace!("Unable to parse greetings header value");
                Error::InvalidData
            })?
            .trim()
            .parse()
            .map_err(|error| {
                trace!(%error, "Unable to parse greetings header value");
                Error::InvalidData
            })?;
        if api_version != API_VERSION {
            return Err(Error::ApiVersion(api_version));
        }
        trace!("reading headers");
        let mut headers_end = false;
        stream.set_read_timeout(Some(op.remaining().map_err(|_| Error::Timeout)?))?;
        // headers are reserved for future use
        for line in lines.by_ref() {
            if line? == HEADERS_TRANSMISSION_END {
                headers_end = true;
                break;
            }
            stream.set_read_timeout(Some(op.remaining().map_err(|_| Error::Timeout)?))?;
        }
        if !headers_end {
            trace!("Invalid headers transmission end");
            return Err(Error::InvalidData);
        }
        trace!(api_version, "connection estabilished");
        stream.set_read_timeout(None)?;
        let (tx, rx) = rtsc::channel::bounded(options.incoming_queue_size);
        let stream_c = stream.try_clone()?;
        thread::spawn(move || handle_connection(tx, stream_c));
        Ok((
            Self {
                stream: Arc::new(Mutex::new(stream)),
            },
            rx,
        ))
    }
    pub fn try_send(&self, data: impl ToString) -> Result<(), Error> {
        let mut stream = self.stream.lock();
        stream
            .write_all(format!("{}\n", data.to_string()).as_bytes())
            .map_err(Into::into)
    }
}

fn handle_connection(tx: Sender<(Direction, String)>, stream: TcpStream) {
    macro_rules! quit {
        () => {{
            stream.shutdown(Shutdown::Both).ok();
            break;
        }};
    }
    macro_rules! report_msg {
        ($dir: expr, $msg: expr) => {
            if tx.send(($dir, $msg)).is_err() {
                quit!();
            }
        };
    }
    let reader = &mut std::io::BufReader::new(&stream);
    let mut last_direction: Option<Direction> = None;
    for line in reader.lines() {
        let Ok(line) = line else {
            quit!();
        };
        if let Some(msg) = line.strip_prefix(Direction::Incoming.as_str()) {
            last_direction = Some(Direction::Incoming);
            report_msg!(Direction::Incoming, msg.to_string());
        } else if let Some(msg) = line.strip_prefix(Direction::Outgoing.as_str()) {
            last_direction = Some(Direction::Outgoing);
            report_msg!(Direction::Outgoing, msg.to_string());
        } else {
            let Some(last_direction) = last_direction else {
                quit!();
            };
            report_msg!(last_direction, line);
        }
    }
}

impl Drop for Client {
    fn drop(&mut self) {
        self.stream.lock().shutdown(Shutdown::Both).ok();
    }
}