-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathconfig.go
More file actions
86 lines (72 loc) · 1.97 KB
/
config.go
File metadata and controls
86 lines (72 loc) · 1.97 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
package github_primary_ratelimit
import "context"
// Config is the configuration for the rate limiter.
// It is used internally and generated from the options.
// It holds the state of the rate limiter in order to enable state sharing.
type Config struct {
state *RateLimitState
bypassLimit bool
resetOnSuccess bool
// callbacks
onLimitReached OnLimitReached
onReuqestPrevented OnRequestPrevented
onLimitReset OnLimitReset
onUnknownCategory OnUnknownCategory
}
// newConfig creates a new config with the given options.
func newConfig(opts ...Option) *Config {
var config Config
config.ApplyOptions(opts...)
if config.state == nil {
config.state = NewRateLimitState(GetAllCategories())
}
return &config
}
// ApplyOptions applies the options to the config.
func (c *Config) ApplyOptions(opts ...Option) {
for _, o := range opts {
if o == nil {
continue
}
o(c)
}
}
type ConfigOverridesKey struct{}
// WithOverrideConfig adds config overrides to the context.
// The overrides are applied on top of the existing config.
// Allows for request-specific overrides.
func WithOverrideConfig(ctx context.Context, opts ...Option) context.Context {
return context.WithValue(ctx, ConfigOverridesKey{}, opts)
}
// GetConfigOverrides returns the config overrides from the context, if any.
func GetConfigOverrides(ctx context.Context) []Option {
cfg := ctx.Value(ConfigOverridesKey{})
if cfg == nil {
return nil
}
return cfg.([]Option)
}
func (c *Config) TriggerLimitReached(ctx *CallbackContext) {
if c.onLimitReached == nil {
return
}
c.onLimitReached(ctx)
}
func (c *Config) TriggerRequestPrevented(ctx *CallbackContext) {
if c.onReuqestPrevented == nil {
return
}
c.onReuqestPrevented(ctx)
}
func (c *Config) TriggerLimitReset(ctx *CallbackContext) {
if c.onLimitReset == nil {
return
}
c.onLimitReset(ctx)
}
func (c *Config) TriggerUnknownCategory(ctx *CallbackContext) {
if c.onUnknownCategory == nil {
return
}
c.onUnknownCategory(ctx)
}