Debian Codegraph @

exporter/exporterhelper/internal/queuebatch/partition_batcher.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package queuebatch // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch"
5
6 import (
7 "context"
8 "sync"
9 "time"
10
11 "go.uber.org/multierr"
12 "go.uber.org/zap"
13
14 "go.opentelemetry.io/collector/component"
15 "go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue"
16 "go.opentelemetry.io/collector/exporter/exporterhelper/internal/request"
17 "go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender"
18 )
19
20 var _ Batcher[request.Request] = (*partitionBatcher)(nil)
21
22 type batch struct {
23 ctx context.Context
24 req request.Request
25 done multiDone
26 }
27
28 // partitionBatcher continuously batch incoming requests and flushes asynchronously if minimum size limit is met or on timeout.
29 type partitionBatcher struct {
30 cfg BatchConfig
31 wp *workerPool
32 sizer request.Sizer
33 mergeCtx func(context.Context, context.Context) context.Context
34 consumeFunc sender.SendFunc[request.Request]
35 stopWG sync.WaitGroup
36 currentBatchMu sync.Mutex
37 currentBatch *batch
38 timer *time.Timer
39 shutdownCh chan struct{}
40 logger *zap.Logger
41 }
42
43 func newPartitionBatcher(
44 cfg BatchConfig,
45 sizer request.Sizer,
46 mergeCtx func(context.Context, context.Context) context.Context,
47 wp *workerPool,
48 next sender.SendFunc[request.Request],
49 logger *zap.Logger,
50 ) *partitionBatcher {
51 return &partitionBatcher{
52 cfg: cfg,
53 wp: wp,
54 sizer: sizer,
55 mergeCtx: mergeCtx,
56 consumeFunc: next,
57 shutdownCh: make(chan struct{}, 1),
58 logger: logger,
59 }
60 }
61
62 func (qb *partitionBatcher) resetTimer() {
63 if qb.cfg.FlushTimeout > 0 {
64 qb.timer.Reset(qb.cfg.FlushTimeout)
65 }
66 }
67
68 func (qb *partitionBatcher) Consume(ctx context.Context, req request.Request, done queue.Done) {
69 qb.currentBatchMu.Lock()
70
71 if qb.currentBatch == nil {
72 reqList, mergeSplitErr := req.MergeSplit(ctx, int(qb.cfg.MaxSize), qb.cfg.Sizer, nil)
73 if mergeSplitErr != nil {
74 // Do not return in case of error if there are data, try to export as much as possible.
75 qb.logger.Warn("Failed to split request.", zap.Error(mergeSplitErr))
76 }
77
78 if len(reqList) == 0 {
79 done.OnDone(mergeSplitErr)
80 qb.currentBatchMu.Unlock()
81 return
82 }
83
84 // If more than one flush is required for this request, call done only when all flushes are done.
85 numRefs := len(reqList)
86 // Need to also inform about the mergeSplitErr, consider the errored data as 1 batch.
87 if mergeSplitErr != nil {
88 numRefs++
89 }
90 if numRefs > 1 {
91 done = newRefCountDone(done, int64(numRefs))
92 if mergeSplitErr != nil {
93 done.OnDone(mergeSplitErr)
94 }
95 }
96
97 // We have at least one result in the reqList. Last in the list may not have enough data to be flushed.
98 // Find if it has at least MinSize, and if it does then move that as the current batch.
99 lastReq := reqList[len(reqList)-1]
100 if qb.sizer.Sizeof(lastReq) < qb.cfg.MinSize {
101 // Do not flush the last item and add it to the current batch.
102 reqList = reqList[:len(reqList)-1]
103 qb.currentBatch = &batch{
104 ctx: ctx,
105 req: lastReq,
106 done: multiDone{done},
107 }
108 qb.resetTimer()
109 }
110
111 qb.currentBatchMu.Unlock()
112 for i := 0; i < len(reqList); i++ {
113 qb.flush(ctx, reqList[i], done)
114 }
115
116 return
117 }
118
119 reqList, mergeSplitErr := qb.currentBatch.req.MergeSplit(ctx, int(qb.cfg.MaxSize), qb.cfg.Sizer, req)
120 // If failed to merge signal all Done callbacks from the current batch as well as the current request and reset the current batch.
121 if mergeSplitErr != nil {
122 // Do not return in case of error if there are data, try to export as much as possible.
123 qb.logger.Warn("Failed to split request.", zap.Error(mergeSplitErr))
124 }
125
126 if len(reqList) == 0 {
127 done.OnDone(mergeSplitErr)
128 qb.currentBatchMu.Unlock()
129 return
130 }
131
132 // If more than one flush is required for this request, call done only when all flushes are done.
133 numRefs := len(reqList)
134 // Need to also inform about the mergeSplitErr, consider the errored data as 1 batch.
135 if mergeSplitErr != nil {
136 numRefs++
137 }
138 if numRefs > 1 {
139 done = newRefCountDone(done, int64(len(reqList)))
140 if mergeSplitErr != nil {
141 done.OnDone(mergeSplitErr)
142 }
143 }
144
145 // We have at least one result in the reqList, if more results here is what that means:
146 // - First result will contain items from the current batch + some results from the current request.
147 // - All other results except first will contain items only from the current request.
148 // - Last result may not have enough data to be flushed.
149
150 // Logic on how to deal with the current batch:
151 qb.currentBatch.req = reqList[0]
152 qb.currentBatch.done = append(qb.currentBatch.done, done)
153
154 mergedCtx := context.Background() //nolint:contextcheck
155 if qb.mergeCtx != nil {
156 mergedCtx = qb.mergeCtx(qb.currentBatch.ctx, ctx)
157 }
158 qb.currentBatch.ctx = contextWithMergedLinks(mergedCtx, qb.currentBatch.ctx, ctx)
159
160 // Save the "currentBatch" if we need to flush it, because we want to execute flush without holding the lock, and
161 // cannot unlock and re-lock because we are not done processing all the responses.
162 var firstBatch *batch
163 // Need to check the currentBatch if more than 1 result returned or if 1 result return but larger than MinSize.
164 if len(reqList) > 1 || qb.sizer.Sizeof(qb.currentBatch.req) >= qb.cfg.MinSize {
165 firstBatch = qb.currentBatch
166 qb.currentBatch = nil
167 }
168 // At this moment we dealt with the first result which is iter in the currentBatch or in the `firstBatch` we will flush.
169 reqList = reqList[1:]
170
171 // If we still have results to process, then we need to check if the last result has enough data to flush, or we add it to the currentBatch.
172 if len(reqList) > 0 {
173 lastReq := reqList[len(reqList)-1]
174 if qb.sizer.Sizeof(lastReq) < qb.cfg.MinSize {
175 // Do not flush the last item and add it to the current batch.
176 reqList = reqList[:len(reqList)-1]
177 qb.currentBatch = &batch{
178 ctx: ctx,
179 req: lastReq,
180 done: multiDone{done},
181 }
182 qb.resetTimer()
183 }
184 }
185
186 qb.currentBatchMu.Unlock()
187 if firstBatch != nil {
188 qb.flush(firstBatch.ctx, firstBatch.req, firstBatch.done)
189 }
190 for i := 0; i < len(reqList); i++ {
191 qb.flush(ctx, reqList[i], done)
192 }
193 }
194
195 // Start starts the goroutine that reads from the queue and flushes asynchronously.
196 func (qb *partitionBatcher) Start(context.Context, component.Host) error {
197 if qb.cfg.FlushTimeout <= 0 {
198 return nil
199 }
200 qb.timer = time.NewTimer(qb.cfg.FlushTimeout)
201 qb.stopWG.Add(1)
202 go func() {
203 defer qb.stopWG.Done()
204 for {
205 select {
206 case <-qb.shutdownCh:
207 return
208 case <-qb.timer.C:
209 qb.flushCurrentBatchIfNecessary()
210 }
211 }
212 }()
213 return nil
214 }
215
216 // Shutdown ensures that queue and all Batcher are stopped.
217 func (qb *partitionBatcher) Shutdown(context.Context) error {
218 close(qb.shutdownCh)
219 // Make sure execute one last flush if necessary.
220 qb.flushCurrentBatchIfNecessary()
221 qb.stopWG.Wait()
222 return nil
223 }
224
225 // flushCurrentBatchIfNecessary sends out the current request batch if it is not nil
226 func (qb *partitionBatcher) flushCurrentBatchIfNecessary() {
227 qb.currentBatchMu.Lock()
228 if qb.currentBatch == nil {
229 qb.currentBatchMu.Unlock()
230 return
231 }
232 batchToFlush := qb.currentBatch
233 qb.currentBatch = nil
234 qb.currentBatchMu.Unlock()
235
236 // flush() blocks until successfully started a goroutine for flushing.
237 qb.flush(batchToFlush.ctx, batchToFlush.req, batchToFlush.done)
238 qb.resetTimer()
239 }
240
241 // flush starts a goroutine that calls consumeFunc. It blocks until a worker is available if necessary.
242 func (qb *partitionBatcher) flush(ctx context.Context, req request.Request, done queue.Done) {
243 qb.stopWG.Add(1)
244 qb.wp.execute(func() {
245 defer qb.stopWG.Done()
246 done.OnDone(qb.consumeFunc(ctx, req))
247 })
248 }
249
250 type workerPool struct {
251 workers chan struct{}
252 }
253
254 func newWorkerPool(maxWorkers int) *workerPool {
255 workers := make(chan struct{}, maxWorkers)
256 for range maxWorkers {
257 workers <- struct{}{}
258 }
259 return &workerPool{workers: workers}
260 }
261
262 func (wp *workerPool) execute(f func()) {
263 <-wp.workers
264 go func() {
265 defer func() {
266 wp.workers <- struct{}{}
267 }()
268 f()
269 }()
270 }
271
272 type multiDone []queue.Done
273
274 func (mdc multiDone) OnDone(err error) {
275 for _, d := range mdc {
276 d.OnDone(err)
277 }
278 }
279
280 type refCountDone struct {
281 done queue.Done
282 mu sync.Mutex
283 refCount int64
284 err error
285 }
286
287 func newRefCountDone(done queue.Done, refCount int64) queue.Done {
288 return &refCountDone{
289 done: done,
290 refCount: refCount,
291 }
292 }
293
294 func (rcd *refCountDone) OnDone(err error) {
295 rcd.mu.Lock()
296 defer rcd.mu.Unlock()
297 rcd.err = multierr.Append(rcd.err, err)
298 rcd.refCount--
299 if rcd.refCount == 0 {
300 // No more references, call done.
301 rcd.done.OnDone(rcd.err)
302 }
303 }