summaryrefslogtreecommitdiff
path: root/lib/caching/lrucache.go
blob: 095a78c2e98166ddc0b49ca8e548a71cb052bdcd (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
// Copyright (C) 2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package caching

import (
	"context"
	"fmt"
	"sync"
)

type lruEntry[K comparable, V any] struct {
	key  K
	val  V
	refs int
	del  chan struct{} // non-nil if a delete is waiting on .refs to drop to zero
}

type lruCache[K comparable, V any] struct {
	cap int
	src Source[K, V]

	mu sync.Mutex

	unused    LinkedList[lruEntry[K, V]]
	evictable LinkedList[lruEntry[K, V]] // only entries with .refs==0
	byName    map[K]*LinkedListEntry[lruEntry[K, V]]

	waiters LinkedList[chan *LinkedListEntry[lruEntry[K, V]]]
}

// NewLRUCache returns a new thread-safe Cache with a simple Least-Recently-Used
// eviction policy.
//
// It is invalid (runtime-panic) to call NewLRUCache with a non-positive
// capacity or a nil source.
func NewLRUCache[K comparable, V any](cap int, src Source[K, V]) Cache[K, V] {
	if cap <= 0 {
		panic(fmt.Errorf("caching.NewLRUCache: invalid capacity: %v", cap))
	}
	if src == nil {
		panic(fmt.Errorf("caching.NewLRUCache: nil source"))
	}
	ret := &lruCache[K, V]{
		cap: cap,
		src: src,
	}
	for i := 0; i < cap; i++ {
		c.unused.Store(new(LinkedListEntry[lruEntry[K, V]]))
	}
	return ret
}

// Acquire implements Cache.
func (c *lruCache[K, V]) Acquire(ctx context.Context, k K) *V {
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.byName == nil {
		c.byName = make(map[K]*LinkedListEntry[lruEntry[K, V]], c.cap)
	}

	entry, ok := c.byName[k]
	if ok {
		if entry.Value.refs == 0 {
			c.evictable.Delete(entry)
		}
		entry.Value.refs++
	} else {
		switch {
		case !c.unused.IsEmpty():
			entry = c.unused.Oldest()
			c.unused.Delete(entry)
		case !c.evictable.IsEmpty():
			entry = c.evictable.Oldest()
			c.evictable.Delete(entry)
			delete(c.byName, entry.Value.key)
		default:
			ch := make(chan *LinkedListEntry[lruEntry[K, V]])
			c.waiters.Store(&LinkedListEntry[chan *LinkedListEntry[lruEntry[K, V]]]{Value: ch})
			c.mu.Unlock()
			entry = <-ch
			c.mu.Lock()
		}

		entry.Value.key = k
		c.src.Load(ctx, k, &entry.Value.val)
		entry.Value.refs = 1

		c.byName[k] = entry
	}

	return &entry.Value.val
}

// Release implements Cache.
func (c *lruCache[K, V]) Release(k K) {
	c.mu.Lock()
	defer c.mu.Unlock()

	entry, ok := c.byName[k]
	if !ok || entry.Value.refs <= 0 {
		panic(fmt.Errorf("caching.lruCache.Release called on key that is not held: %v", k))
	}
	entry.Value.refs--
	if entry.Value.refs == 0 {
		del := entry.Value.del != nil
		if del {
			close(entry.Value.del)
			entry.Value.del = nil
		}
		if c.waiters.IsEmpty() {
			// Add it to the free-list.
			if del {
				delete(c.byName, k)
				c.unused.Store(entry)
			} else {
				c.evictable.Store(entry)
			}
		} else {
			// Someone's waiting to pop something off of the
			// free-list; bypass the free-list and hand it directly
			// to them.

			// Make sure that no one aquires this entry between us
			// writing it to the channel and the waiter calling
			// c.mu.Lock().
			delete(c.byName, k)

			// Pass it to the waiter.
			waiter := c.waiters.Oldest()
			c.waiters.Delete(waiter)
			waiter.Value <- entry
		}
	}
}

// Delete implements Cache.
func (c *lruCache[K, V]) Delete(k K) {
	c.mu.Lock()

	entry, ok := c.byName[k]
	if !ok {
		return
	}
	if entry.Value.refs == 0 {
		delete(c.byName, k)
		if c.waiters.IsEmpty() {
			c.unused.Store(entry)
		} else {
			waiter := c.waiters.Oldest()
			c.waiters.Delete(waiter)
			waiter.Value <- entry
		}
		c.mu.Unlock()
	} else {
		if entry.Value.del == nil {
			entry.Value.del = make(chan struct{})
		}
		ch := entry.Value.del
		c.mu.Unlock()
		<-ch
	}
}

// Flush implements Cache.
func (c *lruCache[K, V]) Flush(ctx context.Context) {
	c.mu.Lock()
	defer c.mu.Unlock()

	for _, entry := range c.byName {
		c.src.Flush(ctx, &entry.Value.val)
	}
	for entry := c.unused.Oldest(); entry != nil; entry = entry.Newer() {
		c.src.Flush(ctx, &entry.Value.val)
	}
}