-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsubscriber.go
202 lines (170 loc) · 4.24 KB
/
subscriber.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
// Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package pubsub
import (
"fmt"
"reflect"
"runtime"
"strings"
"sync"
"time"
"github.com/juju/clock"
)
type subscriber struct {
id int
logger Logger
metrics Metrics
clock clock.Clock
topicMatcher func(topic string) bool
handler func(topic string, data interface{})
handlerName string
msgQueue *queue
data chan struct{}
done chan struct{}
}
func newSubscriber(id int,
matcher func(topic string) bool,
handler func(string, interface{}),
logger Logger, metrics Metrics, clock clock.Clock) *subscriber {
sub := &subscriber{
id: id,
logger: logger,
metrics: metrics,
clock: clock,
topicMatcher: matcher,
handler: handler,
handlerName: getFunctionName(handler, id),
msgQueue: makeQueue(),
data: make(chan struct{}, 1),
done: make(chan struct{}),
}
go sub.loop()
sub.logger.Tracef("created subscriber %p for %v", sub, matcher)
return sub
}
func (s *subscriber) close() {
// need to iterate through all the pending calls and make sure the wait group
// is decremented. this isn't exposed yet, but needs to be.
for message, ok := s.msgQueue.Dequeue(); ok; message, ok = s.msgQueue.Dequeue() {
message.callback.done()
// Notify the metrics that although we've closed the subscriber, all the
// messages that subscriber had, have been drained.
s.metrics.Dequeued(s.handlerName)
}
close(s.done)
}
func (s *subscriber) loop() {
for {
select {
case <-s.done:
return
case <-s.data:
}
for message, ok := s.msgQueue.Dequeue(); ok; message, ok = s.msgQueue.Dequeue() {
s.metrics.Dequeued(s.handlerName)
call := message.callback
s.logger.Tracef("exec callback %p (%d) func %p", s, s.id, s.handler)
s.handler(call.topic, call.data)
call.done()
// Consumed exposes information about how long a given message
// has been on the subscriber pending list. We can use this
// information to workout how much backpressure is being exhorted
// on the system at large.
s.metrics.Consumed(s.handlerName, s.clock.Now().Sub(message.now))
}
}
}
func (s *subscriber) notify(call handlerCallback) {
s.logger.Tracef("notify %d", s.id)
s.msgQueue.Enqueue(message{
now: s.clock.Now(),
callback: call,
})
select {
case s.data <- struct{}{}:
default:
// Notification pending to be processed
}
// Notify the metrics that we're enqueuing a new item onto the subscriber.
s.metrics.Enqueued(s.handlerName)
}
type message struct {
callback handlerCallback
now time.Time
}
// getFunctionName attempts to return a stable function name that is comparable.
// Restarting the program should return the same function name if the method
// is called on the same function.
func getFunctionName(i interface{}, fallback int) string {
fullpath := runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
if len(fullpath) == 0 {
return fmt.Sprintf("func-%d", fallback)
}
parts := strings.Split(fullpath, ".")
var name string
switch len(parts) {
case 0:
name = fullpath
case 1:
name = parts[0]
default:
name = strings.Join(parts[len(parts)-2:], ".")
}
// Ensure we remove potential suffixes from the name of the function.
idx := strings.LastIndex(name, "-")
if idx >= 0 {
name = name[:idx]
}
return name
}
type queueElement struct {
msg message
next *queueElement
}
type queue struct {
elemPool sync.Pool
mu sync.Mutex
head *queueElement
tail *queueElement
}
func makeQueue() *queue {
return &queue{
elemPool: sync.Pool{
New: func() interface{} {
return new(queueElement)
},
},
}
}
// Enqueue a message onto the queue.
func (q *queue) Enqueue(msg message) {
elem := q.elemPool.Get().(*queueElement)
elem.msg = msg
q.mu.Lock()
defer q.mu.Unlock()
if q.head == nil {
q.head = elem
q.tail = elem
return
}
q.tail.next = elem
q.tail = elem
}
// Dequeue a message from the queue. Returns a message or true if it's empty.
func (q *queue) Dequeue() (message, bool) {
q.mu.Lock()
if q.head == nil {
q.mu.Unlock()
return message{}, false // empty
}
elem := q.head
q.head = elem.next
if q.head == nil {
q.tail = nil
}
msg := elem.msg
q.mu.Unlock()
elem.next = nil
q.elemPool.Put(elem)
return msg, true
}