-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnatsclient.h
640 lines (506 loc) · 18.5 KB
/
natsclient.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
#ifndef NATSCLIENT_H
#define NATSCLIENT_H
#include <QHash>
#include <QJsonDocument>
#include <QJsonObject>
#include <QObject>
#include <QProcessEnvironment>
#include <QSslConfiguration>
#include <QSslSocket>
#include <QStringBuilder>
#include <QUuid>
#include <QTextCodec>
#include <QtNetwork>
#include <memory>
namespace Nats {
#define DEBUG(x) do { if (_debug_mode) { qDebug() << x; } } while (0)
//! main callback message
using MessageCallback = std::function < void(QString && message, QString
&& inbox, QString && subject) >;
using ConnectCallback = std::function<void()>;
//!
//! \brief The Options struct
//! holds all client options
struct Options {
bool verbose = false;
bool pedantic = false;
bool ssl_required = false;
bool ssl = false;
bool ssl_verify = true;
QString ssl_key;
QString ssl_cert;
QString ssl_ca;
QString name = "qt-nats";
const QString lang = "cpp";
const QString version = "1.0.0";
QString user;
QString pass;
QString token;
};
//!
//! \brief The Subscription class
//! holds subscription data and emits signal when ready as alternative to callbacks
class Subscription : public QObject {
Q_OBJECT
public:
explicit Subscription(QObject *parent = nullptr): QObject(parent) {}
QString subject;
QString message;
QString inbox;
int padding; //qt告警,让填充四字节
uint64_t ssid = 0;
signals:
void received();
};
//!
//! \brief The Client class
//! main client class
class Client : public QObject {
Q_OBJECT
public:
explicit Client(QObject *parent = nullptr);
//!
//! \brief publish
//! \param subject
//! \param message
//! publish given message with subject
void publish(const QString &subject, const QString &message,
const QString &inbox);
void publish(const QString &subject, const QString &message = "");
//!
//! \brief subscribe
//! \param subject
//! \param callback
//! \return subscription id
//! subscribe to given subject
//! when message is received, callback is fired
uint64_t subscribe(const QString &subject, MessageCallback callback);
//!
//! \brief subscribe
//! \param subject
//! \param queue
//! \param callback
//! \return subscription id
//! overloaded function
//! subscribe to given subject and queue
//! when message is received, callback is fired
//! each message will be delivered to only one subscriber per queue group
uint64_t subscribe(const QString &subject, const QString &queue,
MessageCallback callback);
//!
//! \brief subscribe
//! \param subject
//! \return
//! return subscription class holding result for signal/slot version
Subscription *subscribe(const QString &subject);
//!
//! \brief unsubscribe
//! \param ssid
//! \param max_messages
//!
void unsubscribe(uint64_t ssid, int max_messages = 0);
//!
//! \brief request
//! \param subject
//! \param message
//! \return
//! make request using given subject and optional message
uint64_t request(const QString subject, const QString message,
MessageCallback callback);
uint64_t request(const QString subject, MessageCallback callback);
//!
//! \brief debug
//! \param debug mode value
//! \return
//! set debug mode
void setdebugmode(bool mode = false);
//!
//! \brief is connect
//! \param
//! \return true if open,else false
//! determine whether connect is isValid
bool isOpen();
signals:
//!
//! \brief connected
//! signal that the client is connected
void connected();
//!
//! \brief connected
//! signal that the client is connected
void error(const QString);
//!
//! \brief disconnected
//! signal that the client is disconnected
void disconnected();
public slots:
//!
//! \brief connect
//! \param host
//! \param port
//! connect to server with given host and port options
//! after valid connection is established 'connected' signal is emmited
void connect(const QString &host = "127.0.0.1", quint16 port = 4222,
ConnectCallback callback = nullptr);
void connect(const QString &host, quint16 port, const Options &options,
ConnectCallback callback = nullptr);
//!
//! \brief disconnect
//! disconnect from server by closing socket
void disconnect();
//!
//! \brief connectSync
//! \param host
//! \param port
//! synchronous version of connect, waits until connections with nats server is valid
//! this will still fire 'connected' signal if one wants to use that instead
bool connectSync(const QString &host = "127.0.0.1", quint16 port = 4222);
bool connectSync(const QString &host, quint16 port, const Options &options);
private:
//!
//! \brief debug_mode
//! extra debug output, can be set with enviroment variable DEBUG=qt-nats
bool _debug_mode = false;
//!
//! \brief CLRF
//! NATS protocol separator
const QString CLRF = "\r\n";
//!
//! \brief m_buffer
//! main buffer that holds data from server
QByteArray m_buffer;
//!
//! \brief m_ssid
//! subscribtion id holder
uint64_t m_ssid = 0;
//!
//! \brief m_socket
//! main tcp socket
QSslSocket m_socket;
//!
//! \brief m_options
//! client options
Options m_options;
//!
//! \brief m_callbacks
//! subscription callbacks
QHash<uint64_t, MessageCallback> m_callbacks;
//!
//! \brief send_info
//! \param options
//! send client information and options to server
void send_info(const Options &options);
//!
//! \brief parse_info
//! \param message
//! \return
//! parse INFO message from server and return json object with data
QJsonObject parse_info(const QByteArray &message);
//!
//! \brief set_listeners
//! set connection listeners
void set_listeners();
//!
//! \brief process_inboud
//! \param buffer
//! process messages from buffer
bool process_inboud(const QByteArray &buffer);
};
inline Client::Client(QObject *parent) : QObject(parent) {
//QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
//_debug_mode = (env.value(QStringLiteral("DEBUG")).indexOf("qt-nats") != -1);
if(_debug_mode)
DEBUG("debug mode");
// 报错the proxy type is invalid for this operation,去掉代理
m_socket.setProxy(QNetworkProxy::NoProxy);
}
inline void Client::connect(const QString &host, quint16 port,
ConnectCallback callback) {
connect(host, port, m_options, callback);
}
inline void Client::connect(const QString &host, quint16 port,
const Options &options, ConnectCallback callback) {
// Check is client socket is already connected and return if it is
if(m_socket.isOpen())
return;
QObject::connect(&m_socket,
static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>
(&QAbstractSocket::error), [this](QAbstractSocket::SocketError socketError) {
DEBUG(socketError);
emit error(m_socket.errorString());
});
QObject::connect(&m_socket,
static_cast<void(QSslSocket::*)(const QList<QSslError> &)>
(&QSslSocket::sslErrors), [this](const QList<QSslError> &errors) {
DEBUG(errors);
emit error(m_socket.errorString());
});
QObject::connect(&m_socket, &QSslSocket::encrypted, [this, options, callback] {
DEBUG("SSL/TLS successful");
send_info(options);
set_listeners();
if(callback)
callback();
emit connected();
});
QObject::connect(&m_socket, &QSslSocket::disconnected, [this]() {
DEBUG("socket disconnected");
emit disconnected();
// Disconnect everything connected to an m_socket's signals
QObject::disconnect(&m_socket, nullptr, nullptr, nullptr);
});
// receive first info message and disconnect
auto signal = std::make_shared<QMetaObject::Connection>();
*signal = QObject::connect(&m_socket, &QSslSocket::readyRead, [this, signal,
options, callback] {
QObject::disconnect(*signal);
QByteArray info_message = m_socket.readAll();
QJsonObject json = parse_info(info_message);
bool ssl_required = json.value(QStringLiteral("ssl_required")).toBool();
// if client or server wants ssl start encryption
if(options.ssl || options.ssl_required || ssl_required) {
DEBUG("starting SSL/TLS encryption");
if(!options.ssl_verify)
m_socket.setPeerVerifyMode(QSslSocket::VerifyNone);
if(!options.ssl_ca.isEmpty()) {
QSslConfiguration config = m_socket.sslConfiguration();
config.setCaCertificates(QSslCertificate::fromPath(options.ssl_ca));
}
if(!options.ssl_key.isEmpty())
m_socket.setPrivateKey(options.ssl_key);
if(!options.ssl_cert.isEmpty())
m_socket.setLocalCertificate(options.ssl_cert);
m_socket.startClientEncryption();
} else {
send_info(options);
set_listeners();
if(callback)
callback();
emit connected();
}
});
DEBUG("connect started" << host << port);
m_socket.connectToHost(host, port);
}
inline void Client::disconnect() {
m_socket.flush();
m_socket.close();
}
inline bool Client::connectSync(const QString &host, quint16 port) {
return connectSync(host, port, m_options);
}
inline bool Client::connectSync(const QString &host, quint16 port,
const Options &options) {
QObject::connect(&m_socket,
static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>
(&QAbstractSocket::error), [this](QAbstractSocket::SocketError socketError) {
DEBUG(socketError);
emit error(m_socket.errorString());
});
m_socket.connectToHost(host, port);
if(!m_socket.waitForConnected())
return false;
if(!m_socket.waitForReadyRead())
return false;
// receive first info message
auto info_message = m_socket.readAll();
QJsonObject json = parse_info(info_message);
bool ssl_required = json.value(QStringLiteral("ssl_required")).toBool();
// if client or server wants ssl start encryption
if(options.ssl || options.ssl_required || ssl_required) {
DEBUG("starting SSL/TLS encryption");
if(!options.ssl_verify)
m_socket.setPeerVerifyMode(QSslSocket::VerifyNone);
if(!options.ssl_ca.isEmpty()) {
QSslConfiguration config = m_socket.sslConfiguration();
config.setCaCertificates(QSslCertificate::fromPath(options.ssl_ca));
}
if(!options.ssl_key.isEmpty())
m_socket.setPrivateKey(options.ssl_key);
if(!options.ssl_cert.isEmpty())
m_socket.setLocalCertificate(options.ssl_cert);
m_socket.startClientEncryption();
if(!m_socket.waitForEncrypted())
return false;
}
send_info(options);
set_listeners();
emit connected();
return true;
}
inline void Client::send_info(const Options &options) {
QString message =
QString("CONNECT {")
% "\"verbose\":" % (options.verbose ? "true" : "false") % ","
% "\"pedantic\":" % (options.pedantic ? "true" : "false") % ","
% "\"ssl_required\":" % (options.ssl_required ? "true" : "false") % ","
% "\"name\":" % "\"" % options.name % "\","
% "\"lang\":" % "\"" % options.lang % "\","
% "\"user\":" % "\"" % options.user % "\","
% "\"pass\":" % "\"" % options.pass % "\","
% "\"auth_token\":" % "\"" % options.token % "\""
% "} " % CLRF;
DEBUG("send info message:" << message);
m_socket.write(message.toUtf8());
}
inline QJsonObject Client::parse_info(const QByteArray &message) {
DEBUG(message);
// discard 'INFO '
return QJsonDocument::fromJson(message.mid(5)).object();
}
inline void Client::publish(const QString &subject, const QString &message) {
publish(subject, message, "");
}
inline void Client::publish(const QString &subject, const QString &message,
const QString &inbox) {
QString body = QStringLiteral("PUB ") % subject % " " % inbox %
(inbox.isEmpty() ? "" : " ") % QString::number(message.length()) % CLRF %
message % CLRF;
DEBUG("published:" << body);
m_socket.write(body.toUtf8());
}
inline uint64_t Client::subscribe(const QString &subject,
MessageCallback callback) {
return subscribe(subject, "", callback);
}
inline uint64_t Client::subscribe(const QString &subject, const QString &queue,
MessageCallback callback) {
m_callbacks[++m_ssid] = callback;
QString message = QStringLiteral("SUB ") % subject % " " % queue %
(queue.isEmpty() ? "" : " ") % QString::number(m_ssid) % CLRF;
m_socket.write(message.toUtf8());
DEBUG("subscribed:" << message);
return m_ssid;
}
inline Subscription *Client::subscribe(const QString &subject) {
auto subscription = new Subscription;
subscription->ssid = subscribe(subject,
"", [subscription](const QString & message, const QString & subject,
const QString & inbox) {
subscription->message = message;
subscription->subject = subject;
subscription->inbox = inbox;
emit subscription->received();
});
return subscription;
}
inline void Client::unsubscribe(uint64_t ssid, int max_messages) {
QString message = QStringLiteral("UNSUB ") % QString::number(ssid) %
(max_messages > 0 ? QString(" %1").arg(max_messages) : "") % CLRF;
DEBUG("unsubscribed:" << message);
m_socket.write(message.toUtf8());
}
inline void Client::setdebugmode(bool mode) {
_debug_mode = mode;
}
inline bool Client::isOpen() {
return m_socket.isValid();
}
inline uint64_t Client::request(const QString subject,
MessageCallback callback) {
return request(subject, "", callback);
}
inline uint64_t Client::request(const QString subject, const QString message,
MessageCallback callback) {
QString inbox = QUuid::createUuid().toString();
uint64_t ssid = subscribe(inbox, callback);
unsubscribe(ssid, 1);
publish(subject, message, inbox);
return ssid;
}
//! TODO: disconnect handling
inline void Client::set_listeners() {
DEBUG("set listeners");
QObject::connect(&m_socket, &QSslSocket::readyRead, [this] {
// add new data to buffer
m_buffer += m_socket.readAll();
// process message if exists
int clrf_pos = m_buffer.lastIndexOf(CLRF);
if(clrf_pos != -1) {
QByteArray msg_buffer = m_buffer.left(clrf_pos + CLRF.length());
process_inboud(msg_buffer);
}
});
}
// parse incoming messages, see http://nats.io/documentation/internals/nats-protocol
// QStringRef is used so we don't do any allocation
// TODO: error on invalid message
inline bool Client::process_inboud(const QByteArray &buffer) {
DEBUG("handle message:" << buffer);
// track movement inside buffer for parsing
int last_pos = 0, current_pos = 0;
while(last_pos != buffer.length()) {
// we always get delimited message
current_pos = buffer.indexOf(CLRF, last_pos);
if(current_pos == -1) {
qCritical() << "CLRF not found, should not happen";
break;
}
QString operation(buffer.mid(last_pos, current_pos - last_pos));
// if this is PING operation, reply
if(operation.compare(QStringLiteral("PING"), Qt::CaseInsensitive) == 0) {
DEBUG("sending pong");
m_socket.write(QString("PONG" % CLRF).toUtf8());
last_pos = current_pos + CLRF.length();
continue;
}
// +OK operation
else if(operation.compare(QStringLiteral("+OK"), Qt::CaseInsensitive) == 0) {
DEBUG("+OK");
last_pos = current_pos + CLRF.length();
continue;
}
// if -ERR, close client connection | -ERR <error message>
else if(operation.indexOf("-ERR", 0, Qt::CaseInsensitive) != -1) {
QStringRef error_message = operation.midRef(4);
qCritical() << "error" << error_message;
if(error_message.compare(QStringLiteral("Invalid Subject")) != 0)
m_socket.close();
return false;
}
// only MSG should be now left
else if(operation.indexOf(QStringLiteral("MSG"), Qt::CaseInsensitive) != 0) {
qCritical() << "invalid message - no message left";
m_buffer.remove(0, current_pos + CLRF.length());
return false;
}
// extract MSG data
// MSG format is: 'MSG <subject> <sid> [reply-to] <#bytes>\r\n[payload]\r\n'
// extract message_len = bytes and check if there is a message in this buffer
// if not, wait for next call, otherwise, extract all data
int message_len = 0;
QStringRef subject, sid, inbox;
QStringList parts = operation.split(" ", QString::SkipEmptyParts);
current_pos += CLRF.length();
if(parts.length() == 4) {
message_len = parts[3].toLong();
} else if(parts.length() == 5) {
inbox = &(parts[3]);
message_len = parts[4].toLong();
} else {
qCritical() << "invalid message - wrong length" << parts.length();
break;
}
if(current_pos + message_len + CLRF.length() > buffer.length()) {
DEBUG("message not in buffer, waiting");
break;
}
operation = parts[0];
subject = &(parts[1]);
sid = &(parts[2]);
uint64_t ssid = sid.toULongLong() ;
QString message(buffer.mid(current_pos, message_len));
last_pos = current_pos + message_len + CLRF.length();
DEBUG("message:" << message);
// call correct subscription callback
if(m_callbacks.contains(ssid))
m_callbacks[ssid](QString(message), inbox.toString(), subject.toString());
else
qWarning() << "invalid callback";
}
// remove processed messages from buffer
m_buffer.remove(0, last_pos);
return true;
}
}
#endif // NATSCLIENT_H