-
Notifications
You must be signed in to change notification settings - Fork 13
/
redis_server.ts
236 lines (209 loc) · 6.49 KB
/
redis_server.ts
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
import net from 'net';
import { RedisSerializer } from './redis_serializer';
import { RedisDeserializer } from './redis_deserializer';
import { RedisCommands } from './redis_commands';
import { RespType } from './types';
interface IRedisServer {
/**
* The host on which the Redis Server will start.
* e.g.: 127.0.0.1
*
* @type {string}
*/
host: string;
/**
* The port on which the Redis Server will start listening to messages.
*
* @type {number}
*/
port: number;
/**
* Used for debugging purposes.
* If true, then the Server will log messages to console.
*
* @type {boolean}
*/
debug: boolean;
/**
* This function starts listening on the given host and port.
* It also attaches various a listener on the 'connection' event.
* This listener handles the messages from a Socket instance.
*/
startServer(): void;
/**
* This function returns a Promise that gets resolved when all the connection of the Server are closed and a 'close' event is emitted from the Server.
*
* @returns {Promise<void>}
*/
stopServer(): Promise<void>;
}
export class RedisServer implements IRedisServer {
host;
port;
debug;
private server: net.Server;
private serializer: RedisSerializer;
private map: Map<string, RespType>;
private sockets: Map<string, net.Socket>;
constructor(
port: number = 6379,
host: string = '127.0.0.1',
debug: boolean = false
) {
this.host = host;
this.port = port;
this.debug = debug;
this.serializer = new RedisSerializer();
this.map = new Map<string, string>();
this.server = new net.Server();
this.sockets = new Map<string, net.Socket>();
}
startServer() {
this.server.listen(this.port, this.host, () => {
if (this.debug) {
console.log('Redis server started listening on port: ' + this.port);
}
});
this.server.on('connection', (sock) => {
this.sockets.set(sock.remoteAddress + ':' + sock.remotePort, sock);
if (this.debug) {
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
}
sock.on('error', (err) => {
// End the Socket whe encountered an error.
console.error(err.message);
sock.end();
});
sock.on('close', () => {
// When the Socket is closed, remove the Socket from the Map of Clients.
this.sockets.delete(sock.remoteAddress + ':' + sock.remotePort);
});
sock.on('data', (data) => {
// This data can have multiple commands stitched together
const dataStr = data.toString();
const dataLength = dataStr.length;
if (this.debug) {
console.log(
'DATA ' +
sock.remoteAddress +
':' +
sock.remotePort +
' :' +
JSON.stringify(dataStr)
);
}
let currentPos = 0;
while (currentPos < dataLength) {
// Keep on parsing commands until you reach the end of data.
// This doesn't handle the case when the data is fragmented between two reads.
try {
// Deserialize the data
const deserializer = new RedisDeserializer(
dataStr.substring(currentPos),
true
);
const serializedData = deserializer.parse() as Array<string>;
// Update the current position
currentPos += deserializer.getPos();
// Handle the command received.
this.handleRequests(sock, serializedData);
} catch (e) {
/**
* If some error occurred while deserialization, send an error to the client.
* This doesn't handle the case when there are multiple commands still pending after this error.
* The execution for the data parsing is stopped after this.
*/
if (this.debug) {
console.error(e);
}
sock.emit('sendResponse', new Error('Cannot parse'));
break;
}
}
});
sock.addListener('sendResponse', (data: RespType) => {
// Send the serialized data to the client
const str = this.serializer.serialize(data, true);
sock.write(str);
});
});
}
private handleRequests(sock: net.Socket, data: Array<string>) {
try {
const command = data[0];
switch (command) {
case RedisCommands.PING:
this.handlePing(sock, data);
break;
case RedisCommands.ECHO:
this.handleEcho(sock, data);
break;
case RedisCommands.SET:
this.handleSet(sock, data);
break;
case RedisCommands.GET:
this.handleGet(sock, data);
break;
case RedisCommands.DEL:
this.handleDelete(sock, data);
break;
default:
throw new Error(`UNKNOWN_COMMAND: ${command}`);
}
} catch (e) {
if (e instanceof Error && this.debug) {
console.error(e.message);
}
}
}
private handlePing(sock: net.Socket, data: Array<string>) {
if (data === null) {
throw new Error('PING: Invalid data');
}
let response = 'PONG';
const message = data[1];
if (message !== undefined) {
response = message;
}
sock.emit('sendResponse', response);
}
private handleEcho(sock: net.Socket, data: Array<string>) {
sock.emit('sendResponse', data[1]);
}
private handleSet(sock: net.Socket, data: Array<string>) {
const key = data[1];
const value = data[2];
this.map.set(key, value);
sock.emit('sendResponse', 'OK');
}
private handleGet(sock: net.Socket, data: Array<string>) {
const key = data[1];
const response = this.map.get(key) ?? null;
if (typeof response !== 'string') {
throw new Error(`INVALID type of value ${typeof response}`);
}
sock.emit('sendResponse', response);
}
private handleDelete(sock: net.Socket, data: Array<string>) {
const key = data[1];
const response = this.map.delete(key) ? 1 : 0;
sock.emit('sendResponse', response);
}
stopServer(): Promise<void> {
return new Promise<void>((res) => {
// Close all the sockets first
this.sockets.forEach((sock) => {
sock.destroy();
});
// On 'close' event, resolve the Promise
this.server.on('close', () => {
if (this.debug) {
console.log('Redis server stopped listening on port ' + this.port);
}
res();
});
// Close the server
this.server?.close();
});
}
}