Implement MCNS v1: custom Go DNS server replacing CoreDNS
Replace the CoreDNS precursor with a purpose-built authoritative DNS server. Zones and records (A, AAAA, CNAME) are stored in SQLite and managed via synchronized gRPC + REST APIs authenticated through MCIAS. Non-authoritative queries are forwarded to upstream resolvers with in-memory caching. Key components: - DNS server (miekg/dns) with authoritative zone handling and forwarding - gRPC + REST management APIs with MCIAS auth (mcdsl integration) - SQLite storage with CNAME exclusivity enforcement and auto SOA serials - 30 tests covering database CRUD, DNS resolution, and caching Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
67
internal/dns/cache.go
Normal file
67
internal/dns/cache.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type cacheKey struct {
|
||||
Name string
|
||||
Qtype uint16
|
||||
Class uint16
|
||||
}
|
||||
|
||||
type cacheEntry struct {
|
||||
msg *dns.Msg
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
// Cache is a thread-safe in-memory DNS response cache with TTL-based expiry.
|
||||
type Cache struct {
|
||||
mu sync.RWMutex
|
||||
entries map[cacheKey]*cacheEntry
|
||||
}
|
||||
|
||||
// NewCache creates an empty DNS cache.
|
||||
func NewCache() *Cache {
|
||||
return &Cache{
|
||||
entries: make(map[cacheKey]*cacheEntry),
|
||||
}
|
||||
}
|
||||
|
||||
// Get returns a cached response if it exists and has not expired.
|
||||
func (c *Cache) Get(name string, qtype, class uint16) *dns.Msg {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
key := cacheKey{Name: name, Qtype: qtype, Class: class}
|
||||
entry, ok := c.entries[key]
|
||||
if !ok || time.Now().After(entry.expiresAt) {
|
||||
return nil
|
||||
}
|
||||
return entry.msg
|
||||
}
|
||||
|
||||
// Set stores a DNS response in the cache with the given TTL.
|
||||
func (c *Cache) Set(name string, qtype, class uint16, msg *dns.Msg, ttl time.Duration) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
key := cacheKey{Name: name, Qtype: qtype, Class: class}
|
||||
c.entries[key] = &cacheEntry{
|
||||
msg: msg.Copy(),
|
||||
expiresAt: time.Now().Add(ttl),
|
||||
}
|
||||
|
||||
// Lazy eviction: clean up expired entries if cache is growing.
|
||||
if len(c.entries) > 1000 {
|
||||
now := time.Now()
|
||||
for k, v := range c.entries {
|
||||
if now.After(v.expiresAt) {
|
||||
delete(c.entries, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user