minor improvements

This commit is contained in:
crapStone 2024-04-27 22:13:02 +02:00 committed by crapStone
parent 7071ee9bff
commit acd02709c7
2 changed files with 14 additions and 32 deletions

View file

@ -5,19 +5,14 @@ import (
"strings"
"time"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/hashicorp/golang-lru/v2/expirable"
)
type lookupCacheEntry struct {
cachedName string
timestamp time.Time
}
const lookupCacheValidity = 30 * time.Second
const defaultPagesRepo = "pages"
var lookupCacheValidity = 30 * time.Second
var lookupCache *lru.Cache[string, lookupCacheEntry]
var defaultPagesRepo = "pages"
// TODO(): refactor to not use global variables
var lookupCache *expirable.LRU[string, string] = expirable.NewLRU[string, string](4096, nil, lookupCacheValidity)
// GetTargetFromDNS searches for CNAME or TXT entries on the request domain ending with MainDomainSuffix.
// If everything is fine, it returns the target data.
@ -26,14 +21,8 @@ func GetTargetFromDNS(domain, mainDomainSuffix, firstDefaultBranch string) (targ
var cname string
var err error
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
if entry, ok := lookupCache.Get(domain); ok {
cname = entry
} else {
cname, err = net.LookupCNAME(domain)
cname = strings.TrimSuffix(cname, ".")
@ -51,10 +40,7 @@ func GetTargetFromDNS(domain, mainDomainSuffix, firstDefaultBranch string) (targ
}
}
}
_ = lookupCache.Add(domain, lookupCacheEntry{
cname,
time.Now(),
})
_ = lookupCache.Add(domain, cname)
}
if cname == "" {
return