-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
275 lines (240 loc) · 8.85 KB
/
main.rs
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
use bytes::{Bytes, BytesMut};
use resp::RespConcreteType;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpStream},
sync::RwLock,
};
use std::time::{Duration, SystemTime};
use std::{collections::HashMap, sync::Arc};
enum Command {
Ping,
Set(SetCommand),
Get(String),
Echo(String),
Error(Bytes),
}
struct SetCommand {
key: String,
value: String,
expiry_at: Option<SystemTime>,
}
#[derive(Debug)]
struct StorageValue {
value: String,
expiry_at: Option<SystemTime>,
}
enum CommandError {
UnknownCommand(String),
BadLength(usize),
BadExpiry(String),
}
type Storage = Arc<RwLock<HashMap<String, StorageValue>>>;
const INTERFACE: &str = "127.0.0.1";
const PORT: &str = "6379";
mod resp;
#[tokio::main]
async fn main() {
// You can use print statements as follows for debugging, they'll be visible when running tests.
println!("Starting Server on {} at port {}", INTERFACE, PORT);
let listener = TcpListener::bind(format!("{}:{}", INTERFACE, PORT))
.await
.unwrap();
println!("Listening at {}", listener.local_addr().unwrap());
let storage: Storage = Arc::new(RwLock::new(HashMap::new()));
loop {
let (stream, addr) = listener.accept().await.unwrap();
// A new task is spawned for each inbound socket. The socket is
// moved to the new ta sk and processed there.
println!("New Connection at {addr}");
let st = storage.clone();
tokio::spawn(async {
process(stream, st).await;
});
}
}
async fn process(mut stream: TcpStream, storage: Storage) {
let mut buf = BytesMut::with_capacity(20);
let mut partial: Option<resp::RespTypePartialable> = None;
loop {
let st = storage.clone();
let s = stream
.read_buf(&mut buf)
.await
.expect("Could not read message");
if s == 0 {
continue;
}
let parse_result = resp::parse(&mut buf, partial).expect("Unexpected parsing failure");
match parse_result {
resp::Resp::Partial(partial_res) => {
partial = Some(partial_res);
continue;
}
resp::Resp::Concrete(res) => {
partial = None;
let command = parse_command(res)
.unwrap_or_else(|_| Command::Error(Bytes::from("+Invalid Command\r\n")));
handle_command(command, &mut stream, st).await;
}
}
}
}
fn parse_command(res: RespConcreteType) -> Result<Command, CommandError> {
match res {
RespConcreteType::Array(mut array) => match array.pop_front() {
Some(RespConcreteType::BulkString(command)) => match command.to_lowercase().as_str() {
"ping" => Ok(Command::Ping),
"echo" => match &array[0] {
RespConcreteType::BulkString(arg) => Ok(Command::Echo(arg.to_string())),
_ => Err(CommandError::UnknownCommand(
"Invalid Echo Command".to_string(),
)),
},
"set" => {
if array.len() < 2 {
return Err(CommandError::BadLength(array.len()));
}
let key = array.pop_front();
let value = array.pop_front();
let expiry_at = match array.pop_front() {
Some(RespConcreteType::BulkString(exp)) => {
if exp.to_ascii_lowercase().as_str() == "px" {
let time = array.pop_front();
match time {
Some(RespConcreteType::BulkString(time)) => {
let time = time
.parse::<u64>()
.map_err(|_| CommandError::BadExpiry(time))?;
SystemTime::now().checked_add(Duration::from_millis(time))
}
_ => return Err(CommandError::BadLength(array.len())),
}
} else {
// todo handle error of unknown args
return Err(CommandError::BadLength(array.len()));
}
}
_ => None,
};
match (key, value) {
(
Some(RespConcreteType::BulkString(key)),
Some(RespConcreteType::BulkString(value)),
) => Ok(Command::Set(SetCommand {
key,
value,
expiry_at,
})),
_ => Err(CommandError::UnknownCommand(
"Invalid Set Command".to_string(),
)),
}
}
"get" => {
if array.len() != 1 {
return Err(CommandError::BadLength(array.len()));
}
let key = array.pop_front();
match key {
Some(RespConcreteType::BulkString(key)) => Ok(Command::Get(key)),
_ => Err(CommandError::UnknownCommand(
"Invalid Get Command".to_string(),
)),
}
}
_ => Err(CommandError::UnknownCommand(command.to_string())),
},
_ => panic!("Unknown command"),
},
_ => panic!("Unknown command"),
}
}
// async fn process_all(
// mut buf: &mut BytesMut,
// mut stream: TcpStream,
// partial: Option<resp::RespTypePartialable>,
// ) -> Resp {
// let s = stream
// .read_buf(&mut buf)
// .await
// .expect("Could not read message");
// if s == 0 {
// return process_all(buf, stream, partial).await;
// }
// let parse_result = resp::parse(&mut buf, partial).expect("damn");
// match parse_result {
// resp::Resp::Partial(partial_res) => {
// println!("Partial: {:?}", partial_res);
// return process_all(buf, stream, Some(partial_res)).await;
// }
// concrete_type => concrete_type,
// }
// }
async fn handle_command(command: Command, stream: &mut TcpStream, storage: Storage) {
match command {
Command::Ping => {
stream
.write_all("+PONG\r\n".as_bytes())
.await
.expect("could not write to buffer");
}
Command::Echo(arg) => {
stream
.write_all(format!("${}\r\n{arg}\r\n", arg.len()).as_bytes())
.await
.expect("could not write to buffer");
}
Command::Error(arg) => {
stream
.write_all(&arg)
.await
.expect("could not write to buffer");
}
Command::Set(SetCommand {
key,
value,
expiry_at,
}) => {
let mut storage = storage.write().await;
storage.insert(key, StorageValue { expiry_at, value });
stream
.write_all("+OK\r\n".as_bytes())
.await
.expect("could not write to buffer");
}
Command::Get(key) => {
let rstorage = storage.read().await;
let value = rstorage.get(&key);
match value {
Some(value) => {
let expiry_at = value.expiry_at;
if let Some(expiry_at) = expiry_at {
let now = SystemTime::now();
if now > expiry_at {
drop(rstorage);
let mut storage = storage.write().await;
storage.remove(&key);
return stream
.write_all("$-1\r\n".as_bytes())
.await
.expect("could not write to buffer");
}
}
stream
.write_all(
format!("${}\r\n{}\r\n", value.value.len(), value.value).as_bytes(),
)
.await
.expect("could not write to buffer");
}
None => {
stream
.write_all("$-1\r\n".as_bytes())
.await
.expect("could not write to buffer");
}
}
}
};
}