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
parent 7694deec83
commit 18d09a163c
8 changed files with 49 additions and 36 deletions

View file

@ -1,26 +1,38 @@
package dns
import (
"github.com/hashicorp/golang-lru/v2"
"net"
"strings"
"time"
"github.com/OrlovEvgeny/go-mcache"
)
// 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 *mcache.CacheDriver) (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 +50,10 @@ func GetTargetFromDNS(domain, mainDomainSuffix, firstDefaultBranch string, dnsLo
}
}
}
_ = dnsLookupCache.Set(domain, cname, lookupCacheTimeout)
_ = lookupCache.Add(domain, lookupCacheEntry{
cname,
time.Now(),
})
}
if cname == "" {
return