v1
Test / test (push) Successful in 3m36s
Release / release (push) Successful in 7m31s

This commit is contained in:
Sebastian Unterschütz committed 2026-11-17 19:00:44 +01:00
commit 8d4915543e
132 files changed
+20628

No files matched your search

+428
View File
@@ -0,0 +1,428 @@
package cache
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"golang.org/x/sys/unix"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
)
type Entry struct {
Name string `json:"name"`
IP string `json:"ip"`
Kind string `json:"kind"`
Tags []string `json:"tags,omitempty"`
Cluster string `json:"cluster,omitempty"`
CachedAt time.Time `json:"cached_at"`
LastUsed time.Time `json:"last_used,omitempty"`
// Static marks a host from the config's hosts: list. It never expires;
// it is stored only to remember LastUsed for the recently-used list.
Static bool `json:"static,omitempty"`
}
type changeKind uint8
const (
upsertChange changeKind = iota
deleteChange
usageChange
)
type Cache struct {
mu sync.RWMutex
dirty map[string]changeKind
cleared bool
entries map[string]Entry
path string
ttl time.Duration
refreshStamp string // path to last_refresh timestamp file
static []config.StaticHost
}
type diskFormat struct {
Entries []Entry `json:"entries"`
}
func New(path string, ttlSeconds int) *Cache {
stamp := ""
if path != "" {
stamp = filepath.Join(filepath.Dir(path), "last_refresh")
}
return &Cache{
entries: make(map[string]Entry),
dirty: make(map[string]changeKind),
path: path,
ttl: time.Duration(ttlSeconds) * time.Second,
refreshStamp: stamp,
}
}
// NeedsRefresh reports whether the last full cache refresh (via `cache refresh`)
// is older than d, or has never happened. Always returns false when no path is set.
func (c *Cache) NeedsRefresh(d time.Duration) bool {
if c.refreshStamp == "" {
return false
}
data, err := os.ReadFile(c.refreshStamp)
if err != nil {
return true // file missing → never refreshed
}
var t time.Time
if err := t.UnmarshalText(data); err != nil {
return true
}
return time.Since(t) >= d
}
// ClaimRefresh reports whether a background refresh should start now: the last
// full refresh is older than d and no attempt was claimed within retry. It
// records the attempt, so parallel shells and repeated commands start one
// refresh per retry interval instead of one each.
func (c *Cache) ClaimRefresh(d, retry time.Duration) bool {
if !c.NeedsRefresh(d) {
return false
}
attempt := filepath.Join(filepath.Dir(c.refreshStamp), "refresh_attempt")
if info, err := os.Stat(attempt); err == nil && time.Since(info.ModTime()) < retry {
return false
}
if err := os.MkdirAll(filepath.Dir(attempt), 0o755); err != nil {
return true // cannot record the attempt; refreshing is still right
}
// Best effort: two processes racing here may both refresh once.
_ = os.WriteFile(attempt, nil, 0o600)
return true
}
// SetRefreshed records the current time as the last successful full refresh.
func (c *Cache) SetRefreshed() error {
if c.refreshStamp == "" {
return nil
}
data, err := time.Now().MarshalText()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(c.refreshStamp), 0o755); err != nil {
return err
}
return os.WriteFile(c.refreshStamp, data, 0o644)
}
func (c *Cache) Load() error {
c.mu.Lock()
defer c.mu.Unlock()
data, err := os.ReadFile(c.path)
if os.IsNotExist(err) {
c.applyStatic()
return nil
}
if err != nil {
return err
}
var df diskFormat
if err := json.Unmarshal(data, &df); err != nil {
return err
}
c.dirty = make(map[string]changeKind)
c.cleared = false
c.entries = make(map[string]Entry, len(df.Entries))
for _, e := range df.Entries {
c.entries[e.Name] = e
}
c.applyStatic()
return nil
}
// Save merges only local changes under a process-wide file lock. Atomic rename
// alone prevents torn JSON but cannot prevent lost updates from another process.
func (c *Cache) Save() error {
c.mu.Lock()
defer c.mu.Unlock()
if err := os.MkdirAll(filepath.Dir(c.path), 0o755); err != nil {
return err
}
lock, err := os.OpenFile(c.path+".lock", os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return err
}
defer lock.Close()
if err := unix.Flock(int(lock.Fd()), unix.LOCK_EX); err != nil {
return err
}
defer unix.Flock(int(lock.Fd()), unix.LOCK_UN)
merged := make(map[string]Entry)
if !c.cleared {
data, err := os.ReadFile(c.path)
if err != nil && !os.IsNotExist(err) {
return err
}
if err == nil {
var df diskFormat
if err := json.Unmarshal(data, &df); err != nil {
return err
}
for _, e := range df.Entries {
merged[e.Name] = e
}
}
}
for name, change := range c.dirty {
if change == deleteChange {
delete(merged, name)
continue
}
e := c.entries[name]
old, exists := merged[name]
if change == usageChange && !exists {
// A connection finishing after a refresh or clear must not
// restore an entry that the other process removed.
continue
}
if exists {
lastUsed := e.LastUsed
if change == usageChange || old.CachedAt.After(e.CachedAt) {
e = old
}
if old.LastUsed.After(lastUsed) {
lastUsed = old.LastUsed
}
e.LastUsed = lastUsed
}
merged[name] = e
}
df := diskFormat{Entries: make([]Entry, 0, len(merged))}
for _, e := range merged {
df.Entries = append(df.Entries, e)
}
sort.Slice(df.Entries, func(i, j int) bool { return df.Entries[i].Name < df.Entries[j].Name })
data, err := json.MarshalIndent(df, "", " ")
if err != nil {
return err
}
if err := storage.WriteFile(c.path, data, 0o600); err != nil {
return err
}
// Static hosts come from the config, not the file: keep them in memory.
for name, e := range c.entries {
if e.Static {
if old, ok := merged[name]; ok && old.LastUsed.After(e.LastUsed) {
e.LastUsed = old.LastUsed
}
merged[name] = e
}
}
c.entries = merged
c.dirty = make(map[string]changeKind)
c.cleared = false
return nil
}
func (c *Cache) Upsert(e Entry) {
e.CachedAt = time.Now()
c.mu.Lock()
if old, ok := c.entries[e.Name]; ok && e.LastUsed.IsZero() {
e.LastUsed = old.LastUsed
}
c.entries[e.Name] = e
c.dirty[e.Name] = upsertChange
c.mu.Unlock()
}
// Delete removes an entry when a refresh can no longer resolve it safely.
func (c *Cache) Delete(name string) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.entries, name)
c.dirty[name] = deleteChange
}
// MarkUsed records the current time as LastUsed for the named entry.
// It is a no-op if the entry does not exist.
func (c *Cache) MarkUsed(name string) {
c.mu.Lock()
defer c.mu.Unlock()
if e, ok := c.entries[name]; ok {
e.LastUsed = time.Now()
c.entries[name] = e
if e.Static {
// A static host may not be on disk yet; usage alone would not add it.
c.dirty[name] = upsertChange
} else if _, changed := c.dirty[name]; !changed {
c.dirty[name] = usageChange
}
}
}
// RecentlyUsed returns the n most recently used entries, sorted by LastUsed desc.
// Entries that have never been used (LastUsed zero) are excluded.
// If n <= 0, all used entries are returned.
func (c *Cache) RecentlyUsed(n int) []Entry {
c.mu.RLock()
defer c.mu.RUnlock()
var used []Entry
for _, e := range c.entries {
if !e.LastUsed.IsZero() {
used = append(used, e)
}
}
sort.Slice(used, func(i, j int) bool {
return used[i].LastUsed.After(used[j].LastUsed)
})
if n > 0 && len(used) > n {
used = used[:n]
}
return used
}
// Search returns all entries whose name starts with prefix (case-insensitive).
// TTL is intentionally ignored — this is used for shell completion.
func (c *Cache) Search(prefix string) []Entry {
c.mu.RLock()
defer c.mu.RUnlock()
prefix = strings.ToLower(prefix)
var out []Entry
for name, e := range c.entries {
_, hostname, qualified := strings.Cut(strings.ToLower(name), "/")
if strings.HasPrefix(strings.ToLower(name), prefix) || (qualified && !strings.Contains(prefix, "/") && strings.HasPrefix(hostname, prefix)) {
out = append(out, e)
}
}
return out
}
// GetByShortcut rejects collisions instead of choosing a random map entry.
func (c *Cache) GetByShortcut(shortcut string, normalize func(string) string) (entry Entry, found bool, fresh bool, err error) {
c.mu.RLock()
defer c.mu.RUnlock()
norm := normalize(shortcut)
for _, e := range c.entries {
if normalize(e.Name) == norm {
if found {
return Entry{}, false, false, fmt.Errorf("ambiguous shortcut %q; use a full hostname", shortcut)
}
entry, found = e, true
}
}
return entry, found, found && (entry.Static || c.ttl > 0 && time.Since(entry.CachedAt) < c.ttl), nil
}
// Get returns an entry and reports whether it is still within the TTL.
func (c *Cache) Get(name string) (entry Entry, fresh bool) {
c.mu.RLock()
e, ok := c.entries[name]
c.mu.RUnlock()
if !ok {
return Entry{}, false
}
if e.Static {
return e, true
}
if c.ttl == 0 {
return e, false
}
return e, time.Since(e.CachedAt) < c.ttl
}
// Clear removes all NetBox entries; static hosts come from the config and stay.
func (c *Cache) Clear() {
c.mu.Lock()
static := make(map[string]Entry)
for name, e := range c.entries {
if e.Static {
static[name] = e
}
}
c.entries = static
c.dirty = make(map[string]changeKind)
c.cleared = true
c.mu.Unlock()
}
// SetStatic adds the config's static hosts. They replace cached entries of the
// same name, keep their recorded LastUsed, and static entries that are no
// longer configured are removed on the next Save.
func (c *Cache) SetStatic(hosts []config.StaticHost) {
c.mu.Lock()
defer c.mu.Unlock()
c.static = hosts
c.applyStatic()
}
// WithStatic sets the static hosts now and after every Load.
func (c *Cache) WithStatic(hosts []config.StaticHost) *Cache {
c.SetStatic(hosts)
return c
}
func (c *Cache) applyStatic() {
hosts := c.static
configured := make(map[string]bool, len(hosts))
for _, host := range hosts {
e := Entry{Name: host.Name, IP: host.Address, Kind: config.StaticKind, Tags: host.Tags, CachedAt: time.Now(), Static: true}
if old, ok := c.entries[host.Name]; ok && old.Static {
e.LastUsed = old.LastUsed
}
c.entries[host.Name] = e
configured[host.Name] = true
}
for name, e := range c.entries {
if e.Static && !configured[name] {
delete(c.entries, name)
c.dirty[name] = deleteChange
}
}
}
// GetStatic finds a static host by name or by shortcut. Static hosts are
// checked before NetBox, so they also work when NetBox is unreachable.
func (c *Cache) GetStatic(name string, normalize func(string) string) (Entry, bool, error) {
c.mu.RLock()
defer c.mu.RUnlock()
var match Entry
found := false
for key, e := range c.entries {
if e.Static && strings.EqualFold(key, name) {
return e, true, nil
}
}
if normalize == nil {
return Entry{}, false, nil
}
short := normalize(name)
for _, e := range c.entries {
if e.Static && normalize(e.Name) == short {
if found {
return Entry{}, false, fmt.Errorf("ambiguous shortcut %q; use a full hostname", name)
}
match, found = e, true
}
}
return match, found, nil
}
func (c *Cache) All() []Entry {
c.mu.RLock()
defer c.mu.RUnlock()
out := make([]Entry, 0, len(c.entries))
for _, e := range c.entries {
out = append(out, e)
}
return out
}
+579
View File
@@ -0,0 +1,579 @@
package cache
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestNew(t *testing.T) {
c := New("/tmp/test.json", 60)
if c == nil {
t.Fatal("New returned nil")
}
if c.ttl != 60*time.Second {
t.Errorf("ttl: got %v, want %v", c.ttl, 60*time.Second)
}
}
func TestLoad_MissingFile(t *testing.T) {
c := New("/nonexistent/path/cache.json", 60)
if err := c.Load(); err != nil {
t.Errorf("Load on missing file should not error, got: %v", err)
}
}
func TestLoad_InvalidJSON(t *testing.T) {
f := tempFile(t, []byte("not json"))
c := New(f, 60)
if err := c.Load(); err == nil {
t.Error("Load on invalid JSON should return an error")
}
}
func TestSaveAndLoad_Roundtrip(t *testing.T) {
path := filepath.Join(t.TempDir(), "cache.json")
c := New(path, 3600)
c.Upsert(Entry{Name: "host-a", IP: "10.0.0.1", Kind: "device"})
c.Upsert(Entry{Name: "host-b", IP: "10.0.0.2", Kind: "vm", Tags: []string{"prod"}})
if err := c.Save(); err != nil {
t.Fatalf("Save: %v", err)
}
c2 := New(path, 3600)
if err := c2.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
e, _ := c2.Get("host-a")
if e.IP != "10.0.0.1" {
t.Errorf("host-a IP: got %q, want %q", e.IP, "10.0.0.1")
}
e2, _ := c2.Get("host-b")
if len(e2.Tags) != 1 || e2.Tags[0] != "prod" {
t.Errorf("host-b tags: got %v, want [prod]", e2.Tags)
}
}
func TestSave_CreatesDirectory(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "sub", "dir", "cache.json")
c := New(path, 60)
c.Upsert(Entry{Name: "x", IP: "1.2.3.4", Kind: "device"})
if err := c.Save(); err != nil {
t.Fatalf("Save: %v", err)
}
if _, err := os.Stat(path); err != nil {
t.Errorf("cache file not created: %v", err)
}
}
func TestUpsert_SetsTimestamp(t *testing.T) {
c := New("", 60)
before := time.Now()
c.Upsert(Entry{Name: "h", IP: "1.1.1.1", Kind: "device"})
e, _ := c.Get("h")
if e.CachedAt.Before(before) {
t.Error("CachedAt should be set to current time on Upsert")
}
}
func TestUpsert_Overwrites(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "host", IP: "10.0.0.1", Kind: "device"})
c.Upsert(Entry{Name: "host", IP: "10.0.0.2", Kind: "device"})
e, _ := c.Get("host")
if e.IP != "10.0.0.2" {
t.Errorf("Upsert should overwrite: got %q, want %q", e.IP, "10.0.0.2")
}
}
func TestSearch_PrefixMatch(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "app-server-01", IP: "10.0.0.1", Kind: "device"})
c.Upsert(Entry{Name: "app-server-02", IP: "10.0.0.2", Kind: "vm"})
c.Upsert(Entry{Name: "db-server-01", IP: "10.0.0.3", Kind: "device"})
results := c.Search("app")
if len(results) != 2 {
t.Errorf("Search(app): got %d results, want 2", len(results))
}
}
func TestSearch_CaseInsensitive(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "App-Server", IP: "10.0.0.1", Kind: "device"})
if len(c.Search("app")) != 1 {
t.Error("Search should be case-insensitive")
}
if len(c.Search("APP")) != 1 {
t.Error("Search should be case-insensitive for uppercase")
}
}
func TestSearch_EmptyPrefix(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "a", IP: "1.1.1.1", Kind: "device"})
c.Upsert(Entry{Name: "b", IP: "2.2.2.2", Kind: "vm"})
if len(c.Search("")) != 2 {
t.Error("Search('') should return all entries")
}
}
func TestSearch_NoMatch(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "host", IP: "1.1.1.1", Kind: "device"})
if len(c.Search("xyz")) != 0 {
t.Error("Search should return empty slice when no match")
}
}
func TestGet_Fresh(t *testing.T) {
c := New("", 3600)
c.Upsert(Entry{Name: "host", IP: "10.0.0.1", Kind: "device"})
e, fresh := c.Get("host")
if !fresh {
t.Error("entry just inserted should be fresh")
}
if e.IP != "10.0.0.1" {
t.Errorf("IP: got %q, want %q", e.IP, "10.0.0.1")
}
}
func TestGet_Expired(t *testing.T) {
c := New("", 1) // 1 second TTL
e := Entry{Name: "host", IP: "10.0.0.1", Kind: "device", CachedAt: time.Now().Add(-2 * time.Second)}
c.mu.Lock()
c.entries["host"] = e
c.mu.Unlock()
_, fresh := c.Get("host")
if fresh {
t.Error("entry older than TTL should not be fresh")
}
}
func TestGet_ZeroTTL_AlwaysStale(t *testing.T) {
c := New("", 0) // TTL=0 means never fresh for connect mode
c.Upsert(Entry{Name: "host", IP: "10.0.0.1", Kind: "device"})
_, fresh := c.Get("host")
if fresh {
t.Error("TTL=0 should always return fresh=false")
}
}
func TestGet_Missing(t *testing.T) {
c := New("", 60)
_, fresh := c.Get("nonexistent")
if fresh {
t.Error("missing entry should not be fresh")
}
}
func TestClear(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "a", IP: "1.1.1.1", Kind: "device"})
c.Upsert(Entry{Name: "b", IP: "2.2.2.2", Kind: "vm"})
c.Clear()
if len(c.All()) != 0 {
t.Error("Clear should remove all entries")
}
}
func TestAll(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "a", IP: "1.1.1.1", Kind: "device"})
c.Upsert(Entry{Name: "b", IP: "2.2.2.2", Kind: "vm"})
all := c.All()
if len(all) != 2 {
t.Errorf("All: got %d entries, want 2", len(all))
}
}
func TestSave_ProducesValidJSON(t *testing.T) {
path := filepath.Join(t.TempDir(), "cache.json")
c := New(path, 60)
c.Upsert(Entry{Name: "host", IP: "10.0.0.1", Kind: "device", Tags: []string{"mgmt"}})
if err := c.Save(); err != nil {
t.Fatalf("Save: %v", err)
}
data, _ := os.ReadFile(path)
var df diskFormat
if err := json.Unmarshal(data, &df); err != nil {
t.Fatalf("saved file is not valid JSON: %v", err)
}
if len(df.Entries) != 1 {
t.Errorf("expected 1 entry in JSON, got %d", len(df.Entries))
}
}
func TestMarkUsed_SetsLastUsed(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "host", IP: "10.0.0.1", Kind: "device"})
before := time.Now()
c.MarkUsed("host")
e, _ := c.Get("host")
if e.LastUsed.Before(before) {
t.Error("LastUsed should be set to current time by MarkUsed")
}
}
func TestMarkUsed_NoopForMissingEntry(t *testing.T) {
c := New("", 60)
c.MarkUsed("nonexistent") // should not panic
}
func TestRecentlyUsed_ReturnsTopN(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "a", IP: "1.1.1.1", Kind: "device"})
c.Upsert(Entry{Name: "b", IP: "2.2.2.2", Kind: "device"})
c.Upsert(Entry{Name: "c", IP: "3.3.3.3", Kind: "device"})
c.MarkUsed("c")
time.Sleep(time.Millisecond)
c.MarkUsed("a")
results := c.RecentlyUsed(2)
if len(results) != 2 {
t.Fatalf("RecentlyUsed(2): got %d results, want 2", len(results))
}
if results[0].Name != "a" {
t.Errorf("first result: got %q, want %q", results[0].Name, "a")
}
if results[1].Name != "c" {
t.Errorf("second result: got %q, want %q", results[1].Name, "c")
}
}
func TestRecentlyUsed_ExcludesNeverUsed(t *testing.T) {
c := New("", 60)
c.Upsert(Entry{Name: "used", IP: "1.1.1.1", Kind: "device"})
c.Upsert(Entry{Name: "unused", IP: "2.2.2.2", Kind: "device"})
c.MarkUsed("used")
results := c.RecentlyUsed(10)
if len(results) != 1 || results[0].Name != "used" {
t.Errorf("RecentlyUsed should exclude entries with zero LastUsed, got %v", results)
}
}
func TestRecentlyUsed_EmptyCache(t *testing.T) {
c := New("", 60)
if results := c.RecentlyUsed(10); len(results) != 0 {
t.Errorf("RecentlyUsed on empty cache: got %d, want 0", len(results))
}
}
func TestMarkUsed_RoundtripViaSave(t *testing.T) {
path := filepath.Join(t.TempDir(), "cache.json")
c := New(path, 3600)
c.Upsert(Entry{Name: "host", IP: "10.0.0.1", Kind: "device"})
c.MarkUsed("host")
if err := c.Save(); err != nil {
t.Fatalf("Save: %v", err)
}
c2 := New(path, 3600)
if err := c2.Load(); err != nil {
t.Fatalf("Load: %v", err)
}
results := c2.RecentlyUsed(1)
if len(results) != 1 || results[0].Name != "host" {
t.Errorf("LastUsed not persisted: %v", results)
}
}
// --- GetByShortcut tests ---
func TestGetByShortcut_MatchFresh(t *testing.T) {
c := New("", 3600)
c.Upsert(Entry{Name: "web01.example.com", IP: "10.0.0.1", Kind: "device"})
normalize := func(s string) string {
// strip .example.com
if len(s) > len(".example.com") && s[len(s)-len(".example.com"):] == ".example.com" {
s = s[:len(s)-len(".example.com")]
}
return s
}
e, found, fresh, _ := c.GetByShortcut("web01", normalize)
if !found {
t.Fatal("expected entry to be found")
}
if !fresh {
t.Error("entry just inserted should be fresh")
}
if e.IP != "10.0.0.1" {
t.Errorf("IP: got %q, want %q", e.IP, "10.0.0.1")
}
}
func TestGetByShortcut_MatchStale(t *testing.T) {
c := New("", 1) // 1 second TTL
stale := Entry{Name: "web01.example.com", IP: "10.0.0.1", Kind: "device", CachedAt: time.Now().Add(-2 * time.Second)}
c.mu.Lock()
c.entries["web01.example.com"] = stale
c.mu.Unlock()
normalize := func(s string) string {
if len(s) > len(".example.com") && s[len(s)-len(".example.com"):] == ".example.com" {
s = s[:len(s)-len(".example.com")]
}
return s
}
_, found, fresh, _ := c.GetByShortcut("web01", normalize)
if !found {
t.Fatal("expected entry to be found even when stale")
}
if fresh {
t.Error("entry older than TTL should not be fresh")
}
}
func TestGetByShortcut_NotFound(t *testing.T) {
c := New("", 3600)
c.Upsert(Entry{Name: "db01.example.com", IP: "10.0.0.2", Kind: "device"})
_, found, _, _ := c.GetByShortcut("web01", func(s string) string { return s })
if found {
t.Error("should not find an entry that does not match the shortcut")
}
}
func TestGetByShortcut_EmptyCache(t *testing.T) {
c := New("", 3600)
_, found, _, _ := c.GetByShortcut("web01", func(s string) string { return s })
if found {
t.Error("empty cache should return found=false")
}
}
func TestGetByShortcut_MultiDomain(t *testing.T) {
c := New("", 3600)
// Entry uses second domain (.example.de)
c.Upsert(Entry{Name: "web01.example.de", IP: "10.0.0.5", Kind: "vm"})
normalize := func(s string) string {
for _, suffix := range []string{".example.com", ".example.de"} {
if len(s) > len(suffix) && s[len(s)-len(suffix):] == suffix {
return s[:len(s)-len(suffix)]
}
}
return s
}
e, found, _, _ := c.GetByShortcut("web01", normalize)
if !found {
t.Fatal("should match entry with second configured domain")
}
if e.IP != "10.0.0.5" {
t.Errorf("IP: got %q, want %q", e.IP, "10.0.0.5")
}
}
// --- NeedsRefresh / SetRefreshed tests ---
// These tests require NeedsRefresh(time.Duration) bool and SetRefreshed() error
// to be implemented on *Cache. The refreshStamp field (path to the timestamp file)
// must be set before calling these methods.
func TestNeedsRefresh_NeverRefreshed(t *testing.T) {
dir := t.TempDir()
stampPath := filepath.Join(dir, "last_refresh")
c := New(filepath.Join(dir, "cache.json"), 3600)
c.refreshStamp = stampPath
if !c.NeedsRefresh(24 * time.Hour) {
t.Error("NeedsRefresh should return true when last_refresh file does not exist")
}
}
func TestNeedsRefresh_JustRefreshed(t *testing.T) {
dir := t.TempDir()
stampPath := filepath.Join(dir, "last_refresh")
c := New(filepath.Join(dir, "cache.json"), 3600)
c.refreshStamp = stampPath
if err := c.SetRefreshed(); err != nil {
t.Fatalf("SetRefreshed: %v", err)
}
if c.NeedsRefresh(24 * time.Hour) {
t.Error("NeedsRefresh should return false immediately after SetRefreshed")
}
}
func TestNeedsRefresh_Stale(t *testing.T) {
dir := t.TempDir()
stampPath := filepath.Join(dir, "last_refresh")
// Write a timestamp 25 hours ago
oldTime := time.Now().Add(-25 * time.Hour).Format(time.RFC3339)
if err := os.WriteFile(stampPath, []byte(oldTime), 0o644); err != nil {
t.Fatalf("writing stamp: %v", err)
}
c := New(filepath.Join(dir, "cache.json"), 3600)
c.refreshStamp = stampPath
if !c.NeedsRefresh(24 * time.Hour) {
t.Error("NeedsRefresh should return true when last_refresh is older than duration")
}
}
func TestSetRefreshed_Roundtrip(t *testing.T) {
dir := t.TempDir()
stampPath := filepath.Join(dir, "last_refresh")
c := New(filepath.Join(dir, "cache.json"), 3600)
c.refreshStamp = stampPath
if err := c.SetRefreshed(); err != nil {
t.Fatalf("SetRefreshed: %v", err)
}
// Just refreshed: 24h window → not stale
if c.NeedsRefresh(24 * time.Hour) {
t.Error("NeedsRefresh(24h) should be false right after SetRefreshed")
}
// Zero duration: everything is stale
if !c.NeedsRefresh(0) {
t.Error("NeedsRefresh(0) should always return true")
}
}
// tempFile writes content to a temp file and returns its path.
func tempFile(t *testing.T, content []byte) string {
t.Helper()
f, err := os.CreateTemp(t.TempDir(), "cache-*.json")
if err != nil {
t.Fatal(err)
}
if _, err := f.Write(content); err != nil {
t.Fatal(err)
}
f.Close()
return f.Name()
}
func TestUpsertPreservesUsageHistory(t *testing.T) {
c := New("", 3600)
c.Upsert(Entry{Name: "web01", IP: "10.0.0.1"})
c.MarkUsed("web01")
before, _ := c.Get("web01")
c.Upsert(Entry{Name: "web01", IP: "10.0.0.2"})
after, _ := c.Get("web01")
if after.LastUsed != before.LastUsed || after.IP != "10.0.0.2" {
t.Fatalf("history lost: %+v", after)
}
}
func TestSearchMatchesHostnamesAcrossQualifiedSources(t *testing.T) {
c := New("", 3600)
c.Upsert(Entry{Name: "office/web01", IP: "10.0.0.1"})
c.Upsert(Entry{Name: "lab/web01", IP: "10.0.0.2"})
c.Upsert(Entry{Name: "lab/db01", IP: "10.0.0.3"})
for query, want := range map[string]int{"web": 2, "office/web": 1, "lab/": 2, "WEB": 2} {
if got := len(c.Search(query)); got != want {
t.Errorf("Search(%q)=%d, want %d", query, got, want)
}
}
}
func TestStaticHosts(t *testing.T) {
path := filepath.Join(t.TempDir(), "hosts.json")
hosts := []config.StaticHost{{Name: "router", Address: "192.168.1.1", Tags: []string{"home"}}, {Name: "nas", Address: "nas.lan"}}
c := New(path, 1).WithStatic(hosts)
c.Upsert(Entry{Name: "web01", IP: "10.0.0.1", Kind: "device"})
if err := c.Load(); err != nil { // no file yet; static hosts stay
t.Fatal(err)
}
if e, fresh := c.Get("router"); !fresh || e.IP != "192.168.1.1" || e.Kind != config.StaticKind || !e.Static {
t.Fatalf("static get: %+v %v", e, fresh)
}
if e, found, err := c.GetStatic("ROUTER", nil); !found || err != nil || e.Name != "router" {
t.Fatalf("by name: %+v %v %v", e, found, err)
}
normalize := func(s string) string { return strings.TrimSuffix(strings.ToLower(s), ".lan") }
if e, found, _ := c.GetStatic("nas.lan", normalize); !found || e.Name != "nas" {
t.Fatalf("by shortcut: %+v", e)
}
if _, found, _ := c.GetStatic("web01", normalize); found {
t.Fatal("NetBox entry returned as static")
}
// Usage of a static host persists; the host itself stays after Save and Clear.
c.MarkUsed("router")
if err := c.Save(); err != nil {
t.Fatal(err)
}
if _, fresh := c.Get("nas"); !fresh {
t.Fatal("static host lost after Save")
}
reloaded := New(path, 1).WithStatic(hosts)
if err := reloaded.Load(); err != nil {
t.Fatal(err)
}
if recent := reloaded.RecentlyUsed(5); len(recent) != 1 || recent[0].Name != "router" {
t.Fatalf("recent: %+v", recent)
}
reloaded.Clear()
if _, fresh := reloaded.Get("router"); !fresh {
t.Fatal("Clear removed a static host")
}
// A host removed from the config disappears, also from the file.
removed := New(path, 1).WithStatic(hosts[1:])
if err := removed.Load(); err != nil {
t.Fatal(err)
}
if e, _ := removed.Get("router"); e.Name != "" {
t.Fatalf("removed static host still present: %+v", e)
}
if err := removed.Save(); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(path)
if strings.Contains(string(data), "192.168.1.1") {
t.Fatalf("removed static host still on disk:\n%s", data)
}
}
func TestClaimRefreshThrottlesAttempts(t *testing.T) {
c := New(filepath.Join(t.TempDir(), "netssh", "hosts.json"), 60)
if !c.ClaimRefresh(24*time.Hour, time.Minute) {
t.Fatal("a never refreshed cache must claim a refresh")
}
// NetBox is down: the stamp stays stale, but the attempt is remembered.
if c.ClaimRefresh(24*time.Hour, time.Minute) {
t.Error("a second refresh within the retry interval must not start")
}
if !c.ClaimRefresh(24*time.Hour, 0) {
t.Error("after the retry interval a refresh must start again")
}
if err := c.SetRefreshed(); err != nil {
t.Fatal(err)
}
if c.ClaimRefresh(24*time.Hour, 0) {
t.Error("a freshly refreshed cache must not claim a refresh")
}
}
+182
View File
@@ -0,0 +1,182 @@
package cache
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
func TestShortcutRejectsAmbiguousTargets(t *testing.T) {
c := New("", 3600)
c.Upsert(Entry{Name: "web.prod.example", IP: "10.0.0.1"})
c.Upsert(Entry{Name: "web.dev.example", IP: "10.0.0.2"})
normalize := func(s string) string { return strings.SplitN(s, ".", 2)[0] }
for range 100 {
entry, found, fresh, err := c.GetByShortcut("web", normalize)
if err == nil || found || fresh || entry.Name != "" {
t.Fatalf("ambiguous shortcut returned target: %+v, %v, %v, %v", entry, found, fresh, err)
}
}
}
func TestSaveMergesIndependentlyLoadedCaches(t *testing.T) {
path := filepath.Join(t.TempDir(), "hosts.json")
a, b := New(path, 3600), New(path, 3600)
for _, c := range []*Cache{a, b} {
if err := c.Load(); err != nil {
t.Fatal(err)
}
}
a.Upsert(Entry{Name: "a", IP: "10.0.0.1"})
b.Upsert(Entry{Name: "b", IP: "10.0.0.2"})
for _, c := range []*Cache{a, b} {
if err := c.Save(); err != nil {
t.Fatal(err)
}
}
if err := a.Load(); err != nil {
t.Fatal(err)
}
if len(a.All()) != 2 {
t.Fatalf("lost an update: %+v", a.All())
}
// Saving a stale usage update must retain newer IPs and both usage times.
if err := b.Load(); err != nil {
t.Fatal(err)
}
b.MarkUsed("a")
used, _ := b.Get("a")
a.Upsert(Entry{Name: "a", IP: "10.0.0.3"})
if err := a.Save(); err != nil {
t.Fatal(err)
}
if err := b.Save(); err != nil {
t.Fatal(err)
}
got, _ := b.Get("a")
if got.IP != "10.0.0.3" || !got.LastUsed.Equal(used.LastUsed) {
t.Fatalf("lost refreshed IP or usage: %+v", got)
}
b.Delete("a")
if err := b.Save(); err != nil {
t.Fatal(err)
}
if err := a.Load(); err != nil {
t.Fatal(err)
}
if got, _ := a.Get("a"); got.Name != "" {
t.Fatalf("deleted entry survived: %+v", got)
}
a.Clear()
if err := a.Save(); err != nil {
t.Fatal(err)
}
if err := b.Load(); err != nil {
t.Fatal(err)
}
if len(b.All()) != 0 {
t.Fatal("clear merged old entries back in")
}
}
func TestSaveAcrossProcesses(t *testing.T) {
if path := os.Getenv("NETSSH_TEST_CACHE_WRITER_PATH"); path != "" {
c := New(path, 3600)
if err := c.Load(); err != nil {
t.Fatal(err)
}
c.Upsert(Entry{Name: os.Getenv("NETSSH_TEST_CACHE_WRITER_NAME"), IP: "10.0.0.1"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
return
}
path := filepath.Join(t.TempDir(), "hosts.json")
const writers = 8
cmds := make([]*exec.Cmd, writers)
for i := range cmds {
cmd := exec.Command(os.Args[0], "-test.run=^TestSaveAcrossProcesses$")
cmd.Env = append(os.Environ(), "NETSSH_TEST_CACHE_WRITER_PATH="+path, fmt.Sprintf("NETSSH_TEST_CACHE_WRITER_NAME=host-%d", i))
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
cmds[i] = cmd
}
for _, cmd := range cmds {
if err := cmd.Wait(); err != nil {
t.Error(err)
}
}
c := New(path, 3600)
if err := c.Load(); err != nil {
t.Fatal(err)
}
if len(c.All()) != writers {
t.Fatalf("lost concurrent updates: got %d, want %d", len(c.All()), writers)
}
}
func TestSavePreservesNewerUsageFromDisk(t *testing.T) {
path := filepath.Join(t.TempDir(), "hosts.json")
a := New(path, 3600)
a.Upsert(Entry{Name: "web", IP: "10.0.0.1", LastUsed: time.Now()})
if err := a.Save(); err != nil {
t.Fatal(err)
}
b := New(path, 3600)
if err := b.Load(); err != nil {
t.Fatal(err)
}
a.MarkUsed("web")
used, _ := a.Get("web")
if err := a.Save(); err != nil {
t.Fatal(err)
}
b.Upsert(Entry{Name: "web", IP: "10.0.0.2"})
if err := b.Save(); err != nil {
t.Fatal(err)
}
got, _ := b.Get("web")
if got.IP != "10.0.0.2" || !got.LastUsed.Equal(used.LastUsed) {
t.Fatalf("lost data: %+v", got)
}
}
func TestUsageSaveDoesNotRestoreRemovedHosts(t *testing.T) {
for _, clear := range []bool{false, true} {
t.Run(fmt.Sprintf("clear=%v", clear), func(t *testing.T) {
path := filepath.Join(t.TempDir(), "hosts.json")
a := New(path, 3600)
a.Upsert(Entry{Name: "web", IP: "10.0.0.1"})
if err := a.Save(); err != nil {
t.Fatal(err)
}
b := New(path, 3600)
if err := b.Load(); err != nil {
t.Fatal(err)
}
b.MarkUsed("web")
if clear {
a.Clear()
} else {
a.Delete("web")
}
if err := a.Save(); err != nil {
t.Fatal(err)
}
if err := b.Save(); err != nil {
t.Fatal(err)
}
if len(b.All()) != 0 {
t.Fatalf("usage update restored removed entry: %+v", b.All())
}
})
}
}