-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.go
More file actions
251 lines (218 loc) · 5.52 KB
/
worker.go
File metadata and controls
251 lines (218 loc) · 5.52 KB
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
package taskflow
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
)
type WorkerStatus int
const (
WorkerIdle WorkerStatus = iota
WorkerBusy
WorkerFailing
WorkerExecFailed
)
type Worker struct {
id string
status WorkerStatus
cfg *Config
manager *Manager
currentJob *JobRecord
}
// Run keeps polling the DB for jobs until context is canceled.
func (w *Worker) Run(ctx context.Context) {
ticker := time.NewTicker(w.cfg.PollInterval)
defer ticker.Stop()
w.cfg.logInfo(LogEvent{
Message: fmt.Sprintf("Worker %s started.", w.id),
WorkerID: w.id,
})
for {
select {
case <-ctx.Done():
w.cfg.logInfo(LogEvent{
Message: fmt.Sprintf("Worker %s context canceled, stopping.", w.id),
WorkerID: w.id,
})
return
case <-ticker.C:
w.cfg.logInfo(LogEvent{
Message: fmt.Sprintf("Worker %s polling for jobs...", w.id),
WorkerID: w.id,
})
w.fetchAndProcess(ctx)
case <-w.manager.wakeup:
// got a wakeup request from CreateJob (or somewhere)
w.cfg.logInfo(LogEvent{
Message: fmt.Sprintf("Worker %s got wakeup signal, polling now...", w.id),
WorkerID: w.id,
})
w.fetchAndProcess(ctx)
}
}
}
func (w *Worker) fetchAndProcess(ctx context.Context) {
w.status = WorkerIdle
tx, err := w.cfg.DB.BeginTx(ctx, nil)
if err != nil {
w.cfg.logError(LogEvent{
Message: fmt.Sprintf("Error starting TX for worker %s", w.id),
WorkerID: w.id,
Err: err,
})
return
}
jobRec, err := getPendingJob(tx, w.cfg)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
_ = tx.Commit()
return
}
_ = tx.Rollback()
w.status = WorkerFailing
w.cfg.logError(LogEvent{
Message: fmt.Sprintf("Error fetching job for worker %s", w.id),
WorkerID: w.id,
Err: err,
})
return
}
lockUntil := time.Now().Add(w.cfg.JobTimeout)
if err := assignJobToWorker(w.cfg, tx, jobRec.ID, w.id, lockUntil); err != nil {
_ = tx.Rollback()
w.cfg.logError(LogEvent{
Message: fmt.Sprintf("Error assigning job %d to worker %s", jobRec.ID, w.id),
WorkerID: w.id,
JobID: &jobRec.ID,
Err: err,
})
return
}
if err := tx.Commit(); err != nil {
w.cfg.logError(LogEvent{
Message: fmt.Sprintf("Error committing assignment for job %d (worker %s)", jobRec.ID, w.id),
WorkerID: w.id,
JobID: &jobRec.ID,
Err: err,
})
return
}
w.currentJob = jobRec
w.status = WorkerBusy
start := time.Now()
opStr := string(jobRec.Operation)
w.cfg.logInfo(LogEvent{
Message: fmt.Sprintf("Processing job %d (op: %s)", jobRec.ID, opStr),
WorkerID: w.id,
JobID: &jobRec.ID,
Operation: &opStr,
})
// Actually execute the job
output, execErr := w.executeJob(ctx, jobRec)
finalStatus := JobCompleted
var nextAvailableAt *time.Time
incrementRetry := false
if execErr != nil {
finalStatus = JobFailed
w.status = WorkerExecFailed
if jobRec.Status == JobFailed {
incrementRetry = true
}
t := time.Now().Add(w.cfg.BackoffTime)
nextAvailableAt = &t
}
if err = finishJob(w.cfg, jobRec.ID, finalStatus, output, incrementRetry, nextAvailableAt, execErr); err != nil {
w.cfg.logError(LogEvent{
Message: fmt.Sprintf("Error finishing job %d", jobRec.ID),
WorkerID: w.id,
JobID: &jobRec.ID,
Operation: &opStr,
Err: err,
})
}
elapsed := time.Since(start)
if execErr != nil {
w.cfg.logError(LogEvent{
Message: "Job FAILED.",
WorkerID: w.id,
JobID: &jobRec.ID,
Operation: &opStr,
Duration: &elapsed,
Err: execErr,
})
} else {
w.cfg.logInfo(LogEvent{
Message: "Job COMPLETED.",
WorkerID: w.id,
JobID: &jobRec.ID,
Operation: &opStr,
Duration: &elapsed,
})
w.status = WorkerIdle
}
w.currentJob = nil
}
// executeJob calls the appropriate handler for the job’s operation, optionally enforcing a timeout.
func (w *Worker) executeJob(ctx context.Context, jobRec *JobRecord) (any, error) {
// 1) Try advanced handler first
advConstructor, advErr := w.getAdvancedHandler(jobRec.Operation)
if advErr == nil {
// We have an advanced job constructor, so create the job
advancedJob, err := advConstructor()
if err != nil {
return nil, err
}
// Suppose we respect the job’s own JobTimeout()
jobTimeout := advancedJob.JobTimeout()
if jobTimeout <= 0 {
// No forced timeout: just call it directly
return advancedJob.Run(*jobRec)
}
// Create a context with that timeout
jobCtx, cancel := context.WithTimeout(ctx, jobTimeout)
defer cancel()
// Now run the job in a goroutine
doneCh := make(chan struct{})
var output any
var runErr error
go func() {
output, runErr = advancedJob.Run(*jobRec)
close(doneCh)
}()
// Wait for either the job to finish or the timeout to expire
select {
case <-jobCtx.Done():
msg := fmt.Sprintf("job timed out after %s", jobTimeout)
return &msg, errors.New(msg)
case <-doneCh:
return output, runErr
}
} else {
// 2) If no advanced constructor, use the normal job handler
normalHandler, err := w.getHandler(jobRec.Operation)
if err != nil {
return nil, err
}
// Possibly enforce w.cfg.JobTimeout if non-zero
if w.cfg.JobTimeout <= 0 {
return normalHandler(*jobRec)
}
jobCtx, cancel := context.WithTimeout(ctx, w.cfg.JobTimeout)
defer cancel()
doneCh := make(chan struct{})
var output any
var runErr error
go func() {
output, runErr = normalHandler(*jobRec)
close(doneCh)
}()
select {
case <-jobCtx.Done():
msg := fmt.Sprintf("job timed out after %s", w.cfg.JobTimeout)
return &msg, errors.New(msg)
case <-doneCh:
return output, runErr
}
}
}