-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy paththrottler.go
More file actions
154 lines (139 loc) · 3.91 KB
/
throttler.go
File metadata and controls
154 lines (139 loc) · 3.91 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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package bandwidthlimiter
import (
"errors"
"fmt"
"io"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/aws/aws-lambda-runtime-interface-emulator/internal/lambda/interop"
"github.com/aws/aws-lambda-runtime-interface-emulator/internal/lambda/metering"
)
var ErrBufferSizeTooLarge = errors.New("buffer size cannot be greater than bucket size")
func NewBucket(capacity int64, initialTokenCount int64, refillNumber int64, refillInterval time.Duration) (*Bucket, error) {
if capacity <= 0 || initialTokenCount < 0 || refillNumber <= 0 || refillInterval <= 0 ||
capacity < initialTokenCount {
errorMsg := fmt.Sprintf("invalid bucket parameters (capacity: %d, initialTokenCount: %d, refillNumber: %d,"+
"refillInterval: %d)", capacity, initialTokenCount, refillInterval, refillInterval)
log.Error(errorMsg)
return nil, errors.New(errorMsg)
}
return &Bucket{
capacity: capacity,
tokenCount: initialTokenCount,
refillNumber: refillNumber,
refillInterval: refillInterval,
mutex: sync.Mutex{},
}, nil
}
type Bucket struct {
capacity int64
tokenCount int64
refillNumber int64
refillInterval time.Duration
mutex sync.Mutex
}
func (b *Bucket) produceTokens() {
b.mutex.Lock()
defer b.mutex.Unlock()
if b.tokenCount < b.capacity {
b.tokenCount = min64(b.tokenCount+b.refillNumber, b.capacity)
}
}
func (b *Bucket) consumeTokens(n int64) bool {
b.mutex.Lock()
defer b.mutex.Unlock()
if n <= b.tokenCount {
b.tokenCount -= n
return true
}
return false
}
func (b *Bucket) getTokenCount() int64 {
b.mutex.Lock()
defer b.mutex.Unlock()
return b.tokenCount
}
func NewThrottler(bucket *Bucket) (*Throttler, error) {
if bucket == nil {
errorMsg := "cannot create a throttler with nil bucket"
log.Error(errorMsg)
return nil, errors.New(errorMsg)
}
return &Throttler{
b: bucket,
running: false,
produced: make(chan int64),
done: make(chan struct{}),
// FIXME:
// The runtime tells whether the function response mode is streaming or not.
// Ideally, we would want to use that value here. Since I'm just rebasing, I will leave
// as-is, but we should use that instead of relying on our memory to set this here
// because we "know" it's a streaming code path.
metrics: &interop.InvokeResponseMetrics{FunctionResponseMode: interop.FunctionResponseModeStreaming},
}, nil
}
type Throttler struct {
b *Bucket
running bool
produced chan int64
done chan struct{}
metrics *interop.InvokeResponseMetrics
}
func (th *Throttler) start() {
if th.running {
return
}
th.running = true
th.metrics.StartReadingResponseMonoTimeMs = metering.Monotime()
go func() {
ticker := time.NewTicker(th.b.refillInterval)
for {
select {
case <-ticker.C:
th.b.produceTokens()
select {
case th.produced <- metering.Monotime():
default:
}
case <-th.done:
ticker.Stop()
return
}
}
}()
}
func (th *Throttler) stop() {
if !th.running {
return
}
th.running = false
th.metrics.FinishReadingResponseMonoTimeMs = metering.Monotime()
durationMs := (th.metrics.FinishReadingResponseMonoTimeMs - th.metrics.StartReadingResponseMonoTimeMs) / int64(time.Millisecond)
if durationMs > 0 {
th.metrics.OutboundThroughputBps = (th.metrics.ProducedBytes / durationMs) * int64(time.Second/time.Millisecond)
} else {
th.metrics.OutboundThroughputBps = -1
}
th.done <- struct{}{}
}
func (th *Throttler) bandwidthLimitingWrite(w io.Writer, p []byte) (written int, err error) {
n := int64(len(p))
if n > th.b.capacity {
return 0, ErrBufferSizeTooLarge
}
for {
if th.b.consumeTokens(n) {
written, err = w.Write(p)
th.metrics.ProducedBytes += int64(written)
return
}
waitStart := metering.Monotime()
elapsed := <-th.produced - waitStart
if elapsed > 0 {
th.metrics.TimeShapedNs += elapsed
}
}
}