summaryrefslogtreecommitdiff
path: root/internal/cache/cache.go
blob: bb35b8ee82ec5939a1421688897bd2ec3404449a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package cache

import (
	"database/sql"
	"log/slog"
	"sync"
	"sync/atomic"
	"time"

	"codeberg.org/miekg/dns"
	_ "modernc.org/sqlite"
)

type Key struct {
	Name string
	Qtype uint16
	Class uint16
}

type entry struct {
	msg *dns.Msg
	storedAt time.Time
	ttl time.Duration
}

func (e *entry) expired() bool  {
	return time.Since(e.storedAt) >= e.ttl
}

func (e *entry) remaining() time.Duration {
	d := e.ttl - time.Since(e.storedAt)
	if d < 0 {
		return 0
	}
	return d
}

type Cache struct {
	mu sync.RWMutex
	entries map[Key]*entry
	maxSize int
	db *sql.DB
	dbCh chan dbWrite
	wg sync.WaitGroup
	hits int64
	misses int64
	evicted int64
	stopCh chan struct{}
}
type dbWrite struct {
	key Key
	e *entry
}

func NewCache(maxSize int, dbPath string) (*Cache, error) {
	if maxSize <= 0 {
		maxSize = 100000
	}
	c := &Cache{
		entries: make(map[Key]*entry),
		maxSize: maxSize,
		stopCh: make(chan struct{}),
	}

	if dbPath != "" {
		db, err := sql.Open("sqlite", dbPath)
		if err != nil {
			return nil, err
		}
		c.db = db

		db.Exec("PRAGMA journal_mode=WAL")
		db.Exec("PRAGMA synchronous=NORMAL")
		db.Exec("PRAGMA cache_size=-65536")

		if _, err := db.Exec(`
		CREATE TABLE IF NOT EXISTS cache (
			name TEXT NOT NULL,
			qtype INTEGER NOT NULL,
			class INTEGER NOT NULL,
			data BLOB NOT NULL,
			stored_at INTEGER NOT NULL,
			ttl_ns INTEGER NOT NULL,
			PRIMARY KEY (name, qtype, class)
		)
		`); err != nil {
			db.Close()
			return nil, err
		}

		c.loadFromDB()
		c.dbCh = make(chan dbWrite, 1024)
		c.wg.Add(1)
		go c.dbWriter()
	}
	go c.evictLoop()
	return c, nil
}

func (c *Cache) Stop() {
	close(c.stopCh)
	if c.db != nil {
		close(c.dbCh)
	}
	c.wg.Wait()
	if c.db != nil {
		c.db.Close()
	}
}

func (c *Cache) Get(key Key) (*dns.Msg, bool) {
	c.mu.RLock()
	e, ok := c.entries[key]
	if !ok || e.expired() {
		c.mu.RUnlock()
		atomic.AddInt64(&c.misses, 1)
		return nil, false
	}
	c.mu.RUnlock()

	atomic.AddInt64(&c.hits, 1)
	msg := deepCopyMsg(e.msg)
	remaining := e.remaining()
	adjustTTL(msg, e.ttl, remaining)
	return msg, true
}

func (c *Cache) Set(key Key, msg *dns.Msg, ttl time.Duration) {
	if ttl <= 0 {
		ttl = computeTTL(msg)
	}
	if ttl <= 0 {
		ttl = 60 * time.Second
	}

	e := &entry{
		msg: deepCopyMsg(msg),
		storedAt: time.Now(),
		ttl: ttl,
	}

	c.mu.Lock()
	if len(c.entries) >= c.maxSize {
		c.evictLocked()
	}
	c.entries[key] = e
	c.mu.Unlock()

	if c.db != nil {
		select {
		case c.dbCh <- dbWrite{key: key, e: e}:
		default:
		}
	}
}

func (c *Cache) Stats() (int64, int64, int64) {
	return atomic.LoadInt64(&c.hits),
	atomic.LoadInt64(&c.misses),
	atomic.LoadInt64(&c.evicted)
}

func (c *Cache) Len() int {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return len(c.entries)
}

func (c *Cache) evictLocked() {
	now := time.Now()
	for k, e := range c.entries {
		if now.After(e.storedAt.Add(e.ttl)) {
			delete(c.entries, k)
			atomic.AddInt64(&c.evicted, 1)
		}
	}
	if len(c.entries) < c.maxSize {
		return
	}

	var oldestKey Key
	var oldestTime time.Time
	first := true
	for k, e := range c.entries {
		if first || e.storedAt.Before(oldestTime) {
			oldestKey = k
			oldestTime = e.storedAt
			first = false
		}
	}
	if !first {
		delete(c.entries, oldestKey)
		atomic.AddInt64(&c.evicted, 1)
	}
}

func (c *Cache) evictLoop() {
	tk := time.NewTicker(1 * time.Minute)
	defer tk.Stop()
	for {
		select {
		case <-tk.C:
			now := time.Now()
			c.mu.RLock()
			var expired []Key
			for k, e := range c.entries {
				if now.After(e.storedAt.Add(e.ttl)) {
					expired = append(expired, k)
				}
			}
			c.mu.RUnlock()
			if len(expired) > 0 {
				c.mu.Lock()
				for _, k := range expired {
					if _, ok := c.entries[k]; ok {
						delete(c.entries, k)
						atomic.AddInt64(&c.evicted, 1)
					}
				}
				c.mu.Unlock()
			}
		case <-c.stopCh:
			return
		}
	}
}
func (c *Cache) writeToDB(key Key, e *entry) {
	if c.db == nil {
		return
	}
	err := e.msg.Pack()
	if err != nil {
		return
	}
	data := e.msg.Data
	_, err = c.db.Exec(
		`INSERT OR REPLACE INTO cache (name, qtype, class, data, stored_at, ttl_ns)
		VALUES (?, ?, ?, ?, ?, ?)`,
		key.Name, key.Qtype, key.Class, data,
		e.storedAt.UnixNano(), int64(e.ttl),
	)
	if err != nil {
		slog.Warn("cache write to db failed", "err", err)
	}
}

func (c *Cache) dbWriter() {
	defer c.wg.Done()
	for w := range c.dbCh {
		c.writeToDB(w.key, w.e)
	}
}
func (c *Cache) loadFromDB() {
	rows, err := c.db.Query(
		`SELECT name, qtype, class, data, stored_at, ttl_ns FROM cache`,
	)
	if err != nil {
		return
	}
	defer rows.Close()

	for rows.Next() {
		var name string
		var qtype, class uint16
		var data []byte
		var storedAtNano, ttlNs int64

		if err := rows.Scan(&name, &qtype, &class, &data, &storedAtNano, &ttlNs); err != nil {
			continue
		}

		msg := new(dns.Msg)
		msg.Data = data
		if err := msg.Unpack(); err != nil {
			continue
		}

		e := &entry{
			msg:      msg,
			storedAt: time.Unix(0, storedAtNano),
			ttl:      time.Duration(ttlNs),
		}

		if !e.expired() {
			c.entries[Key{Name: name, Qtype: qtype, Class: class}] = e
		} else {
			c.db.Exec(`DELETE FROM cache WHERE name=? AND qtype=? AND class=?`, name, qtype, class)
		}
	}
}


func computeTTL(msg *dns.Msg) time.Duration {
	if msg.Rcode == dns.RcodeNameError && len(msg.Answer) == 0 {
		for _, rr := range msg.Ns {
			if soa, ok := rr.(*dns.SOA); ok {
				return time.Duration(soa.Minttl) * time.Second
			}
		}
	}

	var min uint32
	first := true
	for _, rr := range msg.Answer {
		if first || rr.Header().TTL < min {
			min = rr.Header().TTL
			first = false
		}
	}
	for _, rr := range msg.Ns {
		if first || rr.Header().TTL < min {
			min = rr.Header().TTL
			first = false
		}
	}
	for _, rr := range msg.Extra {
		if dns.RRToType(rr) == dns.TypeOPT {
			continue
		}
		if first || rr.Header().TTL < min {
			min = rr.Header().TTL
			first = false
		}
	}
	if !first {
		return time.Duration(min) * time.Second
	}
	for _, rr := range msg.Ns {
		if soa, ok := rr.(*dns.SOA); ok {
			return time.Duration(soa.Minttl) * time.Second
		}
	}
	return 0
}

func adjustTTL(msg *dns.Msg, originalTTL, remaining time.Duration) {
	ratio := float64(remaining) / float64(originalTTL)
	for _, rr := range msg.Answer {
		rr.Header().TTL = applyRatio(rr.Header().TTL, ratio)
	}
	for _, rr := range msg.Ns {
		if dns.RRToType(rr) == dns.TypeOPT {
			continue
		}
		rr.Header().TTL = applyRatio(rr.Header().TTL, ratio)
	}
	for _, rr := range msg.Extra {
		if dns.RRToType(rr) == dns.TypeOPT {
			continue
		}
		rr.Header().TTL = applyRatio(rr.Header().TTL, ratio)
	}
}

func applyRatio(ttl uint32, ratio float64) uint32 {
	return uint32(float64(ttl) * ratio)
}

func deepCopyMsg(msg *dns.Msg) *dns.Msg {
	cp := new(dns.Msg)
	cp.Response = msg.Response
	cp.ID = msg.ID
	cp.Opcode = msg.Opcode
	cp.Authoritative = msg.Authoritative
	cp.Truncated = msg.Truncated
	cp.RecursionDesired = msg.RecursionDesired
	cp.RecursionAvailable = msg.RecursionAvailable
	cp.Rcode = msg.Rcode
	cp.UDPSize = msg.UDPSize
	cp.Question = copyRRSlice(msg.Question)
	cp.Answer = copyRRSlice(msg.Answer)
	cp.Ns = copyRRSlice(msg.Ns)
	cp.Extra = copyRRSlice(msg.Extra)
	return cp
}

func copyRRSlice(src []dns.RR) []dns.RR {
	if src == nil {
		return nil
	}
	dst := make([]dns.RR, len(src))
	for i, rr := range src {
		dst[i] = copyRR(rr)
	}
	return dst
}

func copyRR(rr dns.RR) dns.RR {
	if rr == nil {
		return nil
	}
	switch v := rr.(type) {
	case *dns.A:
		cp := *v
		return &cp
	case *dns.AAAA:
		cp := *v
		return &cp
	case *dns.NS:
		cp := *v
		return &cp
	case *dns.CNAME:
		cp := *v
		return &cp
	case *dns.SOA:
		cp := *v
		return &cp
	case *dns.MX:
		cp := *v
		return &cp
	case *dns.TXT:
		cp := *v
		return &cp
	case *dns.SRV:
		cp := *v
		return &cp
	case *dns.PTR:
		cp := *v
		return &cp
	default:
		return rr
	}
}