This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
/
queue.go
285 lines (231 loc) · 6.53 KB
/
queue.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
package workqueue
import (
"context"
"fmt"
"sync"
"github.com/lyft/flytestdlib/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/lyft/flytestdlib/contextutils"
"github.com/lyft/flytestdlib/logger"
"github.com/lyft/flytestdlib/promutils"
lru "github.com/hashicorp/golang-lru"
"k8s.io/client-go/util/workqueue"
)
//go:generate mockery -all -case=underscore
//go:generate enumer --type=WorkStatus
type WorkItemID = string
type WorkStatus uint8
const (
WorkStatusNotDone WorkStatus = iota
WorkStatusSucceeded
WorkStatusFailed
)
const (
ErrNotYetStarted errors.ErrorCode = "NOT_STARTED"
)
func (w WorkStatus) IsTerminal() bool {
return w == WorkStatusFailed || w == WorkStatusSucceeded
}
// WorkItem is a generic item that can be stored in the work queue.
type WorkItem interface{}
// Represents the result of the work item processing.
type WorkItemInfo interface {
Item() WorkItem
ID() WorkItemID
Status() WorkStatus
Error() error
}
// Represents the indexed queue semantics. An indexed work queue is a work queue that additionally keeps track of the
// final processing results of work items.
type IndexedWorkQueue interface {
// Queues the item to be processed. If the item is already in the cache or has been processed before (and is still
// in-memory), it'll not be added again.
Queue(ctx context.Context, id WorkItemID, once WorkItem) error
// Retrieves an item by id.
Get(id WorkItemID) (info WorkItemInfo, found bool, err error)
// Start must be called before queuing items into the queue.
Start(ctx context.Context) error
}
// Represents the processor logic to operate on work items.
type Processor interface {
Process(ctx context.Context, workItem WorkItem) (WorkStatus, error)
}
type workItemWrapper struct {
id WorkItemID
logFields map[string]interface{}
payload WorkItem
status WorkStatus
retryCount uint
err error
}
func (w workItemWrapper) Item() WorkItem {
return w.payload
}
func (w workItemWrapper) ID() WorkItemID {
return w.id
}
func (w workItemWrapper) Status() WorkStatus {
return w.status
}
func (w workItemWrapper) Error() error {
return w.err
}
func (w workItemWrapper) Clone() workItemWrapper {
return w
}
type metrics struct {
CacheHit prometheus.Counter
CacheMiss prometheus.Counter
ProcessorErrors prometheus.Counter
Scope promutils.Scope
}
type queue struct {
name string
metrics metrics
wlock sync.Mutex
rlock sync.RWMutex
workers int
maxRetries int
started bool
queue workqueue.Interface
index workItemCache
processor Processor
}
type workItemCache struct {
*lru.Cache
}
func (c workItemCache) Get(id WorkItemID) (item *workItemWrapper, found bool) {
o, found := c.Cache.Get(id)
if !found {
return nil, found
}
return o.(*workItemWrapper), true
}
func (c workItemCache) Add(item *workItemWrapper) (evicted bool) {
return c.Cache.Add(item.id, item)
}
func copyAllowedLogFields(ctx context.Context) map[string]interface{} {
logFields := contextutils.GetLogFields(ctx)
delete(logFields, contextutils.RoutineLabelKey.String())
return logFields
}
func (q *queue) Queue(ctx context.Context, id WorkItemID, once WorkItem) error {
q.wlock.Lock()
defer q.wlock.Unlock()
if !q.started {
return errors.Errorf(ErrNotYetStarted, "Queue must be started before enqueuing any item.")
}
if _, found := q.index.Get(id); found {
return nil
}
wrapper := &workItemWrapper{
id: id,
logFields: copyAllowedLogFields(ctx),
payload: once,
}
q.index.Add(wrapper)
q.queue.Add(wrapper)
return nil
}
func (q *queue) Get(id WorkItemID) (info WorkItemInfo, found bool, err error) {
q.rlock.Lock()
defer q.rlock.Unlock()
wrapper, found := q.index.Get(id)
if !found {
q.metrics.CacheMiss.Inc()
return nil, found, nil
}
v := wrapper.Clone()
q.metrics.CacheHit.Inc()
return &v, true, nil
}
func contextWithValues(ctx context.Context, fields map[string]interface{}) context.Context {
for key, value := range fields {
ctx = context.WithValue(ctx, contextutils.Key(key), value)
}
return ctx
}
func (q *queue) Start(ctx context.Context) error {
q.wlock.Lock()
defer q.wlock.Unlock()
if q.started {
return fmt.Errorf("queue already started")
}
for i := 0; i < q.workers; i++ {
go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
logger.Debug(ctx, "Context cancelled. Shutting down.")
return
default:
item, shutdown := q.queue.Get()
if shutdown {
logger.Debug(ctx, "Work queue is shutting down.")
return
}
wrapperV := item.(*workItemWrapper).Clone()
wrapper := &wrapperV
ws := wrapper.status
var err error
func() {
defer func() {
if e, ok := recover().(error); ok {
logger.Errorf(ctx, "Worker panic'd while processing item [%v]. Error: %v", wrapper.id, e)
err = e
}
}()
ctxWithFields := contextWithValues(ctx, wrapper.logFields)
ws, err = q.processor.Process(ctxWithFields, wrapper.payload)
}()
if err != nil {
q.metrics.ProcessorErrors.Inc()
wrapper.retryCount++
wrapper.err = err
if wrapper.retryCount >= uint(q.maxRetries) {
logger.Debugf(ctx, "WorkItem [%v] exhausted all retries. Last Error: %v.",
wrapper.ID(), err)
wrapper.status = WorkStatusFailed
ws = WorkStatusFailed
q.index.Add(wrapper)
continue
}
}
wrapper.status = ws
q.index.Add(wrapper)
if !ws.IsTerminal() {
q.queue.Add(wrapper)
}
}
}
}(contextutils.WithGoroutineLabel(ctx, fmt.Sprintf("%v-worker-%v", q.name, i)))
}
q.started = true
return nil
}
func newMetrics(scope promutils.Scope) metrics {
return metrics{
CacheHit: scope.MustNewCounter("cache_hit", "Counter for cache hits."),
CacheMiss: scope.MustNewCounter("cache_miss", "Counter for cache misses."),
ProcessorErrors: scope.MustNewCounter("proc_errors", "Counter for processor errors."),
Scope: scope,
}
}
// Instantiates a new Indexed Work queue.
func NewIndexedWorkQueue(name string, processor Processor, cfg Config, metricsScope promutils.Scope) (IndexedWorkQueue, error) {
cache, err := lru.New(cfg.IndexCacheMaxItems)
if err != nil {
return nil, err
}
return &queue{
name: name,
metrics: newMetrics(metricsScope),
wlock: sync.Mutex{},
rlock: sync.RWMutex{},
workers: cfg.Workers,
maxRetries: cfg.MaxRetries,
queue: workqueue.NewNamed(metricsScope.CurrentScope()),
index: workItemCache{Cache: cache},
processor: processor,
}, nil
}