fix(api): 管理后台成功写入后递增缓存代次 (#40)

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
fu500f
2026-10-31 00:45:55 +00:00
co-authored by Devin AI
parent 36f9c95fa7
commit d0ad1b85f3
6 changed files with 161 additions and 13 deletions
+36
View File
@@ -3,9 +3,11 @@
package adminhandler
import (
"context"
"encoding/json"
"errors"
"io/fs"
"log"
"net/http"
"strings"
"time"
@@ -28,6 +30,11 @@ type Handler struct {
spa fs.FS
submitLimit *rateLimiter
usage *ratelimit.Limiter
cache cacheBumper
}
type cacheBumper interface {
Bump(context.Context) error
}
// New constructs an admin Handler. basePath is e.g. "/ping" (no trailing slash).
@@ -49,6 +56,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)
}
})
}
// Router builds the HTTP handler.
func (h *Handler) Router() http.Handler {
r := chi.NewRouter()
@@ -64,6 +99,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)