-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathringqueue.go
More file actions
174 lines (156 loc) · 4.94 KB
/
Copy pathringqueue.go
File metadata and controls
174 lines (156 loc) · 4.94 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
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
package carousel
import (
"context"
"errors"
"sync"
)
// ErrFull is returned by [RingQueue.Enqueue] when the queue is at capacity.
var ErrFull = errors.New("carousel: queue is full")
// ErrClosed is returned by [RingQueue.Enqueue], [RingQueue.ForceEnqueue], and
// [RingQueue.Pop] after [RingQueue.Close] has been called.
var ErrClosed = errors.New("carousel: queue is closed")
// RingQueue is a concurrent fixed-capacity FIFO queue backed by [RingBuffer].
//
// The zero value is not usable; create instances with [NewRingQueue].
// Multiple goroutines may call Enqueue and ForceEnqueue concurrently.
// Pop is intended to be called by a single goroutine (consumer).
// Close is idempotent and must be called when the queue is no longer needed.
type RingQueue[T any] struct {
mu sync.Mutex
cond *sync.Cond
buf *RingBuffer[T]
closed bool
}
// NewRingQueue creates a RingQueue with the given capacity.
//
// Panics if capacity < 1.
func NewRingQueue[T any](capacity int) *RingQueue[T] {
q := &RingQueue[T]{
buf: NewRingBuffer[T](capacity),
}
q.cond = sync.NewCond(&q.mu)
return q
}
// Enqueue adds item to the queue.
// Returns [ErrFull] if the queue is at capacity.
// Returns [ErrClosed] if the queue has been closed.
func (q *RingQueue[T]) Enqueue(item T) error {
q.mu.Lock()
defer q.mu.Unlock()
if q.closed {
return ErrClosed
}
if !q.buf.Push(item) {
return ErrFull
}
q.cond.Signal()
return nil
}
// ForceEnqueue adds item to the queue, evicting the oldest item if full.
// Returns true if an item was evicted.
// Returns [ErrClosed] if the queue has been closed.
func (q *RingQueue[T]) ForceEnqueue(item T) (evicted bool, err error) {
q.mu.Lock()
defer q.mu.Unlock()
if q.closed {
return false, ErrClosed
}
evicted = q.buf.ForcePush(item)
q.cond.Signal()
return evicted, nil
}
// Pop blocks until an item is available, the context is canceled, or the
// queue is closed. Available items are always delivered before cancellation
// or close signals are returned. Returns [ErrClosed] when the queue is closed
// and all remaining items have been consumed. Returns ctx.Err() when the
// context is canceled and the buffer is empty.
//
// Concurrent calls to Pop are not supported — use a single consumer goroutine.
// ctx must be non-nil; pass [context.Background] to opt out of cancellation.
func (q *RingQueue[T]) Pop(ctx context.Context) (T, error) {
var stop func() bool
defer func() {
if stop != nil {
stop()
}
}()
q.mu.Lock()
defer q.mu.Unlock()
for {
if item, ok := q.buf.Pop(); ok {
return item, nil
}
if q.closed {
var zero T
return zero, ErrClosed
}
if ctx.Err() != nil {
var zero T
return zero, ctx.Err()
}
// Only arm the cancellation wakeup when Pop must actually sleep.
// This avoids paying the AfterFunc allocation cost on the fast path
// where an item is already available.
if stop == nil && ctx.Done() != nil {
// The callback acquires q.mu before broadcasting to prevent a
// lost-wakeup: if cancellation happens between the ctx.Err() check
// and cond.Wait(), the broadcast fires after Wait() is entered.
stop = context.AfterFunc(ctx, func() {
q.mu.Lock()
defer q.mu.Unlock()
q.cond.Broadcast()
})
}
q.cond.Wait()
}
}
// Drain removes and returns all current items in FIFO order without blocking.
// Returns nil if the queue is empty.
//
// Unlike [RingQueue.Pop], Drain does not wait for new items — it returns
// whatever is in the buffer at the moment of the call. Useful for bulk
// reads or flushing remaining items during shutdown without going through
// the blocking Pop interface.
func (q *RingQueue[T]) Drain() []T {
q.mu.Lock()
defer q.mu.Unlock()
return q.buf.Drain()
}
// Snapshot returns a copy of all current items in FIFO order without removing
// them. Returns nil if the queue is empty.
//
// Acquires the queue lock for the duration of the in-package copy; no
// user-supplied code runs under the lock. Non-destructive: queue state is
// unchanged after the call.
//
// Lock hold time is O(N) where N = [RingQueue.Len] at the moment of the
// call. For very large capacities under contention, prefer a steady-state
// design that does not call Snapshot from a hot path.
func (q *RingQueue[T]) Snapshot() []T {
q.mu.Lock()
defer q.mu.Unlock()
return q.buf.Snapshot()
}
// Len returns the number of items currently in the queue.
func (q *RingQueue[T]) Len() int {
q.mu.Lock()
defer q.mu.Unlock()
return q.buf.Len()
}
// Cap returns the fixed capacity of the queue.
// Capacity is set at construction and never changes; RingQueue does not support resizing.
func (q *RingQueue[T]) Cap() int {
// No lock needed — capacity is immutable after construction.
return q.buf.Cap()
}
// Close marks the queue as closed and wakes any goroutine blocked in Pop.
// Idempotent — safe to call more than once; subsequent calls are no-ops.
func (q *RingQueue[T]) Close() {
q.mu.Lock()
defer q.mu.Unlock()
if q.closed {
return
}
q.closed = true
q.cond.Broadcast()
}