-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathschedule.go
141 lines (116 loc) · 3.55 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
package workflow
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/robfig/cron/v3"
"k8s.io/utils/clock"
)
func (w *Workflow[Type, Status]) Schedule(
foreignID string,
startingStatus Status,
spec string,
opts ...ScheduleOption[Type, Status],
) error {
if !w.calledRun {
return fmt.Errorf("schedule failed: workflow is not running")
}
if !w.statusGraph.IsValid(int(startingStatus)) {
w.logger.maybeDebug(
w.ctx,
fmt.Sprintf("ensure %v is configured for workflow: %v", startingStatus, w.Name()),
map[string]string{},
)
return fmt.Errorf("schedule failed: status provided is not configured for workflow: %s", startingStatus)
}
var options scheduleOpts[Type, Status]
for _, opt := range opts {
opt(&options)
}
schedule, err := cron.ParseStandard(spec)
if err != nil {
return err
}
role := makeRole(w.Name(), strconv.FormatInt(int64(startingStatus), 10), foreignID, "scheduler", spec)
processName := makeRole(startingStatus.String(), foreignID, "scheduler", spec)
w.launching.Add(1)
w.run(role, processName, func(ctx context.Context) error {
latestEntry, err := w.recordStore.Latest(ctx, w.Name(), foreignID)
if errors.Is(err, ErrRecordNotFound) {
// NoReturnErr: Rather use zero value for lastRunID and use current clock for first run.
latestEntry = &Record{}
} else if err != nil {
return err
}
lastRun := latestEntry.CreatedAt
// If there is no previous executions of this workflow then schedule the very next from now.
if lastRun.IsZero() {
lastRun = w.clock.Now()
}
nextRun := schedule.Next(lastRun)
err = waitUntil(ctx, w.clock, nextRun)
if err != nil {
return err
}
// If there is a trigger initial value ensure that it is passed down to the trigger function through it's own
// set of optional functions.
var tOpts []TriggerOption[Type, Status]
if options.initialValue != nil {
tOpts = append(tOpts, WithInitialValue[Type, Status](options.initialValue))
}
// If a filter has been provided then allow the ability to skip scheduling when false is returned along with
// a nil error.
var shouldTrigger bool
if options.scheduleFilter != nil {
ok, err := options.scheduleFilter(ctx)
if err != nil {
return err
}
shouldTrigger = ok
} else {
shouldTrigger = true
}
if !shouldTrigger {
return nil
}
_, err = w.Trigger(ctx, foreignID, startingStatus, tOpts...)
if errors.Is(err, ErrWorkflowInProgress) {
// NoReturnErr: Fallthrough to schedule next workflow as there is already one in progress. If this
// happens it is likely that we scheduled a workflow and were unable to schedule the next.
return nil
} else if err != nil {
return err
}
return nil
}, w.defaultOpts.errBackOff)
return nil
}
func waitUntil(ctx context.Context, clock clock.Clock, until time.Time) error {
timeDiffAsDuration := until.Sub(clock.Now())
t := clock.NewTimer(timeDiffAsDuration)
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C():
return nil
}
}
type scheduleOpts[Type any, Status StatusType] struct {
initialValue *Type
scheduleFilter func(ctx context.Context) (bool, error)
}
type ScheduleOption[Type any, Status StatusType] func(o *scheduleOpts[Type, Status])
func WithScheduleInitialValue[Type any, Status StatusType](t *Type) ScheduleOption[Type, Status] {
return func(o *scheduleOpts[Type, Status]) {
o.initialValue = t
}
}
func WithScheduleFilter[Type any, Status StatusType](
fn func(ctx context.Context) (bool, error),
) ScheduleOption[Type, Status] {
return func(o *scheduleOpts[Type, Status]) {
o.scheduleFilter = fn
}
}