Debian Codegraph @

exporter/exporterhelper/internal/queue/memory_queue.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package queue // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue"
5
6 import (
7 "context"
8 "errors"
9 "sync"
10
11 "go.opentelemetry.io/collector/component"
12 "go.opentelemetry.io/collector/exporter/exporterhelper/internal/request"
13 )
14
15 var blockingDonePool = sync.Pool{
16 New: func() any {
17 return &blockingDone{
18 ch: make(chan error, 1),
19 }
20 },
21 }
22
23 var (
24 errInvalidSize = errors.New("invalid element size")
25 errSizeTooLarge = errors.New("element size too large")
26 )
27
28 // memoryQueue is an in-memory implementation of a Queue.
29 type memoryQueue[T request.Request] struct {
30 component.StartFunc
31 refCounter ReferenceCounter[T]
32 sizer request.Sizer
33 cap int64
34
35 mu sync.Mutex
36 hasMoreElements *sync.Cond
37 hasMoreSpace *cond
38 items *linkedQueue[T]
39 size int64
40 stopped bool
41 waitForResult bool
42 blockOnOverflow bool
43 }
44
45 // newMemoryQueue creates a sized elements channel. Each element is assigned a size by the provided sizer.
46 // capacity is the capacity of the queue.
47 func newMemoryQueue[T request.Request](set Settings[T]) readableQueue[T] {
48 sq := &memoryQueue[T]{
49 refCounter: set.ReferenceCounter,
50 sizer: request.NewSizer(set.SizerType),
51 cap: set.Capacity,
52 items: &linkedQueue[T]{},
53 waitForResult: set.WaitForResult,
54 blockOnOverflow: set.BlockOnOverflow,
55 }
56 sq.hasMoreElements = sync.NewCond(&sq.mu)
57 sq.hasMoreSpace = newCond(&sq.mu)
58 return sq
59 }
60
61 // Offer puts the element into the queue with the given sized if there is enough capacity.
62 // Returns an error if the queue is full.
63 func (mq *memoryQueue[T]) Offer(ctx context.Context, el T) error {
64 elSize := mq.sizer.Sizeof(el)
65 // Ignore empty requests, see https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#empty-telemetry-envelopes
66 if elSize == 0 {
67 return nil
68 }
69
70 if elSize <= 0 {
71 return errInvalidSize
72 }
73
74 // If element larger than the capacity, will never been able to add it.
75 if elSize > mq.cap {
76 return errSizeTooLarge
77 }
78
79 if mq.refCounter != nil {
80 mq.refCounter.Ref(el)
81 }
82
83 done, err := mq.add(ctx, el, elSize)
84 if err != nil {
85 // Unref in case of an error since there will not be any async worker to pick it up.
86 if mq.refCounter != nil {
87 mq.refCounter.Unref(el)
88 }
89 return err
90 }
91
92 if mq.waitForResult {
93 // Only re-add the blockingDone instance back to the pool if successfully received the
94 // message from the consumer which guarantees consumer will not use that anymore,
95 // otherwise no guarantee about when the consumer will add the message to the channel so cannot reuse or close.
96 select {
97 case doneErr := <-done.ch:
98 blockingDonePool.Put(done)
99 return doneErr
100 case <-ctx.Done():
101 return ctx.Err()
102 }
103 }
104 return nil
105 }
106
107 func (mq *memoryQueue[T]) add(ctx context.Context, el T, elSize int64) (*blockingDone, error) {
108 mq.mu.Lock()
109 defer mq.mu.Unlock()
110
111 for mq.size+elSize > mq.cap {
112 if !mq.blockOnOverflow {
113 return nil, ErrQueueIsFull
114 }
115 // Wait for more space or before the ctx is Done.
116 if err := mq.hasMoreSpace.Wait(ctx); err != nil {
117 return nil, err
118 }
119 }
120
121 mq.size += elSize
122 done := blockingDonePool.Get().(*blockingDone)
123 done.reset(elSize, mq)
124
125 if !mq.waitForResult {
126 // Prevent cancellation and deadline to propagate to the context stored in the queue.
127 // The grpc/http based receivers will cancel the request context after this function returns.
128 ctx = context.WithoutCancel(ctx)
129 }
130
131 mq.items.push(ctx, el, done)
132 // Signal one consumer if any.
133 mq.hasMoreElements.Signal()
134 return done, nil
135 }
136
137 // Read removes the element from the queue and returns it.
138 // The call blocks until there is an item available or the queue is stopped.
139 // The function returns true when an item is consumed or false if the queue is stopped and emptied.
140 func (mq *memoryQueue[T]) Read(context.Context) (context.Context, T, Done, bool) {
141 mq.mu.Lock()
142 defer mq.mu.Unlock()
143
144 for {
145 if mq.items.hasElements() {
146 elCtx, el, done := mq.items.pop()
147 return elCtx, el, done, true
148 }
149
150 if mq.stopped {
151 var el T
152 return context.Background(), el, nil, false
153 }
154
155 // TODO: Need to change the Queue interface to return an error to allow distinguish between shutdown and context canceled.
156 // Until then use the sync.Cond.
157 mq.hasMoreElements.Wait()
158 }
159 }
160
161 func (mq *memoryQueue[T]) onDone(bd *blockingDone, err error) {
162 mq.mu.Lock()
163 defer mq.mu.Unlock()
164 mq.size -= bd.elSize
165 mq.hasMoreSpace.Signal()
166 if mq.waitForResult {
167 // In this case the done will be added back to the queue by the waiter.
168 bd.ch <- err
169 return
170 }
171 blockingDonePool.Put(bd)
172 }
173
174 // Shutdown closes the queue channel to initiate draining of the queue.
175 func (mq *memoryQueue[T]) Shutdown(context.Context) error {
176 mq.mu.Lock()
177 defer mq.mu.Unlock()
178 mq.stopped = true
179 mq.hasMoreElements.Broadcast()
180 return nil
181 }
182
183 func (mq *memoryQueue[T]) Size() int64 {
184 mq.mu.Lock()
185 defer mq.mu.Unlock()
186 return mq.size
187 }
188
189 func (mq *memoryQueue[T]) Capacity() int64 {
190 return mq.cap
191 }
192
193 type node[T any] struct {
194 ctx context.Context
195 data T
196 done Done
197 next *node[T]
198 }
199
200 type linkedQueue[T any] struct {
201 head *node[T]
202 tail *node[T]
203 }
204
205 func (l *linkedQueue[T]) push(ctx context.Context, data T, done Done) {
206 n := &node[T]{ctx: ctx, data: data, done: done}
207 // If tail is nil means list is empty so update both head and tail to point to same element.
208 if l.tail == nil {
209 l.head = n
210 l.tail = n
211 return
212 }
213 l.tail.next = n
214 l.tail = n
215 }
216
217 func (l *linkedQueue[T]) hasElements() bool {
218 return l.head != nil
219 }
220
221 func (l *linkedQueue[T]) pop() (context.Context, T, Done) {
222 n := l.head
223 l.head = n.next
224 // If it gets to the last element, then update tail as well.
225 if l.head == nil {
226 l.tail = nil
227 }
228 n.next = nil
229 return n.ctx, n.data, n.done
230 }
231
232 type blockingDone struct {
233 queue interface {
234 onDone(*blockingDone, error)
235 }
236 elSize int64
237 ch chan error
238 }
239
240 func (bd *blockingDone) reset(elSize int64, queue interface{ onDone(*blockingDone, error) }) {
241 bd.elSize = elSize
242 bd.queue = queue
243 }
244
245 func (bd *blockingDone) OnDone(err error) {
246 bd.queue.onDone(bd, err)
247 }