This repository has been archived by the owner on Jan 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
261 lines (214 loc) · 4.6 KB
/
worker.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package porter
import (
"context"
"errors"
"sync"
"time"
)
var (
ErrAlreadyRunning = errors.New("worker already running")
ErrWorkerClosed = errors.New("worker is closed")
ErrIdleJob = errors.New("idle job")
)
const (
defaultJobsLimit = 1
defaultShutdownPollTimeout = 500 * time.Millisecond
)
type Worker interface {
Run() error
Shutdown(ctx context.Context) error
}
type JobFunc func(state State) error
type MiddlewareFunc func(JobFunc) JobFunc
type Opt func(w *worker)
func WithJobsLimit(limit int) Opt {
return func(w *worker) {
if limit > 0 {
w.config.jobsLimit = limit
}
}
}
func WithShutdownPollTimeout(shutdownPollTimeout time.Duration) Opt {
return func(w *worker) {
if shutdownPollTimeout > 0 {
w.shutdownPollTimeout = shutdownPollTimeout
}
}
}
// WithRunDelay adds a delay before worker starts
func WithRunDelay(delay time.Duration) Opt {
return func(w *worker) {
if delay > 0 {
w.config.delay = delay
}
}
}
func WithSubscriber(subscribers ...func(subscriber Subscriber)) Opt {
return func(w *worker) {
for _, subscribe := range subscribers {
subscribe(w.events)
}
}
}
// WithErrorTimeout adds a delay after the job that returned the error
func WithErrorTimeout(timeout time.Duration) Opt {
return func(w *worker) {
w.config.errorTimeout = timeout
}
}
// WithIdleTimeout adds a delay after the job that returned ErrIdleJob
func WithIdleTimeout(timeout time.Duration) Opt {
return func(w *worker) {
w.config.idleTimeout = timeout
}
}
// WithSuccessTimeout adds a delay after a successful job
func WithSuccessTimeout(timeout time.Duration) Opt {
return func(w *worker) {
w.config.successTimeout = timeout
}
}
func NewWorker(jobFunc JobFunc, opts ...Opt) Worker {
w := &worker{
jobFunc: jobFunc,
events: &Dispatcher{},
shutdownPollTimeout: defaultShutdownPollTimeout,
config: workerConfig{
jobsLimit: defaultJobsLimit,
},
}
for _, opt := range opts {
if opt != nil {
opt(w)
}
}
return w
}
type worker struct {
// Blocks concurrent start and stop of the worker
mu sync.Mutex
// While the channel is open, it means that the worker is working
done <-chan struct{}
// While the channel is open, the worker will start new tasks
closed chan struct{}
// Events handler
events *Dispatcher
// Timeout between attempts to stop the worker
shutdownPollTimeout time.Duration
// The task that the worker performs
jobFunc JobFunc
config workerConfig
}
type workerConfig struct {
jobsLimit int
delay time.Duration
errorTimeout time.Duration
successTimeout time.Duration
idleTimeout time.Duration
middlewares []MiddlewareFunc
}
func (w *worker) Run() error {
err := w.run()
w.events.OnRun(err)
return err
}
func (w *worker) run() error {
w.mu.Lock()
defer w.mu.Unlock()
if w.done != nil {
select {
case <-w.done:
default:
return ErrAlreadyRunning
}
}
w.closed = make(chan struct{})
w.done = runWorker(w.jobFunc, w.config, w.closed)
return nil
}
func (w *worker) Shutdown(ctx context.Context) error {
err := w.shutdown(ctx)
w.events.OnShutdown(err)
return err
}
func (w *worker) shutdown(ctx context.Context) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.closed == nil {
return ErrWorkerClosed
}
select {
default:
case <-w.closed:
return ErrWorkerClosed
}
close(w.closed)
select {
default:
case <-w.done:
return ErrWorkerClosed
}
ticker := time.NewTicker(w.shutdownPollTimeout)
defer ticker.Stop()
for {
select {
case <-w.done:
return nil
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
}
}
func runWorker(fn JobFunc, config workerConfig, closed <-chan struct{}) <-chan struct{} {
done := make(chan struct{})
jobs := make(chan struct{}, config.jobsLimit)
go func() {
defer func() {
done <- struct{}{}
}()
if config.delay > 0 {
select {
case <-closed:
return
case <-time.After(config.delay):
}
}
for {
select {
default:
case <-closed:
return
}
jobs <- struct{}{}
// TODO use a worker pool to avoid running excess goroutines
go func() {
var err error
defer func() {
if timeout := getTimeout(config, err); timeout > 0 {
select {
case <-time.After(timeout):
case <-closed:
}
}
<-jobs
}()
s := &state{}
err = applyMiddleware(fn, config.middlewares...)(s)
}()
}
}()
return done
}
func getTimeout(c workerConfig, err error) time.Duration {
timeout := time.Duration(0)
switch err {
case ErrIdleJob:
timeout = c.idleTimeout
case nil:
timeout = c.successTimeout
default:
timeout = c.errorTimeout
}
return timeout
}