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
//! TinKV server is a redis-compatible key value server.

use crate::error::{Result, TinkvError};

use crate::store::Store;

use crate::resp::{deserialize_from_reader, serialize_to_writer, Value};
use lazy_static::lazy_static;
use log::{debug, info, trace};

use std::convert::TryFrom;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::net::{TcpListener, TcpStream, ToSocketAddrs};

lazy_static! {
    static ref COMMANDS: Vec<&'static str> =
        vec!["ping", "get", "set", "del", "dbsize", "exists", "compact", "info", "command",];
}

pub struct Server {
    store: Store,
}

impl Server {
    #[allow(dead_code)]
    pub fn new(store: Store) -> Self {
        Server { store }
    }

    pub fn run<A: ToSocketAddrs>(&mut self, addr: A) -> Result<()> {
        let addr = addr.to_socket_addrs()?.next().unwrap();
        info!("TinKV server is listening at '{}'", addr);
        let listener = TcpListener::bind(addr)?;
        for stream in listener.incoming() {
            self.serve(stream?)?;
        }
        Ok(())
    }

    fn serve(&mut self, stream: TcpStream) -> Result<()> {
        let peer_addr = stream.peer_addr()?;
        debug!("got connection from {}", &peer_addr);
        let reader = BufReader::new(&stream);
        let writer = BufWriter::new(&stream);
        let mut conn = Conn::new(writer);

        for value in deserialize_from_reader(reader) {
            let req: Request = Request::try_from(value?)?;
            self.handle_request(&mut conn, req)?;
        }

        debug!("connection disconnected from {}", &peer_addr);

        Ok(())
    }

    fn handle_request<W: Write>(&mut self, conn: &mut Conn<W>, req: Request) -> Result<()> {
        trace!("got request: `{}`, args: `{:?}`", &req.name, &req.args);
        let args = req.args_as_slice();

        macro_rules! send {
            () => {
                conn.write_value(Value::new_null_bulk_string())?
            };
            ($value:expr) => {
                match $value {
                    Err(TinkvError::RespCommon { name, msg }) => {
                        let err = Value::new_error(&name, &msg);
                        conn.write_value(err)?;
                    }
                    Err(TinkvError::RespWrongNumOfArgs(_)) => {
                        let msg = format!("{}", $value.unwrap_err());
                        let err = Value::new_error("ERR", &msg);
                        conn.write_value(err)?;
                    }
                    Err(e) => return Err(e),
                    Ok(v) => conn.write_value(v)?,
                }
            };
        }

        match req.name.as_ref() {
            "ping" => send!(self.handle_ping(&args)),
            "get" => send!(self.handle_get(&args)),
            "set" => send!(self.handle_set(&args)),
            "del" => send!(self.handle_del(&args)),
            "dbsize" => send!(self.handle_dbsize(&args)),
            "exists" => send!(self.handle_exists(&args)),
            "compact" => send!(self.handle_compact(&args)),
            "info" => send!(self.handle_info(&args)),
            "command" => send!(self.handle_command(&args)),
            _ => {
                conn.write_value(Value::new_error(
                    "ERR",
                    &format!("unknown command `{}`", &req.name),
                ))?;
            }
        }

        conn.flush()?;

        Ok(())
    }

    fn handle_ping(&mut self, args: &[&[u8]]) -> Result<Value> {
        match args.len() {
            0 => Ok(Value::new_simple_string("PONG")),
            1 => Ok(Value::new_bulk_string(args[0].to_vec())),
            _ => Err(TinkvError::resp_wrong_num_of_args("ping")),
        }
    }

    fn handle_get(&mut self, args: &[&[u8]]) -> Result<Value> {
        if args.len() != 1 {
            return Err(TinkvError::resp_wrong_num_of_args("get"));
        }

        Ok(self
            .store
            .get(args[0])?
            .map(Value::new_bulk_string)
            .unwrap_or_else(Value::new_null_bulk_string))
    }

    fn handle_set(&mut self, args: &[&[u8]]) -> Result<Value> {
        if args.len() < 2 {
            return Err(TinkvError::resp_wrong_num_of_args("set"));
        }

        match self.store.set(args[0], args[1]) {
            Ok(()) => Ok(Value::new_simple_string("OK")),
            Err(e) => Err(TinkvError::new_resp_common(
                "INTERNALERR",
                &format!("{}", e),
            )),
        }
    }

    fn handle_del(&mut self, args: &[&[u8]]) -> Result<Value> {
        if args.len() != 1 {
            return Err(TinkvError::resp_wrong_num_of_args("del"));
        }

        match self.store.remove(args[0]) {
            Ok(()) => Ok(Value::new_simple_string("OK")),
            Err(e) => Err(TinkvError::new_resp_common(
                "INTERNALERR",
                &format!("{}", e),
            )),
        }
    }

    fn handle_dbsize(&mut self, args: &[&[u8]]) -> Result<Value> {
        if !args.is_empty() {
            return Err(TinkvError::resp_wrong_num_of_args("dbsize"));
        }

        Ok(Value::new_integer(self.store.len() as i64))
    }

    fn handle_exists(&mut self, args: &[&[u8]]) -> Result<Value> {
        if args.len() != 1 {
            return Err(TinkvError::resp_wrong_num_of_args("exists"));
        }

        Ok(Value::new_integer(self.store.contains_key(args[0]) as i64))
    }

    fn handle_compact(&mut self, args: &[&[u8]]) -> Result<Value> {
        if !args.is_empty() {
            return Err(TinkvError::resp_wrong_num_of_args("compact"));
        }

        match self.store.compact() {
            Ok(_) => Ok(Value::new_simple_string("OK")),
            Err(e) => Err(TinkvError::new_resp_common(
                "INTERNALERR",
                &format!("{}", e),
            )),
        }
    }

    fn handle_info(&mut self, args: &[&[u8]]) -> Result<Value> {
        if !args.is_empty() {
            return Err(TinkvError::resp_wrong_num_of_args("info"));
        }

        let mut info = String::new();
        info.push_str("# Server\n");
        info.push_str(&format!("tinkv_version: {}\n", env!("CARGO_PKG_VERSION")));
        let os = os_info::get();
        info.push_str(&format!(
            "os: {}, {}, {}\n",
            os.os_type(),
            os.version(),
            os.bitness()
        ));

        info.push_str("\n# Stats\n");
        let stats = self.store.stats();
        info.push_str(&format!(
            "size_of_stale_entries: {}\n",
            stats.size_of_stale_entries
        ));
        info.push_str(&format!(
            "size_of_stale_entries_human: {}\n",
            bytefmt::format(stats.size_of_stale_entries)
        ));
        info.push_str(&format!(
            "total_stale_entries: {}\n",
            stats.total_stale_entries
        ));
        info.push_str(&format!(
            "total_active_entries: {}\n",
            stats.total_active_entries
        ));
        info.push_str(&format!("total_data_files: {}\n", stats.total_data_files));
        info.push_str(&format!(
            "size_of_all_data_files: {}\n",
            stats.size_of_all_data_files
        ));
        info.push_str(&format!(
            "size_of_all_data_files_human: {}\n",
            bytefmt::format(stats.size_of_all_data_files)
        ));

        Ok(Value::new_bulk_string(info.as_bytes().to_vec()))
    }

    fn handle_command(&mut self, args: &[&[u8]]) -> Result<Value> {
        if !args.is_empty() {
            return Err(TinkvError::resp_wrong_num_of_args("command"));
        }

        let mut values = vec![];
        for cmd in COMMANDS.iter() {
            values.push(Value::new_bulk_string(cmd.as_bytes().to_vec()));
        }

        Ok(Value::new_array(values))
    }
}

#[derive(Debug)]
struct Request {
    name: String,
    args: Vec<Value>,
}
impl Request {
    fn args_as_slice(&self) -> Vec<&[u8]> {
        let mut res = vec![];
        for arg in self.args.iter() {
            if let Some(v) = arg.as_bulk_string() {
                res.push(v);
            }
        }
        res
    }
}

impl TryFrom<Value> for Request {
    type Error = TinkvError;

    fn try_from(value: Value) -> std::result::Result<Self, Self::Error> {
        match value {
            Value::Array(mut v) => {
                if v.is_empty() {
                    return Err(TinkvError::ParseRespValue);
                }
                let name =
                    String::from_utf8_lossy(v.remove(0).as_bulk_string().unwrap()).to_string();
                Ok(Self {
                    name: name.to_ascii_lowercase(),
                    args: v,
                })
            }
            _ => Err(TinkvError::ParseRespValue),
        }
    }
}

struct Conn<W> {
    writer: W,
}

impl<W> Conn<W>
where
    W: Write,
{
    fn new(writer: W) -> Self {
        Self { writer }
    }

    fn write_value(&mut self, value: Value) -> Result<()> {
        trace!("send value to client: {:?}", value);
        serialize_to_writer(&mut self.writer, &value)?;
        Ok(())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.writer.flush()
    }
}