Merge pull request 'fix(api): 后台写操作成功后刷新公开 API 缓存 (#40)' (#50) from devin/1793407455-goods-40-cache-invalidation into main
Merge pull request 'fix(api): 后台写操作成功后刷新公开 API 缓存 (#40)' (#50)
This commit was merged in pull request #50.
This commit is contained in:
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/baicai2026-baicai/goods/api/internal/adminstore"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/adminweb"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/auth"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/cache"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/clientip"
|
||||
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
|
||||
)
|
||||
@@ -75,9 +76,12 @@ func main() {
|
||||
}
|
||||
|
||||
authn := auth.New(username, passwordHash, secret, 12*time.Hour)
|
||||
usage := ratelimit.New(getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0"))
|
||||
redisURL := getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0")
|
||||
usage := ratelimit.New(redisURL)
|
||||
readCache := cache.New(redisURL)
|
||||
h := adminhandler.New(adminstore.New(pool), authn, basePath, adminweb.Dist()).
|
||||
WithUsage(usage).
|
||||
WithCache(readCache).
|
||||
WithClientIP(clientIPs)
|
||||
|
||||
srv := &http.Server{
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package adminhandler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeCacheBumper struct {
|
||||
calls int
|
||||
err error
|
||||
contexts []context.Context
|
||||
}
|
||||
|
||||
func (f *fakeCacheBumper) Bump(ctx context.Context) error {
|
||||
f.calls++
|
||||
f.contexts = append(f.contexts, ctx)
|
||||
return f.err
|
||||
}
|
||||
|
||||
func TestInvalidateCache(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
status int
|
||||
write bool
|
||||
want int
|
||||
}{
|
||||
{name: "successful write", method: http.MethodPost, status: http.StatusCreated, write: true, want: 1},
|
||||
{name: "implicit success", method: http.MethodPost, status: http.StatusOK, want: 1},
|
||||
{name: "client error", method: http.MethodPost, status: http.StatusBadRequest, write: true},
|
||||
{name: "server error", method: http.MethodPost, status: http.StatusInternalServerError, write: true},
|
||||
{name: "get", method: http.MethodGet, status: http.StatusCreated, write: true},
|
||||
{name: "head", method: http.MethodHead, status: http.StatusCreated, write: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
bumper := &fakeCacheBumper{}
|
||||
h := New(nil, nil, "/ping", nil).WithCache(bumper)
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if tt.write {
|
||||
w.WriteHeader(tt.status)
|
||||
}
|
||||
})
|
||||
handler := h.invalidateCache(next)
|
||||
req := httptest.NewRequest(tt.method, "/", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, req)
|
||||
if bumper.calls != tt.want {
|
||||
t.Fatalf("Bump calls = %d, want %d", bumper.calls, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidateCacheDoesNotFailResponseAndUsesUncancelledContext(t *testing.T) {
|
||||
bumper := &fakeCacheBumper{err: errors.New("redis unavailable")}
|
||||
h := New(nil, nil, "/ping", nil).WithCache(bumper)
|
||||
handler := h.invalidateCache(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}))
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
req := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx)
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusCreated {
|
||||
t.Fatalf("response status = %d, want %d", recorder.Code, http.StatusCreated)
|
||||
}
|
||||
if bumper.calls != 1 {
|
||||
t.Fatalf("Bump calls = %d, want 1", bumper.calls)
|
||||
}
|
||||
select {
|
||||
case <-bumper.contexts[0].Done():
|
||||
t.Fatal("Bump context was canceled")
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@
|
||||
package adminhandler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
@@ -30,9 +32,14 @@ type Handler struct {
|
||||
spa fs.FS
|
||||
submitLimit *rateLimiter
|
||||
usage *ratelimit.Limiter
|
||||
cache cacheBumper
|
||||
clientIP *clientip.Resolver
|
||||
}
|
||||
|
||||
type cacheBumper interface {
|
||||
Bump(context.Context) error
|
||||
}
|
||||
|
||||
// New constructs an admin Handler. basePath is e.g. "/ping" (no trailing slash).
|
||||
func New(store *adminstore.Store, authn *auth.Authenticator, basePath string, spa fs.FS) *Handler {
|
||||
basePath = "/" + strings.Trim(basePath, "/")
|
||||
@@ -53,6 +60,34 @@ func (h *Handler) WithUsage(l *ratelimit.Limiter) *Handler {
|
||||
return h
|
||||
}
|
||||
|
||||
// WithCache attaches a cache epoch invalidator for successful admin writes.
|
||||
func (h *Handler) WithCache(c cacheBumper) *Handler {
|
||||
h.cache = c
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *Handler) invalidateCache(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if h.cache == nil || r.Method == http.MethodGet || r.Method == http.MethodHead {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(ww, r)
|
||||
status := ww.Status()
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
if status < http.StatusOK || status >= http.StatusMultipleChoices {
|
||||
return
|
||||
}
|
||||
if err := h.cache.Bump(context.WithoutCancel(r.Context())); err != nil {
|
||||
log.Printf("admin cache invalidation failed: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithClientIP sets the trusted-proxy resolver used to normalize request IPs.
|
||||
func (h *Handler) WithClientIP(resolver *clientip.Resolver) *Handler {
|
||||
if resolver == nil {
|
||||
@@ -77,6 +112,7 @@ func (h *Handler) Router() http.Handler {
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(h.authn.Middleware)
|
||||
r.Use(h.invalidateCache)
|
||||
r.Get("/api/me", h.Me)
|
||||
r.Get("/api/stats", h.Stats)
|
||||
r.Get("/api/audit", h.ListAllAudit)
|
||||
|
||||
Vendored
+24
-4
@@ -6,9 +6,9 @@
|
||||
// so the cache can never take the API down or serve stale data after Redis loss.
|
||||
//
|
||||
// Invalidation is global and O(1): keys are namespaced by an epoch counter
|
||||
// stored in Redis (og:cache:epoch). The Python ingestion bumps that counter
|
||||
// after a write run, which logically invalidates every cached entry at once
|
||||
// while old keys age out via their TTL. The epoch is read at most once per
|
||||
// stored in Redis (og:cache:epoch). Python ingestion and successful admin
|
||||
// writes bump that counter, logically invalidating cached entries at once while
|
||||
// old keys age out via their TTL. The epoch is read at most once per
|
||||
// refresh interval per process, so it adds no per-request round trip.
|
||||
package cache
|
||||
|
||||
@@ -35,7 +35,7 @@ const epochRefresh = 10 * time.Second
|
||||
const opTimeout = 150 * time.Millisecond
|
||||
|
||||
// Cache wraps a Redis client. A nil-backed Cache (Redis unconfigured) disables
|
||||
// caching: every Get misses and every Set is a no-op.
|
||||
// caching: every Get misses, every Set is a no-op, and Bump succeeds.
|
||||
type Cache struct {
|
||||
rdb *redis.Client
|
||||
|
||||
@@ -59,6 +59,26 @@ func New(redisURL string) *Cache {
|
||||
// Enabled reports whether a Redis backend is configured.
|
||||
func (c *Cache) Enabled() bool { return c != nil && c.rdb != nil }
|
||||
|
||||
// Bump increments the global cache epoch to invalidate existing entries.
|
||||
func (c *Cache) Bump(ctx context.Context) error {
|
||||
if !c.Enabled() {
|
||||
return nil
|
||||
}
|
||||
cctx, cancel := context.WithTimeout(ctx, opTimeout)
|
||||
defer cancel()
|
||||
epoch, err := c.rdb.Incr(cctx, epochKey).Result()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
c.epoch = epoch
|
||||
c.epochSetAt = time.Now()
|
||||
c.epochOK = true
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// epochNow returns the current cache generation, reading it from Redis at most
|
||||
// once per epochRefresh. On any Redis error it keeps the last known value and
|
||||
// throttles re-reads so a down backend cannot slow the hot path.
|
||||
|
||||
Vendored
+11
-7
@@ -22,6 +22,15 @@ func TestDisabledFailsOpen(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBumpDisabledCache(t *testing.T) {
|
||||
if err := (*Cache)(nil).Bump(context.Background()); err != nil {
|
||||
t.Fatalf("nil cache Bump(): %v", err)
|
||||
}
|
||||
if err := (&Cache{}).Bump(context.Background()); err != nil {
|
||||
t.Fatalf("disabled cache Bump(): %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func testCache(t *testing.T) *Cache {
|
||||
t.Helper()
|
||||
url := os.Getenv("OPENGOODS_REDIS_URL")
|
||||
@@ -69,14 +78,9 @@ func TestEpochInvalidation(t *testing.T) {
|
||||
t.Fatal("expected hit before epoch bump")
|
||||
}
|
||||
|
||||
// Simulate an ingestion write bumping the global epoch.
|
||||
if err := c.rdb.Incr(ctx, epochKey).Err(); err != nil {
|
||||
t.Fatalf("incr epoch: %v", err)
|
||||
if err := c.Bump(ctx); err != nil {
|
||||
t.Fatalf("bump epoch: %v", err)
|
||||
}
|
||||
// Force the process to re-read the epoch rather than use its cached value.
|
||||
c.mu.Lock()
|
||||
c.epochOK = false
|
||||
c.mu.Unlock()
|
||||
|
||||
if c.GetJSON(ctx, suffix, &dst) {
|
||||
t.Fatal("entry should be invisible after epoch bump")
|
||||
|
||||
@@ -70,6 +70,7 @@
|
||||
- **常用筛选复合索引**:如 `(category_id, quality_score DESC)`、
|
||||
`(archive_kind, quality_score DESC)` 配合域内列表。
|
||||
- **Redis 缓存**(已在技术栈内):缓存热门搜索结果与商品详情,挡住重复读。
|
||||
- 管理后台的成功写操作会递增缓存 epoch,使公开 API 后续读取切换到新缓存代次。
|
||||
|
||||
### 阶段 1 — 千万级以上:读扩展 + 调优
|
||||
触发:单库读 QPS 升高、P99 变慢。
|
||||
|
||||
Reference in New Issue
Block a user