-
Notifications
You must be signed in to change notification settings - Fork 139
/
ticker.go
323 lines (260 loc) · 7.02 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
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/logger"
"github.com/hatchet-dev/hatchet/internal/repository"
"github.com/hatchet-dev/hatchet/internal/services/shared/tasktypes"
"github.com/hatchet-dev/hatchet/internal/taskqueue"
)
type Ticker interface {
Start(ctx context.Context) error
}
type TickerImpl struct {
tq taskqueue.TaskQueue
l *zerolog.Logger
repo repository.Repository
s gocron.Scheduler
crons sync.Map
scheduledWorkflows sync.Map
jobRuns sync.Map
stepRuns sync.Map
getGroupKeyRuns sync.Map
dv datautils.DataDecoderValidator
tickerId string
}
type timeoutCtx struct {
ctx context.Context
cancel context.CancelFunc
}
type TickerOpt func(*TickerOpts)
type TickerOpts struct {
tq taskqueue.TaskQueue
l *zerolog.Logger
repo repository.Repository
tickerId string
dv datautils.DataDecoderValidator
}
func defaultTickerOpts() *TickerOpts {
logger := logger.NewDefaultLogger("ticker")
return &TickerOpts{
l: &logger,
tickerId: uuid.New().String(),
dv: datautils.NewDataDecoderValidator(),
}
}
func WithTaskQueue(tq taskqueue.TaskQueue) TickerOpt {
return func(opts *TickerOpts) {
opts.tq = tq
}
}
func WithRepository(r repository.Repository) TickerOpt {
return func(opts *TickerOpts) {
opts.repo = r
}
}
func WithLogger(l *zerolog.Logger) TickerOpt {
return func(opts *TickerOpts) {
opts.l = l
}
}
func New(fs ...TickerOpt) (*TickerImpl, error) {
opts := defaultTickerOpts()
for _, f := range fs {
f(opts)
}
if opts.tq == nil {
return nil, fmt.Errorf("task queue is required. use WithTaskQueue")
}
if opts.repo == nil {
return nil, fmt.Errorf("repository is required. use WithRepository")
}
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{
tq: opts.tq,
l: opts.l,
repo: opts.repo,
s: s,
dv: opts.dv,
tickerId: opts.tickerId,
}, nil
}
func (t *TickerImpl) Start(ctx context.Context) error {
t.l.Debug().Msgf("starting ticker %s", t.tickerId)
// register the ticker
ticker, err := t.repo.Ticker().CreateNewTicker(&repository.CreateTickerOpts{
ID: t.tickerId,
})
if err != nil {
return err
}
// subscribe to a task queue with the dispatcher id
taskChan, err := t.tq.Subscribe(ctx, taskqueue.QueueTypeFromTickerID(ticker.ID))
if err != nil {
return err
}
_, err = t.s.NewJob(
gocron.DurationJob(time.Second*5),
gocron.NewTask(
t.runStepRunRequeue(ctx),
),
)
if err != nil {
return fmt.Errorf("could not schedule step run requeue: %w", err)
}
_, err = t.s.NewJob(
gocron.DurationJob(time.Second*5),
gocron.NewTask(
t.runGetGroupKeyRunRequeue(ctx),
),
)
if err != nil {
return fmt.Errorf("could not schedule get group key run requeue: %w", err)
}
_, err = t.s.NewJob(
gocron.DurationJob(time.Second*5),
gocron.NewTask(
t.runUpdateHeartbeat(ctx),
),
)
t.s.Start()
for {
select {
case <-ctx.Done():
t.l.Debug().Msg("removing ticker")
// delete the ticker
err = t.repo.Ticker().Delete(t.tickerId)
if err != nil {
t.l.Err(err).Msg("could not delete ticker")
return err
}
// add the task after the ticker is deleted
err := t.tq.AddTask(
ctx,
taskqueue.JOB_PROCESSING_QUEUE,
tickerRemoved(t.tickerId),
)
if err != nil {
t.l.Err(err).Msg("could not add ticker removed task")
return err
}
// return err
return nil
case task := <-taskChan:
go func(task *taskqueue.Task) {
err = t.handleTask(ctx, task)
if err != nil {
t.l.Error().Err(err).Msgf("could not handle ticker task %s", task.ID)
}
}(task)
}
}
}
func (t *TickerImpl) handleTask(ctx context.Context, task *taskqueue.Task) error {
switch task.ID {
case "schedule-step-run-timeout":
return t.handleScheduleStepRunTimeout(ctx, task)
case "cancel-step-run-timeout":
return t.handleCancelStepRunTimeout(ctx, task)
case "schedule-get-group-key-run-timeout":
return t.handleScheduleGetGroupKeyRunTimeout(ctx, task)
case "cancel-get-group-key-run-timeout":
return t.handleCancelGetGroupKeyRunTimeout(ctx, task)
case "schedule-job-run-timeout":
return t.handleScheduleJobRunTimeout(ctx, task)
case "cancel-job-run-timeout":
return t.handleCancelJobRunTimeout(ctx, task)
// case "schedule-step-requeue":
// return t.handleScheduleStepRunRequeue(ctx, task)
// case "cancel-step-requeue":
// return t.handleCancelStepRunRequeue(ctx, task)
case "schedule-cron":
return t.handleScheduleCron(ctx, task)
case "cancel-cron":
return t.handleCancelCron(ctx, task)
case "schedule-workflow":
return t.handleScheduleWorkflow(ctx, task)
case "cancel-workflow":
return t.handleCancelWorkflow(ctx, task)
}
return fmt.Errorf("unknown task: %s", task.ID)
}
func (t *TickerImpl) runStepRunRequeue(ctx context.Context) func() {
return func() {
t.l.Debug().Msgf("ticker: checking step run requeue")
// list all tenants
tenants, err := t.repo.Tenant().ListTenants()
if err != nil {
t.l.Err(err).Msg("could not list tenants")
return
}
for i := range tenants {
t.l.Debug().Msgf("adding step run requeue task for tenant %s", tenants[i].ID)
err := t.tq.AddTask(
ctx,
taskqueue.JOB_PROCESSING_QUEUE,
tasktypes.TenantToStepRunRequeueTask(tenants[i]),
)
if err != nil {
t.l.Err(err).Msg("could not add step run requeue task")
}
}
}
}
func (t *TickerImpl) runGetGroupKeyRunRequeue(ctx context.Context) func() {
return func() {
t.l.Debug().Msgf("ticker: checking get group key run requeue")
// list all tenants
tenants, err := t.repo.Tenant().ListTenants()
if err != nil {
t.l.Err(err).Msg("could not list tenants")
return
}
for i := range tenants {
t.l.Debug().Msgf("adding get group key run requeue task for tenant %s", tenants[i].ID)
err := t.tq.AddTask(
ctx,
taskqueue.WORKFLOW_PROCESSING_QUEUE,
tasktypes.TenantToGroupKeyActionRequeueTask(tenants[i]),
)
if err != nil {
t.l.Err(err).Msg("could not add get group key run requeue task")
}
}
}
}
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(t.tickerId, &repository.UpdateTickerOpts{
LastHeartbeatAt: &now,
})
if err != nil {
t.l.Err(err).Msg("could not update heartbeat")
}
}
}
func tickerRemoved(tickerId string) *taskqueue.Task {
payload, _ := datautils.ToJSONMap(tasktypes.RemoveTickerTaskPayload{
TickerId: tickerId,
})
metadata, _ := datautils.ToJSONMap(tasktypes.RemoveTickerTaskMetadata{})
return &taskqueue.Task{
ID: "ticker-removed",
Payload: payload,
Metadata: metadata,
}
}