-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.go
More file actions
383 lines (341 loc) · 7.33 KB
/
queue.go
File metadata and controls
383 lines (341 loc) · 7.33 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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package chanprobe
import (
"context"
"sync"
"time"
"github.com/devflex-pro/chanprobe/internal/ring"
)
var clockStart = time.Now()
// Queue is a bounded FIFO queue with observable state and counters.
type Queue[T any] struct {
name string
opts Options
mu sync.Mutex
notEmpty *sync.Cond
notFull *sync.Cond
notEmptyCh chan struct{}
notFullCh chan struct{}
recvCondWaiters int
sendCondWaiters int
closed bool
ring *ring.Ring[T]
sentTotal uint64
receivedTotal uint64
droppedTotal uint64
sendBlockedTotal uint64
recvBlockedTotal uint64
sendWaitTotal time.Duration
recvWaitTotal time.Duration
itemWaitTotal time.Duration
}
// New creates a named bounded queue with positive capacity.
// It panics for an empty name or non-positive capacity.
func New[T any](name string, capacity int, opts ...Option) *Queue[T] {
if name == "" {
panic("chanprobe: name must be non-empty")
}
if capacity <= 0 {
panic("chanprobe: capacity must be positive")
}
options := defaultOptions()
for _, opt := range opts {
opt(&options)
}
q := &Queue[T]{
name: name,
opts: options,
ring: ring.New[T](capacity),
}
q.notEmpty = sync.NewCond(&q.mu)
q.notFull = sync.NewCond(&q.mu)
if options.Registry != nil {
options.Registry.Register(name, q)
}
return q
}
// Name returns the queue name.
func (q *Queue[T]) Name() string {
return q.name
}
// Send inserts an item, waiting when needed under the Block drop policy.
// It returns ErrClosed after Close and returns ctx.Err() if the context is
// canceled while waiting.
func (q *Queue[T]) Send(ctx context.Context, item T) error {
if ctx == nil {
ctx = context.Background()
}
var waitStart time.Time
blocked := false
q.mu.Lock()
for {
if q.closed {
if blocked {
q.sendWaitTotal += time.Since(waitStart)
}
q.mu.Unlock()
return ErrClosed
}
if q.ring.Len() < q.ring.Cap() {
now := monotonicNow()
q.ring.Push(item, now)
q.sentTotal++
if blocked {
q.sendWaitTotal += time.Since(waitStart)
}
q.signalNotEmptyLocked()
q.mu.Unlock()
return nil
}
switch q.opts.DropPolicy {
case DropNewest:
q.droppedTotal++
q.mu.Unlock()
return ErrFull
case DropOldest:
now := monotonicNow()
q.ring.DropOldestAndPush(item, now)
q.sentTotal++
q.droppedTotal++
q.signalNotEmptyLocked()
q.mu.Unlock()
return nil
case Block:
if err := ctx.Err(); err != nil {
q.mu.Unlock()
return err
}
if !blocked {
blocked = true
waitStart = time.Now()
q.sendBlockedTotal++
}
if ctx.Done() == nil {
q.sendCondWaiters++
q.notFull.Wait()
q.sendCondWaiters--
continue
}
ch := q.notFullChanLocked()
q.mu.Unlock()
select {
case <-ctx.Done():
q.mu.Lock()
q.sendWaitTotal += time.Since(waitStart)
q.mu.Unlock()
return ctx.Err()
case <-ch:
q.mu.Lock()
}
default:
q.mu.Unlock()
return ErrFull
}
}
}
// Recv removes and returns the oldest item. It returns ok=false when the queue
// is closed and drained or when ctx is canceled while waiting.
func (q *Queue[T]) Recv(ctx context.Context) (T, bool) {
if ctx == nil {
ctx = context.Background()
}
var waitStart time.Time
blocked := false
q.mu.Lock()
for {
entry, ok := q.ring.Pop()
if ok {
now := monotonicNow()
q.receivedTotal++
q.itemWaitTotal += time.Duration(now - entry.Enqueued)
if blocked {
q.recvWaitTotal += time.Since(waitStart)
}
q.signalNotFullLocked()
q.mu.Unlock()
return entry.Value, true
}
var zero T
if q.closed {
if blocked {
q.recvWaitTotal += time.Since(waitStart)
}
q.mu.Unlock()
return zero, false
}
if err := ctx.Err(); err != nil {
q.mu.Unlock()
return zero, false
}
if !blocked {
blocked = true
waitStart = time.Now()
q.recvBlockedTotal++
}
if ctx.Done() == nil {
q.recvCondWaiters++
q.notEmpty.Wait()
q.recvCondWaiters--
continue
}
ch := q.notEmptyChanLocked()
q.mu.Unlock()
select {
case <-ctx.Done():
q.mu.Lock()
q.recvWaitTotal += time.Since(waitStart)
q.mu.Unlock()
return zero, false
case <-ch:
q.mu.Lock()
}
}
}
// TrySend attempts to insert an item without blocking.
func (q *Queue[T]) TrySend(item T) bool {
q.mu.Lock()
if q.closed {
q.mu.Unlock()
return false
}
if q.ring.Len() < q.ring.Cap() {
now := monotonicNow()
q.ring.Push(item, now)
q.sentTotal++
q.signalNotEmptyLocked()
q.mu.Unlock()
return true
}
switch q.opts.DropPolicy {
case DropOldest:
now := monotonicNow()
q.ring.DropOldestAndPush(item, now)
q.sentTotal++
q.droppedTotal++
q.signalNotEmptyLocked()
q.mu.Unlock()
return true
case DropNewest:
q.droppedTotal++
q.mu.Unlock()
return false
case Block:
q.mu.Unlock()
return false
default:
q.mu.Unlock()
return false
}
}
// TryRecv attempts to remove the oldest item without blocking.
func (q *Queue[T]) TryRecv() (T, bool) {
q.mu.Lock()
entry, ok := q.ring.Pop()
if !ok {
var zero T
q.mu.Unlock()
return zero, false
}
q.receivedTotal++
q.itemWaitTotal += time.Duration(monotonicNow() - entry.Enqueued)
q.signalNotFullLocked()
q.mu.Unlock()
return entry.Value, true
}
// Close marks the queue closed and wakes blocked senders and receivers.
// Already queued items remain receivable.
func (q *Queue[T]) Close() {
q.mu.Lock()
if q.closed {
q.mu.Unlock()
return
}
q.closed = true
q.closeNotifiersLocked()
q.mu.Unlock()
}
// Len returns the current queue length.
func (q *Queue[T]) Len() int {
q.mu.Lock()
n := q.ring.Len()
q.mu.Unlock()
return n
}
func (q *Queue[T]) notEmptyChanLocked() chan struct{} {
if q.notEmptyCh == nil {
q.notEmptyCh = make(chan struct{})
}
return q.notEmptyCh
}
func (q *Queue[T]) notFullChanLocked() chan struct{} {
if q.notFullCh == nil {
q.notFullCh = make(chan struct{})
}
return q.notFullCh
}
func (q *Queue[T]) signalNotEmptyLocked() {
if q.recvCondWaiters > 0 {
q.notEmpty.Signal()
}
if q.notEmptyCh == nil {
return
}
close(q.notEmptyCh)
q.notEmptyCh = make(chan struct{})
}
func (q *Queue[T]) signalNotFullLocked() {
if q.sendCondWaiters > 0 {
q.notFull.Signal()
}
if q.notFullCh == nil {
return
}
close(q.notFullCh)
q.notFullCh = make(chan struct{})
}
func (q *Queue[T]) closeNotifiersLocked() {
if q.notEmptyCh != nil {
close(q.notEmptyCh)
q.notEmptyCh = nil
}
if q.notFullCh != nil {
close(q.notFullCh)
q.notFullCh = nil
}
if q.recvCondWaiters > 0 {
q.notEmpty.Broadcast()
}
if q.sendCondWaiters > 0 {
q.notFull.Broadcast()
}
}
// Cap returns the queue capacity.
func (q *Queue[T]) Cap() int {
q.mu.Lock()
n := q.ring.Cap()
q.mu.Unlock()
return n
}
// Snapshot returns a point-in-time copy of queue state and counters.
func (q *Queue[T]) Snapshot() Snapshot {
q.mu.Lock()
snap := Snapshot{
Name: q.name,
Len: q.ring.Len(),
Cap: q.ring.Cap(),
Closed: q.closed,
SentTotal: q.sentTotal,
ReceivedTotal: q.receivedTotal,
DroppedTotal: q.droppedTotal,
SendBlockedTotal: q.sendBlockedTotal,
RecvBlockedTotal: q.recvBlockedTotal,
SendWaitTotal: q.sendWaitTotal,
RecvWaitTotal: q.recvWaitTotal,
ItemWaitTotal: q.itemWaitTotal,
OldestItemAge: q.ring.OldestAge(monotonicNow()),
}
q.mu.Unlock()
return snap
}
func monotonicNow() int64 {
return int64(time.Since(clockStart))
}