-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
129 lines (107 loc) · 2.63 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
package workerbase
import (
"context"
"sync"
"time"
"github.com/derision-test/glock"
"github.com/go-nacelle/nacelle/v2"
"github.com/go-nacelle/process/v2"
"github.com/go-nacelle/service/v2"
"github.com/google/uuid"
)
type (
Worker struct {
Config *nacelle.Config `service:"config"`
Services *nacelle.ServiceContainer `service:"services"`
Health *nacelle.Health `service:"health"`
tagModifiers []nacelle.TagModifier
spec WorkerSpec
clock glock.Clock
halt chan struct{}
done chan struct{}
once *sync.Once
tickInterval time.Duration
strictClock bool
healthToken healthToken
healthStatus *process.HealthComponentStatus
}
WorkerSpec interface {
Init(ctx context.Context) error
Tick(ctx context.Context) error
}
workerSpecFinalizer interface {
process.Finalizer
WorkerSpec
}
)
func NewWorker(spec WorkerSpec, configs ...ConfigFunc) *Worker {
return newWorker(spec, glock.NewRealClock(), configs...)
}
func newWorker(spec WorkerSpec, clock glock.Clock, configs ...ConfigFunc) *Worker {
options := getOptions(configs)
return &Worker{
tagModifiers: options.tagModifiers,
spec: spec,
clock: clock,
halt: make(chan struct{}),
done: make(chan struct{}),
once: &sync.Once{},
healthToken: healthToken(uuid.New().String()),
}
}
func (w *Worker) Init(ctx context.Context) error {
healthStatus, err := w.Health.Register(w.healthToken)
if err != nil {
return err
}
w.healthStatus = healthStatus
workerConfig := &Config{}
if err := w.Config.Load(workerConfig, w.tagModifiers...); err != nil {
return err
}
w.strictClock = workerConfig.StrictClock
w.tickInterval = workerConfig.WorkerTickInterval
if err := service.Inject(ctx, w.Services, w.spec); err != nil {
return err
}
return w.spec.Init(ctx)
}
func (w *Worker) Run(ctx context.Context) (err error) {
if finalizer, ok := w.spec.(nacelle.Finalizer); ok {
defer func() {
finalizeErr := finalizer.Finalize(ctx)
if err == nil {
err = finalizeErr
}
}()
}
defer w.Stop(ctx)
w.healthStatus.Update(true)
defer close(w.done)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
<-w.halt
cancel()
}()
for {
started := w.clock.Now()
if err = w.spec.Tick(ctx); err != nil {
return
}
interval := w.tickInterval
if w.strictClock {
interval -= w.clock.Now().Sub(started)
}
select {
case <-w.halt:
return
case <-w.clock.After(interval):
}
}
}
func (w *Worker) Stop(ctx context.Context) error {
w.once.Do(func() { close(w.halt) })
<-w.done
return nil
}