-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.go
86 lines (67 loc) · 1.38 KB
/
options.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
package batchease
import (
"strconv"
"time"
)
// BatcherOption
type BatcherOption[T any] func(b *Batcher[T]) error
func WithDefaultConfig[T any]() BatcherOption[T] {
return func(b *Batcher[T]) error {
b.size = 5
b.wait = time.Second
b.loadBalancer = &RoundRobinLB[T]{}
return nil
}
}
func WithSize[T any](size int) BatcherOption[T] {
return func(b *Batcher[T]) error {
if size <= 0 {
return ErrInvalidBatchSize
}
b.size = size
return nil
}
}
func WithWait[T any](wait time.Duration) BatcherOption[T] {
return func(b *Batcher[T]) error {
b.wait = wait
return nil
}
}
func WithWorkers[T any](n int, handleFn HandleFunc[T]) BatcherOption[T] {
return func(b *Batcher[T]) error {
if handleFn == nil {
return ErrInvalidHandleFn
}
if n <= 0 {
return ErrInvalidNumberOfWorker
}
b.workerSize = n
b.workers = make([]*Worker[T], n)
for i := 0; i < n; i++ {
w, err := NewWorker(
strconv.Itoa(i),
WorkerWithHandleFn(handleFn),
)
if err != nil {
return err
}
b.workers[i] = w
if i == 0 {
b.currentWorker = b.workers[i]
}
}
return nil
}
}
// WorkerOption
type WorkerOption[T any] func(w *Worker[T]) error
func WorkerWithHandleFn[T any](handleFn HandleFunc[T]) WorkerOption[T] {
return func(w *Worker[T]) error {
if handleFn == nil {
return ErrInvalidHandleFn
}
w.handleFn = handleFn
return nil
}
}