/
matcher.go
428 lines (395 loc) · 13.6 KB
/
matcher.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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package matching
import (
"context"
"errors"
"time"
"golang.org/x/time/rate"
"github.com/uber/cadence/common/metrics"
"github.com/uber/cadence/common/quotas"
"github.com/uber/cadence/common/types"
)
// TaskMatcher matches a task producer with a task consumer
// Producers are usually rpc calls from history or taskReader
// that drains backlog from db. Consumers are the task list pollers
type TaskMatcher struct {
// synchronous task channel to match producer/consumer
taskC chan *internalTask
// synchronous task channel to match query task - the reason to have
// separate channel for this is because there are cases when consumers
// are interested in queryTasks but not others. Example is when domain is
// not active in a cluster
queryTaskC chan *internalTask
// ratelimiter that limits the rate at which tasks can be dispatched to consumers
limiter *quotas.RateLimiter
fwdr *Forwarder
scope func() metrics.Scope // domain metric scope
numPartitions func() int // number of task list partitions
}
const (
_defaultTaskDispatchRPS = 100000.0
_defaultTaskDispatchRPSTTL = 60 * time.Second
)
var errTasklistThrottled = errors.New("cannot add to tasklist, limit exceeded")
// newTaskMatcher returns an task matcher instance. The returned instance can be
// used by task producers and consumers to find a match. Both sync matches and non-sync
// matches should use this implementation
func newTaskMatcher(config *taskListConfig, fwdr *Forwarder, scopeFunc func() metrics.Scope) *TaskMatcher {
dPtr := _defaultTaskDispatchRPS
limiter := quotas.NewRateLimiter(&dPtr, _defaultTaskDispatchRPSTTL, config.MinTaskThrottlingBurstSize())
return &TaskMatcher{
limiter: limiter,
scope: scopeFunc,
fwdr: fwdr,
taskC: make(chan *internalTask),
queryTaskC: make(chan *internalTask),
numPartitions: config.NumReadPartitions,
}
}
// Offer offers a task to a potential consumer (poller)
// If the task is successfully matched with a consumer, this
// method will return true and no error. If the task is matched
// but consumer returned error, then this method will return
// true and error message. This method should not be used for query
// task. This method should ONLY be used for sync match.
//
// When a local poller is not available and forwarding to a parent
// task list partition is possible, this method will attempt forwarding
// to the parent partition.
//
// Cases when this method will block:
//
// Ratelimit:
// When a ratelimit token is not available, this method might block
// waiting for a token until the provided context timeout. Rate limits are
// not enforced for forwarded tasks from child partition.
//
// Forwarded tasks that originated from db backlog:
// When this method is called with a task that is forwarded from a
// remote partition and if (1) this task list is root (2) task
// was from db backlog - this method will block until context timeout
// trying to match with a poller. The caller is expected to set the
// correct context timeout.
//
// returns error when:
// - ratelimit is exceeded (does not apply to query task)
// - context deadline is exceeded
// - task is matched and consumer returns error in response channel
func (tm *TaskMatcher) Offer(ctx context.Context, task *internalTask) (bool, error) {
var err error
var rsv *rate.Reservation
if !task.isForwarded() {
rsv, err = tm.ratelimit(ctx)
if err != nil {
tm.scope().IncCounter(metrics.SyncThrottlePerTaskListCounter)
return false, err
}
}
select {
case tm.taskC <- task: // poller picked up the task
if task.responseC != nil {
// if there is a response channel, block until resp is received
// and return error if the response contains error
err = <-task.responseC
return true, err
}
return false, nil
default:
// no poller waiting for tasks, try forwarding this task to the
// root partition if possible
select {
case token := <-tm.fwdrAddReqTokenC():
if err := tm.fwdr.ForwardTask(ctx, task); err == nil {
// task was remotely sync matched on the parent partition
token.release()
return true, nil
}
token.release()
default:
if !tm.isForwardingAllowed() && // we are the root partition and forwarding is not possible
task.source == types.TaskSourceDbBacklog && // task was from backlog (stored in db)
task.isForwarded() { // task came from a child partition
// a forwarded backlog task from a child partition, block trying
// to match with a poller until ctx timeout
return tm.offerOrTimeout(ctx, task)
}
}
if rsv != nil {
// there was a ratelimit token we consumed
// return it since we did not really do any work
rsv.Cancel()
}
return false, nil
}
}
func (tm *TaskMatcher) offerOrTimeout(ctx context.Context, task *internalTask) (bool, error) {
select {
case tm.taskC <- task: // poller picked up the task
if task.responseC != nil {
select {
case err := <-task.responseC:
return true, err
case <-ctx.Done():
return false, nil
}
}
return false, nil
case <-ctx.Done():
return false, nil
}
}
// OfferQuery will either match task to local poller or will forward query task.
// Local match is always attempted before forwarding is attempted. If local match occurs
// response and error are both nil, if forwarding occurs then response or error is returned.
func (tm *TaskMatcher) OfferQuery(ctx context.Context, task *internalTask) (*types.QueryWorkflowResponse, error) {
select {
case tm.queryTaskC <- task:
<-task.responseC
return nil, nil
default:
}
fwdrTokenC := tm.fwdrAddReqTokenC()
for {
select {
case tm.queryTaskC <- task:
<-task.responseC
return nil, nil
case token := <-fwdrTokenC:
resp, err := tm.fwdr.ForwardQueryTask(ctx, task)
token.release()
if err == nil {
return resp, nil
}
if err == errForwarderSlowDown {
// if we are rate limited, try only local match for the
// remainder of the context timeout left
fwdrTokenC = noopForwarderTokenC
continue
}
return nil, err
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
// MustOffer blocks until a consumer is found to handle this task
// Returns error only when context is canceled or the ratelimit is set to zero (allow nothing)
// The passed in context MUST NOT have a deadline associated with it
func (tm *TaskMatcher) MustOffer(ctx context.Context, task *internalTask) error {
if _, err := tm.ratelimit(ctx); err != nil {
return err
}
// attempt a match with local poller first. When that
// doesn't succeed, try both local match and remote match
select {
case tm.taskC <- task:
return nil
case <-ctx.Done():
return ctx.Err()
default:
}
forLoop:
for {
select {
case tm.taskC <- task:
return nil
case token := <-tm.fwdrAddReqTokenC():
childCtx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second*2))
err := tm.fwdr.ForwardTask(childCtx, task)
token.release()
if err != nil {
// forwarder returns error only when the call is rate limited. To
// avoid a busy loop on such rate limiting events, we only attempt to make
// the next forwarded call after this childCtx expires. Till then, we block
// hoping for a local poller match
select {
case tm.taskC <- task:
cancel()
return nil
case <-childCtx.Done():
case <-ctx.Done():
cancel()
return ctx.Err()
}
cancel()
continue forLoop
}
cancel()
// at this point, we forwarded the task to a parent partition which
// in turn dispatched the task to a poller. Make sure we delete the
// task from the database
task.finish(nil)
return nil
case <-ctx.Done():
return ctx.Err()
}
}
}
// Poll blocks until a task is found or context deadline is exceeded
// On success, the returned task could be a query task or a regular task
// Returns ErrNoTasks when context deadline is exceeded
func (tm *TaskMatcher) Poll(ctx context.Context) (*internalTask, error) {
// try local match first without blocking until context timeout
if task, err := tm.pollNonBlocking(ctx, tm.taskC, tm.queryTaskC); err == nil {
return task, nil
}
// there is no local poller available to pickup this task. Now block waiting
// either for a local poller or a forwarding token to be available. When a
// forwarding token becomes available, send this poll to a parent partition
return tm.pollOrForward(ctx, tm.taskC, tm.queryTaskC)
}
// PollForQuery blocks until a *query* task is found or context deadline is exceeded
// Returns ErrNoTasks when context deadline is exceeded
func (tm *TaskMatcher) PollForQuery(ctx context.Context) (*internalTask, error) {
// try local match first without blocking until context timeout
if task, err := tm.pollNonBlocking(ctx, nil, tm.queryTaskC); err == nil {
return task, nil
}
// there is no local poller available to pickup this task. Now block waiting
// either for a local poller or a forwarding token to be available. When a
// forwarding token becomes available, send this poll to a parent partition
return tm.pollOrForward(ctx, nil, tm.queryTaskC)
}
// UpdateRatelimit updates the task dispatch rate
func (tm *TaskMatcher) UpdateRatelimit(rps *float64) {
if rps == nil {
return
}
rate := *rps
nPartitions := tm.numPartitions()
if rate > float64(nPartitions) {
// divide the rate equally across all partitions
rate = rate / float64(tm.numPartitions())
}
tm.limiter.UpdateMaxDispatch(&rate)
}
// Rate returns the current rate at which tasks are dispatched
func (tm *TaskMatcher) Rate() float64 {
return tm.limiter.Limit()
}
func (tm *TaskMatcher) pollOrForward(
ctx context.Context,
taskC <-chan *internalTask,
queryTaskC <-chan *internalTask,
) (*internalTask, error) {
select {
case task := <-taskC:
if task.responseC != nil {
tm.scope().IncCounter(metrics.PollSuccessWithSyncPerTaskListCounter)
}
tm.scope().IncCounter(metrics.PollSuccessPerTaskListCounter)
return task, nil
case task := <-queryTaskC:
tm.scope().IncCounter(metrics.PollSuccessWithSyncPerTaskListCounter)
tm.scope().IncCounter(metrics.PollSuccessPerTaskListCounter)
return task, nil
case <-ctx.Done():
tm.scope().IncCounter(metrics.PollTimeoutPerTaskListCounter)
return nil, ErrNoTasks
case token := <-tm.fwdrPollReqTokenC():
if task, err := tm.fwdr.ForwardPoll(ctx); err == nil {
token.release()
return task, nil
}
token.release()
return tm.poll(ctx, taskC, queryTaskC)
}
}
func (tm *TaskMatcher) poll(
ctx context.Context,
taskC <-chan *internalTask,
queryTaskC <-chan *internalTask,
) (*internalTask, error) {
select {
case task := <-taskC:
if task.responseC != nil {
tm.scope().IncCounter(metrics.PollSuccessWithSyncPerTaskListCounter)
}
tm.scope().IncCounter(metrics.PollSuccessPerTaskListCounter)
return task, nil
case task := <-queryTaskC:
tm.scope().IncCounter(metrics.PollSuccessWithSyncPerTaskListCounter)
tm.scope().IncCounter(metrics.PollSuccessPerTaskListCounter)
return task, nil
case <-ctx.Done():
tm.scope().IncCounter(metrics.PollTimeoutPerTaskListCounter)
return nil, ErrNoTasks
}
}
func (tm *TaskMatcher) pollNonBlocking(
ctx context.Context,
taskC <-chan *internalTask,
queryTaskC <-chan *internalTask,
) (*internalTask, error) {
select {
case task := <-taskC:
if task.responseC != nil {
tm.scope().IncCounter(metrics.PollSuccessWithSyncPerTaskListCounter)
}
tm.scope().IncCounter(metrics.PollSuccessPerTaskListCounter)
return task, nil
case task := <-queryTaskC:
tm.scope().IncCounter(metrics.PollSuccessWithSyncPerTaskListCounter)
tm.scope().IncCounter(metrics.PollSuccessPerTaskListCounter)
return task, nil
default:
return nil, ErrNoTasks
}
}
func (tm *TaskMatcher) fwdrPollReqTokenC() <-chan *ForwarderReqToken {
if tm.fwdr == nil {
return noopForwarderTokenC
}
return tm.fwdr.PollReqTokenC()
}
func (tm *TaskMatcher) fwdrAddReqTokenC() <-chan *ForwarderReqToken {
if tm.fwdr == nil {
return noopForwarderTokenC
}
return tm.fwdr.AddReqTokenC()
}
func (tm *TaskMatcher) ratelimit(ctx context.Context) (*rate.Reservation, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
deadline, ok := ctx.Deadline()
if !ok {
if err := tm.limiter.Wait(ctx); err != nil {
return nil, err
}
return nil, nil
}
rsv := tm.limiter.Reserve()
// If we have to wait too long for reservation, give up and return
if !rsv.OK() || rsv.Delay() > deadline.Sub(time.Now()) {
if rsv.OK() { // if we were indeed given a reservation, return it before we bail out
rsv.Cancel()
}
return nil, errTasklistThrottled
}
time.Sleep(rsv.Delay())
return rsv, nil
}
func (tm *TaskMatcher) isForwardingAllowed() bool {
return tm.fwdr != nil
}