forked from pkoretic/qt-nats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnatsclient.h
1019 lines (829 loc) · 30.9 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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef NATSCLIENT_H
#define NATSCLIENT_H
#include <QHash>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMultiMap>
#include <QObject>
#include <QProcessEnvironment>
#include <QRandomGenerator>
#include <QSslConfiguration>
#include <QSslSocket>
#include <QStringBuilder>
#include <QTextStream>
namespace Nats
{
#define DEBUG(x) do { if (_debug_mode) { qDebug() << x; } } while (0)
//! Header type
typedef QMultiMap<QString, QString> Headers;
//! main callback message
using MessageCallback = std::function<void(QByteArray &&message, QString &&reply, QString &&subject, Headers &&headers)>;
using ConnectCallback = std::function<void()>;
//!
//! \brief CRLF
//! NATS protocol separator
const QByteArray CRLF = "\r\n";
//!
//! \brief hdrLine
//! NATS headers indicator
const QByteArray hdrLine = "NATS/1.0\r\n";
const int hdrPreEnd = hdrLine.length() - CRLF.length();
const QString statusHdr("Status");
const QString descrHdr("Description");
const QString noResponders("503");
const QString noMessagesSts("404");
const QString reqTimeoutSts("408");
const QString jetStream409Sts("409");
const QString controlMsg("100");
const int statusLen = 3;
//! convert QMultiMap headers into a suitable QByteArray
static const QByteArray makeHeader(const Headers &headers)
{
if(headers.size() == 0)
return QByteArray();
// Start with the header line
QByteArray result(hdrLine);
// Append values
QMapIterator<QString, QString> i(headers);
while(i.hasNext())
{
i.next();
// It might be a good idea to check the headers are valid, but
// for now, leave it up to the user
result += i.key().toUtf8() + ": " + i.value().toUtf8() + CRLF;
}
// Add a final CRLF
result += CRLF;
return result;
}
//! convert QByteArray headers back into a QMultiMap
static const Headers parseHeader(const QByteArray &hdr)
{
QTextStream str(hdr);
QString firstline = str.readLine();
if(firstline.length() < hdrPreEnd || hdrLine.left(hdrPreEnd) != firstline.left(hdrPreEnd))
{
qCritical() << "invalid header" << firstline;
return Headers();
}
Headers headers;
QString line;
while(str.readLineInto(&line))
{
int idx = line.indexOf(':');
// If there is no colon, skip this line
if(idx < 1)
continue;
// Parse key and value
QString key(line.left(idx));
idx++;
QString value(line.mid(idx).trimmed());
// Skip empty values as well
if(value.isEmpty())
continue;
headers.insert(key, value);
}
// Parse inline status, if any
if(firstline.length() > hdrPreEnd)
{
QString description;
QString status = firstline.mid(hdrPreEnd).trimmed();
if(status.length() != statusLen)
{
description = status.mid(statusLen).trimmed();
status = status.left(statusLen);
}
headers.insert(statusHdr, status);
if(!description.isEmpty())
headers.insert(descrHdr, description);
}
return headers;
}
const QString digits("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
const int digitLen = 62;
const int replySuffixLen = 8;
static QString makeRandom(int length) {
QString res(length, 0);
for(int i = 0; i < length; i++)
res[i] = digits[QRandomGenerator::global()->bounded(digitLen)];
return res;
}
//!
//! \brief The Options struct
//! holds all client options
struct Options
{
bool verbose = false;
bool pedantic = false;
bool headers = true;
bool tls_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;
QString inboxPrefix;
};
class Client;
//!
//! \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(Client* client, QObject *parent = nullptr): QObject(parent), m_client(client) {}
QString subject;
QByteArray message;
QString reply;
Headers headers;
qulonglong ssid = 0;
signals:
void received();
public slots:
void unsubscribe(int max_messages = 0);
private:
Client *m_client;
};
//!
//! \brief The Request class
//! holds request data and emits signal when ready as alternative to callbacks
class Request : public QObject
{
Q_OBJECT
public:
explicit Request(QObject *parent = nullptr): QObject(parent) {}
QString subject;
QByteArray message;
QString reply;
Headers headers;
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
//! \param headers
//! publish given message with subject, optionally with headers
void publish(const QString &subject, const QByteArray &message, const QString &reply);
void publish(const QString &subject, const QByteArray &message = "");
void publish(const QString &subject, const Headers &headers, const QByteArray &message = "", const QString &reply = "");
//!
//! \brief subscribe
//! \param subject
//! \param callback
//! \return subscription id
//! subscribe to given subject
//! when message is received, callback is fired
qulonglong subscribe(const QString &subject, Nats::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
qulonglong subscribe(const QString &subject, const QString &queue, Nats::MessageCallback callback);
//!
//! \brief subscribe
//! \param subject
//! \return
//! return subscription class holding result for signal/slot version
Subscription *subscribe(const QString &subject);
//!
//! \brief subscribe
//! \param subject
//! \param queue
//! \return
//! return subscription class holding result for signal/slot version
Subscription *subscribe(const QString &subject, const QString &queue);
//!
//! \brief unsubscribe
//! \param ssid
//! \param max_messages
//!
void unsubscribe(qulonglong ssid, int max_messages = 0);
//!
//! \brief request
//! \param subject
//! \param message
//! \return
//! make request using given subject and optional message
qulonglong request(const QString subject, const QByteArray message, Nats::MessageCallback callback);
qulonglong request(const QString subject, Nats::MessageCallback callback);
qulonglong request(const QString subject, const QByteArray message, const Headers headers, Nats::MessageCallback callback);
qulonglong request(const QString subject, const Headers headers, Nats::MessageCallback callback);
Request *request(const QString &subject);
Request *request(const QString &subject, const QByteArray &message);
Request *request(const QString &subject, const Headers &headers);
Request *request(const QString &subject, const QByteArray &message, const Headers &headers);
//!
//! \brief lastInfo
//! return latest received info from the server
const QJsonObject lastInfo() const;
signals:
//!
//! \brief connected
//! signal that the client is connected
void connected();
//!
//! \brief error
//! signal when there is an error connecting
void error(const QString);
//!
//! \brief disconnected
//! signal that the client is disconnected
void disconnected();
//!
//! \brief serverError
//! signal when there is an error message from the server
void serverError(const QString);
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, Nats::ConnectCallback callback = nullptr);
void connect(const QString &host, quint16 port, const Nats::Options &options, Nats::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 Nats::Options &options);
private:
//!
//! \brief debug_mode
//! extra debug output, can be set with enviroment variable DEBUG=qt-nats
bool _debug_mode = false;
//!
//! \brief m_buffer
//! main buffer that holds data from server
QByteArray m_buffer;
//!
//! \brief m_ssid
//! subscribtion id holder
qulonglong 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<qulonglong, MessageCallback> m_callbacks;
//!
//! \brief m_info
//! latest received info message
QJsonObject m_info;
//!
//! \brief m_inboxPrefix
//! once-generated inbox prefix for the client
QString m_inboxPrefix;
//!
//! \brief send_connect
//! \param options
//! send client information and options to server
void send_connect(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_inbound
//! \param buffer
//! process messages from buffer
bool process_inbound(const QByteArray &buffer);
//!
//! \brief newInbox
//! generate a new inbox name
const QString newInbox();
};
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");
}
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, &QAbstractSocket::errorOccurred, this, [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, [this](const QList<QSslError> &errors)
{
DEBUG(errors);
emit error(m_socket.errorString());
});
QObject::connect(&m_socket, &QSslSocket::encrypted, this, [this, options, callback]
{
DEBUG("SSL/TLS successful");
send_connect(options);
set_listeners();
if(callback)
callback();
emit connected();
});
QObject::connect(&m_socket, &QSslSocket::disconnected, this, [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, [this, signal, options, callback]
{
QObject::disconnect(*signal);
QByteArray info_message = m_socket.readAll();
QJsonObject json = parse_info(info_message);
bool tls_required = json.value(QStringLiteral("tls_required")).toBool();
// if client or server wants ssl start encryption
if(options.ssl || options.tls_required || tls_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_connect(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, &QAbstractSocket::errorOccurred, this, [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 tls_required = json.value(QStringLiteral("tls_required")).toBool();
// if client or server wants ssl start encryption
if(options.ssl || options.tls_required || tls_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_connect(options);
set_listeners();
emit connected();
return true;
}
inline void Client::send_connect(const Options &options)
{
QJsonObject info{
{"verbose", options.verbose},
{"pedantic", options.pedantic},
{"headers", options.headers},
{"tls_required", options.tls_required},
{"name", options.name},
{"lang", options.lang},
{"version", options.version},
{"protocol", 1},
};
// Set username, if any
if (!options.user.isEmpty())
info.insert("user", options.user);
// Set password, if any
if (!options.user.isEmpty())
info.insert("user", options.user);
// Set authorization token, if any
if (!options.user.isEmpty())
info.insert("auth_token", options.token);
// If headers are enabled, also set no_responders
if (options.headers)
info.insert("no_responders", true);
// Compose CONNECT message
QByteArray message("CONNECT ");
message += QJsonDocument(info).toJson(QJsonDocument::Compact);
message += CRLF;
DEBUG("send connect message:" << message);
m_socket.write(message);
}
inline QJsonObject Client::parse_info(const QByteArray &message)
{
DEBUG(message);
// discard 'INFO '
m_info = QJsonDocument::fromJson(message.mid(5)).object();
return m_info;
}
inline const QJsonObject Client::lastInfo() const
{
return m_info;
}
inline void Client::publish(const QString &subject, const QByteArray &message)
{
publish(subject, message, "");
}
inline void Client::publish(const QString &subject, const QByteArray &message, const QString &reply)
{
QByteArray body = QByteArrayLiteral("PUB ") + subject.toUtf8() + \
" " + reply.toUtf8() + (reply.isEmpty() ? "" : " ") + \
QByteArray::number(message.length()) + CRLF + message + CRLF;
DEBUG("published:" << body);
m_socket.write(body);
}
inline void Client::publish(const QString &subject, const Headers &headers, const QByteArray &message, const QString &reply)
{
// Send either PUB or HPUB, depending on header(s)
QByteArray body;
// Convert headers to string
QByteArray hdr = makeHeader(headers);
if (hdr.length() > 0)
{
body = QByteArrayLiteral("HPUB ") + subject.toUtf8() + " " + \
reply.toUtf8() + (reply.isEmpty() ? "" : " ") + \
QByteArray::number(hdr.length()) + " " + \
QByteArray::number(hdr.length() + message.length()) + CRLF + hdr;
}
else
{
body = QByteArrayLiteral("PUB ") + subject.toUtf8() + " " + \
reply.toUtf8() + (reply.isEmpty() ? "" : " ") + \
QByteArray::number(message.length()) + CRLF;
}
// Append message
body += message + CRLF;
DEBUG("published:" << body);
m_socket.write(body);
}
inline qulonglong Client::subscribe(const QString &subject, MessageCallback callback)
{
return subscribe(subject, "", callback);
}
inline qulonglong Client::subscribe(const QString &subject, const QString &queue, MessageCallback callback)
{
m_callbacks[++m_ssid] = callback;
QByteArray message = QByteArrayLiteral("SUB ") + \
subject.toUtf8() + " " + \
queue.toUtf8() + (queue.isEmpty() ? "" : " ") + \
QByteArray::number(m_ssid) + CRLF;
m_socket.write(message);
DEBUG("subscribed:" << message);
return m_ssid;
}
inline Subscription *Client::subscribe(const QString &subject)
{
return subscribe(subject, "");
}
inline Subscription *Client::subscribe(const QString &subject, const QString &queue)
{
auto subscription = new Subscription(this);
subscription->ssid = subscribe(subject, queue, [subscription](const QByteArray &message, const QString &reply, const QString &subject, const Headers &headers)
{
subscription->message = message;
subscription->subject = subject;
subscription->reply = reply;
subscription->headers = headers;
emit subscription->received();
});
return subscription;
}
inline void Client::unsubscribe(qulonglong ssid, int max_messages)
{
QByteArray message = QByteArrayLiteral("UNSUB ") + \
QByteArray::number(ssid) + \
(max_messages > 0 ? QString(" %1").arg(max_messages) : QStringLiteral("")).toUtf8() + CRLF;
DEBUG("unsubscribed:" << message);
m_socket.write(message);
}
inline qulonglong Client::request(const QString subject, MessageCallback callback)
{
return request(subject, "", callback);
}
inline qulonglong Client::request(const QString subject, const QByteArray message, MessageCallback callback)
{
QString reply = newInbox();
qulonglong ssid = subscribe(reply, callback);
unsubscribe(ssid, 1);
publish(subject, message, reply);
return ssid;
}
inline qulonglong Client::request(const QString subject, const Headers headers, Nats::MessageCallback callback)
{
return request(subject, "", headers, callback);
}
inline qulonglong Client::request(const QString subject, const QByteArray message, const Headers headers, Nats::MessageCallback callback)
{
QString reply = newInbox();
qulonglong ssid = subscribe(reply, callback);
unsubscribe(ssid, 1);
publish(subject, headers, message, reply);
return ssid;
}
inline Request *Client::request(const QString &subject)
{
return request(subject, "");
}
inline Request *Client::request(const QString &subject, const QByteArray &message)
{
auto req = new Request(this);
req->ssid = request(subject, message, [req](const QByteArray &message, const QString &reply, const QString &subject, const Headers &headers)
{
req->message = message;
req->subject = subject;
req->reply = reply;
req->headers = headers;
emit req->received();
});
return req;
}
inline Request *Client::request(const QString &subject, const Headers &headers)
{
return request(subject, "", headers);
}
inline Request *Client::request(const QString &subject, const QByteArray &message, const Headers &headers)
{
auto req = new Request(this);
req->ssid = request(subject, message, headers, [req](const QByteArray &message, const QString &reply, const QString &subject, const Headers &headers)
{
req->message = message;
req->subject = subject;
req->reply = reply;
req->headers = headers;
emit req->received();
});
return req;
}
//! TODO: disconnect handling
inline void Client::set_listeners()
{
DEBUG("set listeners");
QObject::connect(&m_socket, &QSslSocket::readyRead, this, [this]
{
// add new data to buffer
m_buffer += m_socket.readAll();
// process message if exists
int CRLF_pos = m_buffer.lastIndexOf(CRLF);
if(CRLF_pos != -1)
{
QByteArray msg_buffer = m_buffer.left(CRLF_pos + CRLF.length());
process_inbound(msg_buffer);
}
});
}
// parse incoming messages, see http://nats.io/documentation/internals/nats-protocol
// QStringView is used so we don't do unnecessary allocations
// TODO: error on invalid message
inline bool Client::process_inbound(const QByteArray &buffer)
{
DEBUG("handle message:" << buffer);
// track movement inside buffer for parsing
int last_pos = 0, current_pos = 0;
bool is_hmsg;
while(last_pos != buffer.length())
{
// we always get delimited message
current_pos = buffer.indexOf(CRLF, last_pos);
if(current_pos == -1)
{
qCritical() << "CRLF not found, this 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(QByteArrayLiteral("PONG") + CRLF);
last_pos = current_pos + CRLF.length();
continue;
}
// +OK operation
else if(operation.compare(QStringLiteral("+OK"), Qt::CaseInsensitive) == 0)
{
DEBUG("+OK");
last_pos = current_pos + CRLF.length();
continue;
}
// if -ERR, close client connection | -ERR <error message>
else if(operation.indexOf("-ERR", 0, Qt::CaseInsensitive) != -1)
{
QStringView error_message = QStringView{operation}.mid(4);
qCritical() << "error" << error_message;
if(error_message.compare(QStringLiteral("Invalid Subject")) != 0)
m_socket.close();
emit serverError(error_message);
return false;
}
// MSG operation
else if(operation.indexOf(QStringLiteral("MSG"), Qt::CaseInsensitive) == 0)
{
is_hmsg = false;
}
// HMSG operation
else if(operation.indexOf(QStringLiteral("HMSG"), Qt::CaseInsensitive) == 0)
{
is_hmsg = true;
}
else
{
qCritical() << "invalid message - no message left";
m_buffer.remove(0,current_pos + CRLF.length());
return false;
}
// extract MSG or HMSG data
// MSG format is: 'MSG <subject> <sid> [reply-to] <#bytes>\r\n[payload]\r\n'
// HMSG format is: 'HMSG <subject> <sid> [reply-to] <#header bytes> <#total bytes>\r\n[headers]\r\n\r\n[payload]\r\n'
// extract total_len = bytes and check if there is a message in this buffer
// if not, wait for next call, otherwise, extract all data
int total_len = 0;
int message_len = 0;
int header_len = 0;
QString subject, sid, reply;
QList<QStringView> parts = QStringView{operation}.split(u" ", Qt::SkipEmptyParts);
current_pos += CRLF.length();
if(is_hmsg)
{
if(parts.length() == 5)
{
header_len = parts[3].toInt();
total_len = parts[4].toInt();
}
else if (parts.length() == 6)
{
reply = (parts[3]).toString();
header_len = parts[4].toInt();
total_len = parts[5].toInt();
}
else
{
qCritical() << "invalid message - wrong length" << parts.length();
break;
}
message_len = total_len - header_len;
}
else
{
if(parts.length() == 4)
{
total_len = message_len = parts[3].toInt();
}
else if (parts.length() == 5)
{
reply = (parts[3]).toString();
total_len = message_len = parts[4].toInt();
}
else
{
qCritical() << "invalid message - wrong length" << parts.length();
break;
}
}
if(current_pos + total_len + CRLF.length() > buffer.length())
{
DEBUG("message not in buffer, waiting");
break;
}
operation = parts[0].toString();
subject = parts[1].toString();
sid = parts[2].toString();
qulonglong ssid = sid.toULong();
QByteArray message;
Headers headers;
// Extract headers, if any
QByteArray hdr;
if(is_hmsg)
{
hdr = buffer.mid(current_pos, header_len);
message = buffer.mid(current_pos + header_len, message_len);
headers = parseHeader(hdr);
}
else
{
message = buffer.mid(current_pos, message_len);
}
// Update last position
last_pos = current_pos + total_len + CRLF.length();
DEBUG("message:" << message);
// call correct subscription callback
if(m_callbacks.contains(ssid))
{
auto callback = m_callbacks[ssid];
callback(std::move(message), std::move(reply), std::move(subject), std::move(headers));
}
else
{
qWarning() << "invalid callback";
}
}
// remove processed messages from buffer
m_buffer.remove(0, last_pos);
return true;
}
inline const QString Client::newInbox()
{
if(m_inboxPrefix.isEmpty())
{
QString prefix;