-
Notifications
You must be signed in to change notification settings - Fork 0
/
schedule.go
370 lines (296 loc) · 7.47 KB
/
schedule.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package boomerang
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
const redisNamespace = "boomerang"
var (
ErrUnexpectedReturnCode = errors.New("unexpected return code from redis")
ErrUnexpectedReturnCodeType = errors.New("unexpected return code type from redis, expected integer")
ErrTaskAlreadyExists = errors.New("task already exists")
ErrTaskDoesNotExist = errors.New("task does not exist")
ErrTaskDataDoesNotExist = errors.New("task data does not exist")
ErrTaskDataInvalidFormat = errors.New("task data has invalid format, expected JSON")
ErrIntervalTooSmall = errors.New("interval must be at least 1 millisecond")
)
type Schedule interface {
Add(ctx context.Context, task *Task, interval time.Duration, firstExecution time.Time) error
Remove(ctx context.Context, kind string, id string) error
Exists(ctx context.Context, kind string, id string) (bool, error)
RunNow(ctx context.Context, kind string, id string) error
On(ctx context.Context, kind string, handler func(ctx context.Context, task *Task)) error
}
type TaskData struct {
Interval time.Duration
Data []byte
}
type ScheduleImpl struct {
redisClient *redis.Client
}
func NewSchedule(redisClient *redis.Client) Schedule {
return &ScheduleImpl{
redisClient: redisClient,
}
}
func (s *ScheduleImpl) Add(ctx context.Context, task *Task, interval time.Duration, firstExecution time.Time) error {
msInterval := interval / time.Millisecond
if msInterval < 1 {
return ErrIntervalTooSmall
}
taskData, err := json.Marshal(TaskData{
Interval: msInterval,
Data: task.Data,
})
if err != nil {
return err
}
nextTick := firstExecution.UnixMilli()
script := redis.NewScript(`
local queueKey = KEYS[1]
local taskDataKey = KEYS[2]
local id = ARGV[1]
local taskData = ARGV[2]
local score = ARGV[3]
-- Check if the task exists
local exists = redis.call("HEXISTS", taskDataKey, id)
if exists == 1 then
-- Error: task already exists
return -1
end
-- Add the task to the sorted set and the task data to the hash set
redis.call("HSETNX", taskDataKey, id, taskData)
redis.call("ZADD", queueKey, score, id)
-- OK
return 0
`)
code, err := script.Run(
ctx,
s.redisClient,
[]string{
s.taskScheduleKey(task.Kind),
s.taskDataKey(task.Kind),
},
task.ID,
taskData,
float64(nextTick),
).Int()
if err != nil {
return err
}
switch code {
case 0:
return nil
case -1:
return ErrTaskAlreadyExists
default:
return ErrUnexpectedReturnCode
}
}
func (s *ScheduleImpl) Remove(ctx context.Context, kind string, id string) error {
script := redis.NewScript(`
local queueKey = KEYS[1]
local taskDataKey = KEYS[2]
local id = ARGV[1]
-- Remove task from sorted set and check if it existed
local existed = redis.call("ZREM", queueKey, id)
if existed == 0 then
-- Error: task does not exist
return -1
end
redis.call("HDEL", taskDataKey, id)
-- OK
return 0
`)
code, err := script.Run(
ctx,
s.redisClient,
[]string{
s.taskScheduleKey(kind),
s.taskDataKey(kind),
},
id,
).Int()
if err != nil {
return err
}
switch code {
case 0:
return nil
case -1:
return ErrTaskDoesNotExist
default:
return ErrUnexpectedReturnCode
}
}
func (s *ScheduleImpl) Exists(ctx context.Context, kind string, id string) (bool, error) {
scheduleKey := s.taskScheduleKey(kind)
exists, err := s.redisClient.ZScore(ctx, scheduleKey, id).Result()
if err == redis.Nil {
return false, nil
}
if err != nil {
return false, err
}
return exists != 0, nil
}
func (s *ScheduleImpl) RunNow(ctx context.Context, kind string, id string) error {
script := redis.NewScript(`
local queueKey = KEYS[1]
local taskDataKey = KEYS[2]
local id = ARGV[1]
local score = ARGV[2]
-- Check if the task exists
local exists = redis.call("HEXISTS", taskDataKey, id)
if exists == 0 then
-- Error: task does not exist
return -1
end
-- Add it to be executed now
redis.call("ZADD", queueKey, score, id)
-- OK
return 0
`)
code, err := script.Run(
ctx,
s.redisClient,
[]string{
s.taskScheduleKey(kind),
s.taskDataKey(kind),
},
id,
float64(time.Now().UnixMilli()),
).Int()
if err != nil {
return err
}
switch code {
case 0:
return nil
case -1:
return ErrTaskDoesNotExist
default:
return ErrUnexpectedReturnCode
}
}
func (s *ScheduleImpl) On(ctx context.Context, kind string, handler func(ctx context.Context, task *Task)) error {
queueKey := s.taskScheduleKey(kind)
script := redis.NewScript(`
local queueKey = KEYS[1]
local taskDataKey = KEYS[2]
local now = tonumber(ARGV[1])
-- Pop the next task from the queue
local res = redis.call("ZPOPMIN", queueKey)
if #res == 0 then
-- Error: No tasks scheduled
return { -1 }
end
local id = res[1]
local score = tonumber(res[2])
-- If the task is scheduled for more than 1 second in the future, put it back in the queue
if score > (now + 1000) then
redis.call("ZADD", queueKey, score, id)
-- Error: Next task is scheduled for more than 1 second in the future
return { -1 }
end
-- Get the task data
local taskDataRaw = redis.call("HGET", taskDataKey, id)
if taskDataRaw == nil then
-- Error: task data does not exist
return { -2 }
end
local taskData = cjson.decode(taskDataRaw)
if taskData == nil then
-- Error: task data has invalid format
return { -3 }
end
-- Schedule the next execution
local nextTick = score + taskData.Interval
-- If the next execution is in the past, schedule it for the next interval
if nextTick < now then
-- Find how many intervals have passed since the last execution
local intervals = math.floor((now - score) / taskData.Interval)
-- Schedule the next execution for the next interval
nextTick = score + (intervals * taskData.Interval) + taskData.Interval
end
redis.call("ZADD", queueKey, nextTick, id)
return {0, id, score, taskDataRaw}
`)
for {
if err := ctx.Err(); err != nil {
return err
}
taskDataKey := s.taskDataKey(kind)
res := script.Run(
ctx,
s.redisClient,
[]string{
queueKey,
taskDataKey,
},
time.Now().UnixMilli(),
)
if err := res.Err(); err != nil {
return err
}
resSlice, err := res.Slice()
if err != nil {
return err
}
code, ok := resSlice[0].(int64)
if !ok {
return ErrUnexpectedReturnCodeType
}
if code == -1 {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Second):
continue
}
}
if code == -2 {
return ErrTaskDataDoesNotExist
}
if code == -3 {
return ErrTaskDataInvalidFormat
}
if code != 0 {
return ErrUnexpectedReturnCode
}
id, ok := resSlice[1].(string)
if !ok {
return errors.New("unexpected type for id")
}
score, ok := resSlice[2].(int64)
if !ok {
return errors.New("unexpected type for score")
}
delta := score - time.Now().UnixMilli()
if delta > 0 {
time.Sleep(time.Duration(delta) * time.Millisecond)
}
data, ok := resSlice[3].(string)
if !ok {
return errors.New("unexpected type for taskDataRaw")
}
var taskData TaskData
if err := json.Unmarshal([]byte(data), &taskData); err != nil {
return err
}
handler(ctx, &Task{
ID: id,
Kind: kind,
Data: taskData.Data,
})
}
}
func (s *ScheduleImpl) taskDataKey(kind string) string {
return fmt.Sprintf("%s:data:%s", redisNamespace, kind)
}
func (s *ScheduleImpl) taskScheduleKey(kind string) string {
return fmt.Sprintf("%s:schedule:%s", redisNamespace, kind)
}