-
Notifications
You must be signed in to change notification settings - Fork 0
/
capacity_landingrate.go
95 lines (79 loc) · 2.49 KB
/
capacity_landingrate.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
// SPDX-FileCopyrightText: © 2024 Kevin Conway
// SPDX-FileCopyrightText: © 2017 Atlassian Pty Ltd
// SPDX-License-Identifier: Apache-2.0
package loadshed
import (
"context"
"time"
"github.com/kevinconway/rolling/v3"
)
type OptionLandingRate func(*CapacityLandingRate)
func OptionLandingRateWindowBuckets(count int) OptionLandingRate {
return func(clr *CapacityLandingRate) {
clr.buckets = count
}
}
func OptionLandingRateBucketDuration(d time.Duration) OptionLandingRate {
return func(clr *CapacityLandingRate) {
clr.bucketDuration = d
}
}
func OptionLandingRateBucketSizeHint(size int) OptionLandingRate {
return func(clr *CapacityLandingRate) {
clr.bucketSizeHint = size
}
}
func OptionLandingrateName(name string) OptionLandingRate {
return func(clr *CapacityLandingRate) {
clr.name = name
}
}
// CapacityLandingRate considers the number of method invocations within a window of
// time that have begun. Note that this counts all attempts to invoke a method
// and does not distinguish success or failure.
//
// The rate calculation is based on a rolling window. The default size of the
// window is 1s with each bucket representing 10ms. Both of these values can
// be modified using constructor options.
type CapacityLandingRate struct {
name string
invocations landingRateWindow
limit int
buckets int
bucketDuration time.Duration
bucketSizeHint int
}
func NewCapacityLandingRate(limit int, options ...OptionLandingRate) *CapacityLandingRate {
c := &CapacityLandingRate{
name: defaultNameLandingRate,
limit: limit,
buckets: 100,
bucketDuration: 10 * time.Millisecond,
bucketSizeHint: 0,
}
for _, opt := range options {
opt(c)
}
w := rolling.NewPreallocatedWindow[int](c.buckets, c.bucketSizeHint)
c.invocations = rolling.NewTimePolicyConcurrent[int](w, c.bucketDuration)
return c
}
func (self *CapacityLandingRate) Name(context.Context) string {
return self.name
}
func (self *CapacityLandingRate) Usage(ctx context.Context) float32 {
total := self.invocations.Reduce(ctx, rolling.Count[int])
return float32(float64(total) / float64(self.limit))
}
func (self *CapacityLandingRate) Wrap(fn Fn) Fn {
return func(ctx context.Context) error {
self.invocations.Append(ctx, 1)
return fn(ctx)
}
}
type landingRateWindow interface {
Append(ctx context.Context, v int)
Reduce(ctx context.Context, r rolling.Reduction[int]) int
}
const defaultNameLandingRate string = "LANDING RATE"
var _ Capacity = &CapacityLandingRate{}