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
|
use crate::resp_parser::RespType;
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::sync::{Arc, Mutex};
use std::{env, thread};
use crate::shared_cache::SharedCache;
#[derive(Debug, Clone)]
pub struct MasterServer {
pub dir: Option<String>,
pub dbfilename: Option<String>,
pub replid: Option<String>,
pub current_offset: Option<String>,
pub port: String,
pub cache: SharedCache,
replicas: Vec<SlaveServer>,
}
impl MasterServer {
fn new() -> Self {
Self {
dir: None,
dbfilename: None,
port: "6379".to_string(),
replid: Some("8371b4fb1155b71f4a04d3e1bc3e18c4a990aeeb".to_string()),
current_offset: Some("0".to_string()),
cache: Arc::new(Mutex::new(HashMap::new())),
replicas: vec![],
}
}
fn port(&self) -> &str {
&self.port
}
pub fn broadcast_command(&mut self, command: &[u8]) {
println!("Hello from brodcast");
self.replicas.retain(|replica| {
if let Some(conn) = &replica.connection {
let mut conn = conn.lock().unwrap();
if let Err(e) = conn.write_all(command) {
eprintln!("Failed to send to replica {}: {}", replica.port, e);
false // Drop dead connections
} else {
true
}
} else {
false
}
});
}
}
#[derive(Debug, Clone)]
pub struct SlaveServer {
pub dir: Option<String>,
pub dbfilename: Option<String>,
pub port: String,
pub master_replid: Option<String>,
pub master_repl_offset: Option<String>,
pub master_host: String,
pub master_port: String,
pub connection: Option<Arc<Mutex<TcpStream>>>,
pub cache: SharedCache,
}
impl SlaveServer {
fn new(
port: String,
master_host: String,
master_port: String,
connection: Option<Arc<Mutex<TcpStream>>>,
) -> Self {
Self {
dir: None,
dbfilename: None,
port,
master_replid: Some("8371b4fb1155b71f4a04d3e1bc3e18c4a990aeeb".to_string()),
master_repl_offset: Some("0".to_string()),
master_host,
master_port,
connection,
cache: Arc::new(Mutex::new(HashMap::new())),
}
}
fn connect(&self) -> Result<TcpStream, std::io::Error> {
let master_address = format!("{}:{}", self.master_host, self.master_port);
return TcpStream::connect(master_address);
}
fn handshake(&mut self) -> Result<(), String> {
match self.connect() {
Ok(mut stream) => {
let mut buffer = [0; 512];
let mut send_command = |command: &[u8]| -> Result<(), String> {
stream
.write_all(command)
.map_err(|e| format!("Failed to send: {}", e))?;
match stream.read(&mut buffer) {
Ok(0) | Err(_) => return Ok(()), // connection closed or error
Ok(_) => Ok(()),
}
};
// PING
send_command(&resp_bytes!(array => [resp!(bulk "PING")]))?;
// REPLCONF listening-port <PORT>
send_command(&resp_bytes!(array => [
resp!(bulk "REPLCONF"),
resp!(bulk "listening-port"),
resp!(bulk self.port.clone())
]))?;
// REPLCONF capa psync2
send_command(&resp_bytes!(array => [
resp!(bulk "REPLCONF"),
resp!(bulk "capa"),
resp!(bulk "psync2")
]))?;
// PSYNC <REPL_ID> <REPL_OFFSSET>
send_command(&resp_bytes!(array => [
resp!(bulk "PSYNC"),
resp!(bulk "?"),
resp!(bulk "-1")
]))?;
// Store the persistent connection
let shared_stream = Arc::new(Mutex::new(stream));
self.connection = Some(shared_stream.clone());
// Spawn the background listener thread
thread::spawn(move || {
let mut buffer = [0u8; 1024];
loop {
let mut stream = shared_stream.lock().unwrap();
match stream.read(&mut buffer) {
Ok(0) => {
println!("Master disconnected");
break;
}
Ok(n) => {
println!(
"REPLICA received: {}",
String::from_utf8_lossy(&buffer[..n])
);
}
Err(e) => {
eprintln!("Error reading from master: {}", e);
break;
}
}
}
});
Ok(())
}
Err(e) => Err(format!("Master node doesn't exist: {}", e)),
}
}
}
#[derive(Debug, Clone)]
pub enum RedisServer {
Master(MasterServer),
Slave(SlaveServer),
}
impl RedisServer {
pub fn master() -> Self {
RedisServer::Master(MasterServer::new())
}
pub fn slave(port: String, master_host: String, master_port: String) -> Self {
RedisServer::Slave(SlaveServer::new(port, master_host, master_port, None))
}
// Helper methods to access common fields regardless of variant
pub fn port(&self) -> &str {
match self {
RedisServer::Master(master) => &master.port,
RedisServer::Slave(slave) => &slave.port,
}
}
pub fn set_port(&mut self, port: String) {
match self {
RedisServer::Master(master) => master.port = port,
RedisServer::Slave(slave) => slave.port = port,
}
}
pub fn dir(&self) -> &Option<String> {
match self {
RedisServer::Master(master) => &master.dir,
RedisServer::Slave(slave) => &slave.dir,
}
}
pub fn set_dir(&mut self, dir: Option<String>) {
match self {
RedisServer::Master(master) => master.dir = dir,
RedisServer::Slave(slave) => slave.dir = dir,
}
}
pub fn dbfilename(&self) -> &Option<String> {
match self {
RedisServer::Master(master) => &master.dbfilename,
RedisServer::Slave(slave) => &slave.dbfilename,
}
}
pub fn set_dbfilename(&mut self, dbfilename: Option<String>) {
match self {
RedisServer::Master(master) => master.dbfilename = dbfilename,
RedisServer::Slave(slave)
|