-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathqueue.go
More file actions
87 lines (77 loc) · 1.96 KB
/
queue.go
File metadata and controls
87 lines (77 loc) · 1.96 KB
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
package queue
import (
"github.com/prometheus/client_golang/prometheus"
"github.com/stackrox/rox/pkg/concurrency"
"github.com/stackrox/rox/pkg/queue"
)
// SimpleQueue defines the pkg/queue that holds the items.
type SimpleQueue[T comparable] interface {
Push(T)
PullBlocking(concurrency.Waitable) T
Seq(waitable concurrency.Waitable) func(yield func(T) bool)
Len() int
}
// Queue wraps a SimpleQueue to make it pullable with a channel.
type Queue[T comparable] struct {
queue SimpleQueue[T]
outputC chan T
stopper concurrency.Stopper
isRunning concurrency.Signal
}
// NewQueue creates a new Queue.
func NewQueue[T comparable](stopper concurrency.Stopper, name string, size int, counter *prometheus.CounterVec, dropped prometheus.Counter) *Queue[T] {
var opts []queue.OptionFunc[T]
if size > 0 {
opts = append(opts, queue.WithMaxSize[T](size))
}
if counter != nil {
opts = append(opts, queue.WithCounterVec[T](counter))
}
if dropped != nil {
opts = append(opts, queue.WithDroppedMetric[T](dropped))
}
if name != "" {
opts = append(opts, queue.WithQueueName[T](name))
}
return &Queue[T]{
queue: queue.NewQueue[T](opts...),
outputC: make(chan T),
stopper: stopper,
isRunning: concurrency.NewSignal(),
}
}
// Start the queue.
func (q *Queue[T]) Start() {
go q.run()
}
// Push an item to the queue.
func (q *Queue[T]) Push(item T) {
q.queue.Push(item)
}
func (q *Queue[T]) run() {
defer close(q.outputC)
for {
select {
case <-q.stopper.Flow().StopRequested():
return
case <-q.isRunning.Done():
select {
case <-q.stopper.Flow().StopRequested():
return
case q.outputC <- q.queue.PullBlocking(q.stopper.LowLevel().GetStopRequestSignal()):
}
}
}
}
// Pause the queue.
func (q *Queue[T]) Pause() {
q.isRunning.Reset()
}
// Resume the queue.
func (q *Queue[T]) Resume() {
q.isRunning.Signal()
}
// Pull returns the channel where run writes the front of the queue.
func (q *Queue[T]) Pull() <-chan T {
return q.outputC
}