-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
100 lines (81 loc) · 1.54 KB
/
worker.go
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
package logger
import (
"context"
"sync"
)
var (
retryPool sync.Pool
retryPoolOnce sync.Once
)
func getRetryPool[T any]() *sync.Pool {
retryPoolOnce.Do(func() {
retryPool = sync.Pool{
New: func() any {
return make([]T, 0)
},
}
})
return &retryPool
}
func logWorker[T any](ctx context.Context, wg *sync.WaitGroup, log Log[T], ch <-chan T, bufferSize, retryCount int) {
cache := make([]T, bufferSize, bufferSize)
idx := 0
defer wg.Done()
reset := func() {
idx = 0
}
set := func(data T) {
cache[idx] = data
idx++
}
retryWrite := func() {
var err error
defer reset()
if err = log.LogMultiple(cache); err == nil {
return
}
retryQueue := getRetryPool[T]().Get().([]T)
copy(retryQueue, cache) // size of the retryQueue is always equal to the size of the cache
go func(retryQueue []T) {
defer func() {
retryQueue = retryQueue[:0]
getRetryPool[T]().Put(retryQueue)
}()
for i := 0; i < retryCount; i++ {
if err = log.LogMultiple(retryQueue); err == nil {
return
}
}
}(retryQueue)
}
for {
select {
case <-ctx.Done():
goto flush
case data, more := <-ch:
var appended bool
if idx < bufferSize-1 {
set(data)
appended = true
}
// Recalculate length again so we can flush the cache
if idx == bufferSize-1 {
retryWrite()
reset()
}
if !appended {
set(data)
}
if !more {
goto flush
}
}
}
flush:
// Empty the buffered channel
cache = cache[:idx]
for data := range ch {
cache = append(cache, data)
}
retryWrite()
}