-
Notifications
You must be signed in to change notification settings - Fork 351
/
executor.go
156 lines (132 loc) · 3.99 KB
/
executor.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
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
package batch
import (
"context"
"time"
"github.com/treeverse/lakefs/pkg/logging"
)
// RequestBufferSize is the amount of requests users can dispatch that haven't been processed yet before
// dispatching new ones would start blocking.
const RequestBufferSize = 1 << 17
type Executer interface {
Execute() (interface{}, error)
}
type ExecuterFunc func() (interface{}, error)
func (b ExecuterFunc) Execute() (interface{}, error) {
return b()
}
type Tracker interface {
// Batched is called when a request is added to an existing batch.
Batched()
}
type DelayFn func(dur time.Duration)
type Batcher interface {
BatchFor(ctx context.Context, key string, dur time.Duration, exec Executer) (interface{}, error)
}
type NoOpBatchingExecutor struct{}
// contextKey used to keep values on context.Context
type contextKey string
// SkipBatchContextKey existence on a context will eliminate the request batching
const SkipBatchContextKey contextKey = "skip_batch"
func (n *NoOpBatchingExecutor) BatchFor(_ context.Context, _ string, _ time.Duration, exec Executer) (interface{}, error) {
return exec.Execute()
}
// ConditionalExecutor will batch requests only if SkipBatchContextKey is not on the context
// of the batch request.
type ConditionalExecutor struct {
executor *Executor
}
func NewConditionalExecutor(logger logging.Logger) *ConditionalExecutor {
return &ConditionalExecutor{executor: NewExecutor(logger)}
}
func (c *ConditionalExecutor) Run(ctx context.Context) {
c.executor.Run(ctx)
}
func (c *ConditionalExecutor) BatchFor(ctx context.Context, key string, timeout time.Duration, exec Executer) (interface{}, error) {
if ctx.Value(SkipBatchContextKey) != nil {
return exec.Execute()
}
return c.executor.BatchFor(ctx, key, timeout, exec)
}
type response struct {
v interface{}
err error
}
type request struct {
key string
timeout time.Duration
exec Executer
onResponse chan *response
}
type Executor struct {
// requests is the channel accepting inbound requests
requests chan *request
// execs is the internal channel used to dispatch the callback functions.
// Several requests with the same key in a given duration will trigger a single write to exec said key.
execs chan string
waitingOnKey map[string][]*request
Logger logging.Logger
Delay DelayFn
}
func NopExecutor() *NoOpBatchingExecutor {
return &NoOpBatchingExecutor{}
}
func NewExecutor(logger logging.Logger) *Executor {
return &Executor{
requests: make(chan *request, RequestBufferSize),
execs: make(chan string, RequestBufferSize),
waitingOnKey: make(map[string][]*request),
Logger: logger,
Delay: time.Sleep,
}
}
func (e *Executor) BatchFor(_ context.Context, key string, timeout time.Duration, exec Executer) (interface{}, error) {
cb := make(chan *response)
e.requests <- &request{
key: key,
timeout: timeout,
exec: exec,
onResponse: cb,
}
res := <-cb
return res.v, res.err
}
func (e *Executor) Run(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case req := <-e.requests:
// see if we have it scheduled already
if _, exists := e.waitingOnKey[req.key]; !exists {
e.waitingOnKey[req.key] = []*request{req}
// this is a new key, let's fire a timer for it
go func(req *request) {
e.Delay(req.timeout)
e.execs <- req.key
}(req)
} else {
if b, ok := req.exec.(Tracker); ok {
b.Batched()
}
e.waitingOnKey[req.key] = append(e.waitingOnKey[req.key], req)
}
case execKey := <-e.execs:
// let's take all callbacks
waiters := e.waitingOnKey[execKey]
delete(e.waitingOnKey, execKey)
go func(key string) {
// execute and call all mapped callbacks
v, err := waiters[0].exec.Execute()
if e.Logger.IsTracing() {
e.Logger.WithFields(logging.Fields{
"waiters": len(waiters),
"key": key,
}).Trace("dispatched execute result")
}
for _, waiter := range waiters {
waiter.onResponse <- &response{v, err}
}
}(execKey)
}
}
}