diff --git a/records.go b/records.go index 1fcbfb6..d053603 100644 --- a/records.go +++ b/records.go @@ -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") diff --git a/records_test.go b/records_test.go index 591b5a1..78fb15e 100644 --- a/records_test.go +++ b/records_test.go @@ -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()) + } +}