util/lru, util/limiter: add debug helper to dump state as HTML

For use in tsweb debug handlers, so that we can easily inspect cache
and limiter state when troubleshooting.

Updates tailscale/corp#3601

Signed-off-by: David Anderson <danderson@tailscale.com>
This commit is contained in:
David Anderson
2023-09-07 17:33:02 -07:00
committed by Dave Anderson
parent d23b8ffb13
commit 95082a8dde
4 changed files with 178 additions and 0 deletions

View File

@ -4,8 +4,12 @@
package lru
import (
"bytes"
"math/rand"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestLRU(t *testing.T) {
@ -44,6 +48,31 @@ func TestLRU(t *testing.T) {
}
}
func TestDumpHTML(t *testing.T) {
c := Cache[int, string]{MaxEntries: 3}
c.Set(1, "foo")
c.Set(2, "bar")
c.Set(3, "qux")
c.Set(4, "wat")
var out bytes.Buffer
c.DumpHTML(&out)
want := strings.Join([]string{
"<table>",
"<tr><th>Key</th><th>Value</th></tr>",
"<tr><td>4</td><td>wat</td></tr>",
"<tr><td>3</td><td>qux</td></tr>",
"<tr><td>2</td><td>bar</td></tr>",
"</table>",
}, "")
if diff := cmp.Diff(out.String(), want); diff != "" {
t.Fatalf("wrong DumpHTML output (-got+want):\n%s", diff)
}
}
func BenchmarkLRU(b *testing.B) {
const lruSize = 10
const maxval = 15 // 33% more keys than the LRU can hold