-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathspec.go
More file actions
395 lines (347 loc) · 11.4 KB
/
spec.go
File metadata and controls
395 lines (347 loc) · 11.4 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
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
package scheduler
import (
"errors"
"fmt"
"math"
"strings"
"time"
"github.com/dgryski/go-farm"
rrule "github.com/teambition/rrule-go"
schedulepb "go.temporal.io/api/schedule/v1"
"go.temporal.io/server/common"
"go.temporal.io/server/common/cache"
"go.temporal.io/server/common/primitives/timestamp"
"go.temporal.io/server/common/util"
)
type (
CompiledSpec struct {
spec *schedulepb.ScheduleSpec
tz *time.Location
calendar []*compiledCalendar
excludes []*compiledCalendar
// RFC 5545 rules with DTSTART applied; union with calendar and interval.
rrules []*rrule.RRule
}
GetNextTimeResult struct {
Nominal time.Time // scheduled time before adding jitter
Next time.Time // scheduled time after adding jitter
}
SpecBuilder struct {
// locationCache is a cache for the results of time.LoadLocation. That function accesses
// the filesystem and is relatively slow. We assume that it returns a semantically
// equivalent value for the same location name. This isn't strictly true, for example if
// the time zone database is changed while the process is running. To handle that, we
// expire entries after a day. Note that we cache negative results also.
locationCache cache.Cache
}
locationAndError struct {
loc *time.Location
err error
}
)
func NewSpecBuilder() *SpecBuilder {
return &SpecBuilder{
locationCache: cache.New(1000,
&cache.Options{
TTL: 24 * time.Hour,
},
),
}
}
func (b *SpecBuilder) NewCompiledSpec(spec *schedulepb.ScheduleSpec) (*CompiledSpec, error) {
spec, err := canonicalizeSpec(spec)
if err != nil {
return nil, err
}
// load timezone
tz, err := b.loadTimezone(spec)
if err != nil {
return nil, err
}
// compile StructuredCalendarSpecs
ccs := make([]*compiledCalendar, len(spec.StructuredCalendar))
for i, structured := range spec.StructuredCalendar {
ccs[i] = newCompiledCalendar(structured, tz)
}
// compile excludes
excludes := make([]*compiledCalendar, len(spec.ExcludeStructuredCalendar))
for i, excal := range spec.ExcludeStructuredCalendar {
excludes[i] = newCompiledCalendar(excal, tz)
}
rrules, err := compileRRuleStrings(spec, tz)
if err != nil {
return nil, err
}
cspec := &CompiledSpec{
spec: spec,
tz: tz,
calendar: ccs,
excludes: excludes,
rrules: rrules,
}
return cspec, nil
}
// CleanSpec sets default values in ranges.
func CleanSpec(spec *schedulepb.ScheduleSpec) {
cleanRanges := func(ranges []*schedulepb.Range) {
for _, r := range ranges {
if r.End < r.Start {
r.End = r.Start
}
if r.Step == 0 {
r.Step = 1
}
}
}
cleanCal := func(structured *schedulepb.StructuredCalendarSpec) {
cleanRanges(structured.Second)
cleanRanges(structured.Minute)
cleanRanges(structured.Hour)
cleanRanges(structured.DayOfMonth)
cleanRanges(structured.Month)
cleanRanges(structured.Year)
cleanRanges(structured.DayOfWeek)
}
for _, structured := range spec.StructuredCalendar {
cleanCal(structured)
}
for _, structured := range spec.ExcludeStructuredCalendar {
cleanCal(structured)
}
}
//revive:disable-next-line:cognitive-complexity
func canonicalizeSpec(spec *schedulepb.ScheduleSpec) (*schedulepb.ScheduleSpec, error) {
// make copy so we can change some fields
spec = common.CloneProto(spec)
// parse CalendarSpecs to StructuredCalendarSpecs
for _, cal := range spec.Calendar {
structured, err := parseCalendarToStructured(cal)
if err != nil {
return nil, err
}
spec.StructuredCalendar = append(spec.StructuredCalendar, structured)
}
spec.Calendar = nil
// parse ExcludeCalendars
for _, cal := range spec.ExcludeCalendar {
structured, err := parseCalendarToStructured(cal)
if err != nil {
return nil, err
}
spec.ExcludeStructuredCalendar = append(spec.ExcludeStructuredCalendar, structured)
}
spec.ExcludeCalendar = nil
// parse CronStrings
const unset = "__unset__"
cronTZ := unset
for _, cs := range spec.CronString {
structured, interval, tz, err := parseCronString(cs)
if err != nil {
return nil, err
}
if cronTZ != unset && tz != cronTZ {
// all cron strings must agree on timezone (whether present or not)
return nil, errConflictingTimezoneNames
}
cronTZ = tz
if structured != nil {
spec.StructuredCalendar = append(spec.StructuredCalendar, structured)
}
if interval != nil {
spec.Interval = append(spec.Interval, interval)
}
}
spec.CronString = nil
// if we have cron string(s), copy the timezone to spec, checking for conflict first.
// if cron string timezone is empty string, don't copy, let the one in spec be used.
if cronTZ != unset && cronTZ != "" {
if spec.TimezoneName != "" && spec.TimezoneName != cronTZ || spec.TimezoneData != nil {
return nil, errConflictingTimezoneNames
} else if spec.TimezoneName == "" {
spec.TimezoneName = cronTZ
}
}
// validate structured calendar
for _, structured := range spec.StructuredCalendar {
if err := validateStructuredCalendar(structured); err != nil {
return nil, err
}
}
// validate intervals
for _, interval := range spec.Interval {
if err := validateInterval(interval); err != nil {
return nil, err
}
}
return spec, nil
}
func validateStructuredCalendar(scs *schedulepb.StructuredCalendarSpec) error {
var errs []string
checkRanges := func(ranges []*schedulepb.Range, field string, minVal, maxVal int32) {
for _, r := range ranges {
if r == nil { // shouldn't happen
errs = append(errs, "range is nil")
continue
}
if r.Start < minVal || r.Start > maxVal {
errs = append(errs, fmt.Sprintf("%s Start is not in range [%d-%d]", field, minVal, maxVal))
}
if r.End != 0 && (r.End < r.Start || r.End > maxVal) {
errs = append(errs, fmt.Sprintf("%s End is before Start or not in range [%d-%d]", field, minVal, maxVal))
}
if r.Step < 0 {
errs = append(errs, fmt.Sprintf("%s has invalid Step", field))
}
}
}
checkRanges(scs.Second, "Second", 0, 59)
checkRanges(scs.Minute, "Minute", 0, 59)
checkRanges(scs.Hour, "Hour", 0, 23)
checkRanges(scs.DayOfMonth, "DayOfMonth", 1, 31)
checkRanges(scs.Month, "Month", 1, 12)
checkRanges(scs.Year, "Year", minCalendarYear, maxCalendarYear)
checkRanges(scs.DayOfWeek, "DayOfWeek", 0, 6)
if len(scs.Comment) > maxCommentLen {
errs = append(errs, "comment is too long")
}
if len(errs) > 0 {
return errors.New("invalid calendar spec: " + strings.Join(errs, ", "))
}
return nil
}
func validateInterval(i *schedulepb.IntervalSpec) error {
if i == nil {
return errors.New("interval is nil")
}
// TODO: use timestamp.ValidateAndCapProtoDuration after switching to state machine based implementation.
// Not adding it to workflow based implementation to avoid potential non-determinism errors.
iv, phase := timestamp.DurationValue(i.Interval), timestamp.DurationValue(i.Phase)
if iv < time.Second {
return errors.New("interval is too small")
} else if phase < 0 {
return errors.New("phase is negative")
} else if phase >= iv {
return errors.New("phase cannot be greater than Interval")
}
return nil
}
func (b *SpecBuilder) loadTimezone(spec *schedulepb.ScheduleSpec) (*time.Location, error) {
if spec.TimezoneData != nil {
return time.LoadLocationFromTZData(spec.TimezoneName, spec.TimezoneData)
}
if cached, ok := b.locationCache.Get(spec.TimezoneName).(*locationAndError); ok {
return cached.loc, cached.err
}
loc, err := time.LoadLocation(spec.TimezoneName)
b.locationCache.Put(spec.TimezoneName, &locationAndError{
loc: loc,
err: err,
})
return loc, err
}
func (cs *CompiledSpec) CanonicalForm() *schedulepb.ScheduleSpec {
return cs.spec
}
// Returns the earliest time that matches the schedule spec that is after the given time.
// Returns: Nominal is the time that matches, pre-jitter. Next is the nominal time with
// jitter applied. If there is no matching time, Nominal and Next will be the zero time.
func (cs *CompiledSpec) GetNextTime(jitterSeed string, after time.Time) GetNextTimeResult {
// If we're starting before the schedule's allowed time range, jump up to right before
// it (so that we can still return the first second of the range if it happens to match).
// note: AsTime returns unix epoch on nil StartTime
after = util.MaxTime(after, cs.spec.StartTime.AsTime().Add(-time.Second))
pastEndTime := func(t time.Time) bool {
return cs.spec.EndTime != nil && t.After(cs.spec.EndTime.AsTime()) || t.Year() > maxCalendarYear
}
var nominal time.Time
for nominal.IsZero() || cs.excluded(nominal) {
nominal = cs.rawNextTime(after)
after = nominal
if nominal.IsZero() || pastEndTime(nominal) {
return GetNextTimeResult{}
}
}
maxJitter := timestamp.DurationValue(cs.spec.Jitter)
// Ensure that jitter doesn't push this time past the _next_ nominal start time
if following := cs.rawNextTime(nominal); !following.IsZero() {
maxJitter = min(maxJitter, following.Sub(nominal))
}
next := cs.addJitter(jitterSeed, nominal, maxJitter)
return GetNextTimeResult{Nominal: nominal, Next: next}
}
// Returns the next matching time (without jitter), or the zero value if no time matches.
func (cs *CompiledSpec) rawNextTime(after time.Time) (nominal time.Time) {
var minTimestamp int64 = math.MaxInt64 // unix seconds-since-epoch as int64
for _, cal := range cs.calendar {
if next := cal.next(after); !next.IsZero() {
nextTs := next.Unix()
if nextTs < minTimestamp {
minTimestamp = nextTs
}
}
}
for _, iv := range cs.spec.Interval {
next := cs.nextIntervalTime(iv, after)
if next < minTimestamp {
minTimestamp = next
}
}
if len(cs.rrules) > 0 {
if n := nextRRuleTime(cs.rrules, after); n < minTimestamp {
minTimestamp = n
}
}
if minTimestamp == math.MaxInt64 {
return time.Time{}
}
return time.Unix(minTimestamp, 0).UTC()
}
// Returns the next matching time for a single interval spec. When the interval
// is a multiple of 86400 seconds and a non-UTC location is set, advance by
// whole calendar days in that zone (observing DST); otherwise use fixed
// Unix-second alignment (backwards compatible when timezone is empty/UTC).
func (cs *CompiledSpec) nextIntervalTime(iv *schedulepb.IntervalSpec, after time.Time) int64 {
interval := int64(timestamp.DurationValue(iv.Interval) / time.Second)
if interval < 1 {
interval = 1
}
phase := int64(timestamp.DurationValue(iv.Phase) / time.Second)
if phase < 0 {
phase = 0
}
if u, ok := nextCivilIntervalTick(phase, interval, after, cs.tz); ok {
return u
}
ts := after.Unix()
return (((ts-phase)/interval)+1)*interval + phase
}
// Returns true if any exclude spec matches the time.
func (cs *CompiledSpec) excluded(nominal time.Time) bool {
for _, excal := range cs.excludes {
if excal.matches(nominal) {
return true
}
}
return false
}
// Adds jitter to a nominal time, deterministically (by hashing the given time and a seed).
func (cs *CompiledSpec) addJitter(seed string, nominal time.Time, maxJitter time.Duration) time.Time {
if maxJitter < 0 {
maxJitter = 0
}
bin, err := nominal.MarshalBinary()
if err != nil {
return nominal
}
bin = append(bin, []byte(seed)...)
// we want to fit the result of a multiply in 64 bits, and use 32 bits of hash, which
// leaves 32 bits for the range. if we use nanoseconds or microseconds, our range is
// limited to only a few seconds or hours. using milliseconds supports up to 49 days.
fp := uint64(farm.Fingerprint32(bin))
ms := uint64(maxJitter.Milliseconds())
if ms > math.MaxUint32 {
ms = math.MaxUint32
}
jitter := time.Duration((fp*ms)>>32) * time.Millisecond
return nominal.Add(jitter)
}