-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdelayer.go
77 lines (66 loc) · 1.46 KB
/
delayer.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
package gosd
import (
"time"
)
type delayer[T any] interface {
stop(drain bool)
wait(msg *ScheduledMessage[T])
available() bool
}
type delayState int
const (
idle delayState = iota
waiting
)
type delay[T any] struct {
state delayState // nolint:unused
idleChannel chan<- bool
egressChannel chan<- T
cancelChannel chan bool
}
func newDelay[T any](egressChannel chan<- T, idleChannel chan<- bool) *delay[T] {
return &delay[T]{
idleChannel: idleChannel,
egressChannel: egressChannel,
cancelChannel: make(chan bool, 1),
}
}
// stop sends a cancel signal to the current timer process.
// nolint:unused
func (d *delay[T]) stop(drain bool) {
if d.state == waiting {
d.cancelChannel <- drain
}
}
// wait will create a timer based on the time from `msg.At` and dispatch the message to the egress channel asynchronously.
// nolint:unused
func (d *delay[T]) wait(msg *ScheduledMessage[T]) {
d.state = waiting
curTimer := time.NewTimer(time.Until(msg.At))
go func() {
for {
select {
case drain, ok := <-d.cancelChannel:
if ok {
curTimer.Stop()
if drain {
d.egressChannel <- msg.Message
}
d.state = idle
d.idleChannel <- true
}
return
case <-curTimer.C:
d.egressChannel <- msg.Message
d.state = idle
d.idleChannel <- true
return
}
}
}()
}
// available returns whether the delay is able to accept a new message to wait on.
// nolint
func (d *delay[T]) available() bool {
return d.state == idle
}