-
Notifications
You must be signed in to change notification settings - Fork 0
/
publishers.go
62 lines (54 loc) · 1.11 KB
/
publishers.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
package sse
import (
"context"
"fmt"
"sync"
)
type client struct {
publisher Publisher
eventCh chan *Event
}
func newPublishers(log logger) *publishers {
return &publishers{
log: log,
clients: map[string]*client{},
}
}
type publishers struct {
log logger
mu sync.RWMutex
clients map[string]*client
}
var _ Publisher = (*publishers)(nil)
func (b *publishers) Set(id string, publisher Publisher) <-chan *Event {
b.mu.Lock()
defer b.mu.Unlock()
eventCh := make(chan *Event)
b.clients[id] = &client{
publisher: publisher,
eventCh: eventCh,
}
return eventCh
}
func (b *publishers) Remove(id string) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, id)
}
// Publish an event to all clients. If a client is slow to receive events,
// events will be dropped.
func (b *publishers) Publish(ctx context.Context, event *Event) error {
b.mu.RLock()
defer b.mu.RUnlock()
for id, client := range b.clients {
select {
case client.eventCh <- event:
b.log.Debug(fmt.Sprintf("sse: sent event to %s", id))
continue
case <-ctx.Done():
return ctx.Err()
default:
}
}
return nil
}