This repository has been archived by the owner on Jun 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asyncwork.go
202 lines (151 loc) · 3.99 KB
/
asyncwork.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
package asyncwork
import (
"context"
"sync"
"time"
"github.com/GustavoKatel/asyncwork/interfaces"
"github.com/GustavoKatel/syncevent"
"github.com/phf/go-queue/queue"
)
var _ interfaces.AsyncWork = &asyncWorkImpl{}
type asyncWorkImpl struct {
queue *queue.Queue
queueMutex *sync.RWMutex
ctx context.Context
ctxCancel context.CancelFunc
event syncevent.SyncEvent
errorChs []chan error
errorChsMutex *sync.RWMutex
lastExecutionMap map[string]time.Time
lastExecutionMapMutex *sync.RWMutex
// Maps tag to the last recorded call
throttleLastMap map[string]*jobImpl
throttleLastMapMutex *sync.RWMutex
}
// New creates a new working channel
func New() (interfaces.AsyncWork, error) {
return NewWithContext(context.Background())
}
// NewWithContext creates a new working channel
func NewWithContext(ctx context.Context) (interfaces.AsyncWork, error) {
ctx, cancel := context.WithCancel(ctx)
aw := &asyncWorkImpl{
queue: queue.New(),
queueMutex: &sync.RWMutex{},
ctx: ctx,
ctxCancel: cancel,
event: syncevent.NewSyncEvent(false),
errorChs: []chan error{},
errorChsMutex: &sync.RWMutex{},
lastExecutionMap: map[string]time.Time{},
lastExecutionMapMutex: &sync.RWMutex{},
throttleLastMap: map[string]*jobImpl{},
throttleLastMapMutex: &sync.RWMutex{},
}
return aw, nil
}
func (aw *asyncWorkImpl) Start() error {
go aw.background()
return nil
}
func (aw *asyncWorkImpl) Stop() error {
aw.ctxCancel()
aw.event.Set()
return nil
}
func (aw *asyncWorkImpl) ErrorChan(ch chan error) {
aw.errorChsMutex.RLock()
defer aw.errorChsMutex.RUnlock()
aw.errorChs = append(aw.errorChs, ch)
}
func (aw *asyncWorkImpl) emitError(err error) {
aw.errorChsMutex.RLock()
defer aw.errorChsMutex.RUnlock()
for _, ch := range aw.errorChs {
ch <- err
}
}
func (aw *asyncWorkImpl) background() {
for aw.ctx.Err() == nil {
aw.event.Wait()
if aw.ctx.Err() != nil {
break
}
aw.queueMutex.RLock()
if aw.queue.Len() == 0 {
aw.event.Reset()
aw.queueMutex.RUnlock()
continue
}
aw.queueMutex.RUnlock()
if err := aw.fetchAndRun(); err != nil {
aw.emitError(err)
}
}
}
func (aw *asyncWorkImpl) waitAndSchedule(job *jobImpl, delay time.Duration) {
aw.throttleLastMapMutex.Lock()
_, prs := aw.throttleLastMap[job.tag]
aw.throttleLastMap[job.tag] = job
aw.throttleLastMapMutex.Unlock()
if prs {
return
}
tag := job.tag
go func() {
select {
case <-time.After(delay):
aw.throttleLastMapMutex.Lock()
defer aw.throttleLastMapMutex.Unlock()
lastJob, prs := aw.throttleLastMap[tag]
if !prs {
return
}
delete(aw.throttleLastMap, tag)
aw.PostTaggedThrottledJob(lastJob.jobFn, lastJob.tag, lastJob.delay)
case <-aw.ctx.Done():
return
}
}()
}
func (aw *asyncWorkImpl) fetchAndRun() error {
aw.queueMutex.Lock()
jobI := aw.queue.PopFront()
aw.queueMutex.Unlock()
job := jobI.(*jobImpl)
aw.lastExecutionMapMutex.Lock()
defer aw.lastExecutionMapMutex.Unlock()
lastExecution, prs := aw.lastExecutionMap[job.tag]
if prs && time.Now().Sub(lastExecution) < job.delay {
aw.waitAndSchedule(job, job.delay-time.Now().Sub(lastExecution))
return nil
}
aw.lastExecutionMap[job.tag] = time.Now()
return job.jobFn(aw.ctx)
}
func (aw *asyncWorkImpl) PostJob(job interfaces.JobFn) error {
return aw.PostTaggedJob(job, "")
}
func (aw *asyncWorkImpl) PostTaggedJob(job interfaces.JobFn, tag string) error {
return aw.PostTaggedThrottledJob(job, tag, 0)
}
func (aw *asyncWorkImpl) PostThrottledJob(job interfaces.JobFn, delay time.Duration) error {
return aw.PostTaggedThrottledJob(job, "", delay)
}
func (aw *asyncWorkImpl) PostTaggedThrottledJob(job interfaces.JobFn, tag string, delay time.Duration) error {
aw.queueMutex.Lock()
defer aw.queueMutex.Unlock()
jobData := jobImpl{
jobFn: job,
tag: tag,
delay: delay,
}
aw.queue.PushBack(&jobData)
aw.event.Set()
return nil
}
func (aw *asyncWorkImpl) Len() int {
aw.queueMutex.RLock()
defer aw.queueMutex.RUnlock()
return aw.queue.Len()
}