This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 576
/
simple.go
207 lines (173 loc) · 4.69 KB
/
simple.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
package worker
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/sirupsen/logrus"
)
var _ Worker = &Simple{}
// NewSimple creates a basic implementation of the Worker interface
// that is backed using just the standard library and goroutines.
func NewSimple() *Simple {
// TODO(sio4): #road-to-v1 - how to check if the worker is ready to work
// when worker should be initialized? how to check if worker is ready?
// and purpose of the context
return NewSimpleWithContext(context.Background())
}
// NewSimpleWithContext creates a basic implementation of the Worker interface
// that is backed using just the standard library and goroutines.
func NewSimpleWithContext(ctx context.Context) *Simple {
ctx, cancel := context.WithCancel(ctx)
l := logrus.New()
l.Level = logrus.InfoLevel
l.Formatter = &logrus.TextFormatter{}
return &Simple{
Logger: l,
ctx: ctx,
cancel: cancel,
handlers: map[string]Handler{},
moot: &sync.Mutex{},
started: false,
}
}
// Simple is a basic implementation of the Worker interface
// that is backed using just the standard library and goroutines.
type Simple struct {
Logger SimpleLogger
ctx context.Context
cancel context.CancelFunc
handlers map[string]Handler
moot *sync.Mutex
wg sync.WaitGroup
started bool
}
// Register Handler with the worker
func (w *Simple) Register(name string, h Handler) error {
if name == "" || h == nil {
return fmt.Errorf("name or handler cannot be empty/nil")
}
w.moot.Lock()
defer w.moot.Unlock()
if _, ok := w.handlers[name]; ok {
return fmt.Errorf("handler already mapped for name %s", name)
}
w.handlers[name] = h
return nil
}
// Start the worker
func (w *Simple) Start(ctx context.Context) error {
// TODO(sio4): #road-to-v1 - define the purpose of Start clearly
w.Logger.Info("starting Simple background worker")
w.moot.Lock()
defer w.moot.Unlock()
w.ctx, w.cancel = context.WithCancel(ctx)
w.started = true
return nil
}
// Stop the worker
func (w *Simple) Stop() error {
// prevent job submission when stopping
w.moot.Lock()
defer w.moot.Unlock()
w.Logger.Info("stopping Simple background worker")
w.cancel()
w.wg.Wait()
w.Logger.Info("all background jobs stopped completely")
return nil
}
// Perform a job as soon as possibly using a goroutine.
func (w *Simple) Perform(job Job) error {
w.moot.Lock()
defer w.moot.Unlock()
if !w.started {
return fmt.Errorf("worker is not yet started")
}
// Perform should not allow a job submission if the worker is not running
if err := w.ctx.Err(); err != nil {
return fmt.Errorf("worker is not ready to perform a job: %v", err)
}
w.Logger.Debugf("performing job %s", job)
if job.Handler == "" {
err := fmt.Errorf("no handler name given: %s", job)
w.Logger.Error(err)
return err
}
if h, ok := w.handlers[job.Handler]; ok {
// TODO(sio4): #road-to-v1 - consider timeout and/or cancellation
w.wg.Add(1)
go func() {
defer w.wg.Done()
err := safeRun(func() error {
return h(job.Args)
})
if err != nil {
w.Logger.Error(err)
}
w.Logger.Debugf("completed job %s", job)
}()
return nil
}
err := fmt.Errorf("no handler mapped for name %s", job.Handler)
w.Logger.Error(err)
return err
}
// safeRun the function safely knowing that if it panics
// the panic will be caught and returned as an error
func safeRun(fn func() error) (err error) {
defer func() {
if ex := recover(); ex != nil {
if e, ok := ex.(error); ok {
err = e
return
}
err = errors.New(fmt.Sprint(ex))
}
}()
return fn()
}
// PerformAt performs a job at a particular time using a goroutine.
func (w *Simple) PerformAt(job Job, t time.Time) error {
return w.PerformIn(job, time.Until(t))
}
// PerformIn performs a job after waiting for a specified amount
// using a goroutine.
func (w *Simple) PerformIn(job Job, d time.Duration) error {
// Perform should not allow a job submission if the worker is not running
if err := w.ctx.Err(); err != nil {
return fmt.Errorf("worker is not ready to perform a job: %v", err)
}
w.wg.Add(1) // waiting job also should be counted
go func() {
defer w.wg.Done()
for {
w.moot.Lock()
if w.started {
w.moot.Unlock()
break
}
w.moot.Unlock()
waiting := 100 * time.Millisecond
time.Sleep(waiting)
d = d - waiting
}
select {
case <-time.After(d):
w.Perform(job)
case <-w.ctx.Done():
// TODO(sio4): #road-to-v1 - it should be guaranteed to be performed
w.cancel()
}
}()
return nil
}
// SimpleLogger is used by the Simple worker to write logs
type SimpleLogger interface {
Debugf(string, ...interface{})
Infof(string, ...interface{})
Errorf(string, ...interface{})
Debug(...interface{})
Info(...interface{})
Error(...interface{})
}