feat: sync public links and phone change updates

This commit is contained in:
A 2026-07-10 22:01:44 +08:00
parent 41c7f1d018
commit da04c0fa6a
53 changed files with 3029 additions and 111 deletions

View file

@ -2,6 +2,8 @@ package redisstore
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
@ -22,14 +24,80 @@ func NewCodeStore(c *redis.Client) *CodeStore {
return &CodeStore{c: c}
}
func codeKey(hash string) string { return "phonecode:" + hash }
const codeKeyPrefix = "phonecode:"
func codeKey(hash string) string { return codeKeyPrefix + hash }
func codeScopeKey(scope store.PhoneCodeScope) string {
// 不把手机号/auth key 明文放进 Redis keyJSON 仅作为稳定的长度分隔编码输入。
raw, _ := json.Marshal(scope)
digest := sha256.Sum256(raw)
return "phonecodescope:" + hex.EncodeToString(digest[:])
}
const rotateScopedCodeScript = `
local old_hash = redis.call('GET', KEYS[2])
if old_hash and old_hash ~= ARGV[1] then
redis.call('DEL', ARGV[4] .. old_hash)
end
local ttl_ms = tonumber(ARGV[3])
if ttl_ms and ttl_ms > 0 then
redis.call('PSETEX', KEYS[1], ttl_ms, ARGV[2])
redis.call('PSETEX', KEYS[2], ttl_ms, ARGV[1])
else
redis.call('SET', KEYS[1], ARGV[2])
redis.call('SET', KEYS[2], ARGV[1])
end
return 1
`
const deleteScopedCodeScript = `
redis.call('DEL', KEYS[1])
if redis.call('GET', KEYS[2]) == ARGV[1] then
redis.call('DEL', KEYS[2])
end
return 1
`
const consumeScopedCodeScript = `
if redis.call('GET', KEYS[2]) ~= ARGV[1] then
return false
end
local raw = redis.call('GET', KEYS[1])
if not raw then
redis.call('DEL', KEYS[2])
return false
end
redis.call('DEL', KEYS[1])
redis.call('DEL', KEYS[2])
return raw
`
func (s *CodeStore) Set(ctx context.Context, hash string, code store.PhoneCode, ttl time.Duration) error {
v, err := json.Marshal(code)
if err != nil {
return fmt.Errorf("marshal phone code: %w", err)
}
if err := s.c.Set(ctx, codeKey(hash), v, ttl).Err(); err != nil {
scope := code.Scope()
if !scope.Valid() {
if err := s.c.Set(ctx, codeKey(hash), v, ttl).Err(); err != nil {
return fmt.Errorf("redis set phone code: %w", err)
}
return nil
}
ttlMillis := ttl.Milliseconds()
if ttl > 0 && ttlMillis == 0 {
ttlMillis = 1
}
if err := s.c.Eval(
ctx,
rotateScopedCodeScript,
[]string{codeKey(hash), codeScopeKey(scope)},
hash,
string(v),
ttlMillis,
codeKeyPrefix,
).Err(); err != nil {
return fmt.Errorf("redis set phone code: %w", err)
}
return nil
@ -52,7 +120,7 @@ func (s *CodeStore) Get(ctx context.Context, hash string) (store.PhoneCode, bool
func (s *CodeStore) Update(ctx context.Context, hash string, code store.PhoneCode) error {
key := codeKey(hash)
ttl, err := s.c.TTL(ctx, key).Result()
ttl, err := s.c.PTTL(ctx, key).Result()
if err != nil {
return fmt.Errorf("redis ttl phone code: %w", err)
}
@ -70,5 +138,57 @@ func (s *CodeStore) Update(ctx context.Context, hash string, code store.PhoneCod
}
func (s *CodeStore) Del(ctx context.Context, hash string) error {
return s.c.Del(ctx, codeKey(hash)).Err()
key := codeKey(hash)
raw, err := s.c.Get(ctx, key).Bytes()
if err != nil {
if errors.Is(err, redis.Nil) {
return s.c.Del(ctx, key).Err()
}
return fmt.Errorf("redis get phone code for delete: %w", err)
}
var code store.PhoneCode
if err := json.Unmarshal(raw, &code); err != nil {
return fmt.Errorf("unmarshal phone code for delete: %w", err)
}
scope := code.Scope()
if !scope.Valid() {
return s.c.Del(ctx, key).Err()
}
if err := s.c.Eval(ctx, deleteScopedCodeScript, []string{key, codeScopeKey(scope)}, hash).Err(); err != nil {
return fmt.Errorf("redis delete scoped phone code: %w", err)
}
return nil
}
func (s *CodeStore) ConsumeScoped(ctx context.Context, hash string, scope store.PhoneCodeScope) (store.PhoneCode, bool, error) {
if !scope.Valid() {
return store.PhoneCode{}, false, nil
}
result, err := s.c.Eval(
ctx,
consumeScopedCodeScript,
[]string{codeKey(hash), codeScopeKey(scope)},
hash,
).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return store.PhoneCode{}, false, nil
}
return store.PhoneCode{}, false, fmt.Errorf("redis consume scoped phone code: %w", err)
}
if result == nil {
return store.PhoneCode{}, false, nil
}
raw, ok := result.(string)
if !ok {
return store.PhoneCode{}, false, fmt.Errorf("redis consume scoped phone code: unexpected result %T", result)
}
var code store.PhoneCode
if err := json.Unmarshal([]byte(raw), &code); err != nil {
return store.PhoneCode{}, false, fmt.Errorf("unmarshal consumed phone code: %w", err)
}
if code.Scope() != scope {
return store.PhoneCode{}, false, fmt.Errorf("consumed phone code scope mismatch")
}
return code, true, nil
}

View file

@ -0,0 +1,83 @@
package redisstore
import (
"context"
"fmt"
"os"
"sync"
"testing"
"time"
"telesrv/internal/store"
)
func TestRedisCodeStoreScopedRotationAndSingleConsume(t *testing.T) {
addr := os.Getenv("TELESRV_TEST_REDIS_ADDR")
if addr == "" {
t.Skip("set TELESRV_TEST_REDIS_ADDR to run redis integration test")
}
ctx := context.Background()
c, err := Open(ctx, addr, "", 0)
if err != nil {
t.Fatalf("open: %v", err)
}
t.Cleanup(func() { _ = c.Close() })
suffix := time.Now().UnixNano()
oldHash := fmt.Sprintf("scope-old-%d", suffix)
newHash := fmt.Sprintf("scope-new-%d", suffix)
rec := store.PhoneCode{
Phone: fmt.Sprintf("1555%d", suffix),
Code: "12345",
Purpose: store.PhoneCodePurposeChangePhone,
UserID: suffix,
AuthKeyID: [8]byte{1, 2, 3, 4},
}
scopeKey := codeScopeKey(rec.Scope())
t.Cleanup(func() { _ = c.Del(ctx, codeKey(oldHash), codeKey(newHash), scopeKey).Err() })
codes := NewCodeStore(c)
if err := codes.Set(ctx, oldHash, rec, time.Minute); err != nil {
t.Fatalf("set old: %v", err)
}
if err := codes.Set(ctx, newHash, rec, time.Minute); err != nil {
t.Fatalf("rotate new: %v", err)
}
if _, found, err := codes.Get(ctx, oldHash); err != nil || found {
t.Fatalf("old hash found=%v err=%v", found, err)
}
const workers = 24
results := make(chan bool, workers)
errs := make(chan error, workers)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
_, found, err := codes.ConsumeScoped(ctx, newHash, rec.Scope())
if err != nil {
errs <- err
return
}
results <- found
}()
}
wg.Wait()
close(results)
close(errs)
for err := range errs {
t.Fatalf("consume: %v", err)
}
foundCount := 0
for found := range results {
if found {
foundCount++
}
}
if foundCount != 1 {
t.Fatalf("successful consumes = %d, want 1", foundCount)
}
if exists, err := c.Exists(ctx, codeKey(newHash), scopeKey).Result(); err != nil || exists != 0 {
t.Fatalf("remaining redis keys=%d err=%v", exists, err)
}
}