This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pubsub.go
2514 lines (2052 loc) · 68 KB
/
pubsub.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 contentpubsub
import (
"context"
"errors"
"fmt"
"io"
"log"
"math/big"
"math/rand"
"net"
"sync"
"time"
"github.com/libp2p/go-libp2p-core/peer"
kaddht "github.com/libp2p/go-libp2p-kad-dht"
kb "github.com/libp2p/go-libp2p-kbucket"
key "github.com/libp2p/go-libp2p-kbucket/keyspace"
pb "github.com/pedroaston/contentpubsub/pb"
"google.golang.org/grpc"
)
// PubSub supports all the middleware logic
type PubSub struct {
maxSubsPerRegion int
powerSubsPoolSize int
maxAttributesPerPredicate int
timeToCheckDelivery time.Duration
opResendRate time.Duration
rpcTimeout time.Duration
faultToleranceFactor int
region string
activeRedirect bool
activeReliability bool
addrOption bool
pb.UnimplementedScoutHubServer
server *grpc.Server
serverAddr string
ipfsDHT *kaddht.IpfsDHT
currentFilterTable *FilterTable
nextFilterTable *FilterTable
myFilters *RouteStats
rvCache []string
myBackups []string
myBackupsFilters map[string]*FilterTable
myTrackers map[string]*Tracker
myETrackers map[string]*EventLedger
myEBackTrackers map[string]*EventLedger
interestingEvents chan *pb.Event
heartbeatTicker *time.Ticker
refreshTicker *time.Ticker
eventTicker *time.Ticker
subTicker *time.Ticker
eventTickerState bool
subTickerState bool
terminate chan string
unconfirmedEvents map[string]*PubEventState
totalUnconfirmedEvents int
unconfirmedSubs map[string]*SubState
totalUnconfirmedSubs int
lives int
tablesLock *sync.RWMutex
upBackLock *sync.RWMutex
ackOpLock *sync.Mutex
ackUpLock *sync.Mutex
capacity int
managedGroups []*MulticastGroup
subbedGroups []*SubGroupView
premiumEvents chan *pb.PremiumEvent
currentAdvertiseBoard []*pb.MulticastGroupID
nextAdvertiseBoard []*pb.MulticastGroupID
advToForward chan *ForwardAdvert
record *HistoryRecord
session int
eventSeq int
}
func NewPubSub(dht *kaddht.IpfsDHT, cfg *SetupPubSub) *PubSub {
filterTable := NewFilterTable(dht, cfg.TestgroundReady)
auxFilterTable := NewFilterTable(dht, cfg.TestgroundReady)
mySubs := NewRouteStats("no need")
ps := &PubSub{
maxSubsPerRegion: cfg.MaxSubsPerRegion,
powerSubsPoolSize: cfg.PowerSubsPoolSize,
maxAttributesPerPredicate: cfg.MaxAttributesPerPredicate,
timeToCheckDelivery: cfg.TimeToCheckDelivery,
faultToleranceFactor: cfg.FaultToleranceFactor,
opResendRate: cfg.OpResendRate,
region: cfg.Region,
capacity: cfg.Capacity,
activeRedirect: cfg.RedirectMechanism,
activeReliability: cfg.ReliableMechanisms,
addrOption: cfg.TestgroundReady,
rpcTimeout: cfg.RPCTimeout,
currentFilterTable: filterTable,
nextFilterTable: auxFilterTable,
myFilters: mySubs,
ipfsDHT: dht,
myBackupsFilters: make(map[string]*FilterTable),
myTrackers: make(map[string]*Tracker),
myETrackers: make(map[string]*EventLedger),
myEBackTrackers: make(map[string]*EventLedger),
unconfirmedEvents: make(map[string]*PubEventState),
unconfirmedSubs: make(map[string]*SubState),
interestingEvents: make(chan *pb.Event, cfg.ConcurrentProcessingFactor),
premiumEvents: make(chan *pb.PremiumEvent, cfg.ConcurrentProcessingFactor),
terminate: make(chan string),
advToForward: make(chan *ForwardAdvert, cfg.ConcurrentProcessingFactor),
heartbeatTicker: time.NewTicker(cfg.SubRefreshRateMin),
refreshTicker: time.NewTicker(2 * cfg.SubRefreshRateMin),
eventTicker: time.NewTicker(cfg.OpResendRate),
subTicker: time.NewTicker(cfg.OpResendRate),
eventTickerState: false,
subTickerState: false,
tablesLock: &sync.RWMutex{},
upBackLock: &sync.RWMutex{},
ackOpLock: &sync.Mutex{},
ackUpLock: &sync.Mutex{},
totalUnconfirmedEvents: 0,
totalUnconfirmedSubs: 0,
record: NewHistoryRecord(),
session: rand.Intn(9999),
eventSeq: 0,
lives: 0,
}
ps.myBackups = ps.getBackups()
ps.eventTicker.Stop()
ps.subTicker.Stop()
dialAddr := addrForPubSubServer(ps.ipfsDHT.Host().Addrs(), ps.addrOption)
lis, err := net.Listen("tcp", dialAddr)
if err != nil {
return nil
}
ps.serverAddr = dialAddr
ps.server = grpc.NewServer()
pb.RegisterScoutHubServer(ps.server, ps)
go ps.server.Serve(lis)
go ps.processLoop()
return ps
}
// +++++++++++++++++++++++++++++++ ScoutSubs ++++++++++++++++++++++++++++++++
type PubEventState struct {
event *pb.Event
aged bool
dialAddr string
}
type SubState struct {
sub *pb.Subscription
aged bool
dialAddr string
started string
}
type AckUp struct {
dialAddr string
eventID *pb.EventID
peerID string
rvID string
}
// MySubscribe subscribes to certain event(s) and saves
// it in myFilters for further resubing operations and
// assess if node is interested in the events it receives
func (ps *PubSub) MySubscribe(info string) error {
fmt.Println("MySubscribe: " + ps.serverAddr)
p, err := NewPredicate(info, ps.maxAttributesPerPredicate)
if err != nil {
return err
}
_, pNew := ps.myFilters.SimpleAddSummarizedFilter(p, nil)
if pNew != nil {
p = pNew
}
for _, attr := range p.attributes {
isRv, _ := ps.rendezvousSelfCheck(attr.name)
if isRv {
return nil
}
}
_, minAttr, err := ps.closerAttrRvToSelf(p)
if err != nil {
return errors.New("failed to find the closest attribute Rv")
}
_, dialAddr := ps.rendezvousSelfCheck(minAttr)
if dialAddr == "" {
return errors.New("no address for closest peer")
}
if ps.activeRedirect {
ps.tablesLock.RLock()
ps.currentFilterTable.addToRouteTracker(minAttr, "sub")
ps.currentFilterTable.addToRouteTracker(minAttr, "closes")
ps.nextFilterTable.addToRouteTracker(minAttr, "sub")
ps.nextFilterTable.addToRouteTracker(minAttr, "closes")
ps.tablesLock.RUnlock()
}
sub := &pb.Subscription{
PeerID: peer.Encode(ps.ipfsDHT.PeerID()),
Predicate: info,
RvId: minAttr,
Shortcut: "!",
SubAddr: ps.serverAddr,
IntAddr: ps.serverAddr,
}
if ps.activeReliability {
ps.tablesLock.RLock()
ps.ackOpLock.Lock()
ps.unconfirmedSubs[sub.Predicate] = &SubState{
sub: sub,
aged: false,
dialAddr: dialAddr,
started: time.Now().Format(time.StampMilli),
}
ps.totalUnconfirmedSubs++
if !ps.subTickerState {
ps.subTicker.Reset(ps.opResendRate)
ps.subTickerState = true
ps.unconfirmedSubs[sub.Predicate].aged = true
}
ps.ackOpLock.Unlock()
ps.tablesLock.RUnlock()
}
go ps.forwardSub(dialAddr, sub)
return nil
}
// Subscribe is a remote function called by a external peer
// to send subscriptions towards the rendezvous node
func (ps *PubSub) Subscribe(ctx context.Context, sub *pb.Subscription) (*pb.Ack, error) {
fmt.Println("Subscribe >> " + ps.serverAddr)
p, err := NewPredicate(sub.Predicate, ps.maxAttributesPerPredicate)
if err != nil {
return &pb.Ack{State: false, Info: "error creating predicate"}, err
}
updateBackups := sub.Backups
var backAddrs []string
for _, addr := range sub.Backups {
backAddrs = append(backAddrs, addr)
}
ps.tablesLock.Lock()
if ps.currentFilterTable.routes[sub.PeerID] == nil {
ps.currentFilterTable.routes[sub.PeerID] = NewRouteStats(sub.IntAddr)
ps.nextFilterTable.routes[sub.PeerID] = NewRouteStats(sub.IntAddr)
} else if ps.nextFilterTable.routes[sub.PeerID] == nil {
ps.nextFilterTable.routes[sub.PeerID] = NewRouteStats(sub.IntAddr)
}
ps.tablesLock.Unlock()
ps.tablesLock.RLock()
if ps.activeRedirect {
if sub.Shortcut == "!" {
ps.currentFilterTable.turnOffRedirect(sub.PeerID, sub.RvId)
ps.nextFilterTable.turnOffRedirect(sub.PeerID, sub.RvId)
} else {
ps.currentFilterTable.addRedirect(sub.PeerID, sub.RvId, sub.Shortcut)
ps.nextFilterTable.addRedirect(sub.PeerID, sub.RvId, sub.Shortcut)
}
}
ps.currentFilterTable.routes[sub.PeerID].SimpleAddSummarizedFilter(p, backAddrs)
alreadyDone, pNew := ps.nextFilterTable.routes[sub.PeerID].SimpleAddSummarizedFilter(p, backAddrs)
ps.tablesLock.RUnlock()
if alreadyDone {
if ps.activeReliability {
ps.sendAckOp(sub.SubAddr, "Subscribe", sub.Predicate)
}
return &pb.Ack{State: true, Info: ""}, nil
} else if pNew != nil {
sub.Predicate = pNew.ToString()
}
isRv, nextHopAddr := ps.rendezvousSelfCheck(sub.RvId)
if !isRv && nextHopAddr != "" {
var backups map[int32]string = make(map[int32]string)
for i, backup := range ps.myBackups {
backups[int32(i)] = backup
}
subForward := &pb.Subscription{
PeerID: peer.Encode(ps.ipfsDHT.PeerID()),
Predicate: sub.Predicate,
RvId: sub.RvId,
Backups: backups,
SubAddr: sub.SubAddr,
IntAddr: ps.serverAddr,
}
if ps.activeRedirect {
ps.tablesLock.RLock()
ps.currentFilterTable.redirectLock.Lock()
if len(ps.currentFilterTable.routeTracker[sub.RvId]) >= 2 {
ps.currentFilterTable.redirectLock.Unlock()
ps.tablesLock.RUnlock()
subForward.Shortcut = "!"
} else if sub.Shortcut != "!" {
ps.currentFilterTable.redirectLock.Unlock()
ps.tablesLock.RUnlock()
subForward.Shortcut = sub.Shortcut
} else {
subForward.Shortcut = ps.currentFilterTable.routes[sub.PeerID].addr
ps.currentFilterTable.redirectLock.Unlock()
ps.tablesLock.RUnlock()
}
}
go ps.forwardSub(nextHopAddr, subForward)
ps.updateMyBackups(sub.PeerID, sub.Predicate, updateBackups)
} else if !isRv {
return &pb.Ack{State: false, Info: "rendezvous check failed"}, nil
} else {
if ps.activeReliability {
ps.sendAckOp(sub.SubAddr, "Subscribe", sub.Predicate)
}
ps.updateRvRegion(sub.PeerID, sub.Predicate, sub.RvId, updateBackups)
}
return &pb.Ack{State: true, Info: ""}, nil
}
// forwardSub is called once a received subscription
// still needs to be forward towards the rendevous
func (ps *PubSub) forwardSub(dialAddr string, sub *pb.Subscription) {
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
conn, err := grpc.Dial(dialAddr, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewScoutHubClient(conn)
ack, err := client.Subscribe(ctx, sub)
if err != nil || !ack.State {
alternatives := ps.alternativesToRv(sub.RvId)
for _, addr := range alternatives {
if addr == ps.serverAddr {
return
}
ctxBackup, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
conn, err := grpc.Dial(addr, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewScoutHubClient(conn)
ack, err := client.Subscribe(ctxBackup, sub)
if err == nil && ack.State {
break
}
}
}
}
// MyUnsubscribe deletes a specific predicate out of mySubs
// list which will stop the refreshing of thatsub and stop
// delivering to the user those contained events
func (ps *PubSub) MyUnsubscribe(info string) error {
fmt.Println("MyUnsubscribe: " + ps.serverAddr)
p, err := NewPredicate(info, ps.maxAttributesPerPredicate)
if err != nil {
return err
}
ps.myFilters.SimpleSubtractFilter(p)
return nil
}
// MyPublish function is used when we want to publish an event on the overlay.
// Data is the message we want to publish and info is the representative
// predicate of that event data. The publish operation is made towards all
// attributes rendezvous in order find the way to all subscribers
func (ps *PubSub) MyPublish(data string, info string) error {
fmt.Println("MyPublish: " + ps.serverAddr)
p, err := NewPredicate(info, ps.maxAttributesPerPredicate)
if err != nil {
return err
}
eventID := &pb.EventID{
PublisherID: peer.Encode(ps.ipfsDHT.PeerID()),
SessionNumber: int32(ps.session),
SeqID: int32(ps.eventSeq),
}
notSent := true
for _, attr := range p.attributes {
event := &pb.Event{
EventID: eventID,
Event: data,
Predicate: info,
RvId: attr.name,
LastHop: peer.Encode(ps.ipfsDHT.PeerID()),
AckAddr: ps.serverAddr,
Backup: false,
BirthTime: time.Now().Format(time.StampMilli),
PubAddr: ps.serverAddr,
}
isRv, nextRvHopAddr := ps.rendezvousSelfCheck(attr.name)
eLog := make(map[string]bool)
if isRv && notSent {
notSent = false
ps.tablesLock.RLock()
for next, route := range ps.currentFilterTable.routes {
if route.IsInterested(p) {
eLog[next] = false
dialAddr := route.addr
newE := &pb.Event{
Event: event.Event,
OriginalRoute: next,
Backup: event.Backup,
Predicate: event.Predicate,
RvId: event.RvId,
AckAddr: event.AckAddr,
PubAddr: event.PubAddr,
EventID: event.EventID,
BirthTime: event.BirthTime,
LastHop: event.LastHop,
}
if ps.activeRedirect {
ps.currentFilterTable.redirectLock.Lock()
ps.nextFilterTable.redirectLock.Lock()
if ps.currentFilterTable.redirectTable[next] == nil {
ps.currentFilterTable.redirectTable[next] = make(map[string]string)
ps.currentFilterTable.redirectTable[next][event.RvId] = ""
ps.nextFilterTable.redirectTable[next] = make(map[string]string)
ps.nextFilterTable.redirectTable[next][event.RvId] = ""
go ps.forwardEventDown(dialAddr, newE, "", route.backups)
} else if ps.currentFilterTable.redirectTable[next][event.RvId] == "" {
go ps.forwardEventDown(dialAddr, newE, "", route.backups)
} else {
go ps.forwardEventDown(dialAddr, newE, ps.currentFilterTable.redirectTable[next][event.RvId], route.backups)
}
ps.currentFilterTable.redirectLock.Unlock()
ps.nextFilterTable.redirectLock.Unlock()
} else {
go ps.forwardEventDown(dialAddr, newE, "", route.backups)
}
}
}
ps.tablesLock.RUnlock()
if ps.activeReliability && len(eLog) > 0 {
ps.sendLogToTrackers(attr.name, eventID, eLog, event)
}
} else {
if ps.activeReliability {
eID := fmt.Sprintf("%s%d%d%s", event.EventID.PublisherID, event.EventID.SessionNumber, event.EventID.SeqID, event.RvId)
ps.tablesLock.RLock()
ps.ackOpLock.Lock()
ps.unconfirmedEvents[eID] = &PubEventState{event: event, aged: false, dialAddr: nextRvHopAddr}
ps.totalUnconfirmedEvents++
if !ps.eventTickerState {
ps.eventTicker.Reset(ps.opResendRate)
ps.eventTickerState = true
ps.unconfirmedEvents[eID].aged = true
}
ps.ackOpLock.Unlock()
ps.tablesLock.RUnlock()
} else {
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
ps.Notify(ctx, event)
}
go ps.forwardEventUp(nextRvHopAddr, event)
}
}
ps.eventSeq++
return nil
}
// Publish is a remote function called by a external peer to send an Event upstream
func (ps *PubSub) Publish(ctx context.Context, event *pb.Event) (*pb.Ack, error) {
fmt.Println("Publish >> " + ps.serverAddr)
p, err := NewPredicate(event.Predicate, ps.maxAttributesPerPredicate)
if err != nil {
return &pb.Ack{State: false, Info: err.Error()}, err
}
isRv, nextRvHopAddr := ps.rendezvousSelfCheck(event.RvId)
if !isRv && nextRvHopAddr != "" {
newE := &pb.Event{
Event: event.Event,
OriginalRoute: event.OriginalRoute,
Backup: event.Backup,
Predicate: event.Predicate,
RvId: event.RvId,
AckAddr: event.AckAddr,
PubAddr: event.PubAddr,
EventID: event.EventID,
BirthTime: event.BirthTime,
LastHop: peer.Encode(ps.ipfsDHT.PeerID()),
}
go ps.forwardEventUp(nextRvHopAddr, newE)
if !ps.activeReliability {
ps.Notify(ctx, event)
}
} else if !isRv {
return &pb.Ack{State: false, Info: "rendezvous check failed"}, nil
} else if isRv {
if ps.iAmRVPublish(p, event, false) != nil {
return &pb.Ack{State: false, Info: "rendezvous role failed"}, nil
}
}
return &pb.Ack{State: true, Info: ""}, nil
}
func (ps *PubSub) iAmRVPublish(p *Predicate, event *pb.Event, failedRv bool) error {
eL := make(map[string]bool)
if failedRv && ps.lives >= 1 {
for backup := range ps.myBackupsFilters {
backupID, _ := peer.Decode(backup)
if kb.Closer(backupID, ps.ipfsDHT.PeerID(), event.RvId) {
newE := &pb.Event{
Event: event.Event,
OriginalRoute: backup,
Backup: true,
Predicate: event.Predicate,
RvId: event.RvId,
AckAddr: ps.serverAddr,
PubAddr: event.PubAddr,
EventID: event.EventID,
BirthTime: event.BirthTime,
LastHop: event.LastHop,
}
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
ack, err := ps.Notify(ctx, newE)
if err == nil && ack.State {
eL[backup] = false
}
break
}
}
} else if ps.lives < 1 {
alternatives := ps.alternativesToRv(event.RvId)
for _, addr := range alternatives {
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
conn, err := grpc.Dial(addr, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewScoutHubClient(conn)
ack, err := client.HelpNewRv(ctx, event)
if err == nil && ack.State {
eL[ack.Info] = false
break
}
}
}
ps.tablesLock.RLock()
eIDRv := fmt.Sprintf("%s%d%d", event.EventID.PublisherID, event.EventID.SessionNumber, event.EventID.SeqID)
for _, cached := range ps.rvCache {
if eIDRv == cached {
return nil
}
}
ps.rvCache = append(ps.rvCache, eIDRv)
event.AckAddr = ps.serverAddr
for next, route := range ps.currentFilterTable.routes {
if !ps.activeReliability && next == event.LastHop {
continue
}
if route.IsInterested(p) {
eL[next] = false
dialAddr := route.addr
newE := &pb.Event{
Event: event.Event,
OriginalRoute: next,
Backup: event.Backup,
Predicate: event.Predicate,
RvId: event.RvId,
AckAddr: event.AckAddr,
PubAddr: event.PubAddr,
EventID: event.EventID,
BirthTime: event.BirthTime,
LastHop: event.LastHop,
}
if ps.activeRedirect {
ps.currentFilterTable.redirectLock.Lock()
ps.nextFilterTable.redirectLock.Lock()
if ps.currentFilterTable.redirectTable[next] == nil {
ps.currentFilterTable.redirectTable[next] = make(map[string]string)
ps.currentFilterTable.redirectTable[next][event.RvId] = ""
ps.nextFilterTable.redirectTable[next] = make(map[string]string)
ps.nextFilterTable.redirectTable[next][event.RvId] = ""
go ps.forwardEventDown(dialAddr, newE, "", route.backups)
} else if ps.currentFilterTable.redirectTable[next][event.RvId] == "" {
go ps.forwardEventDown(dialAddr, newE, "", route.backups)
} else {
go ps.forwardEventDown(dialAddr, newE, ps.currentFilterTable.redirectTable[next][event.RvId], route.backups)
}
ps.currentFilterTable.redirectLock.Unlock()
ps.nextFilterTable.redirectLock.Unlock()
} else {
go ps.forwardEventDown(dialAddr, newE, "", route.backups)
}
}
}
ps.tablesLock.RUnlock()
if ps.activeReliability {
eID := fmt.Sprintf("%s%d%d%s", event.EventID.PublisherID, event.EventID.SessionNumber, event.EventID.SeqID, event.RvId)
if len(eL) > 0 {
ps.sendLogToTrackers(event.RvId, event.EventID, eL, event)
}
ps.sendAckOp(event.PubAddr, "Publish", eID)
}
if ps.myFilters.IsInterested(p) {
ps.interestingEvents <- event
}
return nil
}
func (ps *PubSub) HelpNewRv(ctx context.Context, event *pb.Event) (*pb.Ack, error) {
fmt.Println("HelpNewRv >> " + ps.serverAddr)
for backup := range ps.myBackupsFilters {
backupID, _ := peer.Decode(backup)
if kb.Closer(backupID, ps.ipfsDHT.PeerID(), event.RvId) {
if ps.lives < 1 {
return &pb.Ack{State: false, Info: "new node"}, nil
}
newE := &pb.Event{
Event: event.Event,
OriginalRoute: backup,
Backup: true,
Predicate: event.Predicate,
RvId: event.RvId,
AckAddr: event.AckAddr,
PubAddr: event.PubAddr,
EventID: event.EventID,
BirthTime: event.BirthTime,
LastHop: event.LastHop,
}
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
ack, err := ps.Notify(ctx, newE)
if err == nil && ack.State {
return &pb.Ack{State: true, Info: peer.Encode(ps.ipfsDHT.PeerID())}, nil
}
break
}
}
return &pb.Ack{State: false, Info: "unexpected result"}, nil
}
// sendAckOp just sends an ack to the operation initiator to confirm completion
func (ps *PubSub) sendAckOp(dialAddr string, Op string, info string) {
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
conn, err := grpc.Dial(dialAddr, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
ack := &pb.Ack{
State: true,
Op: Op,
Info: info,
}
client := pb.NewScoutHubClient(conn)
client.AckOp(ctx, ack)
}
// sendAckUp sends an ack upstream to confirm event delivery
func (ps *PubSub) sendAckUp(ack *AckUp) {
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
eAck := &pb.EventAck{
EventID: ack.eventID,
PeerID: ack.peerID,
RvID: ack.rvID,
}
if ack.dialAddr == ps.serverAddr {
ps.AckUp(ctx, eAck)
return
}
conn, err := grpc.Dial(ack.dialAddr, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewScoutHubClient(conn)
client.AckUp(ctx, eAck)
}
// sendLogToTracker
func (ps *PubSub) sendLogToTrackers(attr string, eID *pb.EventID, eLog map[string]bool, e *pb.Event) {
eIDL := fmt.Sprintf("%s%d%d", e.EventID.PublisherID, e.EventID.SessionNumber, e.EventID.SeqID)
if ps.myTrackers[attr] != nil && ps.myTrackers[attr].leader {
ps.myTrackers[attr].newEventToCheck(NewEventLedger(eIDL, eLog, "", e, ""))
} else if ps.myTrackers[attr] != nil {
ps.tablesLock.Lock()
ps.myTrackers[attr].leader = true
ps.tablesLock.Unlock()
ps.myTrackers[attr].newEventToCheck(NewEventLedger(eIDL, eLog, "", e, ""))
} else {
ps.tablesLock.Lock()
ps.myTrackers[attr] = NewTracker(true, attr, ps, ps.timeToCheckDelivery)
ps.tablesLock.Unlock()
ps.myTrackers[attr].newEventToCheck(NewEventLedger(eIDL, eLog, "", e, ""))
}
for _, addr := range ps.alternativesToRv(attr) {
if addr == ps.serverAddr {
continue
}
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
conn, err := grpc.Dial(addr, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
rm := &pb.RecruitTrackerMessage{
RvID: attr,
RvAddr: ps.serverAddr,
}
eL := &pb.EventLog{
RecruitMessage: rm,
RvID: attr,
EventID: eID,
Event: e,
Log: eLog,
}
client := pb.NewScoutHubClient(conn)
client.LogToTracker(ctx, eL)
}
}
// sendAckToTrackers
func (ps *PubSub) sendAckToTrackers(ack *pb.EventAck) {
if ps.myTrackers[ack.RvID] != nil {
ps.myTrackers[ack.RvID].addEventAck <- ack
} else {
ps.tablesLock.Lock()
ps.myTrackers[ack.RvID] = NewTracker(true, ack.RvID, ps, ps.timeToCheckDelivery)
ps.tablesLock.Unlock()
ps.myTrackers[ack.RvID].addEventAck <- ack
}
for _, addr := range ps.alternativesToRv(ack.RvID) {
if addr == ps.serverAddr {
continue
}
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
conn, err := grpc.Dial(addr, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
rm := &pb.RecruitTrackerMessage{
RvID: ack.RvID,
RvAddr: ps.serverAddr,
}
ack.RecruitMessage = rm
client := pb.NewScoutHubClient(conn)
client.AckToTracker(ctx, ack)
}
}
// AckUp processes an event ackknowledge and if it was the last
// missing ack returns its own acknowledge upstream
func (ps *PubSub) AckUp(ctx context.Context, ack *pb.EventAck) (*pb.Ack, error) {
fmt.Println("AckUp >> " + ps.serverAddr)
eID := fmt.Sprintf("%s%d%d%s", ack.EventID.PublisherID, ack.EventID.SessionNumber, ack.EventID.SeqID, ack.RvID)
isRv, _ := ps.rendezvousSelfCheck(ack.RvID)
if ps.myEBackTrackers[eID] != nil {
ps.ackUpLock.Lock()
if ps.myEBackTrackers[eID] == nil || ps.myEBackTrackers[eID].receivedAcks == ps.myEBackTrackers[eID].expectedAcks {
return &pb.Ack{State: true, Info: "Event Tracker already closed"}, nil
}
ps.myEBackTrackers[eID].eventLog[ack.PeerID] = true
ps.myEBackTrackers[eID].receivedAcks++
if ps.myEBackTrackers[eID].receivedAcks == ps.myEBackTrackers[eID].expectedAcks {
newAck := &AckUp{
dialAddr: ps.myEBackTrackers[eID].addrToAck,
eventID: ack.EventID,
peerID: ps.myEBackTrackers[eID].originalDestination,
rvID: ack.RvID,
}
ps.ackUpLock.Unlock()
go ps.sendAckUp(newAck)
} else {
ps.ackUpLock.Unlock()
}
} else if isRv {
ps.sendAckToTrackers(ack)
} else {
ps.ackUpLock.Lock()
if ps.myETrackers[eID] == nil || ps.myETrackers[eID].receivedAcks == ps.myETrackers[eID].expectedAcks {
return &pb.Ack{State: true, Info: "Event Tracker already closed"}, nil
}
ps.myETrackers[eID].eventLog[ack.PeerID] = true
ps.myETrackers[eID].receivedAcks++
if ps.myETrackers[eID].receivedAcks == ps.myETrackers[eID].expectedAcks {
newAck := &AckUp{
dialAddr: ps.myETrackers[eID].addrToAck,
eventID: ack.EventID,
peerID: ps.myETrackers[eID].originalDestination,
rvID: ack.RvID,
}
ps.ackUpLock.Unlock()
go ps.sendAckUp(newAck)
} else {
ps.ackUpLock.Unlock()
}
}
return &pb.Ack{State: true, Info: ""}, nil
}
// AckOp receives confirmation of a Operation and stops its resending from happening
func (ps *PubSub) AckOp(ctx context.Context, ack *pb.Ack) (*pb.Ack, error) {
fmt.Println("AckOp >> " + ps.serverAddr)
ps.ackOpLock.Lock()
if ack.Op == "Publish" {
if ps.unconfirmedEvents[ack.Info] != nil {
ps.unconfirmedEvents[ack.Info] = nil
ps.totalUnconfirmedEvents--
}
if ps.totalUnconfirmedEvents == 0 {
ps.eventTicker.Stop()
ps.eventTickerState = false
}
} else if ack.Op == "Subscribe" {
if ps.unconfirmedSubs[ack.Info] != nil {
ps.record.SaveTimeToSub(ps.unconfirmedSubs[ack.Info].started)
ps.unconfirmedSubs[ack.Info] = nil
ps.totalUnconfirmedSubs--
}
if ps.totalUnconfirmedSubs == 0 {
ps.subTicker.Stop()
ps.subTickerState = false
}
}
ps.ackOpLock.Unlock()
return &pb.Ack{State: true, Info: ""}, nil
}
// LogToTracker is the remote call a tracker receives from
// the Rv node with a event log for him to start tracking
func (ps *PubSub) LogToTracker(ctx context.Context, log *pb.EventLog) (*pb.Ack, error) {
fmt.Println("LogTracker >> " + ps.serverAddr)
if ps.myTrackers[log.RecruitMessage.RvID] == nil {
ps.myTrackers[log.RecruitMessage.RvID] = NewTracker(false, log.RecruitMessage.RvID,
ps, ps.timeToCheckDelivery)
for _, addr := range ps.alternativesToRv(log.RvID) {
if addr == ps.serverAddr {
continue
}
ctx, cancel := context.WithTimeout(context.Background(), ps.rpcTimeout)
defer cancel()
conn, err := grpc.Dial(addr, grpc.WithInsecure())
if err != nil {
return &pb.Ack{State: false, Info: ""}, err
}
defer conn.Close()
log.RecruitMessage.RvAddr = ps.serverAddr