fix(redis): lock acquisition fails open per spec §9
This commit is contained in:
@@ -67,8 +67,12 @@ func (r *R) Lock(ctx context.Context, key string, ttl time.Duration) (func(), bo
|
|||||||
rand.Read(b)
|
rand.Read(b)
|
||||||
tok := hex.EncodeToString(b)
|
tok := hex.EncodeToString(b)
|
||||||
ok, err := r.c.SetNX(ctx, key, tok, ttl).Result()
|
ok, err := r.c.SetNX(ctx, key, tok, ttl).Result()
|
||||||
if err != nil || !ok {
|
if err != nil { // spec §9: Redis 故障降级放行,锁只做尽力去重
|
||||||
return noop, false
|
log.Printf("redis lock %s: %v (proceeding without lock)", key, err)
|
||||||
|
return noop, true
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return noop, false // 锁被持有,别的副本在扫
|
||||||
}
|
}
|
||||||
return func() {
|
return func() {
|
||||||
r.c.Eval(ctx,
|
r.c.Eval(ctx,
|
||||||
|
|||||||
@@ -22,3 +22,12 @@ func TestDisabledIsSafe(t *testing.T) {
|
|||||||
}
|
}
|
||||||
un()
|
un()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestDeadRedisLockFailsOpen(t *testing.T) {
|
||||||
|
r := New("redis://127.0.0.1:16399") // 死端口
|
||||||
|
un, ok := r.Lock(context.Background(), "lk", time.Second)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("Lock on redis error must fail open (spec §9)")
|
||||||
|
}
|
||||||
|
un()
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user