建立凭证快照协调与账号锁回收
This commit is contained in:
1 parent
d851d42cd3
commit
456880f1a6
5 files changed
+274
-16
No files matched your search
@@ -720,3 +720,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-15 | P1 订单读模型 Port 与架构依赖门禁 | 已完成 | 新增 `internal/application/orders` 纯业务 `OrderRow`/`ListFilter`/`Reader`;订单列表适配器负责 `db.*` 到应用模型的转换;架构门禁统一模块路径、禁止应用层依赖 `db/server/xianyu/browser/sql/http`,并对 Server 新增低层依赖要求临时白名单;新增门禁测试,`make check` 通过。订单写入事务 Port、其他应用服务和既有白名单仍未完成,阶段 4/8/9 继续保持“进行中” |
|
||||
| 2026-08-15 | P1 订单事务 Writer Port | 已完成 | 新增 `orders.OrderPatch`、`ItemWrite`、`UpsertOptions`、`Writer` 和 `UnitOfWork`;订单更新、导入、手动发货和刷新统一通过应用 Writer,`*sql.Tx` 仅存在于 Server 基础设施适配器;保留现有提交/回滚语义并通过订单回归与 `make check`。订单实体读取、凭证 Port、其他应用服务和 Server 白名单仍未完成,阶段 4/8/9 继续保持“进行中” |
|
||||
| 2026-08-15 | P1 订单实体读取与平台运行视图 Port | 已完成 | 新增纯应用层 `Order`、`ItemInfo`、`PlatformRuntimeData`;订单详情、商品读取、订单分页和刷新凭证读取不再通过 repository 暴露 `db.Order`、`db.ItemInfo`、`db.OrderRow` 或 `db.CookieDetail`;Server 到现有自动化/会话辅助函数保留显式边界适配;新增字段完整性转换测试,`make check` 和注释门禁通过。该三切片仅收口订单 Port,凭证协调器、生命周期、补偿、批量同步和其他领域依赖仍未完成,阶段 4/8/9 继续保持“进行中” |
|
||||
| 2026-08-15 | P1 凭证快照与账号操作协调器(订单详情切片) | 已完成 | `Store.LockAccountCredentials` 增加引用计数和空闲 entry 回收,并保持同账号互斥与重复释放幂等;订单详情流程改为锁内读取、锁外执行慢速 MTOP、锁内重读提交,检测到期间凭证变化时丢弃旧响应;新增锁回收、并发互斥、慢速 I/O 不占锁和 race 回归测试,`make check`、注释门禁及聚焦 race 通过。其他凭证调用方仍待迁移,版本化持久化冲突控制和协调指标仍未完成,阶段 2/4/5/8/9 继续保持“进行中” |
|
||||
@@ -456,7 +456,13 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
a.lastOrderFetch = time.Now()
|
||||
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
|
||||
credentialUnlock := a.store.LockAccountCredentials(cookieID)
|
||||
defer credentialUnlock()
|
||||
// credentialLocked 标识当前调用是否持有账号凭证锁。
|
||||
credentialLocked := true
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
}()
|
||||
platformData, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) // platformData 只包含订单 MTOP 请求所需的 Cookie 与 metadata。
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取订单账号最新 Cookie: %w", err)
|
||||
@@ -476,15 +482,29 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
} else {
|
||||
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
// 账号凭证快照已读取完成;慢速 MTOP 请求不得继续持有共享凭证锁。
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
// detail、fetchErr 保存detail、fetchErr,供当前处理流程使用
|
||||
detail, fetchErr := a.orderMTop.FetchOrderDetail(requestCtx, cookieStr, orderID)
|
||||
// authoritativeCookies、authoritativeSnapshot、sessionChanged 保存authoritativeCookies、authoritativeSnapshot、sessionChanged,供当前处理流程使用
|
||||
authoritativeCookies, authoritativeSnapshot, sessionChanged := cookieSession.State()
|
||||
if sessionChanged {
|
||||
// credentialUnlock 保存重新进入凭证提交临界区的释放函数。
|
||||
credentialUnlock = a.store.LockAccountCredentials(cookieID)
|
||||
credentialLocked = true
|
||||
// latestPlatformData 和 reloadErr 保存外部调用完成后的最新凭证快照及重读错误。
|
||||
latestPlatformData, reloadErr := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID)
|
||||
if reloadErr != nil {
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("重读订单账号最新 Cookie: %w", reloadErr))
|
||||
} else if latestPlatformData.Value != platformData.Value || latestPlatformData.MetadataJSON != platformData.MetadataJSON {
|
||||
// 凭证在外部调用期间已被其他流程更新,丢弃旧快照响应,避免覆盖更新后的状态。
|
||||
sessionChanged = false
|
||||
authoritativeSnapshot = nil
|
||||
} else if sessionChanged {
|
||||
// metadata 保存metadata,供当前处理流程使用
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(platformData.MetadataJSON)
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(latestPlatformData.MetadataJSON)
|
||||
if authoritativeSnapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(platformData.MetadataJSON, authoritativeSnapshot)
|
||||
metadata = cookierefresh.MetadataWithSnapshot(latestPlatformData.MetadataJSON, authoritativeSnapshot)
|
||||
}
|
||||
if // persistErr 保存persistErr,供当前处理流程使用
|
||||
persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, authoritativeCookies, metadata, time.Now().Unix()); persistErr != nil {
|
||||
@@ -500,15 +520,18 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
if detail == nil {
|
||||
return nil, errors.New("订单详情 MTOP 接口返回空结果")
|
||||
}
|
||||
if !sessionChanged && authoritativeSnapshot == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
if reloadErr == nil && latestPlatformData.Value == platformData.Value && latestPlatformData.MetadataJSON == platformData.MetadataJSON && !sessionChanged && authoritativeSnapshot == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
// metadata 保存metadata,供当前处理流程使用
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(platformData.MetadataJSON)
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(latestPlatformData.MetadataJSON)
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
return nil, fmt.Errorf("保存订单详情响应 Cookie: %w", err)
|
||||
}
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
// 外部调用产生的凭证结果已处理完成,释放短暂提交临界区。
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
return &automation.OrderDetail{
|
||||
Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue,
|
||||
Amount: detail.Amount, OrderStatus: detail.OrderStatus,
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// blockingOrderDetailClient 在外部请求期间阻塞,用于验证凭证锁不会跨越慢速 I/O。
|
||||
type blockingOrderDetailClient struct {
|
||||
// started 表示外部订单详情请求已经开始。
|
||||
started chan struct{}
|
||||
// release 允许测试结束外部请求阻塞。
|
||||
release chan struct{}
|
||||
// detail 是请求结束后返回的订单详情。
|
||||
detail *mtop.OrderDetailResult
|
||||
}
|
||||
|
||||
// FetchOrderDetail 阻塞到测试显式释放后返回订单详情。
|
||||
func (c *blockingOrderDetailClient) FetchOrderDetail(ctx context.Context, _, _ string) (*mtop.OrderDetailResult, error) {
|
||||
close(c.started)
|
||||
select {
|
||||
case <-c.release:
|
||||
return c.detail, nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetailReleasesCredentialLockDuringSlowIO 验证订单详情外部调用不持有共享凭证锁。
|
||||
func TestFetchOrderDetailReleasesCredentialLockDuringSlowIO(t *testing.T) {
|
||||
// store 是订单详情协调器测试使用的账号数据库。
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// client 是阻塞外部 I/O 的订单详情桩。
|
||||
client := &blockingOrderDetailClient{
|
||||
started: make(chan struct{}), release: make(chan struct{}),
|
||||
detail: &mtop.OrderDetailResult{Quantity: "1", Amount: "9.9"},
|
||||
}
|
||||
// adapter 是待验证凭证快照协调行为的适配器。
|
||||
adapter := New(store, nil, nil)
|
||||
adapter.SetOrderDetailClient(client)
|
||||
// result 是订单详情调用完成的同步通道。
|
||||
result := make(chan struct{})
|
||||
go func() {
|
||||
// orderErr 是订单详情调用的错误结果。
|
||||
_, orderErr := adapter.FetchOrderDetail(context.Background(), "cid", "slow-order", "item", "buyer", "")
|
||||
if orderErr != nil {
|
||||
t.Errorf("订单详情调用失败: %v", orderErr)
|
||||
}
|
||||
close(result)
|
||||
}()
|
||||
select {
|
||||
case <-client.started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("订单详情请求未开始")
|
||||
}
|
||||
// lockReleased 是另一个调用方成功取得并释放凭证锁的同步信号。
|
||||
lockReleased := make(chan struct{})
|
||||
go func() {
|
||||
// unlock 是探测调用方取得的凭证锁释放函数。
|
||||
unlock := store.LockAccountCredentials("cid")
|
||||
unlock()
|
||||
close(lockReleased)
|
||||
}()
|
||||
select {
|
||||
case <-lockReleased:
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
t.Fatal("慢速订单详情调用仍占用共享凭证锁")
|
||||
}
|
||||
close(client.release)
|
||||
select {
|
||||
case <-result:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("订单详情调用未完成")
|
||||
}
|
||||
}
|
||||
+38
-10
@@ -35,7 +35,15 @@ type Store struct {
|
||||
Analytics *AnalyticsQueries
|
||||
|
||||
credentialMu sync.Mutex
|
||||
credentialLocks map[string]*sync.Mutex
|
||||
credentialLocks map[string]*credentialLockEntry
|
||||
}
|
||||
|
||||
// credentialLockEntry 保存单个账号凭证锁及当前排队/持有者数量。
|
||||
type credentialLockEntry struct {
|
||||
// mu 串行化该账号的 Cookie、token 和 metadata 状态变更。
|
||||
mu sync.Mutex
|
||||
// refs 记录仍可能使用该 entry 的调用方数量,用于安全回收空闲锁。
|
||||
refs int
|
||||
}
|
||||
|
||||
// NewStore 基于 *sql.DB 构造聚合 store。dialect 用于业务 SQL 方言分支。
|
||||
@@ -69,7 +77,7 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
|
||||
AccountTasks: &AccountTaskStore{DB: db, Dialect: dialect},
|
||||
Admin: &AdminQueries{DB: db},
|
||||
Analytics: &AnalyticsQueries{DB: db},
|
||||
credentialLocks: make(map[string]*sync.Mutex),
|
||||
credentialLocks: make(map[string]*credentialLockEntry),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,15 +91,35 @@ func (s *Store) LockAccountCredentials(cookieID string) func() {
|
||||
}
|
||||
s.credentialMu.Lock()
|
||||
if s.credentialLocks == nil {
|
||||
s.credentialLocks = make(map[string]*sync.Mutex)
|
||||
s.credentialLocks = make(map[string]*credentialLockEntry)
|
||||
}
|
||||
// lock 保存锁,供当前处理流程使用
|
||||
lock := s.credentialLocks[cookieID]
|
||||
if lock == nil {
|
||||
lock = &sync.Mutex{}
|
||||
s.credentialLocks[cookieID] = lock
|
||||
// entry 保存账号锁及其引用计数。
|
||||
entry := s.credentialLocks[cookieID]
|
||||
if entry == nil {
|
||||
entry = &credentialLockEntry{}
|
||||
s.credentialLocks[cookieID] = entry
|
||||
}
|
||||
entry.refs++
|
||||
s.credentialMu.Unlock()
|
||||
lock.Lock()
|
||||
return lock.Unlock
|
||||
entry.mu.Lock()
|
||||
// unlocked 防止异常重复调用释放函数破坏锁和引用计数。
|
||||
unlocked := false
|
||||
// unlockMu 保护释放函数的幂等状态。
|
||||
var unlockMu sync.Mutex
|
||||
return func() {
|
||||
unlockMu.Lock()
|
||||
if unlocked {
|
||||
unlockMu.Unlock()
|
||||
return
|
||||
}
|
||||
unlocked = true
|
||||
unlockMu.Unlock()
|
||||
entry.mu.Unlock()
|
||||
s.credentialMu.Lock()
|
||||
entry.refs--
|
||||
if entry.refs == 0 && s.credentialLocks[cookieID] == entry {
|
||||
delete(s.credentialLocks, cookieID)
|
||||
}
|
||||
s.credentialMu.Unlock()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestLockAccountCredentialsReclaimsIdleEntries 验证账号凭证锁在最后一个持有者释放后会回收。
|
||||
func TestLockAccountCredentialsReclaimsIdleEntries(t *testing.T) {
|
||||
// store 是只初始化凭证锁表的最小 Store。
|
||||
store := &Store{credentialLocks: make(map[string]*credentialLockEntry)}
|
||||
// unlock 是当前账号凭证锁的释放函数。
|
||||
unlock := store.LockAccountCredentials("cookie-1")
|
||||
store.credentialMu.Lock()
|
||||
// entryCount 是当前凭证锁表中的账号数量。
|
||||
entryCount := len(store.credentialLocks)
|
||||
store.credentialMu.Unlock()
|
||||
if entryCount != 1 {
|
||||
t.Fatalf("获取锁后应有一个 entry,got=%d", entryCount)
|
||||
}
|
||||
unlock()
|
||||
unlock()
|
||||
store.credentialMu.Lock()
|
||||
// remainingCount 是释放最后一个锁后的账号数量。
|
||||
remainingCount := len(store.credentialLocks)
|
||||
store.credentialMu.Unlock()
|
||||
if remainingCount != 0 {
|
||||
t.Fatalf("最后一个锁释放后应回收 entry,got=%d", remainingCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLockAccountCredentialsKeepsEntryWhileWaiterExists 验证等待者存在时不会提前回收共享锁。
|
||||
func TestLockAccountCredentialsKeepsEntryWhileWaiterExists(t *testing.T) {
|
||||
// store 是并发凭证锁测试使用的最小 Store。
|
||||
store := &Store{credentialLocks: make(map[string]*credentialLockEntry)}
|
||||
// firstUnlock 是第一个持有者的释放函数。
|
||||
firstUnlock := store.LockAccountCredentials("cookie-2")
|
||||
// waiterAcquired 表示第二个调用方已经获得并释放了账号锁。
|
||||
waiterAcquired := make(chan struct{})
|
||||
go func() {
|
||||
// secondUnlock 是等待者获得的释放函数。
|
||||
secondUnlock := store.LockAccountCredentials("cookie-2")
|
||||
secondUnlock()
|
||||
close(waiterAcquired)
|
||||
}()
|
||||
// waiterStarted 是确认等待者已经登记引用后再释放第一个锁的同步信号。
|
||||
waiterStarted := false
|
||||
// deadline 限制等待者登记引用的最长时间。
|
||||
deadline := time.NewTimer(time.Second)
|
||||
defer deadline.Stop()
|
||||
for !waiterStarted {
|
||||
store.credentialMu.Lock()
|
||||
// entry 是当前账号的共享锁 entry。
|
||||
entry := store.credentialLocks["cookie-2"]
|
||||
if entry != nil && entry.refs == 2 {
|
||||
waiterStarted = true
|
||||
}
|
||||
store.credentialMu.Unlock()
|
||||
if waiterStarted {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-deadline.C:
|
||||
t.Fatal("等待者未登记凭证锁引用")
|
||||
default:
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
firstUnlock()
|
||||
select {
|
||||
case <-waiterAcquired:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("等待者未获得凭证锁")
|
||||
}
|
||||
store.credentialMu.Lock()
|
||||
// remainingCount 是等待者释放后凭证锁表中的账号数量。
|
||||
remainingCount := len(store.credentialLocks)
|
||||
store.credentialMu.Unlock()
|
||||
if remainingCount != 0 {
|
||||
t.Fatalf("等待者释放后应回收 entry,got=%d", remainingCount)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLockAccountCredentialsSerializesConcurrentUpdates 验证同一账号的临界区仍然互斥。
|
||||
func TestLockAccountCredentialsSerializesConcurrentUpdates(t *testing.T) {
|
||||
// store 是并发临界区测试使用的最小 Store。
|
||||
store := &Store{credentialLocks: make(map[string]*credentialLockEntry)}
|
||||
// activeCount 是同时进入临界区的调用方数量。
|
||||
activeCount := 0
|
||||
// maxActiveCount 是测试期间观察到的最大并发数量。
|
||||
maxActiveCount := 0
|
||||
// countMu 保护测试计数器。
|
||||
var countMu sync.Mutex
|
||||
// done 是两个并发调用完成的同步信号。
|
||||
done := make(chan struct{}, 2)
|
||||
for // i 表示当前并发锁测试调用序号。
|
||||
i := 0; i < 2; i++ {
|
||||
go func() {
|
||||
// unlock 是当前调用方的账号锁释放函数。
|
||||
unlock := store.LockAccountCredentials("cookie-3")
|
||||
countMu.Lock()
|
||||
activeCount++
|
||||
if activeCount > maxActiveCount {
|
||||
maxActiveCount = activeCount
|
||||
}
|
||||
countMu.Unlock()
|
||||
time.Sleep(time.Millisecond)
|
||||
countMu.Lock()
|
||||
activeCount--
|
||||
countMu.Unlock()
|
||||
unlock()
|
||||
done <- struct{}{}
|
||||
}()
|
||||
}
|
||||
for // i 表示当前完成信号序号。
|
||||
i := 0; i < 2; i++ {
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("并发凭证锁测试超时")
|
||||
}
|
||||
}
|
||||
if maxActiveCount != 1 {
|
||||
t.Fatalf("同一账号临界区应互斥,最大并发数=%d", maxActiveCount)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user