-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsubscription.go
108 lines (87 loc) · 1.79 KB
/
subscription.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
package kcache
import (
lifecycle "github.com/boz/go-lifecycle"
logutil "github.com/boz/go-logutil"
"github.com/pkg/errors"
)
const (
EventBufsiz = 100
)
type Subscription interface {
CacheController
Events() <-chan Event
Close()
Done() <-chan struct{}
Error() error
}
type subscription interface {
Subscription
send(Event) error
}
type _subscription struct {
outch chan Event
inch chan Event
readych <-chan struct{}
cache CacheReader
log logutil.Log
lc lifecycle.Lifecycle
}
func newSubscription(log logutil.Log, stopch <-chan struct{}, readych <-chan struct{}, cache CacheReader) subscription {
log = log.WithComponent("subscription")
lc := lifecycle.New()
s := &_subscription{
readych: readych,
inch: make(chan Event),
outch: make(chan Event, EventBufsiz),
cache: cache,
log: log,
lc: lc,
}
go s.lc.WatchChannel(stopch)
go s.run()
return s
}
func (s *_subscription) Ready() <-chan struct{} {
return s.readych
}
func (s *_subscription) Events() <-chan Event {
return s.outch
}
func (s *_subscription) Cache() CacheReader {
return s.cache
}
func (s *_subscription) Close() {
s.lc.ShutdownAsync(nil)
}
func (s *_subscription) Done() <-chan struct{} {
return s.lc.Done()
}
func (s *_subscription) Error() error {
return s.lc.Error()
}
func (s *_subscription) send(ev Event) error {
select {
case s.inch <- ev:
return nil
case <-s.lc.ShuttingDown():
return errors.WithStack(ErrNotRunning)
}
}
func (s *_subscription) run() {
defer s.lc.ShutdownCompleted()
defer close(s.outch)
for {
select {
case err := <-s.lc.ShutdownRequest():
s.log.Debugf("shutdown requested: %v", err)
s.lc.ShutdownInitiated(err)
return
case evt := <-s.inch:
select {
case s.outch <- evt:
default:
s.log.Warnf("event buffer overrun")
}
}
}
}