-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththrottler.go
68 lines (55 loc) · 1.35 KB
/
throttler.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
package throttler
import (
"context"
"errors"
"fmt"
"time"
"golang.org/x/sync/semaphore"
)
// Option is a function that configures a Trottler.
type Option func(*Throttler)
// WithTimeout sets the timeout for requests to rate limiter.
// default is 0. 0 means no timeout.
func WithTimeout(timeout time.Duration) Option {
return func(t *Throttler) {
t.timeout = timeout
}
}
// Throttler implements back pressure pattern.
type Throttler struct {
sem *semaphore.Weighted
timeout time.Duration
}
// New creates a new Trottler instance.
func New(maxConcurrency int, opt ...Option) (*Throttler, error) {
if maxConcurrency <= 0 {
return nil, errors.New("maxConcurrency must be positive")
}
t := &Throttler{
sem: semaphore.NewWeighted(int64(maxConcurrency)),
}
for _, o := range opt {
o(t)
}
if t.timeout < 0 {
return nil, errors.New("timeout must be positive")
}
return t, nil
}
// Execute will be the core method controlling request flow.
func (t *Throttler) Execute(
ctx context.Context,
operation func(ctx context.Context) error,
) error {
ctxOp := ctx
if t.timeout > 0 {
var cancel context.CancelFunc
ctxOp, cancel = context.WithTimeout(ctx, t.timeout)
defer cancel()
}
if err := t.sem.Acquire(ctxOp, 1); err != nil {
return fmt.Errorf("failed to acquire semaphore: %w", err)
}
defer t.sem.Release(1)
return operation(ctxOp)
}