Use hashicorp's LRU cache for DNS & certificates

DNS caching is also limited to 30 seconds now instead of 5 minutes
This commit is contained in:
Moritz Marquardt 2024-04-16 22:22:09 +02:00 committed by crapStone
parent eb08c46dcd
commit 7071ee9bff
8 changed files with 50 additions and 24 deletions

View file

@ -5,22 +5,35 @@ import (
"strings"
"time"
"codeberg.org/codeberg/pages/server/cache"
lru "github.com/hashicorp/golang-lru/v2"
)
// lookupCacheTimeout specifies the timeout for the DNS lookup cache.
var lookupCacheTimeout = 15 * time.Minute
type lookupCacheEntry struct {
cachedName string
timestamp time.Time
}
var lookupCacheValidity = 30 * time.Second
var lookupCache *lru.Cache[string, lookupCacheEntry]
var defaultPagesRepo = "pages"
// GetTargetFromDNS searches for CNAME or TXT entries on the request domain ending with MainDomainSuffix.
// If everything is fine, it returns the target data.
func GetTargetFromDNS(domain, mainDomainSuffix, firstDefaultBranch string, dnsLookupCache cache.ICache) (targetOwner, targetRepo, targetBranch string) {
func GetTargetFromDNS(domain, mainDomainSuffix, firstDefaultBranch string) (targetOwner, targetRepo, targetBranch string) {
// Get CNAME or TXT
var cname string
var err error
if cachedName, ok := dnsLookupCache.Get(domain); ok {
cname = cachedName.(string)
if lookupCache == nil {
lookupCache, err = lru.New[string, lookupCacheEntry](4096)
if err != nil {
panic(err) // This should only happen if 4096 < 0 at the time of writing, which should be reason enough to panic.
}
}
if entry, ok := lookupCache.Get(domain); ok && time.Now().Before(entry.timestamp.Add(lookupCacheValidity)) {
cname = entry.cachedName
} else {
cname, err = net.LookupCNAME(domain)
cname = strings.TrimSuffix(cname, ".")
@ -38,7 +51,10 @@ func GetTargetFromDNS(domain, mainDomainSuffix, firstDefaultBranch string, dnsLo
}
}
}
_ = dnsLookupCache.Set(domain, cname, lookupCacheTimeout)
_ = lookupCache.Add(domain, lookupCacheEntry{
cname,
time.Now(),
})
}
if cname == "" {
return