sky/internal/platform/cache/cache.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

401 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cache
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"strconv"
"strings"
"time"
"github.com/redis/go-redis/v9"
"golang.org/x/sync/singleflight"
)
// Key 前缀集中定义,便于审计与批量失效。裸 key 一律禁止。
const (
prefixArticleDetail = "art:v:"
prefixArticleMeta = "art:meta:"
prefixArticleSecs = "art:secs:"
prefixCounters = "cnt:art:"
prefixFeedVersion = "feed:ver:"
prefixFeedList = "feed:list:"
prefixSession = "sess:"
prefixStickyMaster = "sticky_master:"
prefixLock = "lock:"
prefixHotTags = "hot:tags"
// 逻辑过期:业务 TTL 到期后仍返回旧值并异步刷新,
// 保证永远不会出现「缓存消失」的瞬间(防雪崩/击穿)
softTTL = 30 * time.Minute
hardTTL = softTTL + 2*time.Hour
)
// envelope 逻辑过期外壳
type envelope struct {
Data json.RawMessage `json:"d"`
ExpireAt int64 `json:"e"` // unix 毫秒
}
// Stats 是缓存层的可观测钩子。
// 用接口而非直接依赖 metrics 包:cache 属于 platform 底层,
// 不应该反向依赖上层,否则包依赖方向就乱了。
type Stats interface {
Hit()
Miss()
Error()
FlightMerged()
}
type Cache struct {
rdb *redis.Client
sf singleflight.Group
log *slog.Logger
stats Stats
// sessTTL / sessRenewLast 会话滑动续约策略,由 WithSessionPolicy 注入。
// sessTTL <= 0 表示未配置,续约路径整体短路,退化为纯绝对过期。
sessTTL time.Duration
sessRenewLast time.Duration
}
func New(rdb *redis.Client, log *slog.Logger) *Cache {
return &Cache{rdb: rdb, sf: singleflight.Group{}, log: log}
}
// WithStats 注入指标采集器,返回自身便于链式调用
func (c *Cache) WithStats(s Stats) *Cache {
c.stats = s
return c
}
// WithSessionPolicy 注入会话滑动续约策略:TTL 全长 ttl,
// 剩余有效期不足 renewLast 时命中即续回满 ttl。链式调用。
func (c *Cache) WithSessionPolicy(ttl, renewLast time.Duration) *Cache {
c.sessTTL = ttl
c.sessRenewLast = renewLast
return c
}
// 空实现,stats 未注入时所有调用都是 no-op
func (c *Cache) hit() {
if c.stats != nil {
c.stats.Hit()
}
}
func (c *Cache) miss() {
if c.stats != nil {
c.stats.Miss()
}
}
func (c *Cache) cerr() {
if c.stats != nil {
c.stats.Error()
}
}
func (c *Cache) merged() {
if c.stats != nil {
c.stats.FlightMerged()
}
}
func ArticleDetailKey(maskID string) string { return prefixArticleDetail + maskID }
func ArticleMetaKey(id string) string { return prefixArticleMeta + id }
func ArticleSecsKey(id string) string { return prefixArticleSecs + id }
func CountersKey(id string) string { return prefixCounters + id }
func SessionKey(tokenHash string) string { return prefixSession + tokenHash }
func StickyMasterKey(uid string) string { return prefixStickyMaster + uid }
func FeedVersionKey(cat string) string { return prefixFeedVersion + cat }
func FeedListKey(cat, sort, cursor string) string {
return fmt.Sprintf("%s%s:%s:%s", prefixFeedList, cat, sort, cursor)
}
// GetOrLoad 带 singleflight + 逻辑过期的通用读取。
//
// 三种保护:
// 1. singleflight:同一 key 并发未命中时只有第一个 goroutine 查数据库
// 2. 逻辑过期:软过期后同步返回旧值、异步刷新,绝不出现空窗
// 3. 空值缓存:loader 返回 notFound 时缓存 null 短 TTL,防穿透
//
// loader 返回 (nil, nil) 表示资源不存在,会被缓存为空标记。
func GetOrLoad[T any](
ctx context.Context,
c *Cache,
key string,
load func(ctx context.Context) (*T, error),
) (*T, error) {
raw, err := c.rdb.Get(ctx, key).Bytes()
if err == nil {
c.hit()
var env envelope
if json.Unmarshal(raw, &env) == nil {
if env.Data == nil || string(env.Data) == "null" {
return nil, nil // 命中空值缓存
}
var v T
if json.Unmarshal(env.Data, &v) == nil {
// 软过期 → 异步刷新,本次仍返回旧值
if time.Now().UnixMilli() > env.ExpireAt {
go refreshAsync(c, key, load)
}
return &v, nil
}
}
// 缓存内容损坏,删掉走回源
c.rdb.Del(ctx, key)
} else if err == redis.Nil {
c.miss()
} else {
// Valkey 异常时降级直查数据库,不因缓存故障阻断业务
c.cerr()
c.log.Warn("缓存读取失败,降级回源", "key", key, "err", err)
}
// singleflight:并发回源合并为一次
v, err, shared := c.sf.Do(key, func() (any, error) {
loaded, err := load(ctx)
if err != nil {
return nil, err
}
c.store(ctx, key, loaded)
return loaded, nil
})
if shared {
c.merged()
}
if err != nil {
return nil, err
}
if v == nil {
return nil, nil
}
out, _ := v.(*T)
return out, nil
}
// refreshAsync 异步刷新,失败只记日志,不影响本次请求。
// 刷新同样走 singleflight,避免软过期瞬间大量 goroutine 同时查库。
func refreshAsync[T any](c *Cache, key string, load func(context.Context) (*T, error)) {
c.sf.Do(key+":refresh", func() (any, error) {
// 用独立 context:请求结束后刷新仍要能完成
loaded, err := load(context.Background())
if err != nil {
c.log.Warn("异步刷新失败", "key", key, "err", err)
return nil, nil
}
c.store(context.Background(), key, loaded)
return nil, nil
})
}
func (c *Cache) store(ctx context.Context, key string, v any) {
var data json.RawMessage
if v == nil {
data = json.RawMessage("null")
} else {
b, err := json.Marshal(v)
if err != nil {
c.log.Warn("缓存序列化失败", "key", key, "err", err)
return
}
data = b
}
env := envelope{Data: data, ExpireAt: time.Now().Add(softTTL).UnixMilli()}
buf, err := json.Marshal(env)
if err != nil {
return
}
if err := c.rdb.Set(ctx, key, buf, hardTTL).Err(); err != nil {
c.log.Warn("缓存写入失败", "key", key, "err", err)
}
}
// Invalidate 主动失效(发布/更新文章时调用)
func (c *Cache) Invalidate(ctx context.Context, keys ...string) {
if len(keys) == 0 {
return
}
if err := c.rdb.Del(ctx, keys...).Err(); err != nil {
c.log.Warn("缓存失效失败", "keys", keys, "err", err)
}
}
// BumpFeedVersion 批量失效 feed 的正确做法。
//
// 绝对不能用 KEYS feed:* 删除 —— 会阻塞整个 Valkey 实例。
// 这里改版本号,旧 key 自然过期,等于 O(1) 失效全部 feed。
func (c *Cache) BumpFeedVersion(ctx context.Context, categories ...string) {
for _, cat := range categories {
if err := c.rdb.Incr(ctx, FeedVersionKey(cat)).Err(); err != nil {
c.log.Warn("feed 版本自增失败", "cat", cat, "err", err)
}
}
}
func (c *Cache) FeedVersion(ctx context.Context, cat string) int64 {
v, err := c.rdb.Get(ctx, FeedVersionKey(cat)).Int64()
if err != nil {
return 0
}
return v
}
// ── 计数器:实时值在 Valkey,PG 只做最终一致落库 ──
// IncrCounter 原子递增文章计数。返回递增后的值。
func (c *Cache) IncrCounter(ctx context.Context, articleID, field string, delta int64) (int64, error) {
return c.rdb.HIncrBy(ctx, CountersKey(articleID), field, delta).Result()
}
// Counters 读取全部计数
func (c *Cache) Counters(ctx context.Context, articleID string) (map[string]int64, error) {
m, err := c.rdb.HGetAll(ctx, CountersKey(articleID)).Result()
if err != nil {
return nil, err
}
out := make(map[string]int64, len(m))
for k, v := range m {
var n int64
fmt.Sscanf(v, "%d", &n)
out[k] = n
}
return out, nil
}
// SeedCounters 首次访问时用 PG 的值初始化,避免计数从 0 开始跳变
func (c *Cache) SeedCounters(ctx context.Context, articleID string, vals map[string]int64) {
key := CountersKey(articleID)
exists, err := c.rdb.Exists(ctx, key).Result()
if err != nil || exists > 0 {
return
}
fields := make(map[string]any, len(vals))
for k, v := range vals {
fields[k] = v
}
if len(fields) > 0 {
_ = c.rdb.HSet(ctx, key, fields).Err()
}
}
// LikeSetKey 点赞去重集合(用户维度)
func (c *Cache) LikeSetKey(articleID string) string { return "art:likes:" + articleID }
// IncrWindow 固定窗口计数(限流用)。第一次自增时设置过期,
// 保证窗口到期后 key 自动消失,不会无限增长。
func (c *Cache) IncrWindow(ctx context.Context, key string, window time.Duration) (int64, error) {
pipe := c.rdb.TxPipeline()
incr := pipe.Incr(ctx, key)
pipe.Expire(ctx, key, window)
if _, err := pipe.Exec(ctx); err != nil {
return 0, err
}
return incr.Val(), nil
}
// ── 会话 ──
// 会话值格式:"uid|renewAfter"(renewAfter 为 Unix 秒,即本次续约截止时间)。
// 截止前命中零额外写入;截止后的第一次命中用一次 SET 续回满 TTL,
// 活跃会话约每 (TTL - 续约窗口) 才触发一次,其余请求与原先一样只是纯 GET。
// 旧格式(无分隔符)视为待续约:升级上线后存量会话在下次访问时自动续到新 TTL。
func (c *Cache) encodeSessionValue(userID string, ttl time.Duration) string {
if ttl <= 0 || c.sessRenewLast <= 0 || ttl <= c.sessRenewLast {
return userID // 续约关闭或配置退化:存旧格式,读取侧同样短路
}
deadline := time.Now().Add(ttl - c.sessRenewLast).Unix()
return userID + "|" + strconv.FormatInt(deadline, 10)
}
func (c *Cache) SetSession(ctx context.Context, tokenHash, userID string, ttl time.Duration) error {
return c.rdb.Set(ctx, SessionKey(tokenHash), c.encodeSessionValue(userID, ttl), ttl).Err()
}
func (c *Cache) GetSession(ctx context.Context, tokenHash string) (string, bool) {
v, err := c.rdb.Get(ctx, SessionKey(tokenHash)).Result()
if err != nil {
return "", false
}
uid, renewAfter := splitSessionValue(v)
if c.sessTTL > 0 && time.Now().Unix() >= renewAfter {
// 此刻用户尚未校验 status,但封禁/删除路径的中间件随后会 DelSession,
// 这里多续的几毫秒不会留下可用的失效会话。
c.renewSession(ctx, tokenHash, uid)
}
return uid, true
}
// renewSession 把会话续回满 TTL。只在续约窗口内触发,同步执行;
// 失败仅记日志——本次请求的会话已读取成功,续约失败只是下个窗口再试。
func (c *Cache) renewSession(ctx context.Context, tokenHash, uid string) {
err := c.rdb.Set(ctx, SessionKey(tokenHash), c.encodeSessionValue(uid, c.sessTTL), c.sessTTL).Err()
if err != nil {
c.log.Warn("会话续约失败", "key", tokenHash[:8], "err", err)
}
}
// splitSessionValue 拆出 uid 与续约截止时间;旧格式/异常值返回 0(立即续约)。
func splitSessionValue(v string) (uid string, renewAfter int64) {
if i := strings.LastIndexByte(v, '|'); i >= 0 {
if ts, err := strconv.ParseInt(v[i+1:], 10, 64); err == nil {
return v[:i], ts
}
}
return v, 0
}
func (c *Cache) DelSession(ctx context.Context, tokenHash string) {
c.rdb.Del(ctx, SessionKey(tokenHash))
}
// ── 读写分离:强制读主库标记 ──
// MarkStickyMaster 写操作后调用,让该用户接下来 3 秒的读请求走主库,
// 避免刚发布就刷新却读不到(副本复制延迟)的经典问题。
func (c *Cache) MarkStickyMaster(ctx context.Context, userID string) {
_ = c.rdb.Set(ctx, StickyMasterKey(userID), "1", 3*time.Second).Err()
}
// ShouldReadMaster 判断本次读是否必须走主库
func (c *Cache) ShouldReadMaster(ctx context.Context, userID string) bool {
if userID == "" {
return false
}
n, err := c.rdb.Exists(ctx, StickyMasterKey(userID)).Result()
return err == nil && n > 0
}
// ── 计数 key 扫描(worker 用) ──
// ScanCounterKeys 用 cursor 增量扫描计数 key。
// 绝不用 KEYS:KEYS 会阻塞整个 Valkey 实例。
func (c *Cache) ScanCounterKeys(ctx context.Context, limit int64) ([]string, error) {
var (
cursor uint64
out []string
)
for {
keys, next, err := c.rdb.Scan(ctx, cursor, prefixCounters+"*", 200).Result()
if err != nil {
return out, err
}
out = append(out, keys...)
cursor = next
if cursor == 0 || int64(len(out)) >= limit {
break
}
}
if int64(len(out)) > limit {
out = out[:limit]
}
return out, nil
}
// ArticleIDFromCounterKey 从 cnt:art:{articleID} 还原 UUID
func (c *Cache) ArticleIDFromCounterKey(key string) string {
if len(key) <= len(prefixCounters) {
return ""
}
return key[len(prefixCounters):]
}