perf(records): cache decoded record content

This commit is contained in:
bryanpedini committed 2026-11-19 19:58:01 +01:00
1 parent 3623006f25
commit 0c550a91aa
2 files changed
+62

No files matched your search

+31
View File
@@ -15,6 +15,7 @@ import (
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/miekg/dns"
@@ -95,7 +96,37 @@ func decodeRecord(recordType string, content string) (any, error) {
return decoded.data, nil
}
var decodedCacheLimit = 65536
type decodedCacheEntry struct {
decoded decodedRecord
err error
}
var decodedCache = struct {
sync.Mutex
entries map[string]decodedCacheEntry
}{entries: make(map[string]decodedCacheEntry)}
func inspectRecordContent(recordType, content string) (decodedRecord, error) {
key := recordType + "\x00" + content
decodedCache.Lock()
entry, ok := decodedCache.entries[key]
decodedCache.Unlock()
if ok {
return entry.decoded, entry.err
}
decoded, err := parseRecordContent(recordType, content)
decodedCache.Lock()
if len(decodedCache.entries) >= decodedCacheLimit {
clear(decodedCache.entries)
}
decodedCache.entries[key] = decodedCacheEntry{decoded, err}
decodedCache.Unlock()
return decoded, err
}
func parseRecordContent(recordType, content string) (decodedRecord, error) {
rule, ok := recordRules[recordType]
if !ok {
return decodedRecord{}, errors.New("unknown record type")
+31
View File
@@ -312,3 +312,34 @@ func TestRecordFieldBoundaries(t *testing.T) {
})
}
}
func TestInspectRecordContentCache(t *testing.T) {
limit := decodedCacheLimit
decodedCacheLimit = 2
t.Cleanup(func() { decodedCacheLimit = limit })
decodedCache.Lock()
clear(decodedCache.entries)
decodedCache.Unlock()
cached := func() int {
decodedCache.Lock()
defer decodedCache.Unlock()
return len(decodedCache.entries)
}
first, err := inspectRecordContent("A", `{"ip":"192.0.2.1"}`)
if err != nil || first.data != (aData{IP: "192.0.2.1"}) || cached() != 1 {
t.Fatalf("first decode: %+v, %v, %d cached", first, err, cached())
}
again, err := inspectRecordContent("A", `{"ip":"192.0.2.1"}`)
if err != nil || !reflect.DeepEqual(again, first) || cached() != 1 {
t.Fatalf("cached decode: %+v, %v, %d cached", again, err, cached())
}
if _, err := inspectRecordContent("BOGUS", `{}`); err == nil || cached() != 2 {
t.Fatalf("unknown type: %v, %d cached", err, cached())
}
if _, err := inspectRecordContent("BOGUS", `{}`); err == nil || err.Error() != "unknown record type" {
t.Fatalf("cached error: %v", err)
}
if _, err := inspectRecordContent("A", `{"ip":"192.0.2.2"}`); err != nil || cached() != 1 {
t.Fatalf("eviction: %v, %d cached", err, cached())
}
}