-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtick.go
1410 lines (1204 loc) · 30.4 KB
/
tick.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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gotick
import (
"context"
rand2 "crypto/rand"
"encoding/json"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
"github.com/zbysir/gotick/internal/pkg/flow"
"github.com/zbysir/gotick/internal/store"
"log"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
type MetaData map[string]string
type Context struct {
context.Context
CallId string
store NodeStatusStore
collect func(typ string, key string) bool // 预运行来生成 flow 图
s AsyncQueue
lock sync.Mutex
}
func (c *Context) MetaDataAll() MetaData {
if c.store == nil {
return nil
}
m, err := c.store.GetKVAll()
if err != nil {
panic(err)
}
meta := MetaData{}
for k, v := range m {
if strings.HasPrefix(k, "__") {
continue
}
meta[k] = v
}
return meta
}
func (c *Context) SetMetaData(k, v string) {
err := c.store.SetKV(k, v)
if err != nil {
panic(err)
}
}
func (c *Context) MetaData(k string) (string, bool) {
v, ok, err := c.store.GetKV(k)
if err != nil {
panic(err)
}
return v, ok
}
type SequenceWrap struct {
Current int
max int
name string
ctx *Context
}
func (s *SequenceWrap) TaskKey(prefix string) string {
return fmt.Sprintf("%s:%v", prefix, s.Current)
}
func (s *SequenceWrap) Next() bool {
if s.ctx.collect != nil {
end := s.ctx.collect("sequence", s.name)
if end {
s.Current += 1
return s.Current <= 0
}
}
// 存储当前的序列号,而不是下一个
bs, _ := json.Marshal(s)
_ = s.ctx.store.SetKV(s.name, string(bs))
s.Current += 1
if s.max == -1 {
return true
}
return s.Current < s.max
}
func GetFromStore[T interface{}](s NodeStatusStore, key string) (T, bool, error) {
var t T
v, ok, err := s.GetKV("__" + key)
if err != nil {
return t, false, err
}
if !ok {
return t, false, nil
}
err = json.Unmarshal([]byte(v), &t)
if err != nil {
return t, false, err
}
return t, true, nil
}
func SetToStore[T interface{}](s NodeStatusStore, key string, t T) error {
bs, _ := json.Marshal(t)
err := s.SetKV("__"+key, string(bs))
if err != nil {
return err
}
return nil
}
func Sequence(ctx *Context, key string, maxLen int) SequenceWrap {
if ctx.collect != nil {
end := ctx.collect("sequence", key)
if end {
return SequenceWrap{
Current: -1,
max: 0,
name: "",
ctx: ctx,
}
}
}
key = fmt.Sprintf("__%v", key)
s, ok, _ := GetFromStore[SequenceWrap](ctx.store, key)
if !ok {
return SequenceWrap{
Current: -1, // skip first next()
max: maxLen,
name: key,
ctx: ctx,
}
}
return s
}
type FutureT[T interface{}] struct {
Val T
k string
fun func() (T, error)
}
func (f *FutureT[T]) Value() T {
return f.Val
}
func (f *FutureT[T]) exec() (interface{}, error) {
t, err := f.fun()
if err != nil {
return t, err
}
f.Val = t
return t, nil
}
func (f *FutureT[T]) key() string {
return f.k
}
type Future interface {
exec() (interface{}, error)
key() string
}
type AsyncTask struct {
}
func (a *AsyncTask) Done() bool {
return true
}
func (a *AsyncTask) Exec() bool {
return true
}
func AsyncArray[T interface{}, A interface{}](ctx *Context, key string, arr []ArrayWrap[A], f func(ctx *TaskContext, a A) (T, error)) []Future {
var fs []Future
for _, t := range arr {
// 注意闭包问题
t := t
fs = append(fs, Async(ctx, t.Key(key), func(ctx *TaskContext) (T, error) {
return f(ctx, t.Val)
}))
}
return fs
}
func Async[T interface{}](ctx *Context, key string, f func(ctx *TaskContext) (T, error)) *FutureT[T] {
s, exist, _ := ctx.store.GetNodeStatus(key)
if exist {
// 有任务正在运行中,跳过执行
t, _, _ := GetFromStore[T](ctx.store, key)
return &FutureT[T]{
Val: t,
k: key,
fun: func() (T, error) {
return f(newTaskContext(ctx, s))
},
}
}
future := FutureT[T]{
k: key,
fun: func() (T, error) {
return f(newTaskContext(ctx, s))
},
}
return &future
}
// Wait will wait all future done, if Parallel is not 0, then no limit for parallel.
func Wait(ctx *Context, parallel int, fs ...Future) {
allDone := true
runCount := 0
for _, f := range fs {
s, exist, _ := ctx.store.GetNodeStatus(f.key())
if exist {
// 有任务正在运行中,跳过执行
done := false
switch s.Status {
case "done":
done = true
case "fail":
// 如果有一个任务失败了,则算整个失败。
panic(BreakFail(f.key(), fmt.Errorf("task %v, error %v: ", s.Key, strings.Join(s.Errs, ";"))))
}
if done {
continue
} else {
allDone = false
}
if s.Status == "retry" {
// 如果一个任务是 retry 状态,则需要重新执行
} else {
// 任务正在执行,跳过而执行后面的任务
runCount++
continue
}
}
if (s.RunAt.IsZero() || s.RunAt.Before(time.Now())) && (parallel <= 0 || runCount < parallel) {
// 如果任务重试状态,或没有状态,就需要执行
// 如果是 retry,也改为执行状态,让下次调度跳过这次任务
_ = ctx.store.SetNodeStatus(f.key(), s.MakeRunning(), 6*time.Second)
// 如果没到执行时间,则不执行
//log.Printf("step Run")
go func(future Future, s TaskStatus) {
errorc := make(chan error)
datac := make(chan interface{})
go func() {
// 启动心跳
for {
select {
case e := <-errorc:
// 不重新调度,而是等待 BreakWait 自循环。
// 重新调度将面临并发问题:
// 多次任务同时执行成功,将并发调用,可能会导致 task 并发调用出错(状态检查),最好不要并发调度,否则需要加锁导致逻辑复杂。
if s.RetryCount > 5 {
_ = ctx.store.SetNodeStatus(future.key(), s.MakeFail(e))
} else {
_ = ctx.store.SetNodeStatus(future.key(), s.MakeRetry(e))
//log.Printf("step MakeRetry")
}
return
case data := <-datac:
_ = SetToStore(ctx.store, future.key(), data)
_ = ctx.store.SetNodeStatus(future.key(), s.MakeDone())
return
case <-time.After(3 * time.Second):
// 心跳续期
_ = ctx.store.SetNodeStatus(future.key(), s.MakeRunning(), 6*time.Second)
}
}
}()
t, err := future.exec()
if err != nil {
errorc <- err
} else {
datac <- t
}
}(f, s)
// 并行
// log.Printf("step BreakWait %s ", nextCall)
panic(BreakWait(0))
}
}
if !allDone {
//log.Printf("step BreakWait 10")
// 如果还有任务没完成,则等待任务完成
// 循环 1 s 调度一次,检查任务状态,同时检查任务心跳,如果任务没有心跳则重启任务。
panic(BreakWait(time.Second / 1))
}
}
func Memo[T interface{}](ctx *Context, key string, build func() (T, error)) T {
if ctx.collect != nil {
end := ctx.collect("memo", key)
if end {
var t T
return t
}
}
key = fmt.Sprintf("__%v", key)
v, exist, _ := GetFromStore[T](ctx.store, key)
if exist {
return v
}
t, _ := build()
_ = SetToStore(ctx.store, key, t)
return t
}
type ArrayWrap[T interface{}] struct {
ProductKey string `json:"product_key"`
Val T `json:"val"`
Index int `json:"index"`
}
func (a ArrayWrap[T]) Value() (t T) {
return a.Val
}
func (a ArrayWrap[T]) Key(prefix string) string {
// /@/ 表示子集
return fmt.Sprintf("%v/@/%v:%v", a.ProductKey, prefix, a.Index)
}
func Array[T interface{}](ctx *Context, key string, build func() ([]T, error)) []ArrayWrap[T] {
if ctx.collect != nil {
end := ctx.collect("array", key)
if end {
var t T
return []ArrayWrap[T]{
{
ProductKey: key,
Val: t,
Index: 0,
},
}
}
}
v, exist, _ := GetFromStore[[]ArrayWrap[T]](ctx.store, key)
// todo panic error
if exist {
return v
}
t, _ := build()
a := make([]ArrayWrap[T], len(t))
for i, v := range t {
a[i] = ArrayWrap[T]{
ProductKey: key,
Val: v,
Index: i,
}
}
_ = SetToStore(ctx.store, key, a)
return a
}
//
//func UseStatus[T interface{}](ctx *Context, key string, def T) (T, func(T)) {
// // 从上下文中获取变量
// // 如果不存在则创建
// // 如果存在则返回
// // 返回一个函数,用于设置变量
// m, ok, _ := ctx.store.GetKV()
// if ok {
// if v, ok := m[key]; ok {
// var t T
// _ = json.Unmarshal([]byte(v), &t)
// return t, func(t T) {
// m, ok, _ := ctx.store.GetKV()
// if !ok {
// m = make(map[string]string)
// }
// bs, _ := json.Marshal(t)
// m[key] = string(bs)
// _ = ctx.store.SetKV(m)
// }
// }
// }
//
// setV := func(t T) {
// m, ok, _ := ctx.store.GetKV()
// if !ok {
// m = make(map[string]string)
// }
// bs, _ := json.Marshal(t)
// m[key] = string(bs)
// _ = ctx.store.SetKV(m)
// }
// setV(def)
//
// return def, setV
//}
type TaskContext struct {
*Context
Retry int
}
type TaskFun func(ctx *TaskContext) error
func newTaskContext(c *Context, taskStatus TaskStatus) *TaskContext {
return &TaskContext{
Context: c,
Retry: taskStatus.RetryCount,
}
}
func (t *Context) Lock() func() {
t.lock.Lock()
return func() {
t.lock.Unlock()
}
}
// Task 同名的 task 在同一时间只能执行一次
func Task(c *Context, key string, fun TaskFun, opts ...TaskOption) {
if c.collect != nil {
if c.collect("task", key) {
return
}
}
s, exist, _ := c.store.GetNodeStatus(key)
if s.Status == "done" {
return
}
o := TaskOptions(opts).build()
taskContext := newTaskContext(c, s)
if !exist || s.Status == "retry" {
err := fun(taskContext)
if err != nil {
if errors.Is(err, AbortError) {
panic(BreakAbort(key, err))
}
if s.RetryCount > o.MaxRetry {
panic(BreakFail(key, err))
}
panic(BreakRetry(key, err))
}
// 执行成功也需要断点,因为需要依靠断点来存储状态。
panic(BreakDone(key))
}
}
func Sleep(c *Context, key string, duration time.Duration) {
if c.collect != nil {
if c.collect("sleep", key) {
return
}
}
s, exist, _ := c.store.GetNodeStatus(key)
// todo panic error,这个错误应该直接交给 MQ 重试兜底
if s.Status == "done" {
return
}
if !exist {
panic(BreakSleep(key, duration))
}
if s.Status == "sleep" {
d := s.RunAt.Sub(time.Now())
if d > 0 {
panic(BreakSleep(key, d))
}
_ = c.store.SetNodeStatus(key, s.MakeDone())
// todo panic error,这个错误应该直接交给 MQ 重试兜底
}
}
type taskOption struct {
MaxRetry int // 这个 Task 最大重试次数,默认为 5
}
type TaskOptions []TaskOption
func (os TaskOptions) build() taskOption {
option := taskOption{
MaxRetry: 1,
}
for _, o := range os {
o.apply(&option)
}
return option
}
type TaskOption interface {
apply(*taskOption)
}
type maxRetryOption struct {
maxRetry int
}
func (m *maxRetryOption) apply(option *taskOption) {
option.MaxRetry = m.maxRetry
return
}
func WithMaxRetry(maxRetry int) TaskOption {
return &maxRetryOption{maxRetry: maxRetry}
}
type Set interface {
Push(i interface{})
}
type TaskStatus struct {
Key string
// fail, 超过重试次数就算失败
// abort, 手动终止流程
// sleep, 等待中
// retry, 重试中
// done, 完成
// running, 异步任务正在运行
Status string `json:"status"`
RunAt time.Time `json:"run_at"` // sleep 到的时间
Errs []string `json:"errs"` // 每次重试都有错误
RetryCount int `json:"retry_count"`
}
func (t TaskStatus) MakeDone() TaskStatus {
t.Status = "done"
return t
}
func (t TaskStatus) MakeFail(err error) TaskStatus {
t.Status = "fail"
t.RetryCount += 1
if err != nil {
t.Errs = append(t.Errs, err.Error())
}
return t
}
func (t TaskStatus) MakeAbort() TaskStatus {
t.Status = "abort"
return t
}
func (t TaskStatus) MakeRunning() TaskStatus {
t.Status = "running"
return t
}
func (t TaskStatus) MakeSleep(runAt time.Time) TaskStatus {
t.Status = "sleep"
t.RunAt = runAt
return t
}
func (t TaskStatus) MakeRetry(err error) TaskStatus {
t.Status = "retry"
t.RetryCount += 1
t.Errs = append(t.Errs, err.Error())
t.RunAt = time.Now().Add(time.Second * time.Duration(t.RetryCount))
return t
}
type NodeStatusStore interface {
GetNodeStatus(key string) (TaskStatus, bool, error) // 获取每个 task 的运行状态
SetNodeStatus(key string, value TaskStatus, ttl ...time.Duration) error
UpdateNodeStatus(key string, fu func(status TaskStatus, isNew bool) TaskStatus) (TaskStatus, error)
GetKVAll() (map[string]string, error)
SetKV(k string, v string) error
GetKV(k string) (string, bool, error)
Clear() error // 删除所有数据
}
var _ NodeStatusStore = (*KvNodeStatusStore)(nil)
type StoreFactory interface {
New(key string) NodeStatusStore
}
type AsyncQueueFactory interface {
New(key string) AsyncQueue
Start(ctx context.Context) error
}
type TickServer struct {
scheduler *Scheduler
httpServer *HttpServer
measure Measure
}
type Measure interface {
OnExec(flow, key string)
GetCount(flow string) map[string]int64
}
type MockMeasure struct {
m map[string]map[string]int64
}
func NewMockMeasure() *MockMeasure {
return &MockMeasure{
m: map[string]map[string]int64{},
}
}
func (m *MockMeasure) OnExec(flow, key string) {
if _, ok := m.m[flow]; !ok {
m.m[flow] = map[string]int64{}
}
m.m[flow][key] += 1
}
func (m *MockMeasure) GetCount(flow string) map[string]int64 {
return m.m[flow]
}
var _ Measure = (*MockMeasure)(nil)
type RedisMeasure struct {
redis *redis.Client
}
func NewRedisMeasure(redis *redis.Client) *RedisMeasure {
return &RedisMeasure{redis: redis}
}
func (r *RedisMeasure) OnExec(flow, key string) {
r.redis.HIncrBy(context.Background(), "measure:"+flow, key, 1)
}
func (r *RedisMeasure) GetCount(flow string) map[string]int64 {
x, _ := r.redis.HGetAll(context.Background(), "measure:"+flow).Result()
rsp := map[string]int64{}
for k, v := range x {
rsp[k], _ = strconv.ParseInt(v, 10, 64)
}
return rsp
}
var _ Measure = (*RedisMeasure)(nil)
type HttpServer struct {
flows map[string]*Flow // to get flow info
scheduler *Scheduler // to trigger flow
measure Measure
listenAddress string
}
func NewHttpServer(scheduler *Scheduler, measure Measure, listenAddress string) *HttpServer {
return &HttpServer{scheduler: scheduler, measure: measure, flows: map[string]*Flow{}, listenAddress: listenAddress}
}
func (s *HttpServer) Start(ctx context.Context) error {
r := gin.Default()
api := r.Group("/api")
api.GET("/flow_list", func(c *gin.Context) {
r := map[string]flow.DAG{}
for name, f := range s.flows {
dag, err := f.DAG()
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{
"message": err.Error(),
})
return
}
r[name] = dag
}
c.JSON(http.StatusOK, r)
})
go r.Run()
return nil
}
func (s *HttpServer) register(f *Flow) {
s.flows[f.Id] = f
}
type TickClient struct {
scheduler *Scheduler
}
type Flow struct {
Id string
fun func(ctx *Context)
onFail func(ctx *Context, ts TaskStatus) error
onError func(ctx *Context, ts TaskStatus) error
onSuccess func(ctx *Context) error
opt flowOpt
}
// DAG 生成一个数据流图
// 可以使用 reactflow 绘制。
func (f *Flow) DAG() (flow.DAG, error) {
dag := flow.DAG{}
f.fun(&Context{
Context: nil,
CallId: "dag",
store: nil,
collect: func(typ string, key string) bool {
ks := strings.Split(key, "/@/")
var parent string
if len(ks) > 1 {
parent = ks[len(ks)-2]
key = ks[len(ks)-1]
}
var node flow.Node
switch typ {
case "task":
node = flow.Node{
Id: key,
Data: flow.NodeData{
Label: fmt.Sprintf("[task] %s", key),
Data: map[string]interface{}{
"type": typ,
},
},
ParentNode: parent,
}
case "sleep":
node = flow.Node{
Id: key,
Data: flow.NodeData{
Label: fmt.Sprintf("[sleep] %s", key),
Data: map[string]interface{}{
"type": typ,
},
},
}
case "array":
node = flow.Node{
Id: key,
Data: flow.NodeData{
Label: fmt.Sprintf("[%v] %s", typ, key),
Data: map[string]interface{}{
"type": typ,
},
},
}
default:
node = flow.Node{
Id: key,
Data: flow.NodeData{
Label: fmt.Sprintf("[%v] %s", typ, key),
Data: map[string]interface{}{
"type": typ,
},
},
}
}
dag.AppendNode(node, parent)
// 连接上一个节点
if len(dag.Nodes) > 1 {
//l:=len(dag.Nodes)
//sourceId := dag.GetNodeByIndex(l-2).Id
//targetId := nodes[len(nodes)-1].Id
//edge = append(edge, flow.Edge{
// Id: fmt.Sprintf("%s--%s", sourceId, targetId),
// Source: sourceId,
// Target: targetId,
// MarkerEnd: flow.Marker{Type: "arrow"},
// Animated: false,
// Label: "",
// Data: nil,
// Style: nil,
//})
}
return true
},
})
return dag, nil
}
func (f *Flow) OnSuccess(fun func(ctx *Context) error) *Flow {
f.onSuccess = fun
return f
}
func (f *Flow) OnFail(fun func(ctx *Context, ts TaskStatus) error) *Flow {
f.onFail = fun
return f
}
// OnError 添加一个错误回调,和 task 一样,错误回调也支持重试。
func (f *Flow) OnError(fun func(ctx *Context, ts TaskStatus) error) *Flow {
f.onError = fun
return f
}
type Event struct {
CallId string
Critical bool
InitMetaData MetaData // 只有当第一次调度时有效
}
type AsyncQueue interface {
// Publish 当 uniqueKey 不为空时,后面 Publish 的数据会覆盖前面的数据
// uniqueKey 通常为 callId
Publish(ctx context.Context, data Event, delay time.Duration) error
Subscribe(h func(ctx context.Context, data Event) error)
}
type BreakStatus struct {
Type string // abort, sleep, retry, done, fail
RunAt time.Time // 当 sleep 时,表示下次调度的时间
Task string // 表示触发的是哪一个 task 内部断点
Err error
}
func WithCallId(ctx context.Context, callId string) context.Context {
return context.WithValue(ctx, "callId", callId)
}
func GetCallId(ctx context.Context) string {
value := ctx.Value("callId")
if value == nil {
return ""
}
return value.(string)
}
var AbortError = errors.New("abort")
type FlowOption func(f *flowOpt)
type flowOpt struct {
timeout time.Duration
}
// WithTimeout 控制执行整个 flow 的超时时间,超时后将会中断任务并调用 onFail.
func WithTimeout(t time.Duration) FlowOption {
return func(f *flowOpt) {
f.timeout = t
}
}
// Flow Define a flow
func (t *TickServer) Flow(id string, fun func(ctx *Context), opts ...FlowOption) *Flow {
f := &Flow{
Id: id,
fun: fun,
onFail: nil,
onSuccess: nil,
}
for _, o := range opts {
o(&f.opt)
}
// 注册调度
t.scheduler.register(f)
if t.httpServer != nil {
t.httpServer.register(f)
}
return f
}
type Scheduler struct {
asyncScheduler AsyncQueueFactory
statusFactory StoreFactory
debug bool
}
func NewScheduler(asyncScheduler AsyncQueueFactory, statusStore StoreFactory) *Scheduler {
return &Scheduler{asyncScheduler: asyncScheduler, statusFactory: statusStore}
}
func (s *Scheduler) Start(ctx context.Context) error {
return s.asyncScheduler.Start(ctx)
}
func (s *Scheduler) register(f *Flow) {
aw := s.asyncScheduler.New(f.Id)
aw.Subscribe(func(ctx context.Context, event Event) error {
//log.Printf("-----------------------------")
callId := event.CallId
ctx = WithCallId(ctx, callId)
statusStore := s.statusFactory.New(callId)
if event.InitMetaData != nil {
for k, v := range event.InitMetaData {
_ = statusStore.SetKV(k, v)
}
}
// 从缓存中拿出上次的运行状态
//m, _, := statusStore.GetKVAll()
//if m != nil {
// ctx = WithMetaData(ctx, m)
//}
err := func() (err error) {
ctx := &Context{
Context: ctx,
CallId: callId,
store: statusStore,
s: aw,
}
defer func() {
r := recover()
if r == nil {
return
}
ns, ok := r.(Breakpoint)
if !ok {
panic(r)
}
switch breakpoint := ns.(type) {
case *breakContinue:
// 立即调度,实现并行
err = aw.Publish(ctx, Event{
CallId: callId,
Critical: true,
}, 0)
if err != nil {
log.Printf("scheduler event error: %v", err)
return
}
case *breakWait:
err = aw.Publish(ctx, Event{
CallId: callId,
Critical: true,
}, breakpoint.RunAt.Sub(time.Now()))
if err != nil {
log.Printf("scheduler event error: %v", err)
return
}
case *breakRetry:
// 存储重试次数
var newStatus TaskStatus
newStatus, err = statusStore.UpdateNodeStatus(breakpoint.Task, func(status TaskStatus, isNew bool) TaskStatus {
return status.MakeRetry(breakpoint.Err)
})
if f.onError != nil {
err = f.onError(ctx, newStatus)
if err != nil {
// TODO retry when onError error
log.Printf("[gotick error] onFail error: %v", err)
}
}
// 进入下次调度
err = aw.Publish(ctx, Event{
CallId: callId,
Critical: true,
}, time.Duration(newStatus.RetryCount)*time.Second) // TODO 支持指定算法计算回退时间
if err != nil {
log.Printf("[gotick error] Publish error: %v", err)
}