summaryrefslogtreecommitdiffhomepage
path: root/util/latencyqueue/latencyqueue.go
blob: 26d7b4db4ea449d0ce58712b811159087418bfb3 (plain)
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
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause

// Package latencyqueue provides a latency-bounded FIFO queue for asynchronous processing.
package latencyqueue

import (
	"context"
	"errors"
	"fmt"
	"sync"
	"sync/atomic"
	"time"

	"tailscale.com/util/ringbuffer"
)

var (
	// ErrClosed is returned by context.Cause() when Close() has been called.
	ErrClosed = errors.New("queue closed")

	// ErrAborted is returned by context.Cause() when Abort() has been called.
	ErrAborted = errors.New("queue processing aborted")

	// ErrLagged is returned by context.Cause() when the lag threshold was exceeded.
	ErrLagged = errors.New("queue lag threshold exceeded")
)

// ErrPanic wraps a panic value recovered from the processor function.
type ErrPanic struct {
	Panic any
}

func (e *ErrPanic) Error() string {
	return fmt.Sprintf("processor panic: %v", e.Panic)
}

// Queue is a latency-bounded FIFO queue for asynchronous processing.
//
// The queue is unbounded by item count or storage size, but bounded by the age
// of the oldest item. When an item exceeds the configured lag threshold,
// the queue's context is cancelled with ErrLagged.
//
// # Delivery Semantics
//
// During normal operation, each item is delivered exactly once to the processor,
// in the order enqueued. Items are processed one batch at a time, with each batch
// processed on a separate goroutine.
//
// On abnormal termination (lag threshold exceeded, processor panic, abort, or
// explicit close), unprocessed items are lost and any pending barriers are released.
type Queue[T any] struct {
	ctx    context.Context
	cancel context.CancelCauseFunc

	mu      sync.Mutex
	items   *ringbuffer.RingBuffer[queueItem[T]]
	wakeup  chan struct{}
	started bool

	maxLag time.Duration

	numEnqueued  atomic.Uint64
	numProcessed atomic.Uint64

	done chan struct{}
}

type itemKind uint8

const (
	kindBatch itemKind = iota
	kindBarrier
)

type queueItem[T any] struct {
	kind     itemKind
	batch    []T
	enqueued time.Time
	barrier  chan struct{}
}

// QueueCounters contains observability metrics for the queue.
type QueueCounters struct {
	Enqueued  uint64
	Processed uint64
}

// New creates a bounded-latency queue that processes items asynchronously.
// The parent context is used for lifecycle management. If maxLag is > 0,
// items that remain in the queue longer than maxLag will cause the context
// to be cancelled with ErrLagged.
func New[T any](parent context.Context, maxLag time.Duration) *Queue[T] {
	ctx, cancel := context.WithCancelCause(parent)
	q := &Queue[T]{
		ctx:    ctx,
		cancel: cancel,
		items:  ringbuffer.New[queueItem[T]](),
		wakeup: make(chan struct{}, 1),
		maxLag: maxLag,
		done:   make(chan struct{}),
	}
	return q
}

// Start begins processing queued items with the given processor function.
// The processor receives a context (with lag deadline if applicable) and an item.
// The processor is considered infallible; errors should be handled within the processor.
// Must be called before Enqueue. Can only be called once.
func (q *Queue[T]) Start(processor func(context.Context, T)) {
	q.mu.Lock()
	if q.started {
		q.mu.Unlock()
		panic("Start called multiple times")
	}
	q.started = true
	q.mu.Unlock()

	go q.run(processor)
}

// Close stops processing and releases resources.
// Unprocessed items are discarded and barriers are released.
// Blocks until processing stops.
func (q *Queue[T]) Close() {
	q.cancel(ErrClosed)
	<-q.done
}

// Abort stops processing immediately. Unprocessed items are discarded
// and barriers are released. The context will be cancelled with ErrAborted.
// Non-blocking.
func (q *Queue[T]) Abort() {
	q.cancel(ErrAborted)
}

// Enqueue adds a batch of items to the queue.
// Returns false if the queue has terminated (closed, lagged, or aborted).
func (q *Queue[T]) Enqueue(batch []T) bool {
	if len(batch) == 0 {
		return true
	}

	now := time.Now()
	item := queueItem[T]{
		kind:     kindBatch,
		batch:    batch,
		enqueued: now,
	}

	q.mu.Lock()

	select {
	case <-q.ctx.Done():
		return false
	default:
	}

	q.items.Push(item)
	q.numEnqueued.Add(uint64(len(batch)))
	q.mu.Unlock()

	q.wake()
	return true
}

// Barrier returns a channel that closes when all previously enqueued items
// have been processed. Returns an immediately-closed channel if the queue
// has terminated.
func (q *Queue[T]) Barrier() <-chan struct{} {
	q.mu.Lock()

	ch := make(chan struct{})

	select {
	case <-q.ctx.Done():
		close(ch)
		return ch
	default:
	}

	item := queueItem[T]{
		kind:    kindBarrier,
		barrier: ch,
	}
	q.items.Push(item)
	q.mu.Unlock()

	q.wake()
	return ch
}

// Done returns a channel that closes when processing stops.
func (q *Queue[T]) Done() <-chan struct{} {
	return q.done
}

// Context returns the queue's context, which is cancelled when the queue stops.
func (q *Queue[T]) Context() context.Context {
	return q.ctx
}

// Counters returns current queue metrics.
func (q *Queue[T]) Counters() QueueCounters {
	return QueueCounters{
		Enqueued:  q.numEnqueued.Load(),
		Processed: q.numProcessed.Load(),
	}
}

func (q *Queue[T]) wake() {
	select {
	case q.wakeup <- struct{}{}:
	default:
	}
}

func (q *Queue[T]) run(processor func(context.Context, T)) {
	defer close(q.done)
	defer q.drainAndReleaseBarriers()

	var (
		processingCh = make(chan error, 1)
		processing   chan error // nil when not processing, points to processingCh when processing
		itemCtx      context.Context
		itemCancel   context.CancelFunc
	)

	for {
		if processing == nil {
			q.mu.Lock()
			item, hasItems := q.items.Pop()
			q.mu.Unlock()

			if !hasItems {
				select {
				case <-q.ctx.Done():
					return
				case <-q.wakeup:
					continue
				}
			}

			if item.kind == kindBarrier {
				close(item.barrier)
				continue
			}

			itemCtx = q.ctx
			itemCancel = nil
			if q.maxLag > 0 {
				deadline := item.enqueued.Add(q.maxLag)
				remaining := time.Until(deadline)
				if remaining <= 0 {
					q.cancel(ErrLagged)
					return
				}
				var cancel context.CancelFunc
				itemCtx, cancel = context.WithDeadline(q.ctx, deadline)
				itemCancel = cancel
			}

			batch := item.batch
			processing = processingCh
			go func() {
				defer func() {
					if r := recover(); r != nil {
						processingCh <- &ErrPanic{Panic: r}
					} else {
						processingCh <- nil
					}
				}()
				for _, data := range batch {
					if itemCtx.Err() != nil {
						return
					}
					processor(itemCtx, data)
					q.numProcessed.Add(1)
				}
			}()
		}

		select {
		case <-q.ctx.Done():
			if itemCancel != nil {
				itemCancel()
			}
			if processing != nil {
				<-processing
			}
			return

		case err := <-processing:
			// Check lag BEFORE cancelling to distinguish deadline from manual cancel
			lagDetected := itemCtx.Err() == context.DeadlineExceeded

			if itemCancel != nil {
				itemCancel()
				itemCancel = nil
			}

			if err != nil {
				q.cancel(err)
				return
			}

			if lagDetected {
				q.cancel(ErrLagged)
				return
			}

			processing = nil

		case <-q.wakeup:
		}
	}
}

func (q *Queue[T]) drainAndReleaseBarriers() {
	q.mu.Lock()
	defer q.mu.Unlock()

	for !q.items.IsEmpty() {
		item, ok := q.items.Pop()
		if !ok {
			break
		}
		if item.kind == kindBarrier {
			close(item.barrier)
		}
	}
	q.items.Clear()
}