-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisDatastore.h
More file actions
299 lines (259 loc) · 8.25 KB
/
RedisDatastore.h
File metadata and controls
299 lines (259 loc) · 8.25 KB
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
/**
* @file RedisDatastore.h
* @author Atakan S.
* @version 1.0
* @brief Redis Datastore connector, concrete class.
*
* @copyright Copyright (c) 2020 Atakan SARIOGLU ~ www.atakansarioglu.com
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef _H_REDISDATASTORE_H_
#define _H_REDISDATASTORE_H_
#include "IDatastore.h"
#include <cpp_redis/cpp_redis>
#include <string>
#include <chrono>
class RedisDatastore : public IDatastore
{
private:
std::string m_endpoint;
int m_port;
std::string m_credentials;
cpp_redis::client m_client;
std::chrono::duration<double> m_commitTimeout;
public:
/*
* @brief Constructor for Redis connector.
* @param endpoint Endpoint address.
* @param port Port number of Redis.
* @param credentials Database password.
* @param timeout Time to wait for a request.
*/
RedisDatastore(const std::string &endpoint, const int port, const std::string &credentials, const double timeout = 1.0)
: m_endpoint(endpoint), m_port(port), m_credentials(credentials), m_commitTimeout(timeout) {}
/*
* @brief Connect to Redis
* @return True on success.
*/
bool Connect()
{
if (IsConnected())
{
return true;
}
// Connect to Redis.
m_client.connect(m_endpoint, m_port);
// Authenticate using the provided credentials.
m_client.auth(m_credentials);
// Return the connection state.
return IsConnected();
}
/*
* @brief Disconnect from Redis
* @return True on success.
*/
bool Disconnect()
{
// Disconnect.
m_client.disconnect();
return true;
}
/*
* @brief Get connection state.
* @return True if connected.
*/
bool IsConnected() const
{
// Return the connection state.
return m_client.is_connected();
}
/*
* @brief Generate Unique Increasing ID Number
* @return Non-negative unique ID on success, -1 on error.
*/
int GetUniqueNumber()
{
if (!IsConnected())
{
return -1;
}
// Increment and get the value on Redis.
auto request = m_client.incr("uniqueNumber");
m_client.sync_commit(m_commitTimeout);
auto response = request.get();
if (response.ok() && response.is_integer())
{
// Success.
return response.as_integer();
}
// Failure.
return -1;
}
/*
* @brief Adds tweet to Redis memory cache.
* @param userId
* @param tweetAsString Serialized tweet object.
* @param maxTweets Keep no more than this number on datastore, -1 for unlimited.
* @return True on success.
*/
bool AddTweet(const int userId, const std::string &tweetAsString, int maxTweets = 10)
{
if (!IsConnected())
{
return false;
}
// Push the new tweet to the corresponding users tweets list.
auto request1 = m_client.lpush("tweets:" + std::to_string(userId), {tweetAsString});
if(maxTweets > 0) {
auto request2 = m_client.ltrim("tweets:" + std::to_string(userId), 0, maxTweets - 1);
}
// Commit.
m_client.sync_commit(m_commitTimeout);
// Return.
return request1.get().ok();
}
/*
* @brief Get recent tweets of all followed users.
* @param userIdVector users to fetch the recent tweets.
* @param tweets Output vector for fetched tweets.
* @param numberOfTweets Number of tweets for each user, -1 for all tweets.
* @return True on success.
*/
bool GetRecentTweets(const std::vector<int> &userIdVector,
std::vector<std::string> &tweets, int numberOfTweets = -1)
{
if (!IsConnected())
{
return false;
}
// Issue all requests in a loop.
std::vector<std::future<cpp_redis::reply>> requestVector;
for (auto userId : userIdVector)
{
// Get left items of Redis List object.
requestVector.push_back(m_client.lrange("tweets:" + std::to_string(userId),
0, (numberOfTweets == -1) ? -1 : numberOfTweets - 1));
}
// Commit once.
m_client.sync_commit(m_commitTimeout);
// Add the returned tweets to the output vector.
for (auto &request : requestVector)
{
auto response = request.get();
if (response.ok() == false || response.is_array() == false)
{
return false;
}
for (const auto &element : response.as_array())
{
tweets.push_back(element.as_string());
}
}
// Return.
return true;
}
/*
* @brief Get followed users of userId.
* @param userId users to fetch the recent tweets.
* @param followees Output vector for followees.
* @return True on success.
*/
bool GetFollowees(const int userId, std::vector<int> &followees)
{
if (!IsConnected())
{
return false;
}
// Get all members of Redis Hash Set object.
auto request = m_client.smembers("followees:" + std::to_string(userId));
// Commit.
m_client.sync_commit(m_commitTimeout);
// Check the response.
auto response = request.get();
if (response.ok() == false || response.is_array() == false)
{
return false;
}
// Cast the returned strings into integer and push to output vector.
for (const auto &element : response.as_array())
{
try
{
int followeeId = std::stoi(element.as_string());
followees.push_back(followeeId);
}
catch (...)
{
return false;
}
}
// Return.
return true;
}
/*
* @brief Create userId->followeeId record.
* @param userId follower
* @param followeeId followee
* @return True on success.
*/
bool AddFollowee(const int userId, const int followeeId)
{
if (!IsConnected())
{
return false;
}
// Add to Hash Set.
auto request = m_client.sadd("followees:" + std::to_string(userId), {std::to_string(followeeId)});
// Commit.
m_client.sync_commit(m_commitTimeout);
// Return the result.
return request.get().ok();
}
/*
* @brief Remove userId->followeeId record.
* @param userId follower
* @param followeeId followee
* @return True on success.
*/
bool DelFollowee(const int userId, const int followeeId)
{
if (!IsConnected())
{
return false;
}
// Remove from Hash Set.
auto request = m_client.srem("followees:" + std::to_string(userId), {std::to_string(followeeId)});
// Commit.
m_client.sync_commit(m_commitTimeout);
// Return the result.
return request.get().ok();
}
/*
* @brief Destructor. Disconnect if necessary.
*/
~RedisDatastore()
{
if (!IsConnected())
{
Disconnect();
}
}
};
#endif