-
-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathoptions.go
112 lines (95 loc) · 2.22 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
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
package queue
import (
"context"
"runtime"
"github.com/golang-queue/queue/core"
)
var (
defaultCapacity = 0
defaultWorkerCount = int64(runtime.NumCPU())
defaultNewLogger = NewLogger()
defaultFn = func(context.Context, core.TaskMessage) error { return nil }
defaultMetric = NewMetric()
)
// An Option configures a mutex.
type Option interface {
apply(*Options)
}
// OptionFunc is a function that configures a queue.
type OptionFunc func(*Options)
// Apply calls f(option)
func (f OptionFunc) apply(option *Options) {
f(option)
}
// WithWorkerCount set worker count
func WithWorkerCount(num int64) Option {
return OptionFunc(func(q *Options) {
if num <= 0 {
num = defaultWorkerCount
}
q.workerCount = num
})
}
// WithQueueSize set worker count
func WithQueueSize(num int) Option {
return OptionFunc(func(q *Options) {
q.queueSize = num
})
}
// WithLogger set custom logger
func WithLogger(l Logger) Option {
return OptionFunc(func(q *Options) {
q.logger = l
})
}
// WithMetric set custom Metric
func WithMetric(m Metric) Option {
return OptionFunc(func(q *Options) {
q.metric = m
})
}
// WithWorker set custom worker
func WithWorker(w core.Worker) Option {
return OptionFunc(func(q *Options) {
q.worker = w
})
}
// WithFn set custom job function
func WithFn(fn func(context.Context, core.TaskMessage) error) Option {
return OptionFunc(func(q *Options) {
q.fn = fn
})
}
// WithAfterFn set callback function after job done
func WithAfterFn(afterFn func()) Option {
return OptionFunc(func(q *Options) {
q.afterFn = afterFn
})
}
// Options for custom args in Queue
type Options struct {
workerCount int64
logger Logger
queueSize int
worker core.Worker
fn func(context.Context, core.TaskMessage) error
afterFn func()
metric Metric
}
// NewOptions initialize the default value for the options
func NewOptions(opts ...Option) *Options {
o := &Options{
workerCount: defaultWorkerCount,
queueSize: defaultCapacity,
logger: defaultNewLogger,
worker: nil,
fn: defaultFn,
metric: defaultMetric,
}
// Loop through each option
for _, opt := range opts {
// Call the option giving the instantiated
opt.apply(o)
}
return o
}