-
Notifications
You must be signed in to change notification settings - Fork 1
/
group_options.go
76 lines (65 loc) · 1.57 KB
/
group_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
package goload
import (
"github.com/mroth/weightedrand/v2"
"github.com/rs/zerolog/log"
"time"
)
type GroupOptions struct {
name string
weight int
timeout time.Duration
executors []Executor
}
type GroupOption func(*GroupOptions)
func WithGroup(opts ...GroupOption) Executor {
options := &GroupOptions{}
for _, opt := range opts {
opt(options)
}
if len(options.executors) == 0 {
log.Fatal().Msg("group can't be empty")
}
choises := make([]weightedrand.Choice[Executor, int], 0, len(options.executors))
for _, exec := range options.executors {
choises = append(choises, weightedrand.NewChoice(exec, exec.Options().Weight))
}
chooser, err := weightedrand.NewChooser(
choises...,
)
if err != nil {
log.Fatal().Err(err).Msg("can't create chooser")
}
if options.weight == 0 {
weightSum := 0
for _, exec := range options.executors {
weightSum += exec.Options().Weight
}
options.weight = weightSum
}
return &executorGroup{
name: options.name,
chooser: chooser,
weight: options.weight,
timeout: options.timeout,
}
}
func WithGroupWeight(weight int) GroupOption {
return func(options *GroupOptions) {
options.weight = weight
}
}
func WithGroupTimeout(timeout time.Duration) GroupOption {
return func(options *GroupOptions) {
options.timeout = timeout
}
}
func WithGroupExecutors(executors ...Executor) GroupOption {
return func(options *GroupOptions) {
options.executors = append(options.executors, executors...)
}
}
func WithGroupName(name string) GroupOption {
return func(options *GroupOptions) {
options.name = name
}
}