-
Notifications
You must be signed in to change notification settings - Fork 126
/
heartbeater.go
107 lines (84 loc) · 2.14 KB
/
heartbeater.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
package heartbeat
import (
"context"
"fmt"
"time"
"github.com/go-co-op/gocron/v2"
"github.com/rs/zerolog"
"github.com/hatchet-dev/hatchet/internal/logger"
"github.com/hatchet-dev/hatchet/internal/msgqueue"
"github.com/hatchet-dev/hatchet/internal/repository"
)
type Heartbeater interface {
Start(ctx context.Context) error
}
type HeartbeaterImpl struct {
mq msgqueue.MessageQueue
l *zerolog.Logger
repo repository.EngineRepository
s gocron.Scheduler
}
type HeartbeaterOpt func(*HeartbeaterOpts)
type HeartbeaterOpts struct {
mq msgqueue.MessageQueue
l *zerolog.Logger
repo repository.EngineRepository
}
func defaultHeartbeaterOpts() *HeartbeaterOpts {
logger := logger.NewDefaultLogger("heartbeater")
return &HeartbeaterOpts{
l: &logger,
}
}
func WithMessageQueue(mq msgqueue.MessageQueue) HeartbeaterOpt {
return func(opts *HeartbeaterOpts) {
opts.mq = mq
}
}
func WithRepository(r repository.EngineRepository) HeartbeaterOpt {
return func(opts *HeartbeaterOpts) {
opts.repo = r
}
}
func WithLogger(l *zerolog.Logger) HeartbeaterOpt {
return func(opts *HeartbeaterOpts) {
opts.l = l
}
}
func New(fs ...HeartbeaterOpt) (*HeartbeaterImpl, error) {
opts := defaultHeartbeaterOpts()
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")
}
newLogger := opts.l.With().Str("service", "heartbeater").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 &HeartbeaterImpl{
mq: opts.mq,
l: opts.l,
repo: opts.repo,
s: s,
}, nil
}
func (t *HeartbeaterImpl) Start() (func() error, error) {
t.l.Debug().Msg("starting heartbeater")
t.s.Start()
cleanup := func() error {
t.l.Debug().Msg("stopping heartbeater")
if err := t.s.Shutdown(); err != nil {
return fmt.Errorf("could not shutdown scheduler: %w", err)
}
t.l.Debug().Msg("heartbeater has shutdown")
return nil
}
return cleanup, nil
}