-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathschedule.go
More file actions
141 lines (116 loc) · 3.48 KB
/
schedule.go
File metadata and controls
141 lines (116 loc) · 3.48 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
package workflow
import (
"context"
"errors"
"fmt"
"time"
"k8s.io/utils/clock"
"github.com/luno/workflow/internal/cron"
)
func (w *Workflow[Type, Status]) Schedule(
foreignID string,
spec string,
opts ...ScheduleOption[Type, Status],
) error {
if !w.calledRun {
return fmt.Errorf("schedule failed: workflow is not running")
}
var options scheduleOpts[Type, Status]
for _, opt := range opts {
opt(&options)
}
schedule, err := cron.Parse(spec)
if err != nil {
return err
}
role := makeRole(w.Name(), foreignID, "scheduler", spec)
processName := makeRole(foreignID, "scheduler", spec)
var lastRun time.Time
w.launching.Add(1)
w.run(role, processName, func(ctx context.Context) error {
if lastRun.IsZero() {
latestEntry, err := w.recordStore.Latest(ctx, w.Name(), foreignID)
if errors.Is(err, ErrRecordNotFound) {
// NoReturnErr: Rather set the last run to now if there are no previous runs.
lastRun = w.clock.Now()
} else if err != nil {
return err
} else {
// Assign the last run timestamp so that we can use that to determine when it should run next.
lastRun = latestEntry.CreatedAt
}
}
nextRun, ok := schedule.Next(lastRun)
if !ok {
return fmt.Errorf("no next schedule found for spec: %s", spec)
}
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
}
// Update the last run in order to skip this scheduled slot as it was filtered out.
lastRun = w.clock.Now()
// Filter excludes this run. Wait till the next scheduled time to attempt to trigger again.
if shouldTrigger {
_, err = w.Trigger(ctx, foreignID, 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())
if timeDiffAsDuration <= 0 {
return nil
}
t := clock.NewTimer(timeDiffAsDuration)
defer t.Stop()
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
}
}