feat(web): Go W-G9 memory/Redis cache drivers

Wire web_cache_* ABIs with an in-process memory backend and go-redis
ops so drivers smoke covers cache, file storage, postgres URL, and s3 open.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-10 19:41:10 +08:00
1 parent 4c06851e0e
commit 695939ac74
7 files changed
+575 -2

No files matched your search

+260
View File
@@ -0,0 +1,260 @@
// Package cache ports memory and Redis cache backends from the Rust web plugin (W-G9).
package cache
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/redis/go-redis/v9"
)
type entry struct {
value string
exp *uint64 // absolute expiry unix secs; nil = no TTL
}
type memStore struct {
data map[string]entry
}
type backend struct {
mem *memStore
redisURL string
}
var (
handlesMu sync.Mutex
handles = map[string]*backend{}
)
func now() uint64 {
return uint64(time.Now().Unix())
}
func isMemory(url string) bool {
u := strings.ToLower(strings.TrimSpace(url))
return u == "" || u == "memory:" || u == "memory://" || strings.HasPrefix(u, "memory:")
}
func isRedis(url string) bool {
u := strings.ToLower(strings.TrimSpace(url))
return strings.HasPrefix(u, "redis://") || strings.HasPrefix(u, "rediss://")
}
// Open creates or reuses a cache handle. Returns {_type, url}.
func Open(url string) (map[string]any, error) {
url = strings.TrimSpace(url)
if url == "" {
url = "memory:"
}
if !isMemory(url) && !isRedis(url) {
return nil, fmt.Errorf("cache url must be `memory:` or `redis://…`, got `%s`", url)
}
handlesMu.Lock()
defer handlesMu.Unlock()
if _, ok := handles[url]; !ok {
var b backend
if isMemory(url) {
b.mem = &memStore{data: map[string]entry{}}
} else {
b.redisURL = url
}
handles[url] = &b
}
return map[string]any{"_type": "cache", "url": url}, nil
}
func pruneMem(store *memStore) {
t := now()
for k, e := range store.data {
if e.exp != nil && *e.exp <= t {
delete(store.data, k)
}
}
}
func withBackend(url string, f func(*backend) (map[string]any, error)) (map[string]any, error) {
handlesMu.Lock()
defer handlesMu.Unlock()
b, ok := handles[url]
if !ok {
return nil, fmt.Errorf("cache `%s` not opened — call cache.new first", url)
}
return f(b)
}
// Get returns {ok:true,value} on hit or {ok:false} on miss.
func Get(url, key string) (map[string]any, error) {
return withBackend(url, func(b *backend) (map[string]any, error) {
if b.mem != nil {
pruneMem(b.mem)
if e, ok := b.mem.data[key]; ok {
return map[string]any{"ok": true, "value": e.value}, nil
}
return map[string]any{"ok": false}, nil
}
return redisGet(b.redisURL, key)
})
}
// Set stores a value with optional TTL seconds (0/nil = no expiry).
func Set(url, key, value string, ttlSec *uint64) (map[string]any, error) {
return withBackend(url, func(b *backend) (map[string]any, error) {
if b.mem != nil {
pruneMem(b.mem)
var exp *uint64
if ttlSec != nil && *ttlSec > 0 {
t := now() + *ttlSec
exp = &t
}
b.mem.data[key] = entry{value: value, exp: exp}
return map[string]any{"ok": true}, nil
}
return redisSet(b.redisURL, key, value, ttlSec)
})
}
// Del removes a key. Returns {ok:bool} (true if key existed).
func Del(url, key string) (map[string]any, error) {
return withBackend(url, func(b *backend) (map[string]any, error) {
if b.mem != nil {
ok := false
if _, exists := b.mem.data[key]; exists {
delete(b.mem.data, key)
ok = true
}
return map[string]any{"ok": ok}, nil
}
return redisDel(b.redisURL, key)
})
}
// Exists returns {ok:bool} — ok is true when the key is present.
func Exists(url, key string) (map[string]any, error) {
return withBackend(url, func(b *backend) (map[string]any, error) {
if b.mem != nil {
pruneMem(b.mem)
_, ok := b.mem.data[key]
return map[string]any{"ok": ok}, nil
}
return redisExists(b.redisURL, key)
})
}
// TTL returns remaining seconds: -1 no expiry, -2 missing key.
func TTL(url, key string) (map[string]any, error) {
return withBackend(url, func(b *backend) (map[string]any, error) {
if b.mem != nil {
pruneMem(b.mem)
if e, ok := b.mem.data[key]; ok {
var left int64 = -1
if e.exp != nil {
left = int64(*e.exp - now())
if left < 0 {
left = 0
}
}
return map[string]any{"ok": true, "ttl": left}, nil
}
return map[string]any{"ok": false, "ttl": -2}, nil
}
return redisTTL(b.redisURL, key)
})
}
// Reset clears all handles (tests).
func Reset() {
handlesMu.Lock()
defer handlesMu.Unlock()
handles = map[string]*backend{}
}
func redisClient(url string) (*redis.Client, error) {
opts, err := redis.ParseURL(url)
if err != nil {
return nil, err
}
return redis.NewClient(opts), nil
}
func redisGet(url, key string) (map[string]any, error) {
client, err := redisClient(url)
if err != nil {
return nil, err
}
defer client.Close()
ctx := context.Background()
v, err := client.Get(ctx, key).Result()
if err == redis.Nil {
return map[string]any{"ok": false}, nil
}
if err != nil {
return nil, err
}
return map[string]any{"ok": true, "value": v}, nil
}
func redisSet(url, key, value string, ttlSec *uint64) (map[string]any, error) {
client, err := redisClient(url)
if err != nil {
return nil, err
}
defer client.Close()
ctx := context.Background()
if ttlSec != nil && *ttlSec > 0 {
if err := client.SetEx(ctx, key, value, time.Duration(*ttlSec)*time.Second).Err(); err != nil {
return nil, err
}
} else {
if err := client.Set(ctx, key, value, 0).Err(); err != nil {
return nil, err
}
}
return map[string]any{"ok": true}, nil
}
func redisDel(url, key string) (map[string]any, error) {
client, err := redisClient(url)
if err != nil {
return nil, err
}
defer client.Close()
ctx := context.Background()
n, err := client.Del(ctx, key).Result()
if err != nil {
return nil, err
}
return map[string]any{"ok": n > 0}, nil
}
func redisExists(url, key string) (map[string]any, error) {
client, err := redisClient(url)
if err != nil {
return nil, err
}
defer client.Close()
ctx := context.Background()
n, err := client.Exists(ctx, key).Result()
if err != nil {
return nil, err
}
return map[string]any{"ok": n > 0}, nil
}
func redisTTL(url, key string) (map[string]any, error) {
client, err := redisClient(url)
if err != nil {
return nil, err
}
defer client.Close()
ctx := context.Background()
t, err := client.TTL(ctx, key).Result()
if err != nil {
return nil, err
}
secs := int64(t.Seconds())
return map[string]any{"ok": secs >= -1, "ttl": secs}, nil
}
+127
View File
@@ -0,0 +1,127 @@
package cache
import (
"testing"
"time"
)
func TestMemoryRoundtrip(t *testing.T) {
Reset()
url := "memory:test-cache"
if _, err := Open(url); err != nil {
t.Fatal(err)
}
ttl := uint64(60)
if _, err := Set(url, "a", "1", &ttl); err != nil {
t.Fatal(err)
}
g, err := Get(url, "a")
if err != nil {
t.Fatal(err)
}
if g["ok"] != true {
t.Fatalf("get ok: %v", g["ok"])
}
if g["value"] != "1" {
t.Fatalf("value: %v", g["value"])
}
ex, err := Exists(url, "a")
if err != nil {
t.Fatal(err)
}
if ex["ok"] != true {
t.Fatalf("exists: %v", ex["ok"])
}
if _, err := Del(url, "a"); err != nil {
t.Fatal(err)
}
g, err = Get(url, "a")
if err != nil {
t.Fatal(err)
}
if g["ok"] != false {
t.Fatalf("get after del: %v", g["ok"])
}
ex, err = Exists(url, "a")
if err != nil {
t.Fatal(err)
}
if ex["ok"] != false {
t.Fatalf("exists after del: %v", ex["ok"])
}
}
func TestMemoryTTLExpiry(t *testing.T) {
Reset()
url := "memory:ttl-test"
if _, err := Open(url); err != nil {
t.Fatal(err)
}
ttl := uint64(1)
if _, err := Set(url, "k", "v", &ttl); err != nil {
t.Fatal(err)
}
tt, err := TTL(url, "k")
if err != nil {
t.Fatal(err)
}
if tt["ok"] != true {
t.Fatalf("ttl ok: %v", tt["ok"])
}
ttlVal, ok := tt["ttl"].(int64)
if !ok {
// JSON roundtrip may use float64 in some paths; accept both.
if f, ok := tt["ttl"].(float64); ok {
ttlVal = int64(f)
} else {
t.Fatalf("ttl type: %T", tt["ttl"])
}
}
if ttlVal < 0 || ttlVal > 1 {
t.Fatalf("ttl seconds: %d", ttlVal)
}
time.Sleep(1100 * time.Millisecond)
g, err := Get(url, "k")
if err != nil {
t.Fatal(err)
}
if g["ok"] != false {
t.Fatalf("expected expired miss, got %v", g)
}
}
func TestMemoryDelReturnsOk(t *testing.T) {
Reset()
url := "memory:del-test"
if _, err := Open(url); err != nil {
t.Fatal(err)
}
d, err := Del(url, "missing")
if err != nil {
t.Fatal(err)
}
if d["ok"] != false {
t.Fatalf("del missing: %v", d["ok"])
}
if _, err := Set(url, "x", "y", nil); err != nil {
t.Fatal(err)
}
d, err = Del(url, "x")
if err != nil {
t.Fatal(err)
}
if d["ok"] != true {
t.Fatalf("del existing: %v", d["ok"])
}
}
func TestRedisOpenOnly(t *testing.T) {
Reset()
out, err := Open("redis://127.0.0.1:6379/0")
if err != nil {
t.Fatal(err)
}
if out["_type"] != "cache" {
t.Fatalf("type: %v", out["_type"])
}
}