-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.go
More file actions
548 lines (479 loc) · 17.3 KB
/
Copy pathcache.go
File metadata and controls
548 lines (479 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package dbcache
import (
"context"
"errors"
"fmt"
"log/slog"
"reflect"
"time"
"unsafe"
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/store"
"github.com/gomooth/pkg/framework/dbquery"
"github.com/gomooth/pkg/framework/telemetry"
pkgxcode "github.com/gomooth/pkg/framework/xcode"
"github.com/redis/go-redis/v9"
"github.com/gomooth/xerror"
"github.com/gomooth/xerror/xcode"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"golang.org/x/sync/singleflight"
)
// 编译时接口检查
var _ IDBCache[struct{}, struct{}] = (*dbCache[struct{}, struct{}])(nil)
type dbCache[E, F any] struct {
cacheManager *cache.Cache[string]
name string
autoRenew bool // 自动延长缓存有效期
expiration time.Duration
renewThreshold float64 // 续期阈值比例
codec Codec // 序列化编解码器
errorCacheTTL time.Duration // 错误结果缓存时间,0 表示不缓存错误
single singleflight.Group // 按 name 前缀隔离,不同 dbCache 实例不会碰撞
renewSingle singleflight.Group // 续期去重,防止并发续期风暴
tracer trace.Tracer
modelName string
traceConfig *traceConfig
}
// errorCacheKeySuffix 错误占位值的缓存键后缀,与正常数据完全隔离
const errorCacheKeySuffix = ":__err__"
var (
dbCacheHitCounter metric.Int64Counter
dbCacheMissCounter metric.Int64Counter
dbCacheRenewCounter metric.Int64Counter
dbCacheErrorCacheHitCounter metric.Int64Counter
dbCacheWriteCounter metric.Int64Counter
dbCacheOperationDuration metric.Float64Histogram
)
func init() {
telemetry.OnProviderSet(func() {
m := telemetry.Meter("dbcache")
dbCacheHitCounter, _ = m.Int64Counter("cache.dbcache.hit")
dbCacheMissCounter, _ = m.Int64Counter("cache.dbcache.miss")
dbCacheRenewCounter, _ = m.Int64Counter("cache.dbcache.renew")
dbCacheErrorCacheHitCounter, _ = m.Int64Counter("cache.dbcache.error_cache.hit")
dbCacheWriteCounter, _ = m.Int64Counter("cache.dbcache.write")
dbCacheOperationDuration, _ = m.Float64Histogram("cache.dbcache.operation.duration",
metric.WithUnit("s"))
})
}
func recordDBCacheDuration(ctx context.Context, namespace, operation string, dur time.Duration, err error) {
result := "success"
if err != nil {
result = "error"
}
attrs := metric.WithAttributes(
attribute.String("namespace", namespace),
attribute.String("operation", operation),
attribute.String("result", result),
)
dbCacheOperationDuration.Record(ctx, dur.Seconds(), attrs)
}
// startDBCacheMethodSpan 创建 dbcache 方法级 OTel Span
func startDBCacheMethodSpan[E, F any](ctx context.Context, s *dbCache[E, F], operation string) (context.Context, trace.Span) {
if s.traceConfig == nil || !s.traceConfig.methodSpan {
return ctx, nil
}
ctx, span := s.tracer.Start(ctx, "dbcache."+operation,
trace.WithAttributes(
attribute.String("db.operation", operation),
attribute.String("db.model", s.modelName),
),
trace.WithSpanKind(trace.SpanKindClient),
)
return ctx, span
}
// finishSpan 完成 Span,记录错误(如有)
func finishSpan(span trace.Span, err error) {
if span == nil {
return
}
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
}
span.End()
}
// New 创建数据库缓存实例。
//
// 默认使用 JSON 编解码器,可通过 WithCodec 选项替换为 msgpack 或 gob 等更高效的实现。
// 注意:更换编解码器会使现有缓存数据失效。
func New[E, F any](name string, cacheManager *cache.Cache[string], opts ...func(*dbCacheOption)) IDBCache[E, F] {
cnf := &dbCacheOption{
autoRenew: true,
expiration: 5 * time.Minute,
renewThreshold: 0.2,
codec: JSONCodec{},
errorCacheTTL: 0, // 默认不缓存错误
}
for _, opt := range opts {
opt(cnf)
}
tc := cnf.traceConfig
if tc == nil {
tc = &traceConfig{methodSpan: true, buildSpan: false}
}
return &dbCache[E, F]{
name: name,
cacheManager: cacheManager,
autoRenew: cnf.autoRenew,
expiration: cnf.expiration,
renewThreshold: cnf.renewThreshold,
codec: cnf.codec,
errorCacheTTL: cnf.errorCacheTTL,
tracer: telemetry.Tracer("dbcache"),
modelName: reflect.TypeOf(new(E)).Elem().Name(),
traceConfig: tc,
}
}
type queryResult[E any] struct {
Paginate struct {
Data []*E `json:"data"`
Total uint `json:"total"`
} `json:"paginate,omitempty"`
List struct {
Data []*E `json:"data"`
} `json:"list,omitempty"`
First struct {
Data *E `json:"data"`
} `json:"first,omitempty"`
}
func (s *dbCache[E, F]) Codec() Codec {
return s.codec
}
// cacheQuery 封装 "填充 queryResult → marshal → remember → unmarshal" 流程
func (s *dbCache[E, F]) cacheQuery(
ctx context.Context, key string, tags []string,
fill func(ctx context.Context) (*queryResult[E], error),
) (*queryResult[E], error) {
if s.traceConfig != nil && s.traceConfig.buildSpan {
var buildSpan trace.Span
ctx, buildSpan = s.tracer.Start(ctx, "dbcache.buildQuery",
trace.WithAttributes(
attribute.String("db.operation", "build_query"),
attribute.String("db.model", s.modelName),
),
trace.WithSpanKind(trace.SpanKindInternal),
)
defer buildSpan.End()
}
cacheData, err := s.remember(ctx, key, tags, func(ctx context.Context) ([]byte, error) {
res, err := fill(ctx)
if err != nil {
return nil, err
}
return s.codec.Marshal(res)
})
if err != nil {
return nil, err
}
var result *queryResult[E]
if err := s.codec.Unmarshal(cacheData, &result); err != nil {
return nil, xerror.WrapWithXCode(err, pkgxcode.ErrCacheReadFailed)
}
return result, nil
}
func (s *dbCache[E, F]) Paginate(ctx context.Context, q dbquery.IQuery[F],
query func(ctx context.Context) ([]*E, uint, error),
) (records []*E, total uint, err error) {
ctx, span := startDBCacheMethodSpan[E, F](ctx, s, "paginate")
defer func() {
finishSpan(span, err)
}()
start := time.Now()
defer func() {
recordDBCacheDuration(ctx, s.name, "paginate", time.Since(start), err)
}()
k := dbquery.HashKey(q.String())
offset, limit, _ := dbquery.PaginateValues(q)
key := dbquery.FormatPaginateKey(s.name, offset, limit, k)
tags := []string{s.tag("paginate")}
result, err := s.cacheQuery(ctx, key, tags, func(ctx context.Context) (*queryResult[E], error) {
records, total, err := query(ctx)
if err != nil {
return nil, err
}
res := new(queryResult[E])
res.Paginate.Data = records
res.Paginate.Total = total
return res, nil
})
if err != nil {
return nil, 0, err
}
return result.Paginate.Data, result.Paginate.Total, nil
}
func (s *dbCache[E, F]) List(ctx context.Context, q dbquery.IQuery[F],
query func(ctx context.Context) ([]*E, error),
) (records []*E, err error) {
ctx, span := startDBCacheMethodSpan[E, F](ctx, s, "list")
defer func() {
finishSpan(span, err)
}()
start := time.Now()
defer func() {
recordDBCacheDuration(ctx, s.name, "list", time.Since(start), err)
}()
k := dbquery.HashKey(q.String())
key := dbquery.FormatListKey(s.name, k)
tags := []string{s.tag("list")}
result, err := s.cacheQuery(ctx, key, tags, func(ctx context.Context) (*queryResult[E], error) {
records, err := query(ctx)
if err != nil {
return nil, err
}
res := new(queryResult[E])
res.List.Data = records
return res, nil
})
if err != nil {
return nil, err
}
return result.List.Data, nil
}
func (s *dbCache[E, F]) First(ctx context.Context, id uint, query func(ctx context.Context) (*E, error)) (record *E, err error) {
ctx, span := startDBCacheMethodSpan[E, F](ctx, s, "first")
defer func() {
finishSpan(span, err)
}()
start := time.Now()
defer func() {
recordDBCacheDuration(ctx, s.name, "first", time.Since(start), err)
}()
if id == 0 {
return nil, xerror.NewXCode(xcode.RequestParamError, "id error")
}
tags := []string{s.tag(fmt.Sprintf("%d", id))}
key := fmt.Sprintf("%s:first:%d", s.name, id)
result, err := s.cacheQuery(ctx, key, tags, func(ctx context.Context) (*queryResult[E], error) {
record, err := query(ctx)
if err != nil {
return nil, err
}
res := new(queryResult[E])
res.First.Data = record
return res, nil
})
if err != nil {
return nil, err
}
return result.First.Data, nil
}
func (s *dbCache[E, F]) Clear(ctx context.Context, opts ...func(*clearOption)) (err error) {
ctx, span := startDBCacheMethodSpan[E, F](ctx, s, "clear")
defer func() {
finishSpan(span, err)
}()
start := time.Now()
defer func() {
recordDBCacheDuration(ctx, s.name, "clear", time.Since(start), err)
}()
cnf := new(clearOption)
for _, opt := range opts {
opt(cnf)
}
if s.cacheManager == nil {
return xerror.NewXCode(pkgxcode.ErrCacheNotInitialized, "dbcache: manager not initialized")
}
// 显式指定清理所有缓存
if cnf.all {
return s.cacheManager.Invalidate(ctx, store.WithInvalidateTags([]string{
s.ownTag(),
}))
}
// 未指定任何选项时返回错误,避免静默无操作导致调用方误以为缓存已清除
if !cnf.single && !cnf.all {
return xerror.NewXCode(xcode.RequestParamError, "dbcache: Clear requires at least one option (e.g. ClearWithAll, ClearWithID)")
}
tags := make([]string, 0)
if len(cnf.ids) > 0 {
for _, id := range cnf.ids {
tags = append(tags, s.tag(fmt.Sprintf("%d", id)))
}
}
if len(cnf.keys) > 0 {
for _, key := range cnf.keys {
tags = append(tags, s.tag(key))
}
}
if len(cnf.tags) > 0 {
tags = append(tags, cnf.tags...)
}
if cnf.paginate {
tags = append(tags, s.tag("paginate"))
}
if cnf.list {
tags = append(tags, s.tag("list"))
}
if cnf.remember {
tags = append(tags, s.tag("remember"))
}
if len(tags) > 0 {
return s.cacheManager.Invalidate(ctx, store.WithInvalidateTags(tags))
}
return nil
}
func (s *dbCache[E, F]) Remember(ctx context.Context, key string, query func(ctx context.Context) ([]byte, error)) (result []byte, err error) {
ctx, span := startDBCacheMethodSpan[E, F](ctx, s, "remember")
defer func() {
finishSpan(span, err)
}()
start := time.Now()
defer func() {
recordDBCacheDuration(ctx, s.name, "remember", time.Since(start), err)
}()
tags := []string{
s.tag(key),
s.tag("remember"),
s.tag(fmt.Sprintf("remember:%s", key)),
}
cacheKey := fmt.Sprintf("%s:remember:%s", s.name, key)
return s.remember(ctx, cacheKey, tags, query)
}
// remember 核心缓存逻辑:查缓存 → 命中则续期 → 未命中则 singleflight 执行 fn 并写入缓存
// 内部以 []byte 流转数据,仅在缓存存储边界做 string 转换,避免 Remember 方法的双重拷贝
func (s *dbCache[E, F]) remember(ctx context.Context, key string, tags []string,
fun func(ctx context.Context) ([]byte, error),
) ([]byte, error) {
if s.cacheManager == nil {
return nil, xerror.NewXCode(pkgxcode.ErrCacheNotInitialized, "dbcache: manager not initialized")
}
if err := ctx.Err(); err != nil {
return nil, xerror.WrapWithXCode(err, pkgxcode.ErrCacheReadFailed)
}
cachedTags := append([]string{"dbcache", s.ownTag()}, tags...)
cacheData, d, err := s.cacheManager.GetWithTTL(ctx, key)
if err == nil {
return s.handleCacheHit(ctx, key, cacheData, d, cachedTags)
}
// Graceful degradation: 任何 Get 错误都视为缓存未命中,继续查 DB
// 对非 redis.Nil 的异常错误(如网络断连)记录日志,方便排查
if !errors.Is(err, redis.Nil) {
slog.Debug("dbcache: cache miss with unexpected error, falling back to query",
slog.String("component", "dbcache"), slog.String("key", key), slog.String("error", err.Error()))
}
return s.handleCacheMiss(ctx, key, cachedTags, fun)
}
// handleCacheHit 处理缓存命中:记录指标 + 判断是否需要自动续期
func (s *dbCache[E, F]) handleCacheHit(ctx context.Context, key, cacheData string, ttl time.Duration, cachedTags []string) ([]byte, error) {
dbCacheHitCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("namespace", s.name)))
// auto-renew 使用全局 expiration 重置 TTL,而非保留剩余 TTL。
// 这确保续期后的缓存拥有完整的过期窗口,而非逐渐缩短。
// 当前 API 所有缓存键统一使用 s.expiration,如需按 key 自定义 TTL,
// 需扩展 IDBCache 接口。
if s.autoRenew && ttl <= time.Duration(float64(s.expiration)*s.renewThreshold) {
s.tryRenew(ctx, key, cacheData, cachedTags)
}
return []byte(cacheData), nil
}
// tryRenew 自动续期缓存,使用 singleflight 去重防止并发续期风暴
func (s *dbCache[E, F]) tryRenew(ctx context.Context, key, cacheData string, cachedTags []string) {
if _, err, _ := s.renewSingle.Do(key, func() (any, error) {
if err := s.cacheManager.Set(
ctx, key, cacheData,
store.WithExpiration(s.expiration),
store.WithTags(cachedTags),
); err != nil {
slog.Warn("dbcache: auto-renew set failed", slog.String("component", "dbcache"), slog.String("key", key), slog.String("error", err.Error()))
return nil, err
}
dbCacheRenewCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("namespace", s.name), attribute.String("result", "success")))
return nil, nil
}); err != nil {
// 续期失败不影响本次读取,仅记录日志
slog.Warn("dbcache: auto-renew failed", slog.String("component", "dbcache"), slog.String("key", key), slog.String("error", err.Error()))
dbCacheRenewCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("namespace", s.name), attribute.String("result", "failure")))
}
}
// handleCacheMiss 处理缓存未命中:检查错误缓存后,走 singleflight 查询并写入缓存
func (s *dbCache[E, F]) handleCacheMiss(ctx context.Context, key string, cachedTags []string, fun func(ctx context.Context) ([]byte, error)) ([]byte, error) {
dbCacheMissCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("namespace", s.name)))
// 检查是否有错误占位值(独立键存储,与正常数据完全隔离)
if s.errorCacheTTL > 0 {
errKey := key + errorCacheKeySuffix
if errData, _, errErr := s.cacheManager.GetWithTTL(ctx, errKey); errErr == nil {
dbCacheErrorCacheHitCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("namespace", s.name)))
return nil, xerror.NewXCode(pkgxcode.ErrCacheMiss, errData)
}
}
return s.queryAndCache(ctx, key, cachedTags, fun)
}
// queryAndCache singleflight 去重查询 + 缓存写入
func (s *dbCache[E, F]) queryAndCache(ctx context.Context, key string, cachedTags []string, fun func(ctx context.Context) ([]byte, error)) ([]byte, error) {
v, err, _ := s.single.Do(key, func() (any, error) {
result, err := fun(ctx)
if err != nil {
s.cacheError(ctx, key, cachedTags, err)
return nil, err
}
s.cacheResult(ctx, key, cachedTags, result)
return result, nil
})
if err != nil {
return nil, err
}
result, ok := v.([]byte)
if !ok {
return nil, xerror.NewXCode(pkgxcode.ErrCacheReadFailed, "cache store result type assertion failed")
}
return result, nil
}
// cacheError 将错误结果缓存到独立键,防止相同 key 的错误请求反复打到数据库
func (s *dbCache[E, F]) cacheError(ctx context.Context, key string, cachedTags []string, err error) {
if s.errorCacheTTL <= 0 {
return
}
errKey := key + errorCacheKeySuffix
if setErr := s.cacheManager.Set(
ctx, errKey, err.Error(),
store.WithExpiration(s.errorCacheTTL),
store.WithTags(cachedTags),
); setErr != nil {
slog.Debug("dbcache: error cache set failed", slog.String("component", "dbcache"), slog.String("key", errKey), slog.String("error", setErr.Error()))
} else {
dbCacheWriteCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("namespace", s.name), attribute.String("result", "success"), attribute.String("type", "error_cache")))
}
}
// cacheResult 将正常结果写入缓存,使用 unsafe.String 零拷贝转换 []byte→string
func (s *dbCache[E, F]) cacheResult(ctx context.Context, key string, cachedTags []string, result []byte) {
// 使用 unsafe.String 零拷贝转换 []byte→string,避免每次缓存写入的完整拷贝。
// 安全性:result 是 fun(ctx) 的返回值,Set 调用后 []byte 不再被修改。
// gocache 内部将 string 存入 Redis/memstore,不持有原始 []byte 引用。
if err := s.cacheManager.Set(
ctx, key, unsafe.String(unsafe.SliceData(result), len(result)),
store.WithExpiration(s.expiration),
store.WithTags(cachedTags),
); err != nil {
slog.Error("dbcache: cache set failed, degrading to direct result",
slog.String("component", "dbcache"), slog.String("key", key), slog.String("error", err.Error()))
dbCacheWriteCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("namespace", s.name), attribute.String("result", "failure")))
} else {
dbCacheWriteCounter.Add(ctx, 1, metric.WithAttributes(attribute.String("namespace", s.name), attribute.String("result", "success")))
}
}
func (s *dbCache[E, F]) ownTag() string {
return fmt.Sprintf("dbcache:%s", s.name)
}
func (s *dbCache[E, F]) tag(tag string) string {
return fmt.Sprintf("dbcache:%s:%s", s.name, tag)
}
func (s *dbCache[E, F]) Forget(ctx context.Context, key string) (err error) {
ctx, span := startDBCacheMethodSpan[E, F](ctx, s, "forget")
defer func() {
finishSpan(span, err)
}()
start := time.Now()
defer func() {
recordDBCacheDuration(ctx, s.name, "forget", time.Since(start), err)
}()
if s.cacheManager == nil {
return xerror.NewXCode(pkgxcode.ErrCacheNotInitialized, "dbcache: manager not initialized")
}
tags := []string{
s.tag(key),
s.tag(fmt.Sprintf("remember:%s", key)),
}
return s.cacheManager.Invalidate(ctx, store.WithInvalidateTags(tags))
}