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

package containers

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

// 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.
//
//nolint:predeclared // 'cap' is the best name for it.
func NewLRUCache[K comparable, V any](cap int, src Source[K, V]) Cache[K, V] {
	if cap <= 0 {
		panic(fmt.Errorf("containers.NewLRUCache: invalid capacity: %v", cap))
	}
	if src == nil {
		panic(fmt.Errorf("containers.NewLRUCache: nil source"))
	}
	ret := &lruCache[K, V]{
		cap: cap,
		src: src,

		byName: make(map[K]*LinkedListEntry[lruEntry[K, V]], cap),
	}
	for i := 0; i < cap; i++ {
		ret.unused.Store(new(LinkedListEntry[lruEntry[K, V]]))
	}
	return ret
}

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

	// Pinned entries are in .byName, but not in any LinkedList.
	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 struct{}]
}

// Blocking primitives /////////////////////////////////////////////////////////

// waitForAvail is called before storing something into the cache.
// This is nescessary because if the cache is full and all entries are
// pinned, then we won't have to store the entry until something gets
// unpinned ("Release()d").
func (c *lruCache[K, V]) waitForAvail() {
	if !(c.unused.IsEmpty() && c.evictable.IsEmpty()) {
		// There is already an available `lruEntry` that we
		// can either use or evict.
		return
	}
	ch := make(chan struct{})
	c.waiters.Store(&LinkedListEntry[chan struct{}]{Value: ch})
	c.mu.Unlock()
	<-ch // receive the lock from .Release()
	if c.unused.IsEmpty() && c.evictable.IsEmpty() {
		panic(fmt.Errorf("should not happen: waitForAvail is returning, but nothing is available"))
	}
}

// unlockAndNotifyAvail is called when an entry becomes unused or
// evictable, and wakes up the highest-priority .waitForAvail() waiter
// (if there is one).
func (c *lruCache[K, V]) unlockAndNotifyAvail() {
	waiter := c.waiters.Oldest
	if waiter == nil {
		c.mu.Unlock()
		return
	}
	c.waiters.Delete(waiter)
	// We don't actually unlock, we're "transferring" the lock to
	// the waiter.
	close(waiter.Value)
}

// Calling .Delete(k) on an entry that is pinned needs to block until
// the entry is no longer pinned.
func (c *lruCache[K, V]) unlockAndWaitForDel(entry *LinkedListEntry[lruEntry[K, V]]) {
	if entry.Value.del == nil {
		entry.Value.del = make(chan struct{})
	}
	ch := entry.Value.del
	c.mu.Unlock()
	<-ch
}

// notifyOfDel unblocks any calls to .Delete(k), notifying them that
// the entry has been deleted and they can now return.
func (*lruCache[K, V]) notifyOfDel(entry *LinkedListEntry[lruEntry[K, V]]) {
	if entry.Value.del != nil {
		close(entry.Value.del)
		entry.Value.del = nil
	}
}

// Main implementation /////////////////////////////////////////////////////////

// lruReplace is the LRU(c) replacement policy.  It returns an entry
// that is not in any list.
func (c *lruCache[K, V]) lruReplace() *LinkedListEntry[lruEntry[K, V]] {
	c.waitForAvail()

	// If the cache isn't full, no need to do an eviction.
	if entry := c.unused.Oldest; entry != nil {
		c.unused.Delete(entry)
		return entry
	}

	// Replace the oldest entry.
	entry := c.evictable.Oldest
	c.evictable.Delete(entry)
	delete(c.byName, entry.Value.key)
	return entry
}

// Acquire implements the 'Cache' interface.
func (c *lruCache[K, V]) Acquire(ctx context.Context, k K) *V {
	c.mu.Lock()
	defer c.mu.Unlock()

	entry := c.byName[k]
	if entry != nil {
		if entry.Value.refs == 0 {
			c.evictable.Delete(entry)
		}
		entry.Value.refs++
	} else {
		entry = c.lruReplace()

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

		c.byName[k] = entry
	}

	return &entry.Value.val
}

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

	entry := c.byName[k]
	if entry == nil {
		return
	}
	if entry.Value.refs > 0 {
		// Let .Release(k) do the deletion when the
		// refcount drops to 0.
		c.unlockAndWaitForDel(entry)
		return
	}
	delete(c.byName, k)
	c.evictable.Delete(entry)
	c.unused.Store(entry)

	// No need to call c.unlockAndNotifyAvail(); if we were able
	// to delete it, it was already available.

	c.mu.Unlock()
}

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

	entry := c.byName[k]
	if entry == nil || entry.Value.refs <= 0 {
		panic(fmt.Errorf("containers.lruCache.Release called on key that is not held: %v", k))
	}

	entry.Value.refs--
	if entry.Value.refs == 0 {
		if entry.Value.del != nil {
			delete(c.byName, k)
			c.unused.Store(entry)
			c.notifyOfDel(entry)
		} else {
			c.evictable.Store(entry)
		}
		c.unlockAndNotifyAvail()
	} else {
		c.mu.Unlock()
	}
}

// Flush implements the 'Cache' interface.
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)
	}
}