-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessageCenter.h
572 lines (480 loc) · 17 KB
/
MessageCenter.h
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
#ifndef MESSAGE_CENTER_H
#define MESSAGE_CENTER_H
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <chrono>
#include <unordered_map>
#include <thread>
#include <utility>
#include <cstdlib>
#include <mutex>
#include "json.hpp"
using json = nlohmann::json;
/*
* Variadic template for pushing arguments onto a JSON array
*/
template<typename T>
void concatArgs(json &holder, T t) {
holder.push_back(t);
}
template<typename T, typename... Args>
void concatArgs(json &holder, T t, Args... rest)
{
holder.push_back(t);
concatArgs(holder, rest...);
}
/*
* C++ adapter to bits-ipc message center
*/
class MessageCenter {
//////////////////////////////////////////////////////////////////////////
// Typedefs
public:
typedef std::function<void(const json&)> EventCallback;
typedef std::function<json(const json&)> RequestListener;
typedef std::string EventIdentifier;
typedef std::string RequestIdentifier;
//////////////////////////////////////////////////////////////////////////
// Public Methods
public:
MessageCenter() : MessageCenter("") {}
/**
* MessageCenter constructor
*/
MessageCenter(const std::string &socket_path) :
_socket_path(socket_path),
_fd(0),
_stopEvent(false)
{
std::srand(std::time(0));
_requestId = std::abs(std::rand());
}
/**
* MessageCenter destructor
*/
~MessageCenter() {
_stopEvent = true;
stop();
}
/**
* Start the MessageCenter.
*
* @async - if async is false no background threads will be created,
* you will be required to call dispatchMessages() periodically for
* the MessageCenter to work correctly.
*/
bool start(bool async=true) {
if (_socket_path.size() == 0) {
return false;
}
// Create the socket and connect to the BITS server
if ( (_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket error");
exit(-1);
}
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, _socket_path.c_str(), sizeof(addr.sun_path)-1);
if (connect(_fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
perror("connect error");
return false;
}
// Set socket RCV timeout to one second
struct timeval tv;
tv.tv_sec = 1;
setsockopt(_fd, SOL_SOCKET, SO_RCVTIMEO, (struct timeval *)&tv, sizeof(struct timeval));
if (async) {
// Start thread to read incoming messages
_readThread = _spawn();
}
return true;
}
/**
* Stop the MessageCenter background thread.
*/
void stop() {
_readThread.join();
}
/**
* Read up to 'max' messages.
*
* TODO - add timeout, requires nonblock get() timeout support
*/
void dispatchMessages(const size_t max=0) {
size_t nReceived = 0;
while (!_stopEvent) {
// Read the next data segment
std::string data = _get();
if (data.size() > 0) {
// Attempt to parse it
try {
json msg = json::parse(data);
++nReceived;
if (msg["data"]["type"] == "event") {
this->_handleEvent(msg["data"]);
} else if (msg["data"]["type"] == "response") {
this->_handleResponse(msg["data"]);
} else if (msg["data"]["type"] == "request") {
this->_handleRequest(msg["data"]);
}
} catch(...) {
continue;
}
if (max > 0 && nReceived >= max) {
break;
}
}
}
}
/**
* Send a request BITS using the default scope
*/
template<typename... Args>
json sendRequest(const std::string &request, Args... args) {
return sendRequest(request, {}, args...);
}
/**
* Send an request to BITS with no args
*/
template<typename... Args>
json sendRequest(const std::string &request, const std::vector<std::string> scopes) {
std::string requestId = _getRequestId();
json msg;
msg["type"] = "bits-ipc";
msg["data"] = {};
msg["data"]["type"] = "request";
msg["data"]["event"] = request;
msg["data"]["requestId"] = requestId;
msg["data"]["params"] = { };
if (scopes.size() == 0) {
msg["data"]["params"].push_back( { { "scope", nullptr } } );
} else if (scopes.size() == 1) {
msg["data"]["params"].push_back( { { "scopes", { scopes[0] } } } );
} else {
msg["data"]["params"].push_back( { { "scopes", scopes } } );
}
this->_send(msg.dump());
std::mutex _resp_mutex;
json resp;
this->_addReponseListener(requestId, scopes, [&](const json &msg) {
std::lock_guard<std::mutex> lock(_resp_mutex);
resp = msg;
});
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
{
std::lock_guard<std::mutex> lock(_resp_mutex);
if (!resp.is_null()) {
break;
}
}
}
return resp;
}
/**
* Send a request to BITS
*/
template<typename... Args>
json sendRequest(
const std::string &request,
const std::vector<std::string> scopes,
Args... args
) {
std::string requestId = _getRequestId();
json msg;
msg["type"] = "bits-ipc";
msg["data"] = {};
msg["data"]["type"] = "request";
msg["data"]["event"] = request;
msg["data"]["requestId"] = requestId;
msg["data"]["params"] = { };
if (scopes.size() == 0) {
msg["data"]["params"].push_back( { { "scope", nullptr } } );
} else if (scopes.size() == 1) {
msg["data"]["params"].push_back( { { "scopes", { scopes[0] } } } );
} else {
msg["data"]["params"].push_back( { { "scopes", scopes } } );
}
concatArgs(msg["data"]["params"], args...);
this->_send(msg.dump());
std::mutex _resp_mutex;
json resp;
this->_addReponseListener(requestId, scopes, [&](const json &msg) {
std::lock_guard<std::mutex> lock(_resp_mutex);
resp = msg;
});
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
{
std::lock_guard<std::mutex> lock(_resp_mutex);
if (!resp.is_null()) {
break;
}
}
}
return resp;
}
/**
* Send an event to BITS using the default scope.
*/
template<typename... Args>
bool sendEvent(const std::string &event, Args... args) {
return sendEvent(event, {}, args...);
}
/**
* Send an event to BITS with no args
*/
template<typename... Args>
bool sendEvent(const std::string &event, const std::vector<std::string> scopes) {
json msg;
msg["type"] = "bits-ipc";
msg["data"] = {};
msg["data"]["type"] = "event";
msg["data"]["event"] = event;
msg["data"]["params"] = { };
if (scopes.size() == 0) {
msg["data"]["params"].push_back( { { "scope", nullptr } } );
} else if (scopes.size() == 1) {
msg["data"]["params"].push_back( { { "scopes", { scopes[0] } } } );
} else {
msg["data"]["params"].push_back( { { "scopes", scopes } } );
}
return this->_send(msg.dump());
}
/**
* Send an event to BITS
*/
template<typename... Args>
bool sendEvent(
const std::string &event,
const std::vector<std::string> scopes,
Args... args
) {
json msg;
msg["type"] = "bits-ipc";
msg["data"] = {};
msg["data"]["type"] = "event";
msg["data"]["event"] = event;
msg["data"]["params"] = { };
if (scopes.size() == 0) {
msg["data"]["params"].push_back( { { "scope", nullptr } } );
} else if (scopes.size() == 1) {
msg["data"]["params"].push_back( { { "scopes", { scopes[0] } } } );
} else {
msg["data"]["params"].push_back( { { "scopes", scopes } } );
}
concatArgs(msg["data"]["params"], args...);
return this->_send(msg.dump());
}
/**
* Register with BITS to receive events on the default scope.
*/
void addEventListener(const std::string &event, const EventCallback &cb) {
addEventListener(event, {}, cb);
}
/**
* Register with BITS to receive events.
*/
void addEventListener(
const std::string &event,
const std::vector<std::string> &scopes,
const EventCallback &cb
) {
_eventListeners[event].push_back(cb);
json msg;
msg["type"] = "bits-ipc";
msg["data"] = {};
msg["data"]["type"] = "addEventListener";
msg["data"]["event"] = event;
msg["data"]["params"] = { };
if (scopes.size() == 0) {
msg["data"]["params"].push_back( { { "scopes", nullptr } } );
} else if (scopes.size() == 1) {
msg["data"]["params"].push_back( { { "scopes", scopes[0] } } );
} else {
msg["data"]["params"].push_back( { { "scopes", scopes } } );
}
this->_send(msg.dump());
}
/**
* Register with BITS to handle requests on the default scope
*/
void addRequestListener(
const std::string &event,
const RequestListener &cb
) {
addRequestListener(event, {}, cb);
}
/**
* Register with BITS to handle requests on the default scope
*/
void addRequestListener(
const std::string &event,
const std::vector<std::string> &scopes,
const RequestListener &cb
) {
_requestListeners[event] = cb;
json msg;
msg["type"] = "bits-ipc";
msg["data"] = {};
msg["data"]["type"] = "addRequestListener";
msg["data"]["event"] = event;
msg["data"]["params"] = { };
if (scopes.size() == 0) {
msg["data"]["params"].push_back( { { "scopes", nullptr } } );
} else if (scopes.size() == 1) {
msg["data"]["params"].push_back( { { "scopes", { scopes[0] } } } );
} else {
msg["data"]["params"].push_back( { { "scopes", scopes } } );
}
this->_send(msg.dump());
}
//////////////////////////////////////////////////////////////////////////
// Internal Methods & Variables
private:
// the delimiter used by node-ipc
const char* DELIMITER = "\f";
// private member variables
std::string _socket_path;
int _fd;
unsigned int _requestId;
std::thread _readThread;
bool _stopEvent;
// Thread-lock mutex for protected members
std::mutex _fd_wr_mutex;
std::mutex _fd_rd_mutex;
std::mutex _requestId_mutex;
// Listeners and handlers
std::unordered_map< EventIdentifier, std::vector<EventCallback> > _eventListeners;
std::unordered_map< RequestIdentifier, EventCallback > _responseListeners;
std::unordered_map< EventIdentifier, RequestListener > _requestListeners;
/**
* Send a message on the socket, conforming to
* node-ipc by adding a \f delimiter
*/
bool _send(const std::string &msg) {
std::lock_guard<std::mutex> lock(_fd_wr_mutex);
if (_fd == 0) {
return false;
}
if (write(_fd, msg.c_str(), msg.size()) != msg.size()) {
return false;
}
if (write(_fd, DELIMITER, strlen(DELIMITER)) != 1) {
return false;
}
return true;
}
/**
* Get the next message from the socket
*/
std::string _get() {
std::lock_guard<std::mutex> lock(_fd_rd_mutex);
static std::string _buffer;
char buf[1024];
ssize_t rc;
size_t idx;
while ( (rc = read(_fd, buf, sizeof(buf)-1)) > 0) {
if (_stopEvent) {
return "";
}
// Null terminate the string
buf[rc] = '\0';
// Append to the buffer
_buffer.append(buf);
// Find the delimiter
if ((idx = _buffer.find_first_of("\f")) != std::string::npos) {
// Extract the message
std::string msg = _buffer.substr(0, idx);
// Delete the message from the buffer
_buffer.erase(0, idx+1);
return msg;
}
}
return "";
}
/**
* Spawns the dispatchMessage in a loop.
*/
std::thread _spawn() {
return std::thread( [this] { this->dispatchMessages(); } );
}
/**
* Get the next requestId
*/
std::string _getRequestId() {
std::lock_guard<std::mutex> lock(_requestId_mutex);
return std::to_string(_requestId++);
}
/**
* Add a response listener for the defined requestId
*/
void _addReponseListener(
const std::string &requestId,
const std::vector<std::string> &scopes,
const EventCallback &cb
) {
// TODO behaviour if requestId already is in the list
_responseListeners[requestId] = cb;
}
/**
* Handle an incoming event, passing it to the eventListeners
*/
void _handleEvent(const json &msg) {
std::string event = msg["event"];
auto callbacks = _eventListeners.find(event);
if (callbacks != _eventListeners.end()) {
for (auto &&cb : callbacks->second) {
cb(msg["params"]);
}
}
}
/**
* Handle an incoming response, passing it to the responseListener
*/
void _handleResponse(const json &msg) {
std::string responseId = msg["responseId"];
auto callback = _responseListeners.find(responseId);
if (callback != _responseListeners.end()) {
callback->second(msg["result"]);
}
}
/**
* Handle an incoming request, passing it to the requestListener
*/
void _handleRequest(const json &msg) {
std::string event = msg["event"];
auto requestId = msg["requestId"];
auto callback = _requestListeners.find(event);
if (callback != _requestListeners.end()) {
json result = callback->second(msg["params"]);
json resp;
resp["type"] = "bits-ipc";
resp["data"] = {};
resp["data"]["type"] = "response";
resp["data"]["event"] = event;
resp["data"]["responseId"] = requestId;
resp["data"]["params"] = { };
resp["data"]["params"].push_back(result);
this->_send(resp.dump());
}
}
/**
* Prevent copy
*/
MessageCenter(const MessageCenter& other) {
}
/**
* Prevent assignment
*/
MessageCenter& operator=(MessageCenter) {
return *this;
}
};
#endif