-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexecutor.go
More file actions
181 lines (147 loc) · 3.68 KB
/
executor.go
File metadata and controls
181 lines (147 loc) · 3.68 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
package executor
import (
"errors"
"fmt"
"reflect"
"runtime"
"sync"
"go.uber.org/ratelimit"
)
// Executor is a simple thread pool base on goroutine.
type Executor struct {
RateLimit ratelimit.Limiter
WaitGroup *sync.WaitGroup
Channel chan *Job
NumWorkers int
}
// Job is a task will be executor execute.
type Job struct {
Handler interface{}
Args []reflect.Value
}
// Config is a config of executor.
// ReqPerSeconds is request per seconds. If it is 0, no limit for requests.
// QueueSize is size of buffer. Executor use synchronize channel, publisher will waiting if channel is full.
// NumWorkers is a number of goroutine.
type Config struct {
ReqPerSeconds int
QueueSize int
NumWorkers int
}
// DefaultConfig is a default config
func DefaultConfig() Config {
return Config{
ReqPerSeconds: 0,
QueueSize: 2 * runtime.NumCPU(),
NumWorkers: runtime.NumCPU(),
}
}
// New returns a Executors that will manage workers.
func New(config Config) (*Executor, error) {
err := config.validate()
if err != nil {
return nil, err
}
var rl ratelimit.Limiter
if config.ReqPerSeconds > 0 {
rl = ratelimit.New(config.ReqPerSeconds)
}
pipeline := &Executor{
RateLimit: rl,
WaitGroup: &sync.WaitGroup{},
Channel: make(chan *Job, config.QueueSize),
NumWorkers: config.NumWorkers,
}
pipeline.initWorker()
return pipeline, nil
}
// NewJob returns a Job that will be executed in workers.
func NewJob(handler interface{}, inputArgs ...interface{}) (*Job, error) {
var (
err error
args []reflect.Value
)
nArgs := len(inputArgs)
parsedHandler, err := validateFunc(handler, nArgs)
if err != nil {
return nil, err
}
for i := 0; i < nArgs; i++ {
args = append(args, reflect.ValueOf(inputArgs[i]))
}
return &Job{
Handler: parsedHandler,
Args: args,
}, nil
}
// Publish to publish a handler and arguments
// Workers will run handler with provided arguments.
func (pipeline *Executor) Publish(handler interface{}, inputArgs ...interface{}) error {
job, err := NewJob(handler, inputArgs...)
if err != nil {
return err
}
pipeline.PublishJob(job)
return nil
}
// PublishJob publish a provided job.
func (pipeline *Executor) PublishJob(job *Job) {
if pipeline.RateLimit != nil {
pipeline.RateLimit.Take()
}
pipeline.WaitGroup.Add(1)
pipeline.Channel <- job
}
func (pipeline *Executor) initWorker() {
for i := 0; i < pipeline.NumWorkers; i++ {
go pipeline.runWorker()
}
}
func (pipeline *Executor) runWorker() {
for {
job, ok := <-pipeline.Channel
if !ok {
break
}
fn := job.Handler.(reflect.Value)
_ = fn.Call(job.Args)
pipeline.WaitGroup.Done()
}
}
// Wait for all worker done.
func (pipeline *Executor) Wait() {
pipeline.WaitGroup.Wait()
}
// Close channel and wait all worker done.
func (pipeline *Executor) Close() {
pipeline.WaitGroup.Wait()
close(pipeline.Channel)
}
// validateFunc validate type of handler and number of arguments.
func validateFunc(handler interface{}, nArgs int) (interface{}, error) {
f := reflect.Indirect(reflect.ValueOf(handler))
if f.Kind() != reflect.Func {
return f, fmt.Errorf("%T must be a Function ", f)
}
method := reflect.ValueOf(handler)
methodType := method.Type()
numIn := methodType.NumIn()
if nArgs < numIn {
return nil, errors.New("Call with too few input arguments")
} else if nArgs > numIn {
return nil, errors.New("Call with too many input arguments")
}
return f, nil
}
func (p *Config) validate() error {
if p.ReqPerSeconds < 0 {
return fmt.Errorf("%T must non negative", "ReqPerSeconds")
}
if p.QueueSize <= 0 {
return fmt.Errorf("%T must positive", "QueueSize")
}
if p.NumWorkers < 0 {
return fmt.Errorf("%T must positive", "NumWorkers")
}
return nil
}