-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathsubscriptionstore.cpp
1610 lines (1299 loc) · 54.5 KB
/
subscriptionstore.cpp
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
/*
This file is part of FlashMQ (https://www.flashmq.org)
Copyright (C) 2021-2023 Wiebe Cazemier
FlashMQ is free software: you can redistribute it and/or modify
it under the terms of The Open Software License 3.0 (OSL-3.0).
See LICENSE for license details.
*/
#include "subscriptionstore.h"
#include <cassert>
#include "rwlockguard.h"
#include "retainedmessagesdb.h"
#include "publishcopyfactory.h"
#include "threadglobals.h"
#include "utils.h"
#include "settings.h"
#include "plugin.h"
#include "exceptions.h"
#include "threaddata.h"
#include <deque>
ReceivingSubscriber::ReceivingSubscriber(const std::shared_ptr<Session> &ses, uint8_t qos, bool retainAsPublished) :
session(ses),
qos(qos),
retainAsPublished(retainAsPublished)
{
}
SubscriptionNode::SubscriptionNode()
{
}
const std::unordered_map<std::string, Subscription> &SubscriptionNode::getSubscribers() const
{
return subscribers;
}
std::unordered_map<std::string, SharedSubscribers> &SubscriptionNode::getSharedSubscribers()
{
return sharedSubscribers;
}
void SubscriptionNode::addSubscriber(const std::shared_ptr<Session> &subscriber, uint8_t qos, bool noLocal, bool retainAsPublished, const std::string &shareName)
{
if (!subscriber)
return;
Subscription sub;
sub.session = subscriber;
sub.qos = qos;
sub.noLocal = noLocal;
sub.retainAsPublished = retainAsPublished;
const std::string &client_id = subscriber->getClientId();
if (shareName.empty())
{
subscribers[client_id] = sub;
}
else
{
SharedSubscribers &subscribers = sharedSubscribers[shareName];
subscribers.setName(shareName); // c++14 doesn't have try-emplace yet, in which case this separate step wouldn't be needed.
subscribers[client_id] = sub;
}
}
void SubscriptionNode::removeSubscriber(const std::shared_ptr<Session> &subscriber, const std::string &shareName)
{
Subscription sub;
sub.session = subscriber;
sub.qos = 0;
const std::string &clientId = subscriber->getClientId();
if (shareName.empty())
{
auto it = subscribers.find(clientId);
if (it != subscribers.end())
{
subscribers.erase(it);
}
}
else
{
auto pos = sharedSubscribers.find(shareName);
if (pos != sharedSubscribers.end())
{
SharedSubscribers &subscribers = pos->second;
subscribers.erase(clientId);
}
}
}
/**
* @brief SubscriptionNode::getChildren gets children or null pointer. Const, so doesn't default-create node for
* non-existing children.
* @param subtopic
* @return
*/
SubscriptionNode *SubscriptionNode::getChildren(const std::string &subtopic) const
{
auto it = children.find(subtopic);
if (it != children.end())
return it->second.get();
return nullptr;
}
SubscriptionStore::SubscriptionStore() :
root(),
rootDollar(),
sessionsByIdConst(sessionsById)
{
}
/**
* @brief SubscriptionStore::getDeepestNode gets the node in the tree walking the path of 'the/subscription/topic/path', making new nodes as required.
* @param topic
* @param subtopics
* @return
*
* caller is responsible for locking.
*/
SubscriptionNode *SubscriptionStore::getDeepestNode(const std::vector<std::string> &subtopics)
{
SubscriptionNode *deepestNode = &root;
if (!subtopics.empty())
{
const std::string &first = subtopics.front();
if (first.length() > 0 && first[0] == '$')
deepestNode = &rootDollar;
}
for(const std::string &subtopic : subtopics)
{
std::shared_ptr<SubscriptionNode> *selectedChildren = nullptr;
if (subtopic == "#")
selectedChildren = &deepestNode->childrenPound;
else if (subtopic == "+")
selectedChildren = &deepestNode->childrenPlus;
else
selectedChildren = &deepestNode->children[subtopic];
std::shared_ptr<SubscriptionNode> &node = *selectedChildren;
if (!node)
{
node = std::make_shared<SubscriptionNode>();
}
deepestNode = node.get();
}
assert(deepestNode);
return deepestNode;
}
void SubscriptionStore::addSubscription(std::shared_ptr<Client> &client, const std::vector<std::string> &subtopics, uint8_t qos, bool noLocal, bool retainAsPublished)
{
const static std::string empty;
addSubscription(client, subtopics, qos, noLocal, retainAsPublished, empty, AuthResult::success);
}
void SubscriptionStore::addSubscription(std::shared_ptr<Client> &client, const std::vector<std::string> &subtopics, uint8_t qos, bool noLocal, bool retainAsPublished,
const std::string &shareName, AuthResult authResult)
{
RWLockGuard lock_guard(&sessionsAndSubscriptionsRwlock);
lock_guard.wrlock();
SubscriptionNode *deepestNode = getDeepestNode(subtopics);
if (!deepestNode)
return;
auto session_it = sessionsByIdConst.find(client->getClientId());
if (session_it == sessionsByIdConst.end())
return;
const std::shared_ptr<Session> ses = session_it->second;
if (!ses)
return;
deepestNode->addSubscriber(ses, qos, noLocal, retainAsPublished, shareName);
subscriptionCount++;
lock_guard.unlock();
if (authResult == AuthResult::success && shareName.empty())
giveClientRetainedMessages(ses, subtopics, qos);
}
void SubscriptionStore::removeSubscription(std::shared_ptr<Client> &client, const std::string &topic)
{
std::vector<std::string> subtopics = splitTopic(topic);
std::string shareName;
parseSubscriptionShare(subtopics, shareName);
SubscriptionNode *deepestNode = &root;
if (!subtopics.empty())
{
const std::string &first = subtopics.front();
if (first.length() > 0 && first[0] == '$')
deepestNode = &rootDollar;
}
RWLockGuard lock_guard(&sessionsAndSubscriptionsRwlock);
lock_guard.wrlock();
// This code looks like that for addSubscription(), but it's specifically different in that we don't want to default-create non-existing
// nodes. We need to abort when that happens.
for(const std::string &subtopic : subtopics)
{
SubscriptionNode *selectedChildren = nullptr;
if (subtopic == "#")
selectedChildren = deepestNode->childrenPound.get();
else if (subtopic == "+")
selectedChildren = deepestNode->childrenPlus.get();
else
selectedChildren = deepestNode->getChildren(subtopic);
if (!selectedChildren)
{
return;
}
deepestNode = selectedChildren;
}
assert(deepestNode);
if (deepestNode)
{
auto session_it = sessionsByIdConst.find(client->getClientId());
if (session_it != sessionsByIdConst.end())
{
const std::shared_ptr<Session> &ses = session_it->second;
deepestNode->removeSubscriber(ses, shareName);
subscriptionCount--;
}
}
lock_guard.unlock();
}
std::shared_ptr<Session> SubscriptionStore::getBridgeSession(std::shared_ptr<Client> &client)
{
RWLockGuard lock_guard(&sessionsAndSubscriptionsRwlock);
lock_guard.wrlock();
std::shared_ptr<Session> session = std::make_shared<Session>();
session->assignActiveConnection(client);
client->assignSession(session);
sessionsById[client->getClientId()] = session;
return session;
}
/**
* @brief SubscriptionStore::registerClientAndKickExistingOne registers a client with previously set parameters for the session.
* @param client
*
* Under normal MQTT operation, the 'if' clause is always used. The 'else' is only in (fuzz) testing and other rare conditions.
*/
void SubscriptionStore::registerClientAndKickExistingOne(std::shared_ptr<Client> &client)
{
const std::unique_ptr<StowedClientRegistrationData> ®istrationData = client->getRegistrationData();
if (registrationData)
{
registerClientAndKickExistingOne(client, registrationData->clean_start, registrationData->clientReceiveMax, registrationData->sessionExpiryInterval);
client->clearRegistrationData();
}
else
{
const Settings *settings = ThreadGlobals::getSettings();
registerClientAndKickExistingOne(client, true, settings->maxQosMsgPendingPerClient, settings->expireSessionsAfterSeconds);
}
}
// Removes an existing client when it already exists [MQTT-3.1.4-2].
void SubscriptionStore::registerClientAndKickExistingOne(std::shared_ptr<Client> &client, bool clean_start, uint16_t clientReceiveMax, uint32_t sessionExpiryInterval)
{
ThreadGlobals::getThreadData()->queueClientNextKeepAliveCheckLocked(client, true);
// These destructors need to be called outside the sessions lock, so placing here.
std::shared_ptr<Session> session;
std::shared_ptr<Client> clientOfOtherSession;
if (client->getClientId().empty())
throw ProtocolError("Trying to store client without an ID.", ReasonCodes::ProtocolError);
{
RWLockGuard lock_guard(&sessionsAndSubscriptionsRwlock);
lock_guard.wrlock();
auto session_it = sessionsById.find(client->getClientId());
if (session_it != sessionsById.end())
{
session = session_it->second;
if (session)
{
clientOfOtherSession = session->makeSharedClient();
if (clientOfOtherSession)
{
logger->logf(LOG_NOTICE, "Disconnecting existing client with id '%s'", clientOfOtherSession->getClientId().c_str());
clientOfOtherSession->setDisconnectReason("Another client with this ID connected");
clientOfOtherSession->serverInitiatedDisconnect(ReasonCodes::SessionTakenOver);
}
}
}
if (!session || session->getDestroyOnDisconnect() || clean_start)
{
// Don't use sdt::make_shared to avoid the weak pointers from retaining the size of session in the control block.
session = std::shared_ptr<Session>(new Session());
sessionsById[client->getClientId()] = session;
}
}
session->assignActiveConnection(client);
client->assignSession(session);
session->setSessionProperties(clientReceiveMax, sessionExpiryInterval, clean_start, client->getProtocolVersion());
session->sendAllPendingQosData();
}
/**
* @brief SubscriptionStore::lockSession returns the session if it exists. Returning is done keep the shared pointer active, to
* avoid race conditions with session removal.
* @param clientid
* @return
*/
std::shared_ptr<Session> SubscriptionStore::lockSession(const std::string &clientid)
{
RWLockGuard lock_guard(&sessionsAndSubscriptionsRwlock);
lock_guard.rdlock();
auto it = sessionsByIdConst.find(clientid);
if (it != sessionsByIdConst.end())
{
return it->second;
}
return std::shared_ptr<Session>();
}
/**
* @brief SubscriptionStore::sendQueuedWillMessages sends queued will messages.
*
* The expiry interval as set in the properties of the will message is not used to check for expiration here. To
* quote the specs: "If present, the Four Byte value is the lifetime of the Will Message in seconds and is sent as
* the Publication Expiry Interval when the Server publishes the Will Message."
*
* If a new Network Connection to this Session is made before the Will Delay Interval has passed, the Server
* MUST NOT send the Will Message [MQTT-3.1.3-9].
*/
void SubscriptionStore::sendQueuedWillMessages()
{
Authentication &auth = *ThreadGlobals::getAuth();
const auto now = std::chrono::steady_clock::now();
const std::chrono::seconds secondsSinceEpoch = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
std::lock_guard<std::mutex> locker(this->pendingWillsMutex);
auto it = pendingWillMessages.begin();
while (it != pendingWillMessages.end())
{
const std::chrono::seconds &sendAt = it->first;
if (sendAt > secondsSinceEpoch)
break;
std::vector<QueuedWill> &willsOfSlot = it->second;
for(QueuedWill &will : willsOfSlot)
{
std::shared_ptr<WillPublish> p = will.getWill().lock();
// If sessions get a new will, or the will is cleared from a new connecting client, this entry
// will be null and we can ignore it.
if (p)
{
std::shared_ptr<Session> s = will.getSession();
// Check for stale wills, or sessions that have become active again.
if (s && !s->hasActiveClient())
{
logger->logf(LOG_DEBUG, "Sending delayed will on topic '%s'.", p->topic.c_str() );
if (auth.aclCheck(*p, p->payload) == AuthResult::success)
{
PublishCopyFactory factory(p.get());
queuePacketAtSubscribers(factory, p->client_id);
if (p->retain)
setRetainedMessage(*p, p->getSubtopics());
}
s->clearWill();
}
}
}
it = pendingWillMessages.erase(it);
}
}
/**
* @brief SubscriptionStore::queueWillMessage queues the will message in a sorted map.
* @param willMessage
* @param forceNow
*
* The queued will is only valid for that time. Should a new will be placed in the map for a session, the original shared_ptr
* will be cleared and the previously queued entry is void (but still there, so it needs to be checked).
*/
void SubscriptionStore::queueWillMessage(const std::shared_ptr<WillPublish> &willMessage, const std::string &senderClientId, const std::shared_ptr<Session> &session, bool forceNow)
{
if (!willMessage)
return;
Authentication &auth = *ThreadGlobals::getAuth();
Settings *settings = ThreadGlobals::getSettings();
const int delay = forceNow ? 0 : willMessage->will_delay;
logger->logf(LOG_DEBUG, "Queueing will on topic '%s', with delay %d seconds.", willMessage->topic.c_str(), delay );
if (delay == 0)
{
if (settings->willsEnabled && auth.aclCheck(*willMessage, willMessage->payload) == AuthResult::success)
{
PublishCopyFactory factory(willMessage.get());
queuePacketAtSubscribers(factory, senderClientId);
if (willMessage->retain)
setRetainedMessage(*willMessage.get(), (*willMessage).getSubtopics());
}
// Avoid sending two immediate wills when a session is destroyed with the client disconnect.
// Session is null when you're destroying a client before a session is assigned, or
// when an old client has no session anymore after a client with the same ID connects.
if (session)
session->clearWill();
return;
}
willMessage->setQueuedAt();
QueuedWill queuedWill(willMessage, session);
const std::chrono::time_point<std::chrono::steady_clock> sendWillAt = std::chrono::steady_clock::now() + std::chrono::seconds(willMessage->will_delay);
std::chrono::seconds secondsSinceEpoch = std::chrono::duration_cast<std::chrono::seconds>(sendWillAt.time_since_epoch());
std::lock_guard<std::mutex> locker(this->pendingWillsMutex);
this->pendingWillMessages[secondsSinceEpoch].push_back(queuedWill);
}
void SubscriptionStore::publishNonRecursively(SubscriptionNode *this_node, std::forward_list<ReceivingSubscriber> &targetSessions, size_t distributionHash,
const std::string &senderClientId)
{
{
const std::unordered_map<std::string, Subscription> &subscribers = this_node->getSubscribers();
for (auto &pair : subscribers)
{
const Subscription &sub = pair.second;
const std::shared_ptr<Session> session = sub.session.lock();
if (session) // Shared pointer expires when session has been cleaned by 'clean session' connect.
{
const std::string &receiverClientId = session->getClientId();
if (sub.noLocal && receiverClientId == senderClientId)
continue;
targetSessions.emplace_front(session, sub.qos, sub.retainAsPublished);
}
}
}
{
std::unordered_map<std::string, SharedSubscribers> &sharedSubscribers = this_node->getSharedSubscribers();
if (!sharedSubscribers.empty())
{
const Settings *settings = ThreadGlobals::getSettings();
for(auto &pair : sharedSubscribers)
{
SharedSubscribers &subscribers = pair.second;
const Subscription *sub = nullptr;
if (settings->sharedSubscriptionTargeting == SharedSubscriptionTargeting::SenderHash)
sub = subscribers.getNext(distributionHash);
else
sub = subscribers.getNext();
if (sub == nullptr)
continue;
const std::shared_ptr<Session> session = sub->session.lock();
if (session) // Shared pointer expires when session has been cleaned by 'clean session' connect.
{
targetSessions.emplace_front(session, sub->qos, sub->retainAsPublished);
}
}
}
}
}
/**
* @brief SubscriptionStore::publishRecursively
* @param cur_subtopic_it
* @param end
* @param this_node
* @param packet
* @param count as a reference (vs return value) because a return value introduces an extra call i.e. limits tail recursion optimization.
*
* As noted in the params section, this method was written so that it could be (somewhat) optimized for tail recursion by the compiler. If you refactor this,
* look at objdump --disassemble --demangle to see how many calls (not jumps) to itself are made and compare.
*/
void SubscriptionStore::publishRecursively(std::vector<std::string>::const_iterator cur_subtopic_it, std::vector<std::string>::const_iterator end,
SubscriptionNode *this_node, std::forward_list<ReceivingSubscriber> &targetSessions, size_t distributionHash,
const std::string &senderClientId)
{
if (cur_subtopic_it == end) // This is the end of the topic path, so look for subscribers here.
{
if (this_node)
{
publishNonRecursively(this_node, targetSessions, distributionHash, senderClientId);
// Subscribing to 'one/two/three/#' also gives you 'one/two/three'.
if (this_node->childrenPound)
{
publishNonRecursively(this_node->childrenPound.get(), targetSessions, distributionHash, senderClientId);
}
}
return;
}
// Null nodes in the tree shouldn't happen at this point. It points to bugs elsewhere. However, I don't remember why I check the pointer
// inside the if-block above, instead of the start of the method.
assert(this_node != nullptr);
if (this_node->children.empty() && !this_node->childrenPlus && !this_node->childrenPound)
return;
const std::string &cur_subtop = *cur_subtopic_it;
const auto next_subtopic = ++cur_subtopic_it;
if (this_node->childrenPound)
{
publishNonRecursively(this_node->childrenPound.get(), targetSessions, distributionHash, senderClientId);
}
const auto &sub_node = this_node->children.find(cur_subtop);
if (this_node->childrenPlus)
{
publishRecursively(next_subtopic, end, this_node->childrenPlus.get(), targetSessions, distributionHash, senderClientId);
}
if (sub_node != this_node->children.end())
{
publishRecursively(next_subtopic, end, sub_node->second.get(), targetSessions, distributionHash, senderClientId);
}
}
void SubscriptionStore::queuePacketAtSubscribers(PublishCopyFactory ©Factory, const std::string &senderClientId, bool dollar)
{
/*
* Sometimes people publish or set as will topics with dollar. Node-to-Node communication for bridges for instance.
* We still accept them, but just decide to do nothing with them. Only the FlashMQ internals are allowed to publish
* on dollar topics.
*/
if (!dollar)
{
const std::string &topic = copyFactory.getTopic();
if (!topic.empty() && topic[0] == '$')
{
return;
}
}
SubscriptionNode *startNode = dollar ? &rootDollar : &root;
std::forward_list<ReceivingSubscriber> subscriberSessions;
{
const std::vector<std::string> &subtopics = copyFactory.getSubtopics();
RWLockGuard lock_guard(&sessionsAndSubscriptionsRwlock);
lock_guard.rdlock();
publishRecursively(subtopics.begin(), subtopics.end(), startNode, subscriberSessions, copyFactory.getSharedSubscriptionHashKey(), senderClientId);
}
for(const ReceivingSubscriber &x : subscriberSessions)
{
x.session->writePacket(copyFactory, x.qos, x.retainAsPublished);
}
}
void SubscriptionStore::giveClientRetainedMessagesRecursively(std::vector<std::string>::const_iterator cur_subtopic_it,
std::vector<std::string>::const_iterator end,
const std::shared_ptr<RetainedMessageNode> &this_node,
bool poundMode,
const std::shared_ptr<Session> &session, const uint8_t max_qos,
const std::chrono::time_point<std::chrono::steady_clock> &limit,
std::deque<DeferredRetainedMessageNodeDelivery> &deferred,
int &drop_count, int &processed_nodes_count)
{
if (!this_node)
return;
if (cur_subtopic_it == end)
{
Authentication &auth = *ThreadGlobals::getAuth();
std::lock_guard<std::mutex> locker(this_node->messageSetMutex);
if (this_node->message)
{
const RetainedMessage &rm = *this_node->message;
if (!rm.hasExpired()) // We can't also erase here, because we're operating under a read lock.
{
Publish publish = rm.publish;
if (auth.aclCheck(publish, publish.payload) == AuthResult::success)
{
PublishCopyFactory copyFactory(&publish);
const PacketDropReason drop_reason = session->writePacket(copyFactory, max_qos, true);
if (drop_reason == PacketDropReason::BufferFull || drop_reason == PacketDropReason::QoSTODOSomethingSomething)
{
drop_count++;
DeferredRetainedMessageNodeDelivery d;
d.node = this_node;
d.cur = cur_subtopic_it;
d.end = end;
d.poundMode = poundMode;
deferred.push_back(d);
/*
* Capacity-wise, we wouldn't have to return here if it was merely a QoS limit, but then it becomes hard
* to filter out the children of this node, which you'd need to avoid duplicate deliveries. So,
* this is the easier approach.
*/
return;
}
}
}
}
if (poundMode)
{
const int drop_count_start = drop_count;
for (auto &pair : this_node->children)
{
if (std::chrono::steady_clock::now() >= limit || drop_count_start != drop_count)
{
DeferredRetainedMessageNodeDelivery d;
d.node = pair.second;
d.cur = cur_subtopic_it;
d.end = end;
d.poundMode = poundMode;
deferred.push_back(d);
}
else
{
std::shared_ptr<RetainedMessageNode> &child = pair.second;
giveClientRetainedMessagesRecursively(cur_subtopic_it, end, child, poundMode, session, max_qos, limit, deferred, drop_count, ++processed_nodes_count);
}
}
}
return;
}
const std::string &cur_subtop = *cur_subtopic_it;
const auto next_subtopic = ++cur_subtopic_it;
if (cur_subtop == "#")
{
// We start at this node, so that a subscription on 'one/two/three/#' gives you 'one/two/three' too.
giveClientRetainedMessagesRecursively(next_subtopic, end, this_node, true, session, max_qos, limit, deferred, drop_count, ++processed_nodes_count);
}
else if (cur_subtop == "+")
{
const int drop_count_start = drop_count;
for (std::pair<const std::string, std::shared_ptr<RetainedMessageNode>> &pair : this_node->children)
{
if (std::chrono::steady_clock::now() >= limit || drop_count_start != drop_count)
{
DeferredRetainedMessageNodeDelivery d;
d.node = pair.second;
d.cur = next_subtopic;
d.end = end;
d.poundMode = poundMode;
deferred.push_back(d);
}
else
{
std::shared_ptr<RetainedMessageNode> &child = pair.second;
giveClientRetainedMessagesRecursively(next_subtopic, end, child, false, session, max_qos, limit, deferred, drop_count, ++processed_nodes_count);
}
}
}
else
{
std::shared_ptr<RetainedMessageNode> children = this_node->getChildren(cur_subtop);
if (children)
{
if (std::chrono::steady_clock::now() >= limit)
{
DeferredRetainedMessageNodeDelivery d;
d.node = children;
d.cur = next_subtopic;
d.end = end;
d.poundMode = poundMode;
deferred.push_back(d);
}
else
{
giveClientRetainedMessagesRecursively(next_subtopic, end, children, false, session, max_qos, limit, deferred, drop_count, ++processed_nodes_count);
}
}
}
}
void SubscriptionStore::giveClientRetainedMessagesInitiateDeferred(const std::weak_ptr<Session> ses,
const std::shared_ptr<const std::vector<std::string>> subscribeSubtopicsCopy,
std::shared_ptr<std::deque<DeferredRetainedMessageNodeDelivery>> deferred,
int &requeue_count, uint &total_node_count, uint8_t max_qos)
{
std::shared_ptr<Session> session = ses.lock();
if (!session)
return;
const Settings *settings = ThreadGlobals::getSettings();
const std::chrono::time_point<std::chrono::steady_clock> new_limit = std::chrono::steady_clock::now() + std::chrono::milliseconds(10);
int drop_count = 0;
int processed_nodes = 0;
for (; !deferred->empty(); deferred->pop_front())
{
if (std::chrono::steady_clock::now() >= new_limit)
break;
if (drop_count > 0)
break;
DeferredRetainedMessageNodeDelivery &d = deferred->front();
std::shared_ptr<RetainedMessageNode> node = d.node.lock();
if (!node)
continue;
RWLockGuard locker(&retainedMessagesRwlock);
locker.rdlock();
giveClientRetainedMessagesRecursively(d.cur, d.end, node, d.poundMode, session, max_qos, new_limit, *deferred, drop_count, processed_nodes);
}
total_node_count += processed_nodes;
if (processed_nodes > 0)
{
requeue_count = 0;
}
if (!deferred->empty() && ++requeue_count < 100 && total_node_count < settings->retainedMessagesNodeLimit)
{
ThreadData *t = ThreadGlobals::getThreadData();
auto again = std::bind(&SubscriptionStore::giveClientRetainedMessagesInitiateDeferred, this, ses, subscribeSubtopicsCopy, deferred, requeue_count, total_node_count, max_qos);
/*
* Adding a delayed retry is kind of a cheap way to avoid detecting when there is buffer or QoS space in the event loop, but that comes
* with several layers of complexity that makes the the normal (non-retained) flow more complicated. Also, buffer full situations
* is probably most likely to happen when clients subscribe to a broad wildcard on a big subscription tree, and this
* allows some depriorirzation.
*/
if (drop_count > 0)
t->addDelayedTask(again, 50);
else
t->addImmediateTask(again);
}
}
void SubscriptionStore::giveClientRetainedMessages(const std::shared_ptr<Session> &ses,
const std::vector<std::string> &subscribeSubtopics, uint8_t max_qos)
{
if (!ses)
return;
const Settings *settings = ThreadGlobals::getSettings();
if (settings->retainedMessagesMode != RetainedMessagesMode::Enabled)
return;
// The specs aren't clear whether retained messages should be dropped, or just have their retain flag stripped. I chose the former,
// otherwise clients have no way of knowing if a message was retained or not.
{
const std::shared_ptr<Client> client = ses->makeSharedClient();
if (client && !client->isRetainedAvailable())
return;
}
const std::shared_ptr<RetainedMessageNode> *startNode = &retainedMessagesRoot;
if (!subscribeSubtopics.empty() && !subscribeSubtopics[0].empty() > 0 && subscribeSubtopics[0][0] == '$')
startNode = &retainedMessagesRootDollar;
const std::shared_ptr<const std::vector<std::string>> subscribeSubtopicsCopy = std::make_shared<const std::vector<std::string>>(subscribeSubtopics);
std::shared_ptr<std::deque<DeferredRetainedMessageNodeDelivery>> deferred = std::make_shared<std::deque<DeferredRetainedMessageNodeDelivery>>();
DeferredRetainedMessageNodeDelivery start;
start.node = *startNode;
start.cur = subscribeSubtopicsCopy->begin();
start.end = subscribeSubtopicsCopy->end();
deferred->push_back(start);
int requeue_count = 0;
uint total_node_count = 0;
giveClientRetainedMessagesInitiateDeferred(ses, subscribeSubtopicsCopy, deferred, requeue_count, total_node_count, max_qos);
}
void SubscriptionStore::setRetainedMessage(const Publish &publish, const std::vector<std::string> &subtopics)
{
assert(!subtopics.empty());
const Settings *settings = ThreadGlobals::getSettings();
if (settings->retainedMessagesMode != RetainedMessagesMode::Enabled)
return;
RetainedMessageNode *deepestNode = retainedMessagesRoot.get();
if (!subtopics.empty() && !subtopics[0].empty() > 0 && subtopics[0][0] == '$')
deepestNode = retainedMessagesRootDollar.get();
bool needsWriteLock = false;
auto subtopic_pos = subtopics.begin();
// First do a read-only search for the node.
{
RWLockGuard locker(&retainedMessagesRwlock);
locker.rdlock();
while(subtopic_pos != subtopics.end())
{
auto pos = deepestNode->children.find(*subtopic_pos);
if (pos == deepestNode->children.end())
{
needsWriteLock = true;
break;
}
std::shared_ptr<RetainedMessageNode> &selectedChildren = pos->second;
if (!selectedChildren)
{
needsWriteLock = true;
break;
}
deepestNode = selectedChildren.get();
subtopic_pos++;
}
assert(deepestNode);
if (!needsWriteLock && deepestNode)
{
deepestNode->addPayload(publish, retainedMessageCount);
}
}
if (needsWriteLock)
{
RWLockGuard locker(&retainedMessagesRwlock);
locker.wrlock();
while(subtopic_pos != subtopics.end())
{
std::shared_ptr<RetainedMessageNode> &selectedChildren = deepestNode->children[*subtopic_pos];
if (!selectedChildren)
{
selectedChildren = std::make_shared<RetainedMessageNode>();
}
deepestNode = selectedChildren.get();
subtopic_pos++;
}
assert(deepestNode);
if (deepestNode)
{
deepestNode->addPayload(publish, retainedMessageCount);
}
}
}
// Clean up the weak pointers to sessions and remove nodes that are empty.
int SubscriptionNode::cleanSubscriptions(std::deque<std::weak_ptr<SubscriptionNode>> &defferedLeafs)
{
const size_t children_amount = children.size();
const bool split = children_amount > 15;
int subscribersLeftInChildren = 0;
auto childrenIt = children.begin();
while(childrenIt != children.end())
{
std::shared_ptr<SubscriptionNode> &node = childrenIt->second;
if (!node)
continue;
if (split && !node->empty())
{
defferedLeafs.push_back(node);
subscribersLeftInChildren += 1; // We just have to be sure it's not 0.
childrenIt++;
continue;
}
int n = node->cleanSubscriptions(defferedLeafs);
subscribersLeftInChildren += n;
if (n > 0)
childrenIt++;
else
childrenIt = children.erase(childrenIt);
}
std::list<std::shared_ptr<SubscriptionNode>*> wildcardChildren;
wildcardChildren.push_back(&childrenPlus);
wildcardChildren.push_back(&childrenPound);
for (std::shared_ptr<SubscriptionNode> *node : wildcardChildren)
{
std::shared_ptr<SubscriptionNode> &node_ = *node;
if (!node_)
continue;
int n = node_->cleanSubscriptions(defferedLeafs);
subscribersLeftInChildren += n;
if (n == 0)
{
Logger::getInstance()->logf(LOG_DEBUG, "Resetting wildcard children");
node_.reset();
}
}
{
// This is not particularlly fast when it's many items. But we don't do it often, so is probably okay.
auto it = subscribers.begin();
while (it != subscribers.end())
{
auto cur_it = it;
it++;
if (cur_it->second.session.expired())
{
Logger::getInstance()->logf(LOG_DEBUG, "Removing empty spot in subscribers map");
subscribers.erase(cur_it);
}
}
}
{
auto shared_it = sharedSubscribers.begin();
while (shared_it != sharedSubscribers.end())
{
auto cur_shared = shared_it;
shared_it++;
SharedSubscribers &subscribers_of_share = cur_shared->second;
subscribers_of_share.purgeAndReIndex();