-
Notifications
You must be signed in to change notification settings - Fork 58
/
broker.go
1282 lines (1153 loc) · 35.8 KB
/
broker.go
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
package router
import (
"fmt"
"time"
"github.com/gammazero/nexus/v3/stdlog"
"github.com/gammazero/nexus/v3/wamp"
)
const (
detailTopic = "topic"
)
// Role information for this broker.
var brokerRole = wamp.Dict{
"features": wamp.Dict{
wamp.FeaturePatternSub: true,
wamp.FeaturePubExclusion: true,
wamp.FeaturePubIdent: true,
wamp.FeatureSessionMetaAPI: true,
wamp.FeatureSubBlackWhiteListing: true,
wamp.FeatureSubMetaAPI: true,
wamp.FeaturePayloadPassthruMode: true,
wamp.FeatureEventHistory: true,
},
}
// subscription manages all the subscribers to a particular topic.
type subscription struct {
id wamp.ID // subscription ID
topic wamp.URI // topic URI
match string // match policy
created string // when subscription was created
subscribers map[*wamp.Session]struct{}
}
// storedEvent is a wrapper around wamp event message with timestamp
// to be used in event history
type storedEvent struct {
timestamp time.Time
Subscription wamp.ID
Publication wamp.ID
Details wamp.Dict
Arguments wamp.List `wamp:"omitempty"`
ArgumentsKw wamp.Dict `wamp:"omitempty"`
}
type historyEntry struct {
publication *wamp.Publish
event storedEvent
}
type historyStore struct {
entries []historyEntry
matchPolicy string
limit int
isLimitReached bool
}
type broker struct {
// topic -> subscription
topicSubscription map[wamp.URI]*subscription
pfxTopicSubscription map[wamp.URI]*subscription
wcTopicSubscription map[wamp.URI]*subscription
// event history in-memory store
eventHistoryStore map[*subscription]*historyStore
// subscription ID -> subscription
subscriptions map[wamp.ID]*subscription
// Session -> subscription ID set
sessionSubIDSet map[*wamp.Session]map[wamp.ID]struct{}
actionChan chan func()
stopped chan struct{}
// Generate subscription IDs.
idGen *wamp.IDGen
strictURI bool
allowDisclose bool
log stdlog.StdLog
debug bool
filterFactory FilterFactory
}
// newBroker returns a new default broker implementation instance.
func newBroker(logger stdlog.StdLog, strictURI, allowDisclose, debug bool, publishFilter FilterFactory, evntCfgs []*TopicEventHistoryConfig) (*broker, error) { //nolint:lll
if logger == nil {
panic("logger is nil")
}
if publishFilter == nil {
publishFilter = NewSimplePublishFilter
}
b := &broker{
topicSubscription: map[wamp.URI]*subscription{},
pfxTopicSubscription: map[wamp.URI]*subscription{},
wcTopicSubscription: map[wamp.URI]*subscription{},
eventHistoryStore: map[*subscription]*historyStore{},
subscriptions: map[wamp.ID]*subscription{},
sessionSubIDSet: map[*wamp.Session]map[wamp.ID]struct{}{},
// The action handler should be nearly always runable, since it is the
// critical section that does the only routing. So, and unbuffered
// channel is appropriate.
actionChan: make(chan func()),
stopped: make(chan struct{}),
idGen: new(wamp.IDGen),
strictURI: strictURI,
allowDisclose: allowDisclose,
log: logger,
debug: debug,
filterFactory: publishFilter,
}
err := b.PreInitEventHistoryTopics(evntCfgs)
// if broker fails initialize event history store we just log it,
// the broker itself will continue to operate but without event history store
if err != nil {
return nil, configError{Err: err}
}
go b.run()
return b, nil
}
// role returns the role information for the "broker" role. The data returned
// is suitable for use as broker role info in a WELCOME message.
func (b *broker) role() wamp.Dict {
return brokerRole
}
// PreInitEventHistoryTopics initializes storage for event history enabled topics.
func (b *broker) PreInitEventHistoryTopics(evntCfgs []*TopicEventHistoryConfig) error {
for _, topicCfg := range evntCfgs {
if !topicCfg.Topic.ValidURI(b.strictURI, topicCfg.MatchPolicy) {
return fmt.Errorf("invalid topic/match configuration found: %s %s", topicCfg.Topic, topicCfg.MatchPolicy)
}
if topicCfg.Limit <= 0 {
return fmt.Errorf("invalid limit for topic configuration found: %d %s", topicCfg.Limit, topicCfg.Topic)
}
sub, _ := b.syncInitSubscription(topicCfg.Topic, topicCfg.MatchPolicy, nil)
b.eventHistoryStore[sub] = &historyStore{
entries: []historyEntry{},
matchPolicy: topicCfg.MatchPolicy,
limit: topicCfg.Limit,
isLimitReached: false,
}
}
return nil
}
// publish finds all subscriptions for the topic being published to, including
// those matching the topic by pattern, and sends an event to the subscribers
// of that topic.
//
// When a single event matches more than one of a Subscriber's subscriptions,
// the event will be delivered for each subscription.
//
// The Subscriber can detect the delivery of that same event on multiple
// subscriptions via EVENT.PUBLISHED.Publication, which will be identical.
func (b *broker) publish(pub *wamp.Session, msg *wamp.Publish) {
if pub == nil || msg == nil {
panic("broker.Publish with nil session or message")
}
// Send a publish error only when pubAck is set.
pubAck, _ := msg.Options[wamp.OptAcknowledge].(bool)
// Validate URI. For PUBLISH, must be valid URI (either strict or loose),
// and all URI components must be non-empty.
if !msg.Topic.ValidURI(b.strictURI, "") {
if !pubAck {
return
}
errMsg := fmt.Sprintf(
"publish with invalid topic URI %v (URI strict checking %v)",
msg.Topic, b.strictURI)
b.trySend(pub, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Error: wamp.ErrInvalidURI,
Arguments: wamp.List{errMsg},
Details: wamp.Dict{},
})
return
}
details := wamp.Dict{}
// Check and handle Payload PassThru Mode
// @see https://wamp-proto.org/wamp_latest_ietf.html#name-payload-passthru-mode
if pptScheme, _ := msg.Options[wamp.OptPPTScheme].(string); pptScheme != "" {
// Let's check: was ppt feature announced by publisher?
if !pub.HasFeature(wamp.RolePublisher, wamp.FeaturePayloadPassthruMode) {
// It's protocol violation, so we need to abort connection
abortMsg := wamp.Abort{Reason: wamp.ErrProtocolViolation}
abortMsg.Details = wamp.Dict{}
abortMsg.Details[wamp.OptMessage] = ErrPPTNotSupportedByPeer.Error()
b.trySend(pub, &abortMsg)
pub.Close()
return
}
// Every side supports PPT feature
// Let's fill PPT options for callee
pptOptionsToDetails(msg.Options, details)
}
excludePub := true
if exclude, ok := msg.Options[wamp.OptExcludeMe].(bool); ok {
if !pub.HasFeature(wamp.RolePublisher, wamp.FeaturePubExclusion) {
b.log.Println(wamp.RolePublisher, "included", wamp.OptExcludeMe,
"option but did not announce support for",
wamp.FeaturePubExclusion)
// Do not return error here, even though published did not announce
// for publisher_exclusion. Assume that publisher supports it
// since specify option that requires it.
}
excludePub = exclude
}
// A Broker may also (automatically) disclose the identity of a
// publisher even without the publisher having explicitly requested to
// do so when the Broker configuration (for the publication topic) is
// set up to do so. TODO: Currently no broker config for this.
var disclose bool
if opt, _ := msg.Options[wamp.OptDiscloseMe].(bool); opt {
// Broker MAY deny a publisher's request to disclose its identity.
if !b.allowDisclose {
if pubAck {
b.trySend(pub, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrOptionDisallowedDiscloseMe,
})
}
// When the publisher requested disclosure, but it isn't
// allowed, don't continue to publish the message.
return
}
disclose = true
}
pubID := wamp.GlobalID()
// Get blacklists and whitelists, if any, from publish message.
filter := b.filterFactory(msg)
b.actionChan <- func() {
b.syncPublish(pub, msg, pubID, excludePub, disclose, filter, details)
}
// Send PUBLISHED message if acknowledge is present and true.
if pubAck {
b.trySend(pub, &wamp.Published{Request: msg.Request, Publication: pubID})
}
}
// subscribe subscribes the client to the given topic.
//
// In case of receiving a SUBSCRIBE message from the same Subscriber and to
// already subscribed topic, Broker should answer with SUBSCRIBED message,
// containing the existing Subscription|id.
//
// By default, Subscribers subscribe to topics with exact matching policy. A
// Subscriber might want to subscribe to topics based on a pattern. If the
// Broker and the Subscriber support pattern-based subscriptions, this matching
// can happen by prefix-matching policy or wildcard-matching policy.
func (b *broker) subscribe(sub *wamp.Session, msg *wamp.Subscribe) {
if sub == nil || msg == nil {
panic("broker.Subscribe with nil session or message")
}
// Validate topic URI. For SUBSCRIBE, must be valid URI (either strict or
// loose), and all URI components must be non-empty for normal
// subscriptions, may be empty for wildcard subscriptions and must be
// non-empty for all but the last component for prefix subscriptions.
match, _ := wamp.AsString(msg.Options[wamp.OptMatch])
if !msg.Topic.ValidURI(b.strictURI, match) {
errMsg := fmt.Sprintf(
"subscribe for invalid topic URI %v (URI strict checking %v)",
msg.Topic, b.strictURI)
b.trySend(sub, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Error: wamp.ErrInvalidURI,
Arguments: wamp.List{errMsg},
Details: wamp.Dict{},
})
return
}
b.actionChan <- func() {
b.syncSubscribe(sub, msg, match)
}
}
// unsubscribe removes the requested subscription.
func (b *broker) unsubscribe(sub *wamp.Session, msg *wamp.Unsubscribe) {
if sub == nil || msg == nil {
panic("broker.Unsubscribe with nil session or message")
}
b.actionChan <- func() {
b.syncUnsubscribe(sub, msg)
}
}
// removeSession removes all subscriptions of the subscriber. This is called
// when a client leaves the realm by sending a GOODBYE message or by
// disconnecting from the router. If there are any subscriptions for this
// session a wamp.subscription.on_delete meta event is published for each.
func (b *broker) removeSession(sess *wamp.Session) {
if sess == nil {
return
}
b.actionChan <- func() {
b.syncRemoveSession(sess)
}
}
// Close stops the broker, letting already queued actions finish.
func (b *broker) close() {
close(b.actionChan)
<-b.stopped
if b.debug {
b.log.Print("Broker stopped")
}
}
func (b *broker) run() {
for action := range b.actionChan {
action()
}
close(b.stopped)
}
func (b *broker) syncPublish(pub *wamp.Session, msg *wamp.Publish, pubID wamp.ID, excludePub, disclose bool, filter PublishFilter, eventDetails wamp.Dict) { //nolint:lll
// Publish to subscribers with exact match.
if sub, ok := b.topicSubscription[msg.Topic]; ok {
b.syncPubEvent(pub, msg, pubID, sub, excludePub, false, disclose, filter, eventDetails)
}
// Publish to subscribers with prefix match.
for pfxTopic, sub := range b.pfxTopicSubscription {
if msg.Topic.PrefixMatch(pfxTopic) {
b.syncPubEvent(pub, msg, pubID, sub, excludePub, true, disclose, filter, eventDetails)
}
}
// Publish to subscribers with wildcard match.
for wcTopic, sub := range b.wcTopicSubscription {
if msg.Topic.WildcardMatch(wcTopic) {
b.syncPubEvent(pub, msg, pubID, sub, excludePub, true, disclose, filter, eventDetails)
}
}
}
func newSubscription(id wamp.ID, subscriber *wamp.Session, topic wamp.URI, match string) *subscription {
subscribers := map[*wamp.Session]struct{}{}
if subscriber != nil {
subscribers[subscriber] = struct{}{}
}
return &subscription{
id: id,
topic: topic,
match: match,
created: wamp.NowISO8601(),
subscribers: subscribers,
}
}
func (b *broker) syncSaveEvent(eventStore *historyStore, pub *wamp.Publish, event *wamp.Event) {
if eventStore.isLimitReached {
eventStore.entries = eventStore.entries[1:]
} else if len(eventStore.entries) >= eventStore.limit {
eventStore.isLimitReached = true
eventStore.entries = eventStore.entries[1:]
}
item := historyEntry{
publication: pub,
event: storedEvent{
timestamp: time.Now(),
Subscription: event.Subscription,
Publication: event.Publication,
Details: event.Details,
Arguments: event.Arguments,
ArgumentsKw: event.ArgumentsKw,
},
}
eventStore.entries = append(eventStore.entries, item)
}
func (b *broker) syncInitSubscription(topic wamp.URI, match string, subscriber *wamp.Session) (sub *subscription, existingSub bool) {
switch match {
case wamp.MatchPrefix:
// Subscribe to any topic that matches by the given prefix URI
sub, existingSub = b.pfxTopicSubscription[topic]
if !existingSub {
// Create a new prefix subscription.
sub = newSubscription(b.idGen.Next(), subscriber, topic, match)
b.pfxTopicSubscription[topic] = sub
}
case wamp.MatchWildcard:
// Subscribe to any topic that matches by the given wildcard URI.
sub, existingSub = b.wcTopicSubscription[topic]
if !existingSub {
// Create a new wildcard subscription.
sub = newSubscription(b.idGen.Next(), subscriber, topic, match)
b.wcTopicSubscription[topic] = sub
}
default:
// Subscribe to the topic that exactly matches the given URI.
sub, existingSub = b.topicSubscription[topic]
if !existingSub {
// Create a new subscription.
sub = newSubscription(b.idGen.Next(), subscriber, topic, match)
b.topicSubscription[topic] = sub
}
}
b.subscriptions[sub.id] = sub
return sub, existingSub
}
func (b *broker) syncSubscribe(subscriber *wamp.Session, msg *wamp.Subscribe, match string) {
sub, existingSub := b.syncInitSubscription(msg.Topic, match, subscriber)
// If the topic already has subscribers, then see if the session requesting
// a subscription is already subscribed to the topic.
if existingSub {
if _, already := sub.subscribers[subscriber]; already {
// Already subscribed; send existing subscription ID.
b.trySend(subscriber, &wamp.Subscribed{
Request: msg.Request,
Subscription: sub.id,
})
return
}
// Add subscriber to existing subscription.
sub.subscribers[subscriber] = struct{}{}
}
// Add the subscription ID to the set of subscriptions for the subscriber.
subIdSet, ok := b.sessionSubIDSet[subscriber]
if !ok {
// This subscriber does not have any other subscriptions, so new set.
subIdSet = map[wamp.ID]struct{}{}
b.sessionSubIDSet[subscriber] = subIdSet
}
subIdSet[sub.id] = struct{}{}
// Tell sender the new subscription ID.
b.trySend(subscriber, &wamp.Subscribed{Request: msg.Request, Subscription: sub.id})
if !existingSub {
b.syncPubSubCreateMeta(msg.Topic, subscriber.ID, sub)
}
// Publish WAMP on_subscribe meta event.
b.syncPubSubMeta(wamp.MetaEventSubOnSubscribe, subscriber.ID, sub.id)
}
// syncDeleteSubscription removes the the ID->subscription mapping and removes
// the topic->subscription mapping.
func (b *broker) syncDelSubscription(sub *subscription) {
// Remove ID -> subscription.
delete(b.subscriptions, sub.id)
// Delete topic -> subscription
switch sub.match {
case wamp.MatchPrefix:
delete(b.pfxTopicSubscription, sub.topic)
case wamp.MatchWildcard:
delete(b.wcTopicSubscription, sub.topic)
default:
delete(b.topicSubscription, sub.topic)
}
}
// syncUnsibsubscribe removes the subscriber from the specified subscription.
func (b *broker) syncUnsubscribe(subscriber *wamp.Session, msg *wamp.Unsubscribe) {
subID := msg.Subscription
sub, ok := b.subscriptions[subID]
if !ok {
b.trySend(subscriber, &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Error: wamp.ErrNoSuchSubscription,
Details: wamp.Dict{},
})
b.log.Println("Error unsubscribing: no such subscription", subID)
return
}
// Remove subscribed session from subscription.
delete(sub.subscribers, subscriber)
// If no more subscribers on this subscription, delete subscription and
// send on_delete meta event.
var delLastSub bool
if len(sub.subscribers) == 0 {
b.syncDelSubscription(sub)
delLastSub = true
}
// Clean up subscriber's subscription ID set.
if subIDSet, ok := b.sessionSubIDSet[subscriber]; !ok {
b.log.Print("Error unsubscribing: no subscriptions for sender")
} else if _, ok := subIDSet[subID]; !ok {
b.log.Println("Error unsubscribing: no such subscription for sender:",
subID)
} else {
delete(subIDSet, subID)
// If subscriber has no remaining subscriptions.
if len(subIDSet) == 0 {
// Remove subscribers subscription ID set.
delete(b.sessionSubIDSet, subscriber)
}
}
// Tell sender they are unsubscribed.
b.trySend(subscriber, &wamp.Unsubscribed{Request: msg.Request})
// Publish WAMP unsubscribe meta event.
b.syncPubSubMeta(wamp.MetaEventSubOnUnsubscribe, subscriber.ID, subID)
if delLastSub {
// Fired when a subscription is deleted after the last session attached
// to it has been removed.
b.syncPubSubMeta(wamp.MetaEventSubOnDelete, subscriber.ID, subID)
}
}
// syncRemoveSession removed all subscriptions for the session.
func (b *broker) syncRemoveSession(subscriber *wamp.Session) {
subIDSet, ok := b.sessionSubIDSet[subscriber]
if !ok {
return
}
delete(b.sessionSubIDSet, subscriber)
// For each subscription ID, lookup the subscription and remove the
// subscriber from the subscription. If there are no more subscribers on
// the subscription, then delete the subscription.
var sub *subscription
for subID := range subIDSet {
sub, ok = b.subscriptions[subID]
if !ok {
continue
}
// Remove subscribed session from subscription.
delete(sub.subscribers, subscriber)
// If no more subscribers on this subscription.
if len(sub.subscribers) == 0 {
b.syncDelSubscription(sub)
// Fired when a subscription is deleted after the last
// session attached to it has been removed.
b.syncPubSubMeta(wamp.MetaEventSubOnDelete, subscriber.ID, subID)
}
}
}
// syncPubEvent sends an event to all subscribers that are not excluded from
// receiving the event.
func (b *broker) syncPubEvent(pub *wamp.Session, msg *wamp.Publish, pubID wamp.ID, sub *subscription, excludePublisher, sendTopic, disclose bool, filter PublishFilter, eventDetails wamp.Dict) { //nolint:lll
for subscriber := range sub.subscribers {
// Do not send event to publisher.
if subscriber == pub && excludePublisher {
continue
}
// Check if receiver is restricted.
if filter != nil {
// Create a safe session to prevent access to the session.Peer.
safeSession := wamp.Session{
ID: subscriber.ID,
Details: subscriber.Details,
}
subscriber.Lock()
ok := filter.Allowed(&safeSession)
subscriber.Unlock()
if !ok {
continue
}
}
event := prepareEvent(pub, msg, pubID, sub, sendTopic, disclose, eventDetails, subscriber)
b.trySend(subscriber, event)
}
// If event history store is enabled for subscription let's save event
if eventStore, ok := b.eventHistoryStore[sub]; ok {
// We should ignore publications that have exclude or eligible lists of session IDs
// As session ID is a runtime thing, it is impossible to check later: is history asker allowed to get
// this publication or not
// @see Security Aspects paragraph of Event History section in WAMP Spec
if _, ok := msg.Options["exclude"]; ok {
return
}
if _, ok := msg.Options["eligible"]; ok {
return
}
event := prepareEvent(pub, msg, pubID, sub, sendTopic, disclose, eventDetails, nil)
b.syncSaveEvent(eventStore, msg, event)
}
}
// syncPubMeta publishes the subscription meta event, using the supplied
// function, to the matching subscribers.
func (b *broker) syncPubMeta(metaTopic wamp.URI, sendMeta func(metaSub *subscription, sendTopic bool)) {
// Publish to subscribers with exact match.
if metaSub, ok := b.topicSubscription[metaTopic]; ok {
sendMeta(metaSub, false)
}
// Publish to subscribers with prefix match.
for pfxTopic, metaSub := range b.pfxTopicSubscription {
if metaTopic.PrefixMatch(pfxTopic) {
sendMeta(metaSub, true)
}
}
// Publish to subscribers with wildcard match.
for wcTopic, metaSub := range b.wcTopicSubscription {
if metaTopic.WildcardMatch(wcTopic) {
sendMeta(metaSub, true)
}
}
}
// syncPubSubMeta publishes a subscription meta event when a subscription is
// added, removed, or deleted.
func (b *broker) syncPubSubMeta(metaTopic wamp.URI, subSessID, subID wamp.ID) {
pubID := wamp.GlobalID() // create here so that it is same for all events
b.syncPubMeta(metaTopic, func(metaSub *subscription, sendTopic bool) {
makeEvent := func() *wamp.Event {
evt := &wamp.Event{
Publication: pubID,
Subscription: metaSub.id,
Details: wamp.Dict{},
Arguments: wamp.List{subSessID, subID},
}
if sendTopic {
evt.Details[detailTopic] = metaTopic
}
return evt
}
var event *wamp.Event
for subscriber := range metaSub.subscribers {
// Do not send the meta event to the session that is causing the
// meta event to be generated. This prevents useless events that
// could lead to race conditions on the client.
if subscriber.ID == subSessID {
continue
}
// Need to send separate event message to each local subscriber,
// since local clients could modify contents.
if subscriber.Peer.IsLocal() {
b.trySend(subscriber, makeEvent())
continue
}
if event == nil {
event = makeEvent()
}
b.trySend(subscriber, event)
}
})
}
// syncPubSubCreateMeta publishes a meta event on subscription creation.
//
// Fired when a subscription is created through a subscription request for a
// topic which was previously without subscribers.
func (b *broker) syncPubSubCreateMeta(topic wamp.URI, subSessID wamp.ID, sub *subscription) {
pubID := wamp.GlobalID() // create here so that it is same for all events
b.syncPubMeta(wamp.MetaEventSubOnCreate, func(metaSub *subscription, sendTopic bool) {
makeEvent := func() *wamp.Event {
evt := &wamp.Event{
Publication: pubID,
Subscription: metaSub.id,
Details: wamp.Dict{},
Arguments: wamp.List{
subSessID,
wamp.Dict{
"id": sub.id,
"created": sub.created,
"uri": sub.topic,
wamp.OptMatch: sub.match,
},
},
}
if sendTopic {
evt.Details[detailTopic] = wamp.MetaEventSubOnCreate
}
return evt
}
var event *wamp.Event
for subscriber := range metaSub.subscribers {
// Do not send the meta event to the session that is causing the
// meta event to be generated. This prevents useless events that
// could lead to race conditions on the client.
if subscriber.ID == subSessID {
continue
}
// Need to send separate event message to each locsl subscriber,
// since local clients could modify contents.
if subscriber.Peer.IsLocal() {
b.trySend(subscriber, makeEvent())
continue
}
if event == nil {
event = makeEvent()
}
b.trySend(subscriber, event)
}
})
}
func (b *broker) trySend(sess *wamp.Session, msg wamp.Message) {
select {
case sess.Send() <- msg:
default:
b.log.Printf("!!! Dropped %s to session %s: blocked", msg.MessageType(), sess)
}
}
func prepareEvent(pub *wamp.Session, msg *wamp.Publish, pubID wamp.ID, sub *subscription, sendTopic, disclose bool, eventDetails wamp.Dict, subscriber *wamp.Session) *wamp.Event { //nolint:lll
details := eventDetails
if details == nil {
details = wamp.Dict{}
}
event := &wamp.Event{
Publication: pubID,
Subscription: sub.id,
Arguments: msg.Arguments,
ArgumentsKw: msg.ArgumentsKw,
Details: details,
}
// If a subscription was established with a pattern-based matching
// policy, a Broker MUST supply the original PUBLISH.Topic as provided
// by the Publisher in EVENT.Details.topic|uri.
if sendTopic {
event.Details[detailTopic] = msg.Topic
}
if disclose && subscriber != nil && subscriber.HasFeature(wamp.RoleSubscriber, wamp.FeaturePubIdent) {
disclosePublisher(pub, event.Details)
}
// TODO: Handle publication trust levels
if subscriber != nil && subscriber.Peer.IsLocal() {
// the local handler may be lousy and may try to modify
// either of those fields, make sure that each event
// carries a copy of the respective structure, even if
// it's empty
if event.Details != nil {
options := make(map[string]interface{}, len(event.Details))
for k, v := range event.Details {
options[k] = v
}
event.Details = options
}
if msg.Arguments != nil {
event.Arguments = make([]interface{}, len(msg.Arguments))
copy(event.Arguments, msg.Arguments)
}
if msg.ArgumentsKw != nil {
argsKw := make(map[string]interface{}, len(msg.ArgumentsKw))
for k, v := range msg.ArgumentsKw {
argsKw[k] = v
}
event.ArgumentsKw = argsKw
}
}
return event
}
// disclosePublisher adds publisher identity information to EVENT.Details.
func disclosePublisher(pub *wamp.Session, details wamp.Dict) {
details[wamp.RolePublisher] = pub.ID
// These values are not required by the specification, but are here for
// compatibility with Crossbar.
pub.Lock()
for _, f := range []string{"authid", "authrole"} {
if val, ok := pub.Details[f]; ok {
details[fmt.Sprintf("%s_%s", wamp.RolePublisher, f)] = val
}
}
pub.Unlock()
}
// ----- Subscription Meta Procedure Handlers -----
// subList retrieves subscription IDs listed according to match policies.
func (b *broker) subList(msg *wamp.Invocation) wamp.Message {
var exactSubs, pfxSubs, wcSubs []wamp.ID
sync := make(chan struct{})
b.actionChan <- func() {
for subID, sub := range b.subscriptions {
switch sub.match {
case wamp.MatchPrefix:
pfxSubs = append(pfxSubs, subID)
case wamp.MatchWildcard:
wcSubs = append(wcSubs, subID)
default:
exactSubs = append(exactSubs, subID)
}
}
close(sync)
}
<-sync
dict := wamp.Dict{
wamp.MatchExact: exactSubs,
wamp.MatchPrefix: pfxSubs,
wamp.MatchWildcard: wcSubs,
}
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{dict},
}
}
// subLookup obtains the subscription (if any) managing a topic, according
// to some match policy.
func (b *broker) subLookup(msg *wamp.Invocation) wamp.Message {
var subID wamp.ID
if len(msg.Arguments) != 0 {
if topic, ok := wamp.AsURI(msg.Arguments[0]); ok {
var match string
if len(msg.Arguments) > 1 {
if opts, ok := wamp.AsDict(msg.Arguments[1]); ok {
match, _ = wamp.AsString(opts[wamp.OptMatch])
}
}
sync := make(chan struct{})
b.actionChan <- func() {
var sub *subscription
var ok bool
switch match {
default:
sub, ok = b.topicSubscription[topic]
case wamp.MatchPrefix:
sub, ok = b.pfxTopicSubscription[topic]
case wamp.MatchWildcard:
sub, ok = b.wcTopicSubscription[topic]
}
if ok {
subID = sub.id
}
close(sync)
}
<-sync
}
}
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{subID},
}
}
// subMatch retrieves a list of IDs of subscriptions matching a topic URI,
// irrespective of match policy.
func (b *broker) subMatch(msg *wamp.Invocation) wamp.Message {
var subIDs []wamp.ID
if len(msg.Arguments) != 0 {
if topic, ok := wamp.AsURI(msg.Arguments[0]); ok {
sync := make(chan struct{})
b.actionChan <- func() {
if sub, ok := b.topicSubscription[topic]; ok {
subIDs = append(subIDs, sub.id)
}
for pfxTopic, sub := range b.pfxTopicSubscription {
if topic.PrefixMatch(pfxTopic) {
subIDs = append(subIDs, sub.id)
}
}
for wcTopic, sub := range b.wcTopicSubscription {
if topic.WildcardMatch(wcTopic) {
subIDs = append(subIDs, sub.id)
}
}
close(sync)
}
<-sync
}
}
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{subIDs},
}
}
// subGet retrieves information on a particular subscription.
func (b *broker) subGet(msg *wamp.Invocation) wamp.Message {
var dict wamp.Dict
if len(msg.Arguments) != 0 {
if subID, ok := wamp.AsID(msg.Arguments[0]); ok {
sync := make(chan struct{})
b.actionChan <- func() {
if sub, ok := b.subscriptions[subID]; ok {
dict = wamp.Dict{
"id": subID,
"created": sub.created,
"uri": sub.topic,
wamp.OptMatch: sub.match,
}
}
close(sync)
}
<-sync
}
}
if dict == nil {
return &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrNoSuchSubscription,
}
}
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{dict},
}
}
// subListSubscribers retrieves a list of session IDs for sessions currently
// attached to the subscription.
func (b *broker) subListSubscribers(msg *wamp.Invocation) wamp.Message {
var subscriberIDs []wamp.ID
if len(msg.Arguments) != 0 {
if subID, ok := wamp.AsID(msg.Arguments[0]); ok {
sync := make(chan struct{})
b.actionChan <- func() {
if sub, ok := b.subscriptions[subID]; ok {
subscriberIDs = make([]wamp.ID, len(sub.subscribers))
var i int
for subscriber := range sub.subscribers {
subscriberIDs[i] = subscriber.ID
i++
}
}
close(sync)
}
<-sync
}
}
if len(subscriberIDs) == 0 {
return &wamp.Error{
Type: msg.MessageType(),
Request: msg.Request,
Details: wamp.Dict{},
Error: wamp.ErrNoSuchSubscription,
}
}
return &wamp.Yield{
Request: msg.Request,
Arguments: wamp.List{subscriberIDs},
}
}
// subCountSubscribers obtains the number of sessions currently attached to the
// subscription.
func (b *broker) subCountSubscribers(msg *wamp.Invocation) wamp.Message {
var count int
var ok bool
if len(msg.Arguments) != 0 {
var subID wamp.ID
if subID, ok = wamp.AsID(msg.Arguments[0]); ok {
sync := make(chan struct{})
b.actionChan <- func() {
if sub, found := b.subscriptions[subID]; found {
count = len(sub.subscribers)
} else {
ok = false
}
close(sync)
}