forked from dunglas/mercure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_transport.go
116 lines (94 loc) · 2.27 KB
/
local_transport.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
package mercure
import (
"net/url"
"sync"
)
func init() { //nolint:gochecknoinits
RegisterTransportFactory("local", NewLocalTransport)
}
// LocalTransport implements the TransportInterface without database and simply broadcast the live Updates.
type LocalTransport struct {
sync.RWMutex
subscribers *SubscriberList
lastEventID string
closed chan struct{}
closedOnce sync.Once
}
// NewLocalTransport create a new LocalTransport.
func NewLocalTransport(u *url.URL, l Logger, tss *TopicSelectorStore) (Transport, error) { //nolint:ireturn
return &LocalTransport{
subscribers: NewSubscriberList(1e5),
closed: make(chan struct{}),
lastEventID: EarliestLastEventID,
}, nil
}
// Dispatch dispatches an update to all subscribers.
func (t *LocalTransport) Dispatch(update *Update) error {
select {
case <-t.closed:
return ErrClosedTransport
default:
}
AssignUUID(update)
for _, s := range t.subscribers.MatchAny(update) {
s.Dispatch(update, false)
}
t.Lock()
t.lastEventID = update.ID
t.Unlock()
return nil
}
// AddSubscriber adds a new subscriber to the transport.
func (t *LocalTransport) AddSubscriber(s *Subscriber) error {
select {
case <-t.closed:
return ErrClosedTransport
default:
}
t.Lock()
defer t.Unlock()
t.subscribers.Add(s)
if s.RequestLastEventID != "" {
s.HistoryDispatched(EarliestLastEventID)
}
s.Ready()
return nil
}
// RemoveSubscriber removes a subscriber from the transport.
func (t *LocalTransport) RemoveSubscriber(s *Subscriber) error {
select {
case <-t.closed:
return ErrClosedTransport
default:
}
t.Lock()
defer t.Unlock()
t.subscribers.Remove(s)
return nil
}
// GetSubscribers gets the list of active subscribers.
func (t *LocalTransport) GetSubscribers() (string, []*Subscriber, error) {
t.RLock()
defer t.RUnlock()
var subscribers []*Subscriber
t.subscribers.Walk(0, func(s *Subscriber) bool {
subscribers = append(subscribers, s)
return true
})
return t.lastEventID, subscribers, nil
}
// Close closes the Transport.
func (t *LocalTransport) Close() (err error) {
t.closedOnce.Do(func() {
t.Lock()
defer t.Unlock()
close(t.closed)
t.subscribers.Walk(0, func(s *Subscriber) bool {
s.Disconnect()
return true
})
})
return nil
}
// Interface guard.
var _ Transport = (*LocalTransport)(nil)