-
Notifications
You must be signed in to change notification settings - Fork 0
/
accumulator.go
217 lines (179 loc) · 4.09 KB
/
accumulator.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
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
/*
* Copyright (c) 2023.
*
* License MIT (https://raw.githubusercontent.com/nar10z/go-accumulator/main/LICENSE)
*
* Developed thanks to Nikita Terentyev (nar10z). Use it for good, and let your code work without problems!
*/
package goaccum
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
)
const (
defaultFlushSize = 1000
defaultFlushInterval = time.Millisecond * 250
)
// New creates a new data Accumulator
func New[T any](
flushSize uint,
flushInterval time.Duration,
flushTimeout time.Duration,
flushFunc FlushExec[T],
) *Accumulator[T] {
if flushSize == 0 {
flushSize = defaultFlushSize
}
if flushInterval == 0 {
flushInterval = defaultFlushInterval
}
if flushTimeout == 0 {
flushTimeout = flushInterval
}
if flushFunc == nil {
flushFunc = noop[T]
}
a := &Accumulator[T]{
flushFunc: flushFunc,
flushTimeout: flushTimeout,
chEvents: make(chan eventExtended[T], flushSize),
batchEvents: sync.Pool{
New: func() any {
return make([]eventExtended[T], 0, flushSize)
},
},
batchOrigEvents: sync.Pool{
New: func() any {
return make([]T, 0, flushSize)
},
},
chStop: make(chan struct{}),
}
go a.startFlusher(flushInterval, int(flushSize))
return a
}
type Accumulator[T any] struct {
batchEvents sync.Pool
batchOrigEvents sync.Pool
flushFunc FlushExec[T]
flushTimeout time.Duration
chEvents chan eventExtended[T]
chStop chan struct{}
isClose atomic.Bool
}
func (a *Accumulator[T]) AddAsync(ctx context.Context, event T) (err error) {
if a.isClose.Load() {
return ErrSendToClose
}
defer func() {
// recover from panic caused by writing to a closed channel
if r := recover(); r != nil {
err = fmt.Errorf("AddSync, recover: %v", r)
}
}()
select {
case <-ctx.Done():
return fmt.Errorf("AddAsync, check on write: %w", ctx.Err())
default:
a.chEvents <- eventExtended[T]{e: event}
}
return nil
}
func (a *Accumulator[T]) AddSync(ctx context.Context, event T) (err error) {
// check context before alloc eventExtended
select {
case <-ctx.Done():
return fmt.Errorf("AddSync, check before: %w", ctx.Err())
default:
}
e := eventExtended[T]{
fallback: make(chan error),
e: event,
}
if a.isClose.Load() {
return ErrSendToClose
}
defer func() {
// recover from panic caused by writing to a closed channel
if r := recover(); r != nil {
err = fmt.Errorf("AddSync, recover: %v", r)
}
}()
// check context with write to channel
select {
case <-ctx.Done():
return fmt.Errorf("AddSync, check on write: %w", ctx.Err())
case a.chEvents <- e:
}
// check context with wait event result
select {
case err = <-e.fallback:
if err != nil {
return fmt.Errorf("AddSync, check fallback: %w", err)
}
return nil
case <-ctx.Done():
return fmt.Errorf("AddSync, check fallback: %w", ctx.Err())
}
}
func (a *Accumulator[T]) Stop() {
if !a.isClose.CompareAndSwap(false, true) {
return
}
close(a.chEvents)
<-a.chStop
}
func (a *Accumulator[T]) IsClosed() bool {
return a.isClose.Load()
}
func (a *Accumulator[T]) startFlusher(interval time.Duration, size int) {
ticker := time.NewTicker(interval)
batch, _ := a.batchEvents.Get().([]eventExtended[T])
flush := func() {
a.flush(batch)
a.batchEvents.Put(batch[:0])
batch, _ = a.batchEvents.Get().([]eventExtended[T])
}
loop:
for {
select {
case e, ok := <-a.chEvents:
if !ok {
break loop
}
batch = append(batch, e)
if len(batch) < size {
continue
}
flush()
case <-ticker.C:
flush()
}
}
ticker.Stop()
a.chEvents = nil
flush()
a.chStop <- struct{}{}
}
func (a *Accumulator[T]) flush(events []eventExtended[T]) {
if len(events) == 0 {
return
}
ctx, cancel := context.WithTimeout(context.Background(), a.flushTimeout)
defer cancel()
originalEvents, _ := a.batchOrigEvents.Get().([]T)
for i := 0; i < len(events); i++ {
originalEvents = append(originalEvents, events[i].e)
}
err := a.flushFunc(ctx, originalEvents)
for i := 0; i < len(events); i++ {
if events[i].fallback == nil {
continue
}
events[i].fallback <- err
}
a.batchOrigEvents.Put(originalEvents[:0])
}