cache.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package dns
  2. import (
  3. "log/slog"
  4. "time"
  5. "github.com/TecharoHQ/anubis/lib/store"
  6. _ "github.com/TecharoHQ/anubis/lib/store/all"
  7. )
  8. type DnsCache struct {
  9. forward store.JSON[[]string]
  10. reverse store.JSON[[]string]
  11. forwardTTL time.Duration
  12. reverseTTL time.Duration
  13. }
  14. func NewDNSCache(forwardTTL int, reverseTTL int, backend store.Interface) *DnsCache {
  15. return &DnsCache{
  16. forward: store.JSON[[]string]{
  17. Underlying: backend,
  18. Prefix: "forwardDNS",
  19. },
  20. reverse: store.JSON[[]string]{
  21. Underlying: backend,
  22. Prefix: "reverseDNS",
  23. },
  24. forwardTTL: time.Duration(forwardTTL) * time.Second,
  25. reverseTTL: time.Duration(reverseTTL) * time.Second,
  26. }
  27. }
  28. func (d *Dns) getCachedForward(host string) ([]string, bool) {
  29. if d.cache == nil {
  30. return nil, false
  31. }
  32. if cached, err := d.cache.forward.Get(d.ctx, host); err == nil {
  33. slog.Debug("DNS: forward cache hit", "name", host, "ips", cached)
  34. return cached, true
  35. }
  36. slog.Debug("DNS: forward cache miss", "name", host)
  37. return nil, false
  38. }
  39. func (d *Dns) getCachedReverse(addr string) ([]string, bool) {
  40. if d.cache == nil {
  41. return nil, false
  42. }
  43. if cached, err := d.cache.reverse.Get(d.ctx, addr); err == nil {
  44. slog.Debug("DNS: reverse cache hit", "addr", addr, "names", cached)
  45. return cached, true
  46. }
  47. slog.Debug("DNS: reverse cache miss", "addr", addr)
  48. return nil, false
  49. }
  50. func (d *Dns) forwardCachePut(host string, entries []string) {
  51. if d.cache == nil {
  52. return
  53. }
  54. d.cache.forward.Set(d.ctx, host, entries, d.cache.forwardTTL)
  55. }
  56. func (d *Dns) reverseCachePut(addr string, entries []string) {
  57. if d.cache == nil {
  58. return
  59. }
  60. d.cache.reverse.Set(d.ctx, addr, entries, d.cache.reverseTTL)
  61. }