Compare commits
1 commit
| Author | SHA1 | Date | |
|---|---|---|---|
| 4d8afbcf68 |
6 changed files with 178 additions and 407 deletions
274
cache.go
274
cache.go
|
|
@ -5,11 +5,13 @@ package cache
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"errors"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"dappco.re/go/core"
|
||||
coreio "dappco.re/go/core/io"
|
||||
coreerr "dappco.re/go/core/log"
|
||||
)
|
||||
|
||||
// DefaultTTL is the default cache expiry time.
|
||||
|
|
@ -19,50 +21,56 @@ import (
|
|||
// c, err := cache.New(coreio.NewMockMedium(), "/tmp/cache", cache.DefaultTTL)
|
||||
const DefaultTTL = 1 * time.Hour
|
||||
|
||||
// Cache stores JSON-encoded entries in a Medium-backed cache rooted at baseDir.
|
||||
// Cache represents a file-based cache.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// c, err := cache.New(coreio.NewMockMedium(), "/tmp/cache", time.Minute)
|
||||
type Cache struct {
|
||||
medium coreio.Medium
|
||||
baseDir string
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// Entry is the serialized cache record written to the backing Medium.
|
||||
// Entry represents a cached item with metadata.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// entry := cache.Entry{CachedAt: time.Now(), ExpiresAt: time.Now().Add(time.Minute)}
|
||||
type Entry struct {
|
||||
Data json.RawMessage `json:"data"`
|
||||
CachedAt time.Time `json:"cached_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// New creates a cache and applies default Medium, base directory, and TTL values
|
||||
// when callers pass zero values.
|
||||
// New creates a new cache instance.
|
||||
// If medium is nil, uses coreio.Local (filesystem).
|
||||
// If baseDir is empty, uses .core/cache in current directory.
|
||||
//
|
||||
// c, err := cache.New(coreio.Local, "/tmp/cache", time.Hour)
|
||||
// Usage example:
|
||||
//
|
||||
// c, err := cache.New(coreio.NewMockMedium(), "/tmp/cache", 30*time.Minute)
|
||||
func New(medium coreio.Medium, baseDir string, ttl time.Duration) (*Cache, error) {
|
||||
if medium == nil {
|
||||
medium = coreio.Local
|
||||
}
|
||||
|
||||
if baseDir == "" {
|
||||
cwd := currentDir()
|
||||
if cwd == "" || cwd == "." {
|
||||
return nil, core.E("cache.New", "failed to resolve current working directory", nil)
|
||||
// Use .core/cache in current working directory
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return nil, coreerr.E("cache.New", "failed to get working directory", err)
|
||||
}
|
||||
|
||||
baseDir = normalizePath(core.JoinPath(cwd, ".core", "cache"))
|
||||
} else {
|
||||
baseDir = absolutePath(baseDir)
|
||||
}
|
||||
|
||||
if ttl < 0 {
|
||||
return nil, core.E("cache.New", "ttl must be >= 0", nil)
|
||||
baseDir = core.Path(cwd, ".core", "cache")
|
||||
}
|
||||
|
||||
if ttl == 0 {
|
||||
ttl = DefaultTTL
|
||||
}
|
||||
|
||||
// Ensure cache directory exists
|
||||
if err := medium.EnsureDir(baseDir); err != nil {
|
||||
return nil, core.E("cache.New", "failed to create cache directory", err)
|
||||
return nil, coreerr.E("cache.New", "failed to create cache directory", err)
|
||||
}
|
||||
|
||||
return &Cache{
|
||||
|
|
@ -72,34 +80,38 @@ func New(medium coreio.Medium, baseDir string, ttl time.Duration) (*Cache, error
|
|||
}, nil
|
||||
}
|
||||
|
||||
// Path returns the storage path used for key and rejects path traversal
|
||||
// attempts.
|
||||
// Path returns the full path for a cache key.
|
||||
// Returns an error if the key attempts path traversal.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// path, err := c.Path("github/acme/repos")
|
||||
func (c *Cache) Path(key string) (string, error) {
|
||||
if err := c.ensureConfigured("cache.Path"); err != nil {
|
||||
return "", err
|
||||
path := joinPath(c.baseDir, key+".json")
|
||||
|
||||
// Ensure the resulting path is still within baseDir to prevent traversal attacks
|
||||
absBase, err := pathAbs(c.baseDir)
|
||||
if err != nil {
|
||||
return "", coreerr.E("cache.Path", "failed to get absolute path for baseDir", err)
|
||||
}
|
||||
absPath, err := pathAbs(path)
|
||||
if err != nil {
|
||||
return "", coreerr.E("cache.Path", "failed to get absolute path for key", err)
|
||||
}
|
||||
|
||||
baseDir := absolutePath(c.baseDir)
|
||||
path := absolutePath(core.JoinPath(baseDir, key+".json"))
|
||||
pathPrefix := normalizePath(core.Concat(baseDir, pathSeparator()))
|
||||
|
||||
if path != baseDir && !core.HasPrefix(path, pathPrefix) {
|
||||
return "", core.E("cache.Path", "invalid cache key: path traversal attempt", nil)
|
||||
if !core.HasPrefix(absPath, absBase+pathSeparator()) && absPath != absBase {
|
||||
return "", coreerr.E("cache.Path", "invalid cache key: path traversal attempt", nil)
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// Get unmarshals the cached item into dest if it exists and has not expired.
|
||||
// Get retrieves a cached item if it exists and hasn't expired.
|
||||
//
|
||||
// found, err := c.Get("github/acme/repos", &repos)
|
||||
// Usage example:
|
||||
//
|
||||
// found, err := c.Get("session/user-42", &dest)
|
||||
func (c *Cache) Get(key string, dest any) (bool, error) {
|
||||
if err := c.ensureReady("cache.Get"); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
path, err := c.Path(key)
|
||||
if err != nil {
|
||||
return false, err
|
||||
|
|
@ -107,147 +119,109 @@ func (c *Cache) Get(key string, dest any) (bool, error) {
|
|||
|
||||
dataStr, err := c.medium.Read(path)
|
||||
if err != nil {
|
||||
if core.Is(err, fs.ErrNotExist) {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
return false, core.E("cache.Get", "failed to read cache file", err)
|
||||
return false, coreerr.E("cache.Get", "failed to read cache file", err)
|
||||
}
|
||||
|
||||
var entry Entry
|
||||
entryResult := core.JSONUnmarshalString(dataStr, &entry)
|
||||
if !entryResult.OK {
|
||||
if err := json.Unmarshal([]byte(dataStr), &entry); err != nil {
|
||||
// Invalid cache file, treat as miss
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Check expiry
|
||||
if time.Now().After(entry.ExpiresAt) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if err := core.JSONUnmarshal(entry.Data, dest); !err.OK {
|
||||
return false, core.E("cache.Get", "failed to unmarshal cached data", err.Value.(error))
|
||||
// Unmarshal the actual data
|
||||
if err := json.Unmarshal(entry.Data, dest); err != nil {
|
||||
return false, coreerr.E("cache.Get", "failed to unmarshal cached data", err)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Set marshals data and stores it in the cache.
|
||||
// Set stores an item in the cache.
|
||||
//
|
||||
// err := c.Set("github/acme/repos", repos)
|
||||
// Usage example:
|
||||
//
|
||||
// err := c.Set("session/user-42", map[string]string{"name": "Ada"})
|
||||
func (c *Cache) Set(key string, data any) error {
|
||||
if err := c.ensureReady("cache.Set"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
path, err := c.Path(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
if err := c.medium.EnsureDir(core.PathDir(path)); err != nil {
|
||||
return core.E("cache.Set", "failed to create directory", err)
|
||||
return coreerr.E("cache.Set", "failed to create directory", err)
|
||||
}
|
||||
|
||||
dataResult := core.JSONMarshal(data)
|
||||
if !dataResult.OK {
|
||||
return core.E("cache.Set", "failed to marshal cache data", dataResult.Value.(error))
|
||||
}
|
||||
|
||||
ttl := c.ttl
|
||||
if ttl < 0 {
|
||||
return core.E("cache.Set", "cache ttl must be >= 0", nil)
|
||||
}
|
||||
if ttl == 0 {
|
||||
ttl = DefaultTTL
|
||||
// Marshal the data
|
||||
dataBytes, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return coreerr.E("cache.Set", "failed to marshal data", err)
|
||||
}
|
||||
|
||||
entry := Entry{
|
||||
Data: dataResult.Value.([]byte),
|
||||
Data: dataBytes,
|
||||
CachedAt: time.Now(),
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
ExpiresAt: time.Now().Add(c.ttl),
|
||||
}
|
||||
|
||||
entryBytes, err := json.MarshalIndent(entry, "", " ")
|
||||
if err != nil {
|
||||
return core.E("cache.Set", "failed to marshal cache entry", err)
|
||||
return coreerr.E("cache.Set", "failed to marshal cache entry", err)
|
||||
}
|
||||
|
||||
if err := c.medium.Write(path, string(entryBytes)); err != nil {
|
||||
return core.E("cache.Set", "failed to write cache file", err)
|
||||
return coreerr.E("cache.Set", "failed to write cache file", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete removes the cached item for key.
|
||||
// Delete removes an item from the cache.
|
||||
//
|
||||
// err := c.Delete("github/acme/repos")
|
||||
// Usage example:
|
||||
//
|
||||
// err := c.Delete("session/user-42")
|
||||
func (c *Cache) Delete(key string) error {
|
||||
if err := c.ensureReady("cache.Delete"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
path, err := c.Path(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = c.medium.Delete(path)
|
||||
if core.Is(err, fs.ErrNotExist) {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return core.E("cache.Delete", "failed to delete cache file", err)
|
||||
return coreerr.E("cache.Delete", "failed to delete cache file", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteMany removes several cached items in one call.
|
||||
// Clear removes all cached items.
|
||||
//
|
||||
// err := c.DeleteMany("github/acme/repos", "github/acme/meta")
|
||||
func (c *Cache) DeleteMany(keys ...string) error {
|
||||
if err := c.ensureReady("cache.DeleteMany"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, key := range keys {
|
||||
path, err := c.Path(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = c.medium.Delete(path)
|
||||
if core.Is(err, fs.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return core.E("cache.DeleteMany", "failed to delete cache file", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Clear removes all cached items under the cache base directory.
|
||||
// Usage example:
|
||||
//
|
||||
// err := c.Clear()
|
||||
func (c *Cache) Clear() error {
|
||||
if err := c.ensureReady("cache.Clear"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := c.medium.DeleteAll(c.baseDir); err != nil {
|
||||
return core.E("cache.Clear", "failed to clear cache", err)
|
||||
return coreerr.E("cache.Clear", "failed to clear cache", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Age reports how long ago key was cached, or -1 if it is missing or unreadable.
|
||||
// Age returns how old a cached item is, or -1 if not cached.
|
||||
//
|
||||
// age := c.Age("github/acme/repos")
|
||||
// Usage example:
|
||||
//
|
||||
// age := c.Age("session/user-42")
|
||||
func (c *Cache) Age(key string) time.Duration {
|
||||
if err := c.ensureReady("cache.Age"); err != nil {
|
||||
return -1
|
||||
}
|
||||
|
||||
path, err := c.Path(key)
|
||||
if err != nil {
|
||||
return -1
|
||||
|
|
@ -259,8 +233,7 @@ func (c *Cache) Age(key string) time.Duration {
|
|||
}
|
||||
|
||||
var entry Entry
|
||||
entryResult := core.JSONUnmarshalString(dataStr, &entry)
|
||||
if !entryResult.OK {
|
||||
if err := json.Unmarshal([]byte(dataStr), &entry); err != nil {
|
||||
return -1
|
||||
}
|
||||
|
||||
|
|
@ -269,80 +242,53 @@ func (c *Cache) Age(key string) time.Duration {
|
|||
|
||||
// GitHub-specific cache keys
|
||||
|
||||
// GitHubReposKey returns the cache key used for an organisation's repo list.
|
||||
// GitHubReposKey returns the cache key for an org's repo list.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// key := cache.GitHubReposKey("acme")
|
||||
func GitHubReposKey(org string) string {
|
||||
return core.JoinPath("github", org, "repos")
|
||||
}
|
||||
|
||||
// GitHubRepoKey returns the cache key used for a repository metadata entry.
|
||||
// GitHubRepoKey returns the cache key for a specific repo's metadata.
|
||||
//
|
||||
// Usage example:
|
||||
//
|
||||
// key := cache.GitHubRepoKey("acme", "widgets")
|
||||
func GitHubRepoKey(org, repo string) string {
|
||||
return core.JoinPath("github", org, repo, "meta")
|
||||
}
|
||||
|
||||
func pathSeparator() string {
|
||||
if ds := core.Env("DS"); ds != "" {
|
||||
return ds
|
||||
func joinPath(segments ...string) string {
|
||||
return normalizePath(core.JoinPath(segments...))
|
||||
}
|
||||
|
||||
func pathAbs(path string) (string, error) {
|
||||
path = normalizePath(path)
|
||||
if core.PathIsAbs(path) {
|
||||
return core.CleanPath(path, pathSeparator()), nil
|
||||
}
|
||||
|
||||
return "/"
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return core.Path(cwd, path), nil
|
||||
}
|
||||
|
||||
func normalizePath(path string) string {
|
||||
ds := pathSeparator()
|
||||
normalized := core.Replace(path, "\\", ds)
|
||||
|
||||
if ds != "/" {
|
||||
normalized = core.Replace(normalized, "/", ds)
|
||||
if pathSeparator() == "/" {
|
||||
return path
|
||||
}
|
||||
|
||||
return core.CleanPath(normalized, ds)
|
||||
return core.Replace(path, "/", pathSeparator())
|
||||
}
|
||||
|
||||
func absolutePath(path string) string {
|
||||
normalized := normalizePath(path)
|
||||
if core.PathIsAbs(normalized) {
|
||||
return normalized
|
||||
func pathSeparator() string {
|
||||
sep := core.Env("DS")
|
||||
if sep == "" {
|
||||
return "/"
|
||||
}
|
||||
|
||||
cwd := currentDir()
|
||||
if cwd == "" || cwd == "." {
|
||||
return normalized
|
||||
}
|
||||
|
||||
return normalizePath(core.JoinPath(cwd, normalized))
|
||||
}
|
||||
|
||||
func currentDir() string {
|
||||
cwd := normalizePath(core.Env("PWD"))
|
||||
if cwd != "" && cwd != "." {
|
||||
return cwd
|
||||
}
|
||||
|
||||
return normalizePath(core.Env("DIR_CWD"))
|
||||
}
|
||||
|
||||
func (c *Cache) ensureConfigured(op string) error {
|
||||
if c == nil {
|
||||
return core.E(op, "cache is nil", nil)
|
||||
}
|
||||
if c.baseDir == "" {
|
||||
return core.E(op, "cache base directory is empty; construct with cache.New", nil)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Cache) ensureReady(op string) error {
|
||||
if err := c.ensureConfigured(op); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.medium == nil {
|
||||
return core.E(op, "cache medium is nil; construct with cache.New", nil)
|
||||
}
|
||||
|
||||
return nil
|
||||
return sep
|
||||
}
|
||||
|
|
|
|||
297
cache_test.go
297
cache_test.go
|
|
@ -3,274 +3,79 @@
|
|||
package cache_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"dappco.re/go/core"
|
||||
"dappco.re/go/core/cache"
|
||||
coreio "dappco.re/go/core/io"
|
||||
)
|
||||
|
||||
func newTestCache(t *testing.T, baseDir string, ttl time.Duration) (*cache.Cache, *coreio.MockMedium) {
|
||||
t.Helper()
|
||||
|
||||
func TestCache(t *testing.T) {
|
||||
m := coreio.NewMockMedium()
|
||||
c, err := cache.New(m, baseDir, ttl)
|
||||
// Use a path that MockMedium will understand
|
||||
baseDir := "/tmp/cache"
|
||||
c, err := cache.New(m, baseDir, 1*time.Minute)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create cache: %v", err)
|
||||
}
|
||||
|
||||
return c, m
|
||||
}
|
||||
|
||||
func readEntry(t *testing.T, raw string) cache.Entry {
|
||||
t.Helper()
|
||||
|
||||
var entry cache.Entry
|
||||
result := core.JSONUnmarshalString(raw, &entry)
|
||||
if !result.OK {
|
||||
t.Fatalf("failed to unmarshal cache entry: %v", result.Value)
|
||||
}
|
||||
|
||||
return entry
|
||||
}
|
||||
|
||||
func TestCache_New_Good(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
t.Chdir(tmpDir)
|
||||
|
||||
c, m := newTestCache(t, "", 0)
|
||||
|
||||
const key = "defaults"
|
||||
if err := c.Set(key, map[string]string{"foo": "bar"}); err != nil {
|
||||
t.Fatalf("Set failed: %v", err)
|
||||
}
|
||||
|
||||
path, err := c.Path(key)
|
||||
if err != nil {
|
||||
t.Fatalf("Path failed: %v", err)
|
||||
}
|
||||
|
||||
wantPath := core.JoinPath(tmpDir, ".core", "cache", key+".json")
|
||||
if path != wantPath {
|
||||
t.Fatalf("expected default path %q, got %q", wantPath, path)
|
||||
}
|
||||
|
||||
raw, err := m.Read(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Read failed: %v", err)
|
||||
}
|
||||
if !strings.Contains(raw, "\n \"data\":") {
|
||||
t.Fatalf("expected pretty-printed cache entry, got %q", raw)
|
||||
}
|
||||
|
||||
entry := readEntry(t, raw)
|
||||
ttl := entry.ExpiresAt.Sub(entry.CachedAt)
|
||||
if ttl < cache.DefaultTTL || ttl > cache.DefaultTTL+time.Second {
|
||||
t.Fatalf("expected ttl near %v, got %v", cache.DefaultTTL, ttl)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_New_Bad(t *testing.T) {
|
||||
_, err := cache.New(coreio.NewMockMedium(), "/tmp/cache-negative-ttl", -time.Second)
|
||||
if err == nil {
|
||||
t.Fatal("expected New to reject negative ttl, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_Path_Good(t *testing.T) {
|
||||
c, _ := newTestCache(t, "/tmp/cache-path", time.Minute)
|
||||
|
||||
path, err := c.Path("github/acme/repos")
|
||||
if err != nil {
|
||||
t.Fatalf("Path failed: %v", err)
|
||||
}
|
||||
|
||||
want := "/tmp/cache-path/github/acme/repos.json"
|
||||
if path != want {
|
||||
t.Fatalf("expected path %q, got %q", want, path)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_Path_Bad(t *testing.T) {
|
||||
c, _ := newTestCache(t, "/tmp/cache-traversal", time.Minute)
|
||||
|
||||
_, err := c.Path("../../etc/passwd")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for path traversal key, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_Get_Good(t *testing.T) {
|
||||
c, _ := newTestCache(t, "/tmp/cache", time.Minute)
|
||||
|
||||
key := "test-key"
|
||||
data := map[string]string{"foo": "bar"}
|
||||
|
||||
// Test Set
|
||||
if err := c.Set(key, data); err != nil {
|
||||
t.Fatalf("Set failed: %v", err)
|
||||
t.Errorf("Set failed: %v", err)
|
||||
}
|
||||
|
||||
// Test Get
|
||||
var retrieved map[string]string
|
||||
found, err := c.Get(key, &retrieved)
|
||||
if err != nil {
|
||||
t.Fatalf("Get failed: %v", err)
|
||||
t.Errorf("Get failed: %v", err)
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("expected to find cached item")
|
||||
t.Error("expected to find cached item")
|
||||
}
|
||||
if retrieved["foo"] != "bar" {
|
||||
t.Errorf("expected foo=bar, got %v", retrieved["foo"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_Get_Ugly(t *testing.T) {
|
||||
c, _ := newTestCache(t, "/tmp/cache-expiry", 10*time.Millisecond)
|
||||
|
||||
if err := c.Set("test-key", map[string]string{"foo": "bar"}); err != nil {
|
||||
t.Fatalf("Set for expiry test failed: %v", err)
|
||||
// Test Age
|
||||
age := c.Age(key)
|
||||
if age < 0 {
|
||||
t.Error("expected age >= 0")
|
||||
}
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
|
||||
var retrieved map[string]string
|
||||
found, err := c.Get("test-key", &retrieved)
|
||||
// Test Delete
|
||||
if err := c.Delete(key); err != nil {
|
||||
t.Errorf("Delete failed: %v", err)
|
||||
}
|
||||
found, err = c.Get(key, &retrieved)
|
||||
if err != nil {
|
||||
t.Fatalf("Get for expired item returned an unexpected error: %v", err)
|
||||
}
|
||||
if found {
|
||||
t.Error("expected item to be expired")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_Age_Good(t *testing.T) {
|
||||
c, _ := newTestCache(t, "/tmp/cache-age", time.Minute)
|
||||
|
||||
if err := c.Set("test-key", map[string]string{"foo": "bar"}); err != nil {
|
||||
t.Fatalf("Set failed: %v", err)
|
||||
}
|
||||
|
||||
if age := c.Age("test-key"); age < 0 {
|
||||
t.Errorf("expected age >= 0, got %v", age)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_NilReceiver_Good(t *testing.T) {
|
||||
var c *cache.Cache
|
||||
var target map[string]string
|
||||
|
||||
if _, err := c.Path("x"); err == nil {
|
||||
t.Fatal("expected Path to fail on nil receiver")
|
||||
}
|
||||
|
||||
if _, err := c.Get("x", &target); err == nil {
|
||||
t.Fatal("expected Get to fail on nil receiver")
|
||||
}
|
||||
|
||||
if err := c.Set("x", map[string]string{"foo": "bar"}); err == nil {
|
||||
t.Fatal("expected Set to fail on nil receiver")
|
||||
}
|
||||
|
||||
if err := c.Delete("x"); err == nil {
|
||||
t.Fatal("expected Delete to fail on nil receiver")
|
||||
}
|
||||
|
||||
if err := c.Clear(); err == nil {
|
||||
t.Fatal("expected Clear to fail on nil receiver")
|
||||
}
|
||||
|
||||
if age := c.Age("x"); age != -1 {
|
||||
t.Fatalf("expected Age to return -1 on nil receiver, got %v", age)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_ZeroValue_Ugly(t *testing.T) {
|
||||
var c cache.Cache
|
||||
var target map[string]string
|
||||
|
||||
if _, err := c.Path("x"); err == nil {
|
||||
t.Fatal("expected Path to fail on zero-value cache")
|
||||
}
|
||||
|
||||
if _, err := c.Get("x", &target); err == nil {
|
||||
t.Fatal("expected Get to fail on zero-value cache")
|
||||
}
|
||||
|
||||
if err := c.Set("x", map[string]string{"foo": "bar"}); err == nil {
|
||||
t.Fatal("expected Set to fail on zero-value cache")
|
||||
}
|
||||
|
||||
if err := c.Delete("x"); err == nil {
|
||||
t.Fatal("expected Delete to fail on zero-value cache")
|
||||
}
|
||||
|
||||
if err := c.Clear(); err == nil {
|
||||
t.Fatal("expected Clear to fail on zero-value cache")
|
||||
}
|
||||
|
||||
if age := c.Age("x"); age != -1 {
|
||||
t.Fatalf("expected Age to return -1 on zero-value cache, got %v", age)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_Delete_Good(t *testing.T) {
|
||||
c, _ := newTestCache(t, "/tmp/cache-delete", time.Minute)
|
||||
|
||||
if err := c.Set("test-key", map[string]string{"foo": "bar"}); err != nil {
|
||||
t.Fatalf("Set failed: %v", err)
|
||||
}
|
||||
|
||||
if err := c.Delete("test-key"); err != nil {
|
||||
t.Fatalf("Delete failed: %v", err)
|
||||
}
|
||||
|
||||
var retrieved map[string]string
|
||||
found, err := c.Get("test-key", &retrieved)
|
||||
if err != nil {
|
||||
t.Fatalf("Get after delete returned an unexpected error: %v", err)
|
||||
t.Errorf("Get after delete returned an unexpected error: %v", err)
|
||||
}
|
||||
if found {
|
||||
t.Error("expected item to be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_DeleteMany_Good(t *testing.T) {
|
||||
c, _ := newTestCache(t, "/tmp/cache-delete-many", time.Minute)
|
||||
data := map[string]string{"foo": "bar"}
|
||||
|
||||
if err := c.Set("key1", data); err != nil {
|
||||
t.Fatalf("Set failed for key1: %v", err)
|
||||
}
|
||||
if err := c.Set("key2", data); err != nil {
|
||||
t.Fatalf("Set failed for key2: %v", err)
|
||||
}
|
||||
if err := c.DeleteMany("key1", "missing", "key2"); err != nil {
|
||||
t.Fatalf("DeleteMany failed: %v", err)
|
||||
}
|
||||
|
||||
var retrieved map[string]string
|
||||
found, err := c.Get("key1", &retrieved)
|
||||
// Test Expiry
|
||||
cshort, err := cache.New(m, "/tmp/cache-short", 10*time.Millisecond)
|
||||
if err != nil {
|
||||
t.Fatalf("Get after DeleteMany returned an unexpected error: %v", err)
|
||||
t.Fatalf("failed to create short-lived cache: %v", err)
|
||||
}
|
||||
if err := cshort.Set(key, data); err != nil {
|
||||
t.Fatalf("Set for expiry test failed: %v", err)
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
found, err = cshort.Get(key, &retrieved)
|
||||
if err != nil {
|
||||
t.Errorf("Get for expired item returned an unexpected error: %v", err)
|
||||
}
|
||||
if found {
|
||||
t.Error("expected key1 to be deleted")
|
||||
t.Error("expected item to be expired")
|
||||
}
|
||||
|
||||
found, err = c.Get("key2", &retrieved)
|
||||
if err != nil {
|
||||
t.Fatalf("Get after DeleteMany returned an unexpected error: %v", err)
|
||||
}
|
||||
if found {
|
||||
t.Error("expected key2 to be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_Clear_Good(t *testing.T) {
|
||||
c, _ := newTestCache(t, "/tmp/cache-clear", time.Minute)
|
||||
data := map[string]string{"foo": "bar"}
|
||||
|
||||
// Test Clear
|
||||
if err := c.Set("key1", data); err != nil {
|
||||
t.Fatalf("Set for clear test failed for key1: %v", err)
|
||||
}
|
||||
|
|
@ -278,29 +83,49 @@ func TestCache_Clear_Good(t *testing.T) {
|
|||
t.Fatalf("Set for clear test failed for key2: %v", err)
|
||||
}
|
||||
if err := c.Clear(); err != nil {
|
||||
t.Fatalf("Clear failed: %v", err)
|
||||
t.Errorf("Clear failed: %v", err)
|
||||
}
|
||||
|
||||
var retrieved map[string]string
|
||||
found, err := c.Get("key1", &retrieved)
|
||||
found, err = c.Get("key1", &retrieved)
|
||||
if err != nil {
|
||||
t.Fatalf("Get after clear returned an unexpected error: %v", err)
|
||||
t.Errorf("Get after clear returned an unexpected error: %v", err)
|
||||
}
|
||||
if found {
|
||||
t.Error("expected key1 to be cleared")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_GitHubReposKey_Good(t *testing.T) {
|
||||
func TestCacheDefaults(t *testing.T) {
|
||||
// Test default Medium (io.Local) and default TTL
|
||||
c, err := cache.New(nil, "", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create cache with defaults: %v", err)
|
||||
}
|
||||
if c == nil {
|
||||
t.Fatal("expected cache instance")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitHubKeys(t *testing.T) {
|
||||
key := cache.GitHubReposKey("myorg")
|
||||
if key != "github/myorg/repos" {
|
||||
t.Errorf("unexpected GitHubReposKey: %q", key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCache_GitHubRepoKey_Good(t *testing.T) {
|
||||
key := cache.GitHubRepoKey("myorg", "myrepo")
|
||||
key = cache.GitHubRepoKey("myorg", "myrepo")
|
||||
if key != "github/myorg/myrepo/meta" {
|
||||
t.Errorf("unexpected GitHubRepoKey: %q", key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathTraversalRejected(t *testing.T) {
|
||||
m := coreio.NewMockMedium()
|
||||
c, err := cache.New(m, "/tmp/cache-traversal", 1*time.Minute)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create cache: %v", err)
|
||||
}
|
||||
|
||||
_, err = c.Path("../../etc/passwd")
|
||||
if err == nil {
|
||||
t.Error("expected error for path traversal key, got nil")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,7 +22,6 @@ own usage example in a doc comment or Go example test.
|
|||
| `(*Cache).Get` | `func (c *Cache) Get(key string, dest any) (bool, error)` | `dappco.re/go/core/cache` | Retrieves a cached item if it exists and has not expired. | yes | no |
|
||||
| `(*Cache).Set` | `func (c *Cache) Set(key string, data any) error` | `dappco.re/go/core/cache` | Stores an item in the cache. | yes | no |
|
||||
| `(*Cache).Delete` | `func (c *Cache) Delete(key string) error` | `dappco.re/go/core/cache` | Removes an item from the cache. | yes | no |
|
||||
| `(*Cache).DeleteMany` | `func (c *Cache) DeleteMany(keys ...string) error` | `dappco.re/go/core/cache` | Removes several items from the cache in one call. | yes | no |
|
||||
| `(*Cache).Clear` | `func (c *Cache) Clear() error` | `dappco.re/go/core/cache` | Removes all cached items. | yes | no |
|
||||
| `(*Cache).Age` | `func (c *Cache) Age(key string) time.Duration` | `dappco.re/go/core/cache` | Returns how old a cached item is, or `-1` if it is not cached. | yes | no |
|
||||
| `GitHubReposKey` | `func GitHubReposKey(org string) string` | `dappco.re/go/core/cache` | Returns the cache key for an organization's repo list. | yes | no |
|
||||
|
|
|
|||
|
|
@ -136,8 +136,6 @@ Key behaviours:
|
|||
|
||||
- **`Delete(key)`** removes a single entry. If the file does not exist, the
|
||||
operation succeeds silently.
|
||||
- **`DeleteMany(keys...)`** removes several entries in one call and ignores
|
||||
missing files, using the same per-key path validation as `Delete()`.
|
||||
- **`Clear()`** calls `medium.DeleteAll(baseDir)`, removing the entire cache
|
||||
directory and all its contents.
|
||||
|
||||
|
|
|
|||
5
go.mod
5
go.mod
|
|
@ -3,8 +3,9 @@ module dappco.re/go/core/cache
|
|||
go 1.26.0
|
||||
|
||||
require (
|
||||
dappco.re/go/core v0.8.0-alpha.1
|
||||
dappco.re/go/core v0.6.0
|
||||
dappco.re/go/core/io v0.2.0
|
||||
dappco.re/go/core/log v0.1.0
|
||||
)
|
||||
|
||||
require dappco.re/go/core/log v0.0.4 // indirect
|
||||
require forge.lthn.ai/core/go-log v0.0.4 // indirect
|
||||
|
|
|
|||
6
go.sum
6
go.sum
|
|
@ -1,7 +1,9 @@
|
|||
dappco.re/go/core v0.8.0-alpha.1 h1:gj7+Scv+L63Z7wMxbJYHhaRFkHJo2u4MMPuUSv/Dhtk=
|
||||
dappco.re/go/core v0.8.0-alpha.1/go.mod h1:f2/tBZ3+3IqDrg2F5F598llv0nmb/4gJVCFzM5geE4A=
|
||||
dappco.re/go/core v0.6.0 h1:0wmuO/UmCWXxJkxQ6XvVLnqkAuWitbd49PhxjCsplyk=
|
||||
dappco.re/go/core v0.6.0/go.mod h1:f2/tBZ3+3IqDrg2F5F598llv0nmb/4gJVCFzM5geE4A=
|
||||
dappco.re/go/core/io v0.2.0 h1:zuudgIiTsQQ5ipVt97saWdGLROovbEB/zdVyy9/l+I4=
|
||||
dappco.re/go/core/io v0.2.0/go.mod h1:1QnQV6X9LNgFKfm8SkOtR9LLaj3bDcsOIeJOOyjbL5E=
|
||||
dappco.re/go/core/log v0.1.0 h1:pa71Vq2TD2aoEUQWFKwNcaJ3GBY8HbaNGqtE688Unyc=
|
||||
dappco.re/go/core/log v0.1.0/go.mod h1:Nkqb8gsXhZAO8VLpx7B8i1iAmohhzqA20b9Zr8VUcJs=
|
||||
forge.lthn.ai/core/go-log v0.0.4 h1:KTuCEPgFmuM8KJfnyQ8vPOU1Jg654W74h8IJvfQMfv0=
|
||||
forge.lthn.ai/core/go-log v0.0.4/go.mod h1:r14MXKOD3LF/sI8XUJQhRk/SZHBE7jAFVuCfgkXoZPw=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue