-
Notifications
You must be signed in to change notification settings - Fork 249
/
subscriptions.go
88 lines (66 loc) · 1.7 KB
/
subscriptions.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
package subscriptions
import (
"fmt"
"sync"
"time"
"github.com/ethereum/go-ethereum/log"
)
type Subscriptions struct {
mu sync.Mutex
subs map[SubscriptionID]*Subscription
checkPeriod time.Duration
log log.Logger
}
func NewSubscriptions(period time.Duration) *Subscriptions {
return &Subscriptions{
subs: make(map[SubscriptionID]*Subscription),
checkPeriod: period,
log: log.New("package", "status-go/services/subsriptions.Subscriptions"),
}
}
func (s *Subscriptions) Create(namespace string, filter filter) (SubscriptionID, error) {
s.mu.Lock()
defer s.mu.Unlock()
newSub := NewSubscription(namespace, filter)
go func() {
err := newSub.Start(s.checkPeriod)
if err != nil {
s.log.Error("error while starting subscription", "err", err)
}
}()
s.subs[newSub.id] = newSub
return newSub.id, nil
}
func (s *Subscriptions) Remove(id SubscriptionID) error {
s.mu.Lock()
defer s.mu.Unlock()
found, err := s.stopSubscription(id, true)
if found {
delete(s.subs, id)
}
return err
}
func (s *Subscriptions) removeAll() error {
s.mu.Lock()
defer s.mu.Unlock()
unsubscribeErrors := make(map[SubscriptionID]error)
for id := range s.subs {
_, err := s.stopSubscription(id, false)
if err != nil {
unsubscribeErrors[id] = err
}
}
s.subs = make(map[SubscriptionID]*Subscription)
if len(unsubscribeErrors) > 0 {
return fmt.Errorf("errors while cleaning up subscriptions: %+v", unsubscribeErrors)
}
return nil
}
// stopSubscription isn't thread safe!
func (s *Subscriptions) stopSubscription(id SubscriptionID, uninstall bool) (bool, error) {
sub, found := s.subs[id]
if !found {
return false, nil
}
return true, sub.Stop(uninstall)
}