80 lines
1.6 KiB
Go
80 lines
1.6 KiB
Go
package cache
|
|
|
|
import "sync"
|
|
|
|
// DNSCache is a simple in-memory cache for DNS records
|
|
type DNSCache struct {
|
|
mu sync.RWMutex
|
|
cache map[string]string // key: "fqdn:provider" -> value: IP
|
|
}
|
|
|
|
var globalCache *DNSCache
|
|
|
|
func init() {
|
|
globalCache = &DNSCache{
|
|
cache: make(map[string]string),
|
|
}
|
|
}
|
|
|
|
// GetCache returns the global cache instance
|
|
func GetCache() *DNSCache {
|
|
return globalCache
|
|
}
|
|
|
|
// makeKey creates a unique cache key from FQDN and provider
|
|
func (c *DNSCache) makeKey(fqdn, provider string) string {
|
|
return fqdn + ":" + provider
|
|
}
|
|
|
|
// NeedsUpdate checks if the record needs updating
|
|
// Returns true if IP is different or not in cache
|
|
func (c *DNSCache) NeedsUpdate(fqdn, provider, newIP string) bool {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
|
|
key := c.makeKey(fqdn, provider)
|
|
cachedIP, exists := c.cache[key]
|
|
|
|
if !exists {
|
|
return true // Not in cache, needs update
|
|
}
|
|
|
|
return cachedIP != newIP // Update if IP changed
|
|
}
|
|
|
|
// Set updates the cache with the new IP
|
|
func (c *DNSCache) Set(fqdn, provider, ip string) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
key := c.makeKey(fqdn, provider)
|
|
c.cache[key] = ip
|
|
}
|
|
|
|
// Get retrieves the cached IP
|
|
func (c *DNSCache) Get(fqdn, provider string) (string, bool) {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
|
|
key := c.makeKey(fqdn, provider)
|
|
ip, exists := c.cache[key]
|
|
return ip, exists
|
|
}
|
|
|
|
// Clear removes a specific entry from cache
|
|
func (c *DNSCache) Clear(fqdn, provider string) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
key := c.makeKey(fqdn, provider)
|
|
delete(c.cache, key)
|
|
}
|
|
|
|
// ClearAll removes all entries from cache
|
|
func (c *DNSCache) ClearAll() {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
c.cache = make(map[string]string)
|
|
}
|