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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
|
use crate::{resp_parser::*, shared_cache::*};
use crate::{Config, SharedConfig};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone)]
pub enum SetCondition {
/// NX - only set if key doesn't exists
NotExists,
/// XX - only set if key already exists
Exists,
}
#[derive(Debug, Clone)]
pub enum ExpiryOption {
/// EX seconds - expire in N seconds
Seconds(u64),
/// PX milliseconds - expire in N milliseconds
Milliseconds(u64),
/// EXAT timestamp-seconds - expire at Unix timestamp (seconds)
ExpiresAtSeconds(u64),
/// PXAT timestamp-milliseconds - expire at Unix timestamp (milliseconds)
ExpiresAtMilliseconds(u64),
/// KEEPTTL - retain existing TTL
KeepTtl,
}
/// Link: https://redis.io/docs/latest/commands/set/
/// Syntax:
/// -------
/// SET key value [NX | XX] [GET] [EX seconds | PX milliseconds |
/// EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL]
///
/// Options:
/// --------
/// EX seconds -- Set the specified expire time, in seconds (a positive integer).
/// PX milliseconds -- Set the specified expire time, in milliseconds (a positive integer).
/// EXAT timestamp-seconds -- Set the specified Unix time at which the key will expire, in seconds (a positive integer).
/// PXAT timestamp-milliseconds -- Set the specified Unix time at which the key will expire, in milliseconds (a positive integer).
/// NX -- Only set the key if it does not already exist.
/// XX -- Only set the key if it already exists.
/// KEEPTTL -- Retain the time to live associated with the key.
/// GET -- Return the old string stored at key, or nil if key did not exist. An error is returned and SET aborted if the value stored at key is not a string.
#[derive(Debug, Clone)]
pub struct SetCommand {
pub key: String,
pub value: String,
pub condition: Option<SetCondition>,
pub expiry: Option<ExpiryOption>,
pub get_old_value: bool,
}
impl SetCommand {
pub fn new(key: String, value: String) -> Self {
Self {
key,
value,
condition: None,
expiry: None,
get_old_value: false,
}
}
pub fn with_condition(mut self, condition: Option<SetCondition>) -> Self {
self.condition = condition;
self
}
pub fn with_expiry(mut self, expiry: Option<ExpiryOption>) -> Self {
self.expiry = expiry;
self
}
pub fn with_get(mut self, value: bool) -> Self {
self.get_old_value = value;
self
}
/// Calculate the absolute expiry time in milliseconds since Unix epoch
pub fn calculate_expiry_time(&self) -> Option<u64> {
match &self.expiry {
Some(ExpiryOption::Seconds(secs)) => {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
Some(now + (secs * 1000))
}
Some(ExpiryOption::Milliseconds(ms)) => {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64;
Some(now + ms)
}
Some(ExpiryOption::ExpiresAtSeconds(timestamp)) => Some(timestamp * 1000),
Some(ExpiryOption::ExpiresAtMilliseconds(timestamp)) => Some(*timestamp),
Some(ExpiryOption::KeepTtl) => None, // Handled specially
None => None,
}
}
}
// Helper function to extract string from BulkString
fn extract_string(resp: &RespType) -> Option<String> {
match resp {
RespType::BulkString(bytes) => str::from_utf8(bytes).ok().map(|s| s.to_owned()),
_ => None,
}
}
// Helper function to parse u64 from BulkString
fn parse_u64(resp: &RespType) -> Option<u64> {
extract_string(resp)?.parse().ok()
}
pub enum RedisCommands {
PING,
ECHO(String),
GET(String),
SET(SetCommand),
CONFIG_GET(String),
Invalid,
}
impl RedisCommands {
pub fn execute(self, cache: SharedCache, config: SharedConfig) -> Vec<u8> {
match self {
RedisCommands::PING => resp!("PONG"),
RedisCommands::ECHO(echo_string) => resp!(echo_string),
RedisCommands::GET(key) => {
let mut cache = cache.lock().unwrap();
match cache.get(&key).cloned() {
Some(entry) => {
if entry.is_expired() {
cache.remove(&key); // Clean up expired key
resp!(null)
} else {
resp!(bulk entry.value)
}
}
None => resp!(null),
}
}
RedisCommands::SET(command) => {
let mut cache = cache.lock().unwrap();
// Check conditions (NX/XX)
let key_exists = cache.contains_key(&command.key);
match command.condition {
Some(SetCondition::NotExists) if key_exists => {
return resp!(null); // Key exists, NX failed
}
Some(SetCondition::Exists) if !key_exists => {
return resp!(null); // Key doesn't exist, XX failed
}
_ => {} // No condition or condition met
}
let mut get_value: Option<String> = None;
// Handle GET option
if command.get_old_value {
match cache.get(&command.key) {
Some(val) => get_value = Some(val.value.clone()),
None => {}
}
} else {
}
// Calculate expiry
let expires_at = if let Some(ExpiryOption::KeepTtl) = command.expiry {
// Keep existing TTL
cache.get(&command.key).and_then(|e| e.expires_at)
} else {
command.calculate_expiry_time()
};
// Set the value
cache.insert(
command.key.clone(),
CacheEntry {
value: command.value.clone(),
expires_at,
},
);
if !command.get_old_value {
return resp!("OK");
}
match get_value {
Some(val) => return resp!(bulk val),
None => return resp!(null),
}
}
RedisCommands::CONFIG_GET(s) => {
use RespType as RT;
let config = config.clone();
if let Some(conf) = config.as_ref() {
let dir = conf.dir.clone().unwrap();
let dbfilename = conf.dbfilename.clone().unwrap();
match s.as_str() {
"dir" => RT::Array(vec![
RT::BulkString(s.as_bytes().to_vec()),
RT::BulkString(dir.as_bytes().to_vec()),
])
.to_resp_bytes(),
"dbfilename" => RT::Array(vec![
RT::BulkString(s.as_bytes().to_vec()),
RT::BulkString(dbfilename.as_bytes().to_vec()),
])
.to_resp_bytes(),
_ => unreachable!(),
}
} else {
unreachable!()
}
}
RedisCommands::Invalid => todo!(),
}
}
}
// Parser for SET command options
struct SetOptionParser {
command: SetCommand,
}
impl SetOptionParser {
fn new(key: String, value: String) -> Self {
Self {
command: SetCommand::new(key, value),
}
}
fn parse_option(&mut self, option: &str, next_arg: Option<&str>) -> Result<bool, &'static str> {
match option.to_ascii_uppercase().as_str() {
"GET" => {
self.command = self.command.clone().with_get(true
|