MCPcopy Create free account
hub / github.com/cloud-native-go/examples / Throttle

Function Throttle

ch04/throttle.go:28–73  ·  view source on GitHub ↗
(e Effector, max uint, refill uint, d time.Duration)

Source from the content-addressed store, hash-verified

26type Effector func(context.Context) (string, error)
27
28func Throttle(e Effector, max uint, refill uint, d time.Duration) Effector {
29 var tokens = max
30 var once sync.Once
31 var m sync.Mutex
32
33 return func(ctx context.Context) (string, error) {
34 if ctx.Err() != nil {
35 return "", ctx.Err()
36 }
37
38 once.Do(func() {
39 ticker := time.NewTicker(d)
40
41 go func() {
42 defer ticker.Stop()
43
44 for {
45 select {
46 case <-ctx.Done():
47 return
48
49 case <-ticker.C:
50 m.Lock()
51 t := tokens + refill
52 if t > max {
53 t = max
54 }
55 tokens = t
56 m.Unlock()
57 }
58 }
59 }()
60 })
61
62 m.Lock()
63 defer m.Unlock()
64
65 if tokens <= 0 {
66 return "", fmt.Errorf("too many calls")
67 }
68
69 tokens--
70
71 return e(ctx)
72 }
73}

Callers 5

TestThrottleMax1Function · 0.70
TestThrottleMax10Function · 0.70

Calls 1

ErrMethod · 0.65

Tested by 5

TestThrottleMax1Function · 0.56
TestThrottleMax10Function · 0.56