autoresearch iter 32: PERF whitelist parses patterns once, 14 allocs/op to 1

This commit is contained in:
ryan
2026-08-29 19:03:27 +08:00
parent 22a491ff37
commit f7a86d3608
4 changed files with 283 additions and 54 deletions
+5 -16
View File
@@ -13,33 +13,22 @@ import (
"crypto/sha256"
"encoding/hex"
"errors"
"sync"
"github.com/gin-gonic/gin"
)
var (
whitelistMu sync.RWMutex
whitelist []string
)
// whitelist holds the no-auth route patterns. They are registered during Apply and
// matched on every request, so PathWhitelist parses them once up front.
var whitelist = extpoints.NewPathWhitelist()
// RegisterWhitelist registers route patterns that bypass mandatory authentication.
func RegisterWhitelist(patterns ...string) {
whitelistMu.Lock()
defer whitelistMu.Unlock()
whitelist = append(whitelist, patterns...)
whitelist.Add(patterns...)
}
// IsWhitelisted checks if the specified path matches the auth whitelist.
func IsWhitelisted(path string) bool {
whitelistMu.RLock()
defer whitelistMu.RUnlock()
for _, pattern := range whitelist {
if extpoints.MatchPathPattern(pattern, path) {
return true
}
}
return false
return whitelist.Match(path)
}
func hashToken(token string) string {
@@ -25,29 +25,20 @@ import (
var (
apiPrefixMu sync.RWMutex
apiPrefix = "/api/v1"
whitelistMu sync.RWMutex
whitelistPatterns []string
)
// whitelist holds the global no-auth HTTP patterns. They are set once at
// configuration time and matched per request, so PathWhitelist parses them up front.
var whitelist = extpoints.NewPathWhitelist()
// SetWhitelist configures global whitelist patterns for HTTP routes.
func SetWhitelist(patterns []string) {
whitelistMu.Lock()
defer whitelistMu.Unlock()
whitelistPatterns = make([]string, len(patterns))
copy(whitelistPatterns, patterns)
whitelist.Replace(patterns...)
}
// IsPathWhitelisted checks if the given path matches any registered whitelist pattern.
func IsPathWhitelisted(path string) bool {
whitelistMu.RLock()
defer whitelistMu.RUnlock()
for _, pattern := range whitelistPatterns {
if extpoints.MatchPathPattern(pattern, path) {
return true
}
}
return false
return whitelist.Match(path)
}
func setAPIPrefix(prefix string) {