-
Notifications
You must be signed in to change notification settings - Fork 145
/
ticker.go
357 lines (281 loc) · 7.49 KB
/
ticker.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
package ticker
import (
"context"
"fmt"
"sync"
"time"
"github.com/go-co-op/gocron/v2"
"github.com/google/uuid"
"github.com/rs/zerolog"
"github.com/hatchet-dev/hatchet/internal/datautils"
"github.com/hatchet-dev/hatchet/internal/integrations/alerting"
"github.com/hatchet-dev/hatchet/internal/logger"
"github.com/hatchet-dev/hatchet/internal/msgqueue"
"github.com/hatchet-dev/hatchet/internal/repository"
)
type Ticker interface {
Start(ctx context.Context) error
}
type TickerImpl struct {
mq msgqueue.MessageQueue
l *zerolog.Logger
entitlements repository.EntitlementsRepository
repo repository.EngineRepository
s gocron.Scheduler
ta *alerting.TenantAlertManager
crons sync.Map
scheduledWorkflows sync.Map
dv datautils.DataDecoderValidator
tickerId string
}
type TickerOpt func(*TickerOpts)
type TickerOpts struct {
mq msgqueue.MessageQueue
l *zerolog.Logger
entitlements repository.EntitlementsRepository
repo repository.EngineRepository
tickerId string
ta *alerting.TenantAlertManager
dv datautils.DataDecoderValidator
}
func defaultTickerOpts() *TickerOpts {
logger := logger.NewDefaultLogger("ticker")
return &TickerOpts{
l: &logger,
tickerId: uuid.New().String(),
dv: datautils.NewDataDecoderValidator(),
}
}
func WithMessageQueue(mq msgqueue.MessageQueue) TickerOpt {
return func(opts *TickerOpts) {
opts.mq = mq
}
}
func WithRepository(r repository.EngineRepository) TickerOpt {
return func(opts *TickerOpts) {
opts.repo = r
}
}
func WithEntitlementsRepository(r repository.EntitlementsRepository) TickerOpt {
return func(opts *TickerOpts) {
opts.entitlements = r
}
}
func WithLogger(l *zerolog.Logger) TickerOpt {
return func(opts *TickerOpts) {
opts.l = l
}
}
func WithTenantAlerter(ta *alerting.TenantAlertManager) TickerOpt {
return func(opts *TickerOpts) {
opts.ta = ta
}
}
func New(fs ...TickerOpt) (*TickerImpl, error) {
opts := defaultTickerOpts()
for _, f := range fs {
f(opts)
}
if opts.mq == nil {
return nil, fmt.Errorf("task queue is required. use WithMessageQueue")
}
if opts.repo == nil {
return nil, fmt.Errorf("repository is required. use WithRepository")
}
if opts.entitlements == nil {
return nil, fmt.Errorf("entitlements repository is required. use WithEntitlementsRepository")
}
if opts.ta == nil {
return nil, fmt.Errorf("tenant alerter is required. use WithTenantAlerter")
}
newLogger := opts.l.With().Str("service", "ticker").Logger()
opts.l = &newLogger
s, err := gocron.NewScheduler(gocron.WithLocation(time.UTC))
if err != nil {
return nil, fmt.Errorf("could not create scheduler: %w", err)
}
return &TickerImpl{
mq: opts.mq,
l: opts.l,
repo: opts.repo,
entitlements: opts.entitlements,
s: s,
dv: opts.dv,
tickerId: opts.tickerId,
ta: opts.ta,
}, nil
}
func (t *TickerImpl) Start() (func() error, error) {
ctx, cancel := context.WithCancel(context.Background())
t.l.Debug().Msgf("starting ticker %s", t.tickerId)
// register the ticker
_, err := t.repo.Ticker().CreateNewTicker(ctx, &repository.CreateTickerOpts{
ID: t.tickerId,
})
if err != nil {
cancel()
return nil, err
}
_, err = t.s.NewJob(
gocron.DurationJob(time.Second*5),
gocron.NewTask(
t.runUpdateHeartbeat(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not create update heartbeat job: %w", err)
}
_, err = t.s.NewJob(
gocron.DurationJob(time.Second*1),
gocron.NewTask(
t.runPollStepRuns(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not create update heartbeat job: %w", err)
}
_, err = t.s.NewJob(
gocron.DurationJob(time.Second*1),
gocron.NewTask(
t.runPollGetGroupKeyRuns(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not create update heartbeat job: %w", err)
}
_, err = t.s.NewJob(
// crons only have a resolution of 1 minute, so only poll every 15 seconds
gocron.DurationJob(time.Second*15),
gocron.NewTask(
t.runPollCronSchedules(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not create poll cron schedules job: %w", err)
}
_, err = t.s.NewJob(
// we look ahead every 5 seconds
gocron.DurationJob(time.Second*5),
gocron.NewTask(
t.runPollSchedules(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not create poll cron schedules job: %w", err)
}
_, err = t.s.NewJob(
gocron.DurationJob(time.Minute*5),
gocron.NewTask(
t.runStreamEventCleanup(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not schedule stream event cleanup: %w", err)
}
// poll for tenant alerts every minute, since minimum alerting frequency is 5 minutes
_, err = t.s.NewJob(
gocron.DurationJob(time.Minute*1),
gocron.NewTask(
t.runPollTenantAlerts(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not schedule tenant alert polling: %w", err)
}
// poll for expiring tokens every 15 minutes
_, err = t.s.NewJob(
gocron.DurationJob(time.Minute*15),
gocron.NewTask(
t.runExpiringTokenAlerts(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not schedule tenant alert polling: %w", err)
}
// poll for tenant resource limit alerts every 15 minutes
_, err = t.s.NewJob(
gocron.DurationJob(time.Minute*15),
gocron.NewTask(
t.runTenantResourceLimitAlerts(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not schedule tenant resource limit alert polling: %w", err)
}
// poll to resolve worker semaphore slots every 1 minute
_, err = t.s.NewJob(
gocron.DurationJob(time.Minute*1),
gocron.NewTask(
t.runWorkerSemaphoreSlotResolver(ctx),
),
)
if err != nil {
cancel()
return nil, fmt.Errorf("could not schedule worker semaphore slot resolver polling: %w", err)
}
t.s.Start()
cleanup := func() error {
t.l.Debug().Msg("removing ticker")
cancel()
if err := t.s.Shutdown(); err != nil {
return fmt.Errorf("could not shutdown scheduler: %w", err)
}
deleteCtx, deleteCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer deleteCancel()
// delete the ticker
err = t.repo.Ticker().Delete(deleteCtx, t.tickerId)
if err != nil {
t.l.Err(err).Msg("could not delete ticker")
return err
}
return nil
}
return cleanup, nil
}
func (t *TickerImpl) runUpdateHeartbeat(ctx context.Context) func() {
return func() {
t.l.Debug().Msgf("ticker: updating heartbeat")
now := time.Now().UTC()
// update the heartbeat
_, err := t.repo.Ticker().UpdateTicker(ctx, t.tickerId, &repository.UpdateTickerOpts{
LastHeartbeatAt: &now,
})
if err != nil {
t.l.Err(err).Msg("could not update heartbeat")
}
}
}
func (t *TickerImpl) runStreamEventCleanup(ctx context.Context) func() {
return func() {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
t.l.Debug().Msgf("ticker: cleaning up stream event")
err := t.repo.StreamEvent().CleanupStreamEvents(ctx)
if err != nil {
t.l.Err(err).Msg("could not cleanup stream events")
}
}
}
func (t *TickerImpl) runWorkerSemaphoreSlotResolver(ctx context.Context) func() {
return func() {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
t.l.Debug().Msgf("ticker: resolving orphaned worker semaphore slots")
n, err := t.repo.Worker().ResolveWorkerSemaphoreSlots(ctx)
if n > 0 {
t.l.Warn().Msgf("resolved %d orphaned worker semaphore slots", n)
}
if err != nil {
t.l.Err(err).Msg("could ")
}
}
}