-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch.go
More file actions
317 lines (276 loc) · 7.29 KB
/
batch.go
File metadata and controls
317 lines (276 loc) · 7.29 KB
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
package gencache
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/gozephyr/gencache/errors"
"github.com/gozephyr/gencache/ttl"
)
// BatchConfig represents configuration for batch operations
type BatchConfig struct {
MaxBatchSize int
OperationTimeout time.Duration
MaxConcurrent int
TTLConfig ttl.Config
}
// DefaultBatchConfig returns the default batch configuration
func DefaultBatchConfig() BatchConfig {
return BatchConfig{
MaxBatchSize: 1000,
OperationTimeout: 5 * time.Second,
MaxConcurrent: 10,
TTLConfig: ttl.DefaultConfig(),
}
}
// BatchMetrics represents metrics for batch operations
type BatchMetrics struct {
TotalOperations atomic.Int64
TotalItems atomic.Int64
SuccessCount atomic.Int64
ErrorCount atomic.Int64
TimeoutCount atomic.Int64
LastOperation atomic.Value // time.Time
}
// BatchResult represents the result of a batch operation
type BatchResult[K comparable, V any] struct {
Key K
Value V
Error error
}
// BatchCache extends Cache with batch operations
type BatchCache[K comparable, V any] interface {
Cache[K, V]
// GetMany retrieves multiple values from the cache
GetMany(ctx context.Context, keys []K) map[K]V
// SetMany stores multiple values in the cache
SetMany(ctx context.Context, entries map[K]V, ttl time.Duration) error
// DeleteMany removes multiple values from the cache
DeleteMany(ctx context.Context, keys []K) error
// GetBatchMetrics returns the current batch operation metrics
GetBatchMetrics() *BatchMetrics
// ResetBatchMetrics resets the batch operation metrics
ResetBatchMetrics()
}
// batchCache implements BatchCache
type batchCache[K comparable, V any] struct {
Cache[K, V]
config BatchConfig
metrics BatchMetrics
mu sync.RWMutex
}
// NewBatchCache creates a new cache with batch operations
func NewBatchCache[K comparable, V any](c Cache[K, V], config BatchConfig) BatchCache[K, V] {
return &batchCache[K, V]{
Cache: c,
config: config,
}
}
// GetMany retrieves multiple values from the cache
func (bc *batchCache[K, V]) GetMany(ctx context.Context, keys []K) map[K]V {
// Update metrics atomically
bc.metrics.TotalOperations.Add(1)
bc.metrics.TotalItems.Add(int64(len(keys)))
bc.metrics.LastOperation.Store(time.Now())
// Limit batch size
if len(keys) > bc.config.MaxBatchSize {
keys = keys[:bc.config.MaxBatchSize]
}
result := make(map[K]V, len(keys))
var resultMu sync.RWMutex
// Create a context with timeout for individual operations
opCtx, cancel := context.WithTimeout(ctx, bc.config.OperationTimeout)
defer cancel()
// Use a buffered channel for results to prevent goroutine leaks
results := make(chan struct {
key K
value V
err error
}, len(keys))
var wg sync.WaitGroup
// Process keys in parallel with timeout
for _, key := range keys {
select {
case <-opCtx.Done():
bc.metrics.TimeoutCount.Add(1)
return result
default:
wg.Add(1)
go func(k K) {
defer wg.Done()
value, err := bc.Get(k)
if err == nil {
select {
case results <- struct {
key K
value V
err error
}{k, value, nil}:
case <-opCtx.Done():
return
}
}
}(key)
}
}
// Start a goroutine to close results channel when all operations complete
go func() {
wg.Wait()
close(results)
}()
// Collect results
for {
select {
case <-opCtx.Done():
bc.metrics.TimeoutCount.Add(1)
return result
case r, ok := <-results:
if !ok {
return result
}
if r.err == nil {
resultMu.Lock()
result[r.key] = r.value
resultMu.Unlock()
bc.metrics.SuccessCount.Add(1)
}
}
}
}
// SetMany stores multiple values in the cache
func (bc *batchCache[K, V]) SetMany(ctx context.Context, entries map[K]V, ttlDuration time.Duration) error {
bc.metrics.TotalOperations.Add(1)
bc.metrics.TotalItems.Add(int64(len(entries)))
bc.metrics.LastOperation.Store(time.Now())
// Validate TTL
if err := ttl.Validate(ttlDuration, bc.config.TTLConfig); err != nil {
return errors.WrapError("SetMany", nil, err)
}
// Normalize TTL
normalizedTTL := ttl.Normalize(ttlDuration, bc.config.TTLConfig)
// Limit batch size
if len(entries) > bc.config.MaxBatchSize {
// Create a new map with limited size
limitedEntries := make(map[K]V, bc.config.MaxBatchSize)
count := 0
for k, v := range entries {
if count >= bc.config.MaxBatchSize {
break
}
limitedEntries[k] = v
count++
}
entries = limitedEntries
}
var wg sync.WaitGroup
var timeoutOccurred atomic.Bool
errs := make([]error, 0, len(entries)) // Pre-allocate error slice
errChan := make(chan error, len(entries))
for key, value := range entries {
// Check context before launching goroutine
if ctx.Err() != nil {
bc.metrics.TimeoutCount.Add(1)
return ctx.Err()
}
wg.Add(1)
go func(k K, v V) {
defer wg.Done()
select {
case <-ctx.Done():
timeoutOccurred.Store(true)
return
default:
if err := bc.SetWithContext(ctx, k, v, normalizedTTL); err != nil {
errChan <- errors.WrapError("SetMany", k, err)
} else {
bc.metrics.SuccessCount.Add(1)
}
}
}(key, value)
}
// Wait for all goroutines to complete
wg.Wait()
close(errChan)
// Collect errors
for err := range errChan {
errs = append(errs, err)
}
// Check context again after all goroutines
if ctx.Err() != nil || timeoutOccurred.Load() {
bc.metrics.TimeoutCount.Add(1)
return ctx.Err()
}
if len(errs) > 0 {
bc.metrics.ErrorCount.Add(int64(len(errs)))
return errors.WrapError("SetMany", nil, errors.ErrBatchOperation)
}
return nil
}
// DeleteMany removes multiple values from the cache
func (bc *batchCache[K, V]) DeleteMany(ctx context.Context, keys []K) error {
bc.metrics.TotalOperations.Add(1)
bc.metrics.TotalItems.Add(int64(len(keys)))
bc.metrics.LastOperation.Store(time.Now())
// Limit batch size
if len(keys) > bc.config.MaxBatchSize {
keys = keys[:bc.config.MaxBatchSize]
}
var wg sync.WaitGroup
var errs []error
sem := make(chan struct{}, bc.config.MaxConcurrent)
errChan := make(chan error, len(keys))
// Process keys in parallel with timeout
done := make(chan struct{})
go func() {
for _, key := range keys {
select {
case <-ctx.Done():
bc.metrics.TimeoutCount.Add(1)
return
default:
wg.Add(1)
sem <- struct{}{} // Acquire semaphore
go func(k K) {
defer wg.Done()
defer func() { <-sem }() // Release semaphore
if err := bc.DeleteWithContext(ctx, k); err != nil {
errChan <- errors.WrapError("DeleteMany", k, err)
} else {
bc.metrics.SuccessCount.Add(1)
}
}(key)
}
}
wg.Wait()
close(done)
close(errChan)
}()
// Wait for completion or timeout
select {
case <-done:
// Collect errors
for err := range errChan {
errs = append(errs, err)
}
if len(errs) > 0 {
bc.metrics.ErrorCount.Add(int64(len(errs)))
return errors.WrapError("DeleteMany", nil, errors.ErrBatchOperation)
}
return nil
case <-ctx.Done():
bc.metrics.TimeoutCount.Add(1)
return ctx.Err()
}
}
// GetBatchMetrics returns the current batch operation metrics
func (bc *batchCache[K, V]) GetBatchMetrics() *BatchMetrics {
bc.mu.RLock()
defer bc.mu.RUnlock()
return &bc.metrics
}
// ResetBatchMetrics resets the batch operation metrics
func (bc *batchCache[K, V]) ResetBatchMetrics() {
bc.mu.Lock()
defer bc.mu.Unlock()
bc.metrics = BatchMetrics{}
}