-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathRedis.mqh
340 lines (284 loc) · 9.25 KB
/
Redis.mqh
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
//+------------------------------------------------------------------+
//| EA31337 framework |
//| Copyright 2016-2021, EA31337 Ltd |
//| https://github.com/EA31337 |
//+------------------------------------------------------------------+
/*
* This file is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* @file
* Implements class for storing/retrieving Redis database data.
*/
#include "Dict.mqh"
#include "Object.mqh"
#include "Redis.struct.h"
#include "Serializer.mqh"
#include "SerializerConversions.h"
#include "SerializerJson.mqh"
#include "Socket.mqh"
enum ENUM_REDIS_VALUE_SET { REDIS_VALUE_SET_ALWAYS, REDIS_VALUE_SET_IF_NOT_EXIST, REDIS_VALUE_SET_IF_ALREADY_EXIST };
typedef void (*RedisCallback)(string);
/**
* Redis queue for simulation.
*/
class RedisQueue {
protected:
// Messages queue for simulation purposes.
string _queue[];
// Current message index to be processed. Set to 0 if all messages have been popped out.
int _queue_index;
public:
/**
* Constructor.
*/
RedisQueue() { _queue_index = 0; }
/**
* Enqueues a single messange on the queue.
*/
void Enqueue(RedisMessage& message) { Enqueue(message.ToString()); }
/**
* Enqueues a single messange on the queue.
*/
void Enqueue(string message) {
ArrayResize(_queue, ArraySize(_queue) + 1, 10);
_queue[ArraySize(_queue) - 1] = message;
}
/**
* Checks whether there are any awaiting message to be processed.
*/
bool HasData() { return ArraySize(_queue) > 0; }
/**
* Clears message queue.
*/
void Clear() { ArrayResize(_queue, 0); }
/**
* Pops out the oldest added message and clears the queue if all messages are popped out.
*/
RedisMessage PopFirst() {
string result = _queue[_queue_index++];
if (_queue_index >= ArraySize(_queue)) {
// Popped last item.
ArrayResize(_queue, 0);
_queue_index = 0;
#ifdef __debug__
Print("Redis Queue Cleared!");
#endif
}
RedisMessage msg;
msg.FromString(result);
return msg;
}
};
/**
* Redis class.
*/
class Redis : public Object {
protected:
Socket _socket;
// List of messages sent by server back to client.
RedisQueue _messages;
// List of client channels subscriptions.
Dict<string, bool> _subscriptions;
// Whether Redis is simualting being both, the client & the server.
bool _simulate;
public:
/**
* Constructor.
*/
Redis(const string address = "127.0.0.1", const int port = 6379, bool simulate = false) {
_simulate = simulate;
if (!simulate) {
Connect(address, port);
}
}
/**
* Constructor.
*/
Redis(bool simulate) {
_simulate = simulate;
if (!simulate) {
Connect("127.0.0.1", 6379);
}
}
/**
* Connects to Redis socket.
*/
bool Connect(const string address = "127.0.0.1", const int port = 6379) { return _socket.Connect(address, port); }
/**
* Returns list of messages sent by server back to client.
*/
RedisQueue* Messages() { return &_messages; }
/**
* Parses server's command such as SUBSCRIBE, UNSUBSCRIBE.
*/
string ParseCommand(string command) {
StringTrimLeft(command);
StringTrimRight(command);
string command_name = StringSubstr(command, 0, StringFind(command, " "));
string command_args = StringSubstr(command, StringLen(command_name) + 1);
if (command_name == "SUBSCRIBE") {
string subscriptions[];
StringSplit(command_args, ' ', subscriptions);
for (int i = 0; i < ArraySize(subscriptions); ++i) {
_subscriptions.Set(subscriptions[i], true);
}
return "OK";
}
return "UNKNOWN COMMAND!";
}
/**
* Checks whether we are simulating Redis client/server.
*/
bool Simulated() { return _simulate; }
/**
* Checks whether Redis channel has been subscribed. Only works in simulation mode.
*/
bool Subscribed(string channel) { return _subscriptions.KeyExists(channel); }
/**
* Ping and returns whether pong was received back.
*/
bool Ping() { return Command("PING") == "PONG"; }
/**
* Set string-based variable.
*/
bool SetString(string _key, string _value, unsigned int _expiration_ms = 0,
ENUM_REDIS_VALUE_SET _set_type = REDIS_VALUE_SET_ALWAYS) {
string _command = "SET " + SerializerConversions::ValueToString(_key, true) + " " +
SerializerConversions::ValueToString(_value, true);
if (_expiration_ms != 0) {
_command += " PX " + IntegerToString(_expiration_ms);
}
switch (_set_type) {
case REDIS_VALUE_SET_ALWAYS:
break;
case REDIS_VALUE_SET_IF_NOT_EXIST:
_command += " NX";
break;
case REDIS_VALUE_SET_IF_ALREADY_EXIST:
_command += " XX";
break;
}
return Command(_command) == "OK";
}
/**
* Returns string-based variable, default value or NULL.
*/
string GetString(const string _key, string _default = NULL) {
string result = Command("GET " + SerializerConversions::ValueToString(_key, true));
if (result == NULL) return _default;
return result;
}
/**
* Increments integer-based value by given amount.
*/
bool Increment(const string _key, const int _value = 1) {
if (_value > 0) {
return Command("INCRBY " + SerializerConversions::ValueToString(_key, true) + " " + IntegerToString(_value)) !=
NULL;
} else if (_value < 0) {
return Command("DECRBY " + SerializerConversions::ValueToString(_key, true) + " " + IntegerToString(-_value)) !=
NULL;
}
// _value was 0. Nothing to do.
return true;
}
/**
* Increments float-based value by given amount.
*/
bool Increment(const string _key, const float _value = 1.0f) {
if (_value > 0.0f) {
return Command("INCRBYFLOAT " + SerializerConversions::ValueToString(_key, true) + " " +
DoubleToString(_value)) != NULL;
} else if (_value < 0.0f) {
return Command("DECRBYFLOAT " + SerializerConversions::ValueToString(_key, true) + " " +
DoubleToString(_value)) != NULL;
}
// _value was 0. Nothing to do.
return true;
}
/**
* Decrements integer-based value by given amount.
*/
bool Decrement(const string _key, const int _value = 1) { return Increment(_key, -_value); }
/**
* Decrements float-based value by given amount.
*/
bool Decrement(const string _key, const float _value = 1.0f) { return Increment(_key, -_value); }
/**
* Deletes variable by given key.
*/
bool Delete(const string _key) { return Command("DEL " + SerializerConversions::ValueToString(_key, true)) != NULL; }
/**
* Subscribes to string-based values on the given channels (separated by space).
*
* After subscribe, please use TryReadString() in the loop to retrieve values.
*/
bool Subscribe(const string _channel_list) { return Command("SUBSCRIBE " + _channel_list) != NULL; }
/**
* Unsubscribes from the given channels (separated by space).
*/
bool Unsubscribe(const string _channel_list) { return Command("UNSUBSCRIBE " + _channel_list) != NULL; }
/**
* Publishes string-based value on the given channel (channel must be previously subscribed).
*/
bool Publish(const string _channel, const string _value) {
return Command("PUBLISH " + _channel + " " + SerializerConversions::ValueToString(_value, true)) != NULL;
}
/**
* Checks whether there is any data waiting on the Redis socket to be read.
*/
bool HasData() { return _messages.HasData() || _socket.HasData(); }
/**
* Executes Redis command on the given socket.
*/
string Command(const string _command) {
if (_simulate) {
return ParseCommand(_command);
}
_socket.EnsureConnected();
_socket.Send(_command + "\n");
string _response = _socket.ReadString();
string _header = StringSubstr(_response, 0, StringFind(_response, "\r\n"));
if (StringSubstr(_header, 0, 1) == "+") {
// A tiny response.
_response = StringSubstr(_header, 1);
} else {
if (_header == "$-1" || StringSubstr(_header, 0, 1) == "-") {
// No response or error happened.
return NULL;
}
_response = StringSubstr(_response, StringFind(_response, "\r\n") + 2);
_response = StringSubstr(_response, 0, StringLen(_response) - 2);
}
return _response;
}
/**
* Reads a single string from subscribed channels.
*/
RedisMessage ReadMessage() {
if (_messages.HasData()) {
// Retrieving message from queue.
return _messages.PopFirst();
}
RedisMessage msg;
if (_socket.HasData()) {
msg.FromString(_socket.ReadString());
return msg;
}
// Empty message.
return msg;
}
};