-
Notifications
You must be signed in to change notification settings - Fork 0
/
timewheel.go
547 lines (486 loc) · 11.5 KB
/
timewheel.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
package timewheel
import (
"context"
"fmt"
"math/rand"
"strconv"
"sync/atomic"
"time"
zstd "github.com/klauspost/compress/zstd"
redis "github.com/redis/go-redis/v9"
)
type OptionFunc func(*TimeWheel)
func WithInterval(interval time.Duration) OptionFunc {
return func(options *TimeWheel) {
options.interval = interval
}
}
func WithSlotNums(slotNums int64) OptionFunc {
return func(options *TimeWheel) {
options.slotNums = slotNums
}
}
func WithContext(ctx context.Context) OptionFunc {
return func(options *TimeWheel) {
options.ctx = ctx
}
}
func WithEnableEvalRO(enableEvalRO bool) OptionFunc {
return func(options *TimeWheel) {
options.enableEvalRO = enableEvalRO
}
}
func WithConcurrent(concurrent int) OptionFunc {
return func(options *TimeWheel) {
if concurrent < 1 {
return
}
options.concurrent = concurrent
}
}
func WithRetrySleep(retrySleep time.Duration) OptionFunc {
return func(options *TimeWheel) {
options.retrySleep = retrySleep
}
}
// retryMax == 0 means never retry
// retryMax < 0 means always retry
func WithRetryMax(retryMax int) OptionFunc {
return func(options *TimeWheel) {
options.retryMax = retryMax
}
}
type Timer struct {
Id string
Payload []byte
}
type Callback func(*Timer) bool
type TimeWheel struct {
name string
interval time.Duration
slotNums int64
currentPos int64
client *redis.Client
ctx context.Context
cancel context.CancelFunc
callback Callback
enableEvalRO bool
concurrent int
retrySleep time.Duration
retryMax int
}
func NewTimeWheel(client *redis.Client, name string, callback Callback, opts ...OptionFunc) *TimeWheel {
if client == nil || len(name) == 0 {
panic("client and name must not be nil")
}
if callback == nil {
panic("callback must not be nil")
}
timewheel := &TimeWheel{
client: client,
name: name,
interval: time.Second,
slotNums: 60,
ctx: context.Background(),
callback: callback,
concurrent: 5,
retrySleep: time.Second * 10,
retryMax: 3,
}
for _, opt := range opts {
opt(timewheel)
}
if timewheel.slotNums < 1 {
panic("slotNums must be greater than 0")
}
timewheel.currentPos = rand.Int63n(timewheel.slotNums)
timewheel.ctx, timewheel.cancel = context.WithCancel(timewheel.ctx)
return timewheel
}
func (wheel *TimeWheel) getTargetLockExpire() time.Duration {
if wheel.slotNums > 1 {
return time.Duration(wheel.slotNums-1) * wheel.interval
}
return time.Duration(wheel.slotNums) * wheel.interval
}
func (wheel *TimeWheel) getTargetExpire(delay time.Duration) time.Duration {
return time.Duration(wheel.slotNums)*wheel.interval*2 + delay
}
var delTargetScript = redis.NewScript(`
local name = KEYS[1]
local id = KEYS[2]
local t = name .. ":t:" .. id
local idx = redis.call("HGET", t, "idx")
if not idx then
return false
end
local s = name .. ":s:" .. idx
redis.call("SREM", s, id)
redis.call("DEL", t)
local d = name .. ":d"
redis.call("SREM", d, id)
local dl = name .. ":dl:" .. id
redis.call("DEL", dl)
return true
`)
var getDoneTargetsPayloadScript = redis.NewScript(`
local name = KEYS[1]
local expire = KEYS[2]
local retry = KEYS[3]
local retry_max = tonumber(KEYS[4])
local results = {}
for _, id in ipairs(ARGV) do
local t = name .. ":t:" .. id
local d = name .. ":d"
local dl = name .. ":dl:" .. id
if redis.call("EXISTS", t) == 0 then
redis.call("SREM", d, id)
redis.call("DEL", dl)
elseif redis.call("SET", dl, "", "NX", "EX", retry) then
local no_retry = false
if retry_max == 0 then
no_retry = true
elseif retry_max > 0 and redis.call("HINCRBY", t, "retry_count", 1) > retry_max then
no_retry = true
end
local r = redis.call("HMGET", t, "payload")
if r then
table.insert(results, id)
table.insert(results, r[1])
end
if no_retry then
redis.call("DEL", dl)
redis.call("DEL", t)
redis.call("SREM", d, id)
else
redis.call("EXPIRE", t, expire)
end
end
end
return results
`)
func parseDecrTargetsResp(ss []string) (map[string][]byte, error) {
if len(ss)%2 != 0 {
return nil, fmt.Errorf("decr targets response length invalid: %v", ss)
}
results := make(map[string][]byte, len(ss)/2)
for i := 0; i < len(ss); i += 2 {
id := ss[i]
dec, _ := zstd.NewReader(nil)
defer dec.Close()
payload, err := dec.DecodeAll(stringToBytes(ss[i+1]), make([]byte, 0, len(ss[i+1])))
if err != nil {
// return nil, fmt.Errorf("decompress payload failed: %w", err)
continue
}
results[id] = payload
}
return results, nil
}
var deleteDoneTargetScript = redis.NewScript(`
local name = KEYS[1]
local id = KEYS[2]
local d = name .. ":d"
if redis.call("SREM", d, id) == 0 then
return false
end
local dl = name .. ":dl:" .. id
redis.call("DEL", dl)
local t = name .. ":t:" .. id
redis.call("DEL", t)
return true
`)
func (wheel *TimeWheel) deleteDoneTarget(id string) error {
return deleteDoneTargetScript.Run(
wheel.ctx,
wheel.client,
[]string{
wheel.name,
id,
},
).Err()
}
func slice2interface[T any](s []T) []interface{} {
var r []interface{} = make([]interface{}, len(s))
for i, v := range s {
r[i] = v
}
return r
}
func (wheel *TimeWheel) getDoneTargetsPayload(ids []string) (map[string][]byte, error) {
ss, err := getDoneTargetsPayloadScript.Run(
wheel.ctx,
wheel.client,
[]string{
wheel.name,
strconv.FormatInt(int64(wheel.getTargetLockExpire().Seconds()), 10),
strconv.FormatInt(int64(wheel.retrySleep.Seconds()), 10),
strconv.FormatInt(int64(wheel.retryMax), 10),
},
slice2interface(ids)...,
).StringSlice()
if err != nil {
return nil, err
}
return parseDecrTargetsResp(ss)
}
var clockAndGetDoneTargetScript = redis.NewScript(`
local name = KEYS[1]
local idx = KEYS[2]
local s = name .. ":s:" .. idx
local ts = redis.call("SMEMBERS", s)
for _, v in ipairs(ts) do
local tl = name .. ":tl:" .. v
if redis.call("EXISTS", tl) == 0 then
local d = name .. ":d"
redis.call("SADD", d, v)
redis.call("SREM", s, v)
end
end
local res = {}
local d = name .. ":d"
local ds = redis.call("SMEMBERS", d)
for _, v in ipairs(ds) do
local dl = name .. ":dl:" .. v
if redis.call("EXISTS", dl) == 0 then
table.insert(res, v)
end
end
return res
`)
func (wheel *TimeWheel) clockAndGetDoneTargets(idx int64) ([]string, error) {
var f func(ctx context.Context, c redis.Scripter, keys []string, args ...interface{}) *redis.Cmd
if wheel.enableEvalRO {
f = clockAndGetDoneTargetScript.RunRO
} else {
f = clockAndGetDoneTargetScript.Run
}
ts, err := f(
wheel.ctx,
wheel.client,
[]string{
wheel.name,
strconv.FormatInt(idx, 10),
},
).StringSlice()
if err != nil {
return nil, err
}
return ts, nil
}
func (wheel *TimeWheel) proxy(ctx context.Context, idx int64, run func(idx int64, ids []string)) {
ts, err := wheel.clockAndGetDoneTargets(idx)
if err != nil {
return
}
if len(ts) == 0 {
return
}
for _, t := range splitIntoBatches(ts, wheel.concurrent) {
select {
case <-ctx.Done():
return
default:
run(idx, t)
}
}
}
type addTimerOptions struct {
force bool
payload []byte
}
type AddTimerOption func(*addTimerOptions)
// will delete old target if exists
func WithForce() AddTimerOption {
return func(options *addTimerOptions) {
options.force = true
}
}
func WithPayload(payload []byte) AddTimerOption {
return func(options *addTimerOptions) {
options.payload = payload
}
}
var putTargetScript = redis.NewScript(`
local name = KEYS[1]
local id = KEYS[2]
local t = name .. ":t:" .. id
if redis.call("EXISTS", t) == 1 then
return {err="already exists"}
end
local idx = ARGV[1]
redis.call("HMSET", t, "idx", idx, "payload", ARGV[2])
redis.call("EXPIRE", t, ARGV[3])
local s = name .. ":s:" .. idx
redis.call("SADD", s, id)
local tl = name .. ":tl:" .. id
redis.call("SET", tl, "", "EX", ARGV[4])
return true
`)
var forcePutTargetScript = redis.NewScript(`
local name = KEYS[1]
local id = KEYS[2]
local t = name .. ":t:" .. id
local oldIdx = redis.call("HGET", t, "idx")
if oldIdx then
local d = name .. ":d"
redis.call("SREM", d, id)
local dl = name .. ":dl:" .. id
redis.call("DEL", dl)
local oldS = name .. ":s:" .. oldIdx
redis.call("SREM", oldS, id)
end
local idx = ARGV[1]
redis.call("HMSET", t, "idx", idx, "payload", ARGV[2])
redis.call("EXPIRE", t, ARGV[3])
local s = name .. ":s:" .. idx
redis.call("SADD", s, id)
local tl = name .. ":tl:" .. id
redis.call("SET", tl, "", "EX", ARGV[4])
return true
`)
func (wheel *TimeWheel) AddTimer(id string, delay time.Duration, opts ...AddTimerOption) error {
if delay < 0 {
return fmt.Errorf("delay must be greater than 0")
}
if delay <= wheel.interval {
delay = wheel.interval
}
var options addTimerOptions
for _, opt := range opts {
opt(&options)
}
currentPos := atomic.LoadInt64(&wheel.currentPos)
delaySec := int64(delay.Seconds())
idx := (currentPos + delaySec/int64(wheel.interval.Seconds())) % wheel.slotNums
enc, _ := zstd.NewWriter(nil)
defer enc.Close()
var script *redis.Script
if options.force {
script = forcePutTargetScript
} else {
script = putTargetScript
}
err := script.Run(
wheel.ctx,
wheel.client,
[]string{
wheel.name,
id,
},
idx,
enc.EncodeAll(options.payload, make([]byte, 0, len(options.payload))),
int(wheel.getTargetExpire(delay).Seconds()),
delaySec,
).Err()
if err != nil {
return fmt.Errorf("put target failed: %w", err)
}
return nil
}
func (wheel *TimeWheel) RemoveTimer(id string) error {
return delTargetScript.Run(
wheel.ctx,
wheel.client,
[]string{
wheel.name,
id,
},
).Err()
}
func (wheel *TimeWheel) GetTimer(id string) (time.Duration, error) {
t, err := wheel.client.TTL(
wheel.ctx,
fmt.Sprintf("%s:tl:%s", wheel.name, id),
).Result()
if err != nil {
return 0, err
}
return t, nil
}
var resetTimerScript = redis.NewScript(`
local name = KEYS[1]
local id = KEYS[2]
local t = name .. ":t:" .. id
local idx = redis.call("HGET", t, "idx")
if not idx then
return false
end
local d = name .. ":d"
if redis.call("SISMEMBER", d, id) == 1 then
return false
end
local tl = name .. ":tl:" .. id
redis.call("SET", tl, "", "EX", ARGV[2])
local s = name .. ":s:" .. idx
redis.call("SREM", s, id)
local s = name .. ":s:" .. ARGV[1]
redis.call("SADD", s, id)
redis.call("HMSET", t, "idx", ARGV[1])
return true
`)
func (wheel *TimeWheel) ResetTimer(id string, delay time.Duration) error {
if delay < 0 {
return fmt.Errorf("delay must be greater than 0")
}
if delay <= wheel.interval {
delay = wheel.interval
}
delaySec := int64(delay.Seconds())
idx := (atomic.LoadInt64(&wheel.currentPos) + delaySec/int64(wheel.interval.Seconds())) % wheel.slotNums
return resetTimerScript.Run(
wheel.ctx,
wheel.client,
[]string{
wheel.name,
id,
},
idx,
delaySec,
).Err()
}
func (wheel *TimeWheel) Run() {
ticker := time.NewTicker(wheel.interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
go wheel.exec(
wheel.ctx,
wheel.tickPos(),
)
case <-wheel.ctx.Done():
return
}
}
}
func (wheel *TimeWheel) tickPos() int64 {
if !atomic.CompareAndSwapInt64(&wheel.currentPos, wheel.slotNums-1, 0) {
return atomic.AddInt64(&wheel.currentPos, 1) - 1
} else {
return wheel.slotNums - 1
}
}
func (wheel *TimeWheel) exec(ctx context.Context, idx int64) {
wheel.proxy(ctx, idx, func(idx int64, ids []string) {
resp, err := wheel.getDoneTargetsPayload(ids)
if err != nil {
return
}
for id, payload := range resp {
_ = wheel.call(&Timer{
Id: id,
Payload: payload,
})
}
})
}
func (wheel *TimeWheel) call(t *Timer) error {
if wheel.callback(t) {
return wheel.deleteDoneTarget(t.Id)
}
return nil
}
func (wheel *TimeWheel) Stop() {
wheel.cancel()
}