Source File
quota.go
Belonging Package
golang.org/x/pkgsite/internal/middleware
package middleware
import (
rrate
)
var (
keyQuotaBlocked = tag.MustNewKey("quota.blocked")
quotaResults = stats.Int64(
"go-discovery/quota_result_count",
"The result of a quota check.",
stats.UnitDimensionless,
QuotaResultCount = &view.View{
Name: "go-discovery/quota/result_count",
Measure: quotaResults,
Aggregation: view.Count(),
Description: "quota results, by blocked or allowed",
TagKeys: []tag.Key{keyQuotaBlocked},
}
)
func ( context.Context, string) {
stats.RecordWithTags(, []tag.Mutator{
tag.Upsert(keyQuotaBlocked, ),
}, quotaResults.M(1))
}
func ( string) string {
func ( config.QuotaSettings, *redis.Client) Middleware {
return func( http.Handler) http.Handler {
return http.HandlerFunc(func( http.ResponseWriter, *http.Request) {
:= .Context()
if !.Enable {
recordQuotaMetric(, "disabled")
.ServeHTTP(, )
return
}
:= .Header.Get(config.BypassQuotaAuthHeader)
for , := range .AuthValues {
if == {
recordQuotaMetric(, "bypassed")
log.Infof(, "Quota: accepting %q", )
.ServeHTTP(, )
return
}
}
:= .Header.Get("X-Godoc-Forwarded-For")
if == "" {
= .Header.Get("X-Forwarded-For")
}
, := enforceQuota(, , .QPS, , .HMACKey)
recordQuotaMetric(, )
if && .RecordOnly != nil && !*.RecordOnly {
const = http.StatusTooManyRequests
http.Error(, http.StatusText(), )
return
}
.ServeHTTP(, )
})
}
}
if == "" {
return false, "no header"
}
:= ipKey()
if == "" {
return false, "bad header"
}
:= hmac.New(sha256.New, )
io.WriteString(, )
:= string(.Sum(nil))
, := rrate.NewLimiter(.WithTimeout(15*time.Millisecond)).Allow(, , rrate.PerSecond())
if != nil {
var *net.OpError
if errors.Is(, context.DeadlineExceeded) || (errors.As(, &) && .Timeout()) {
log.Warningf(, "quota: redis limiter: %v", )
return false, "timeout"
}
log.Errorf(, "quota: redis limiter: %v", )
return false, "error"
}
if .Allowed > 0 {
return false, "allowed"
}
return true, "blocked"
![]() |
The pages are generated with Golds v0.3.2-preview. (GOOS=darwin GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |