-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathdispatcher.go
74 lines (65 loc) · 1.61 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
64
65
66
67
68
69
70
71
72
73
74
package dispatcher
import (
"github.com/wagslane/go-rabbitmq/internal/logger"
"math"
"math/rand"
"sync"
"time"
)
// Dispatcher -
type Dispatcher struct {
subscribers map[int]dispatchSubscriber
subscribersMux *sync.Mutex
logger logger.Logger
}
type dispatchSubscriber struct {
notifyCancelOrCloseChan chan error
closeCh <-chan struct{}
}
// NewDispatcher -
func NewDispatcher(logger logger.Logger) *Dispatcher {
return &Dispatcher{
subscribers: make(map[int]dispatchSubscriber),
subscribersMux: &sync.Mutex{},
logger: logger,
}
}
// Dispatch -
func (d *Dispatcher) Dispatch(err error) error {
d.subscribersMux.Lock()
defer d.subscribersMux.Unlock()
for _, subscriber := range d.subscribers {
select {
case <-time.After(time.Second * 5):
d.logger.Errorf("Unexpected rabbitmq error: timeout in dispatch")
case subscriber.notifyCancelOrCloseChan <- err:
}
}
return nil
}
// AddSubscriber -
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)
d.subscribersMux.Lock()
d.subscribers[id] = dispatchSubscriber{
notifyCancelOrCloseChan: notifyCancelOrCloseChan,
closeCh: closeCh,
}
d.subscribersMux.Unlock()
go func(id int) {
<-closeCh
d.subscribersMux.Lock()
defer d.subscribersMux.Unlock()
sub, ok := d.subscribers[id]
if !ok {
return
}
close(sub.notifyCancelOrCloseChan)
delete(d.subscribers, id)
}(id)
return notifyCancelOrCloseChan, closeCh
}