/
dispatcher.go
63 lines (51 loc) · 1.22 KB
/
dispatcher.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
package amqp
import (
"math"
"math/rand"
"sync"
"time"
"github.com/Ja7ad/amqp/logger"
)
type dispatcher struct {
subscribers sync.Map
logger logger.Logger
}
type subscriber struct {
notifyCancelOrCloseChan chan error
closeCh <-chan struct{}
}
func newDispatcher(logger logger.Logger) *dispatcher {
return &dispatcher{
subscribers: sync.Map{},
logger: logger,
}
}
func (d *dispatcher) dispatch(err error) {
d.subscribers.Range(func(_, value interface{}) bool {
s := value.(subscriber)
select {
case <-time.After(5 * time.Second):
d.logger.Error("Unexpected rabbitmq error: timeout in dispatcher")
case s.notifyCancelOrCloseChan <- err:
}
return true
})
}
func (d *dispatcher) addSubscriber() (<-chan error, chan<- struct{}) {
const maxRand = math.MaxInt
const minRand = 0
id := rand.Intn(maxRand-minRand) + minRand
closeCh := make(chan struct{})
notifyCancelOrCloseChan := make(chan error)
sub := subscriber{
notifyCancelOrCloseChan: notifyCancelOrCloseChan,
closeCh: closeCh,
}
d.subscribers.Store(id, sub)
go func(id int) {
<-closeCh
d.subscribers.Delete(id)
close(notifyCancelOrCloseChan)
}(id)
return notifyCancelOrCloseChan, closeCh
}