- Add internal/cache package using go-redis/v9 (Valkey-compatible) - Cache keys are deterministic SHA-256 hashes of search parameters - Cache wraps the Search() method: check cache → miss → execute → store - Gracefully disabled if Valkey is unreachable or unconfigured - Configurable TTL (default 5m), address, password, and DB index - Environment variable overrides: VALKEY_ADDRESS, VALKEY_PASSWORD, VALKEY_DB, VALKEY_CACHE_TTL - Structured JSON logging via slog throughout cache layer - Refactored service.go: extract executeSearch() from Search() for clarity - Update config.example.toml with [cache] section - Add cache package tests (key generation, nop behavior)
77 lines
2 KiB
Go
77 lines
2 KiB
Go
package cache
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/ashie/gosearch/internal/contracts"
|
|
)
|
|
|
|
func TestKey_Deterministic(t *testing.T) {
|
|
req := contracts.SearchRequest{
|
|
Format: contracts.FormatJSON,
|
|
Query: "kafka metamorphosis",
|
|
Pageno: 1,
|
|
Safesearch: 0,
|
|
Language: "auto",
|
|
Engines: []string{"wikipedia", "braveapi"},
|
|
Categories: []string{"general"},
|
|
}
|
|
|
|
key1 := Key(req)
|
|
key2 := Key(req)
|
|
|
|
if key1 != key2 {
|
|
t.Errorf("Key should be deterministic: %q != %q", key1, key2)
|
|
}
|
|
if len(key1) != 32 {
|
|
t.Errorf("expected 32-char key, got %d", len(key1))
|
|
}
|
|
}
|
|
|
|
func TestKey_DifferentQueries(t *testing.T) {
|
|
reqA := contracts.SearchRequest{Query: "kafka", Format: contracts.FormatJSON}
|
|
reqB := contracts.SearchRequest{Query: "orwell", Format: contracts.FormatJSON}
|
|
|
|
if Key(reqA) == Key(reqB) {
|
|
t.Error("different queries should produce different keys")
|
|
}
|
|
}
|
|
|
|
func TestKey_DifferentPageno(t *testing.T) {
|
|
req1 := contracts.SearchRequest{Query: "test", Pageno: 1}
|
|
req2 := contracts.SearchRequest{Query: "test", Pageno: 2}
|
|
|
|
if Key(req1) == Key(req2) {
|
|
t.Error("different pageno should produce different keys")
|
|
}
|
|
}
|
|
|
|
func TestKey_DifferentEngines(t *testing.T) {
|
|
req1 := contracts.SearchRequest{Query: "test", Engines: []string{"wikipedia"}}
|
|
req2 := contracts.SearchRequest{Query: "test", Engines: []string{"braveapi"}}
|
|
|
|
if Key(req1) == Key(req2) {
|
|
t.Error("different engines should produce different keys")
|
|
}
|
|
}
|
|
|
|
func TestKey_TimeRange(t *testing.T) {
|
|
req1 := contracts.SearchRequest{Query: "test"}
|
|
req2 := contracts.SearchRequest{Query: "test", TimeRange: strPtr("week")}
|
|
|
|
if Key(req1) == Key(req2) {
|
|
t.Error("with/without time_range should produce different keys")
|
|
}
|
|
}
|
|
|
|
func TestNew_NopWithoutAddress(t *testing.T) {
|
|
c := New(Config{}, nil)
|
|
if c.Enabled() {
|
|
t.Error("cache should be disabled when no address is configured")
|
|
}
|
|
if err := c.Close(); err != nil {
|
|
t.Errorf("Close on nop cache should not error: %v", err)
|
|
}
|
|
}
|
|
|
|
func strPtr(s string) *string { return &s }
|