-
Notifications
You must be signed in to change notification settings - Fork 145
/
worker.go
592 lines (444 loc) · 13.6 KB
/
worker.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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
package worker
import (
"context"
"encoding/json"
"fmt"
"os"
"reflect"
"sync"
"time"
"github.com/rs/zerolog"
"github.com/hatchet-dev/hatchet/internal/logger"
"github.com/hatchet-dev/hatchet/pkg/client"
"github.com/hatchet-dev/hatchet/pkg/client/types"
"github.com/hatchet-dev/hatchet/pkg/errors"
"github.com/hatchet-dev/hatchet/pkg/integrations"
)
type actionFunc func(args ...any) []any
// Action is an individual action that can be run by the worker.
type Action interface {
// Name returns the name of the action
Name() string
// Run runs the action
Run(args ...any) []any
MethodFn() any
ConcurrencyFn() GetWorkflowConcurrencyGroupFn
// Service returns the service that the action belongs to
Service() string
}
type actionImpl struct {
name string
run actionFunc
runConcurrencyAction GetWorkflowConcurrencyGroupFn
method any
service string
}
func (j *actionImpl) Name() string {
return j.name
}
func (j *actionImpl) Run(args ...interface{}) []interface{} {
return j.run(args...)
}
func (j *actionImpl) MethodFn() any {
return j.method
}
func (j *actionImpl) ConcurrencyFn() GetWorkflowConcurrencyGroupFn {
return j.runConcurrencyAction
}
func (j *actionImpl) Service() string {
return j.service
}
type Worker struct {
client client.Client
name string
actions map[string]Action
l *zerolog.Logger
cancelMap sync.Map
cancelConcurrencyMap sync.Map
services sync.Map
alerter errors.Alerter
middlewares *middlewares
maxRuns *int
}
type WorkerOpt func(*WorkerOpts)
type WorkerOpts struct {
client client.Client
name string
l *zerolog.Logger
integrations []integrations.Integration
alerter errors.Alerter
maxRuns *int
}
func defaultWorkerOpts() *WorkerOpts {
logger := logger.NewDefaultLogger("worker")
return &WorkerOpts{
name: getHostName(),
l: &logger,
integrations: []integrations.Integration{},
alerter: errors.NoOpAlerter{},
}
}
func WithName(name string) WorkerOpt {
return func(opts *WorkerOpts) {
opts.name = name
}
}
func WithClient(client client.Client) WorkerOpt {
return func(opts *WorkerOpts) {
opts.client = client
}
}
func WithIntegration(integration integrations.Integration) WorkerOpt {
return func(opts *WorkerOpts) {
opts.integrations = append(opts.integrations, integration)
}
}
func WithErrorAlerter(alerter errors.Alerter) WorkerOpt {
return func(opts *WorkerOpts) {
opts.alerter = alerter
}
}
func WithMaxRuns(maxRuns int) WorkerOpt {
return func(opts *WorkerOpts) {
opts.maxRuns = &maxRuns
}
}
// NewWorker creates a new worker instance
func NewWorker(fs ...WorkerOpt) (*Worker, error) {
opts := defaultWorkerOpts()
for _, f := range fs {
f(opts)
}
mws := newMiddlewares()
mws.add(panicMiddleware)
w := &Worker{
client: opts.client,
name: opts.name,
l: opts.l,
actions: map[string]Action{},
alerter: opts.alerter,
middlewares: mws,
maxRuns: opts.maxRuns,
}
// register all integrations
for _, integration := range opts.integrations {
actions := integration.Actions()
integrationId := integration.GetId()
for _, integrationAction := range actions {
action := fmt.Sprintf("%s:%s", integrationId, integrationAction)
err := w.registerAction(integrationId, action, integration.ActionHandler(integrationAction))
if err != nil {
return nil, fmt.Errorf("could not register integration action %s: %w", action, err)
}
}
}
w.NewService("default")
return w, nil
}
func (w *Worker) Use(mws ...MiddlewareFunc) {
w.middlewares.add(mws...)
}
func (w *Worker) NewService(name string) *Service {
svc := &Service{
Name: name,
worker: w,
mws: newMiddlewares(),
}
w.services.Store(name, svc)
return svc
}
func (w *Worker) On(t triggerConverter, workflow workflowConverter) error {
// get the default service
svc, ok := w.services.Load("default")
if !ok {
return fmt.Errorf("could not load default service")
}
return svc.(*Service).On(t, workflow)
}
// RegisterAction can be used to register a single action which can be reused across multiple workflows.
//
// An action should be of the format <service>:<verb>, for example slack:create-channel.
//
// The method must match the following signatures:
// - func(ctx context.Context) error
// - func(ctx context.Context, input *Input) error
// - func(ctx context.Context, input *Input) (*Output, error)
// - func(ctx context.Context) (*Output, error)
func (w *Worker) RegisterAction(actionId string, method any) error {
// parse the action
action, err := types.ParseActionID(actionId)
if err != nil {
return fmt.Errorf("could not parse action id: %w", err)
}
return w.registerAction(action.Service, action.Verb, method)
}
func (w *Worker) registerAction(service, verb string, method any) error {
actionId := fmt.Sprintf("%s:%s", service, verb)
// if the service is "concurrency", then this is a special action
if service == "concurrency" {
w.actions[actionId] = &actionImpl{
name: actionId,
runConcurrencyAction: method.(GetWorkflowConcurrencyGroupFn),
method: method,
service: service,
}
return nil
}
actionFunc, err := getFnFromMethod(method)
if err != nil {
return fmt.Errorf("could not get function from method: %w", err)
}
// if action has already been registered, ensure that the method is the same
if currMethod, ok := w.actions[actionId]; ok {
if reflect.ValueOf(currMethod.MethodFn()).Pointer() != reflect.ValueOf(method).Pointer() {
return fmt.Errorf("action %s is already registered with function %s", actionId, getFnName(currMethod.MethodFn()))
}
}
w.actions[actionId] = &actionImpl{
name: actionId,
run: actionFunc,
method: method,
service: service,
}
return nil
}
// Start starts the worker in blocking fashion
func (w *Worker) Start(ctx context.Context) error {
actionNames := []string{}
for _, action := range w.actions {
actionNames = append(actionNames, action.Name())
}
listener, err := w.client.Dispatcher().GetActionListener(ctx, &client.GetActionListenerRequest{
WorkerName: w.name,
Actions: actionNames,
MaxRuns: w.maxRuns,
})
if err != nil {
return fmt.Errorf("could not get action listener: %w", err)
}
errCh := make(chan error)
actionCh, err := listener.Actions(ctx, errCh)
if err != nil {
return fmt.Errorf("could not get action channel: %w", err)
}
RunWorker:
for {
select {
case err := <-errCh:
w.l.Err(err).Msg("action listener error")
break RunWorker
case action := <-actionCh:
go func(action *client.Action) {
err := w.executeAction(context.Background(), action)
if err != nil {
w.l.Error().Err(err).Msgf("could not execute action: %s", action.ActionId)
}
w.l.Debug().Msgf("action %s completed", action.ActionId)
}(action)
case <-ctx.Done():
w.l.Debug().Msgf("worker %s received context done, stopping", w.name)
break RunWorker
}
}
w.l.Debug().Msgf("worker %s stopped", w.name)
err = listener.Unregister()
if err != nil {
return fmt.Errorf("could not unregister worker: %w", err)
}
return nil
}
func (w *Worker) executeAction(ctx context.Context, assignedAction *client.Action) error {
switch assignedAction.ActionType {
case client.ActionTypeStartStepRun:
return w.startStepRun(ctx, assignedAction)
case client.ActionTypeCancelStepRun:
return w.cancelStepRun(ctx, assignedAction)
case client.ActionTypeStartGetGroupKey:
return w.startGetGroupKey(ctx, assignedAction)
default:
return fmt.Errorf("unknown action type: %s", assignedAction.ActionType)
}
}
func (w *Worker) startStepRun(ctx context.Context, assignedAction *client.Action) error {
// send a message that the step run started
_, err := w.client.Dispatcher().SendStepActionEvent(
ctx,
w.getActionEvent(assignedAction, client.ActionEventTypeStarted),
)
if err != nil {
return fmt.Errorf("could not send action event: %w", err)
}
action, ok := w.actions[assignedAction.ActionId]
if !ok {
return fmt.Errorf("job not found")
}
arg, err := decodeArgsToInterface(reflect.TypeOf(action.MethodFn()))
if err != nil {
return fmt.Errorf("could not decode args to interface: %w", err)
}
runContext, cancel := context.WithCancel(context.Background())
w.cancelMap.Store(assignedAction.StepRunId, cancel)
hCtx, err := newHatchetContext(runContext, assignedAction)
if err != nil {
return fmt.Errorf("could not create hatchet context: %w", err)
}
// get the action's service
svcAny, ok := w.services.Load(action.Service())
if !ok {
return fmt.Errorf("could not load service %s", action.Service())
}
svc := svcAny.(*Service)
// wrap the run with middleware. start by wrapping the global worker middleware, then
// the service-specific middleware
return w.middlewares.runAll(hCtx, func(ctx HatchetContext) error {
return svc.mws.runAll(ctx, func(ctx HatchetContext) error {
args := []any{ctx}
if arg != nil {
args = append(args, arg)
}
runResults := action.Run(args...)
// check whether run context was cancelled while action was running
select {
case <-ctx.Done():
w.l.Debug().Msgf("step run %s was cancelled, returning", assignedAction.StepRunId)
return nil
default:
}
var result any
if len(runResults) == 2 {
result = runResults[0]
}
if runResults[len(runResults)-1] != nil {
err = runResults[len(runResults)-1].(error)
}
if err != nil {
failureEvent := w.getActionEvent(assignedAction, client.ActionEventTypeFailed)
w.alerter.SendAlert(context.Background(), err, map[string]interface{}{
"actionId": assignedAction.ActionId,
"workerId": assignedAction.WorkerId,
"stepRunId": assignedAction.StepRunId,
"jobName": assignedAction.JobName,
"actionType": assignedAction.ActionType,
})
failureEvent.EventPayload = err.Error()
_, err := w.client.Dispatcher().SendStepActionEvent(
ctx,
failureEvent,
)
if err != nil {
return fmt.Errorf("could not send action event: %w", err)
}
return err
}
// send a message that the step run completed
finishedEvent, err := w.getActionFinishedEvent(assignedAction, result)
if err != nil {
return fmt.Errorf("could not create finished event: %w", err)
}
_, err = w.client.Dispatcher().SendStepActionEvent(
ctx,
finishedEvent,
)
if err != nil {
return fmt.Errorf("could not send action event: %w", err)
}
return nil
})
})
}
func (w *Worker) startGetGroupKey(ctx context.Context, assignedAction *client.Action) error {
// send a message that the step run started
_, err := w.client.Dispatcher().SendGroupKeyActionEvent(
ctx,
w.getActionEvent(assignedAction, client.ActionEventTypeStarted),
)
if err != nil {
return fmt.Errorf("could not send action event: %w", err)
}
action, ok := w.actions[assignedAction.ActionId]
if !ok {
return fmt.Errorf("job not found")
}
// action should be concurrency action
if action.ConcurrencyFn() == nil {
return fmt.Errorf("action %s is not a concurrency action", action.Name())
}
runContext, cancel := context.WithCancel(context.Background())
w.cancelConcurrencyMap.Store(assignedAction.WorkflowRunId, cancel)
hCtx, err := newHatchetContext(runContext, assignedAction)
if err != nil {
return fmt.Errorf("could not create hatchet context: %w", err)
}
concurrencyKey, err := action.ConcurrencyFn()(hCtx)
if err != nil {
failureEvent := w.getActionEvent(assignedAction, client.ActionEventTypeFailed)
w.alerter.SendAlert(context.Background(), err, map[string]interface{}{
"actionId": assignedAction.ActionId,
"workerId": assignedAction.WorkerId,
"workflowRunId": assignedAction.WorkflowRunId,
"jobName": assignedAction.JobName,
"actionType": assignedAction.ActionType,
})
failureEvent.EventPayload = err.Error()
_, err := w.client.Dispatcher().SendGroupKeyActionEvent(
ctx,
failureEvent,
)
if err != nil {
return fmt.Errorf("could not send action event: %w", err)
}
return err
}
// send a message that the step run completed
finishedEvent, err := w.getGroupKeyActionFinishedEvent(assignedAction, concurrencyKey)
if err != nil {
return fmt.Errorf("could not create finished event: %w", err)
}
_, err = w.client.Dispatcher().SendGroupKeyActionEvent(
ctx,
finishedEvent,
)
if err != nil {
return fmt.Errorf("could not send action event: %w", err)
}
return nil
}
func (w *Worker) cancelStepRun(ctx context.Context, assignedAction *client.Action) error {
cancel, ok := w.cancelMap.Load(assignedAction.StepRunId)
if !ok {
return fmt.Errorf("could not find step run to cancel")
}
w.l.Debug().Msgf("cancelling step run %s", assignedAction.StepRunId)
cancelFn := cancel.(context.CancelFunc)
cancelFn()
return nil
}
func (w *Worker) getActionEvent(action *client.Action, eventType client.ActionEventType) *client.ActionEvent {
timestamp := time.Now().UTC()
return &client.ActionEvent{
Action: action,
EventTimestamp: ×tamp,
EventType: eventType,
}
}
func (w *Worker) getActionFinishedEvent(action *client.Action, output any) (*client.ActionEvent, error) {
event := w.getActionEvent(action, client.ActionEventTypeCompleted)
outputBytes, err := json.Marshal(output)
if err != nil {
return nil, fmt.Errorf("could not marshal step output: %w", err)
}
event.EventPayload = string(outputBytes)
return event, nil
}
func (w *Worker) getGroupKeyActionFinishedEvent(action *client.Action, output string) (*client.ActionEvent, error) {
event := w.getActionEvent(action, client.ActionEventTypeCompleted)
event.EventPayload = output
return event, nil
}
func getHostName() string {
hostName, err := os.Hostname()
if err != nil {
hostName = "Unknown"
}
return hostName
}