aboutsummaryrefslogtreecommitdiff
path: root/cmd/anubis/decaymap.go
diff options
context:
space:
mode:
authorXe Iaso <me@xeiaso.net>2025-02-14 15:56:47 -0500
committerXe Iaso <me@xeiaso.net>2025-02-14 15:56:47 -0500
commit5423db9a6d3752b2f8f20d368bf2a346e9f268f3 (patch)
tree2c56dc9c3fca8533e8232a7b69ccd7ea253ae74a /cmd/anubis/decaymap.go
parent7db4269d7113007f2c1ec609e9ac6138a3067a22 (diff)
downloadx-5423db9a6d3752b2f8f20d368bf2a346e9f268f3.tar.xz
x-5423db9a6d3752b2f8f20d368bf2a346e9f268f3.zip
cmd/anubis: cache DNSBL hits in a DecayMap
Signed-off-by: Xe Iaso <me@xeiaso.net>
Diffstat (limited to 'cmd/anubis/decaymap.go')
-rw-r--r--cmd/anubis/decaymap.go57
1 files changed, 57 insertions, 0 deletions
diff --git a/cmd/anubis/decaymap.go b/cmd/anubis/decaymap.go
new file mode 100644
index 0000000..bf55d2a
--- /dev/null
+++ b/cmd/anubis/decaymap.go
@@ -0,0 +1,57 @@
+package main
+
+import (
+ "sync"
+ "time"
+)
+
+func zilch[T any]() T {
+ var zero T
+ return zero
+}
+
+type DecayMap[K, V comparable] struct {
+ data map[K]DecayMapEntry[V]
+ lock sync.RWMutex
+}
+
+type DecayMapEntry[V comparable] struct {
+ Value V
+ expiry time.Time
+}
+
+func NewDecayMap[K, V comparable]() *DecayMap[K, V] {
+ return &DecayMap[K, V]{
+ data: make(map[K]DecayMapEntry[V]),
+ }
+}
+
+func (m *DecayMap[K, V]) Get(key K) (V, bool) {
+ m.lock.RLock()
+ value, ok := m.data[key]
+ m.lock.RUnlock()
+
+ if !ok {
+ return zilch[V](), false
+ }
+
+ if time.Now().After(value.expiry) {
+ m.lock.Lock()
+ delete(m.data, key)
+ m.lock.Unlock()
+
+ return zilch[V](), false
+ }
+
+ return value.Value, true
+}
+
+func (m *DecayMap[K, V]) Set(key K, value V, ttl time.Duration) {
+ m.lock.Lock()
+ defer m.lock.Unlock()
+
+ m.data[key] = DecayMapEntry[V]{
+ Value: value,
+ expiry: time.Now().Add(ttl),
+ }
+}