From 2ca4ac9f2b090f95f22dc754e9b727e72e41356b Mon Sep 17 00:00:00 2001 From: Christ Date: Sat, 15 Aug 2026 03:12:04 +0800 Subject: [PATCH] =?UTF-8?q?=E9=98=B6=E6=AE=B5=E5=85=AB=EF=BC=9A=E5=AE=8C?= =?UTF-8?q?=E6=88=90=E5=8F=91=E5=B8=83=E5=BA=94=E7=94=A8=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?repository=E6=94=B6=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/architecture/refactoring-master-plan.md | 1 + internal/server/application_services.go | 2 +- internal/server/item_publish_repository.go | 138 +++++++++++++++++++ internal/server/item_publish_service.go | 52 +++---- 4 files changed, 166 insertions(+), 27 deletions(-) create mode 100644 internal/server/item_publish_repository.go diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 6314544..5304398 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -615,3 +615,4 @@ npm --prefix frontend run build | 2026-08-15 | 完成阶段 8 第三个 PR 切片“通知与通信应用服务 repository 边界” | 新增 `notify.Repository`,通知器仅持有渠道、SMTP 系统设置和 outbox 所需的最小接口,保留同步发送、异步租约、重试和测试发送语义;新增通信应用服务窄 repository,账号任务、通知渠道/绑定和聊天历史持久化不再直接访问完整 `db.Store`,实时账号、MTOP 和聊天服务仍由 Server 装配;通知/Server 定向测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:剩余应用服务与事务 repository 边界 | | 2026-08-15 | 完成阶段 8 第四个 PR 切片“分析应用服务只读 repository 边界” | 新增分析服务窄 repository,统一封装 Dashboard 固定统计、订单分析聚合、有效订单分页、卡密库存读取和数据库方言;应用服务不再持有完整 `Server` 或直接访问 `Store.Analytics/Cards`,查询阶段错误、金额表达式和响应聚合语义保持不变;Server 全量测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:订单与发布应用服务 repository 边界 | | 2026-08-15 | 完成阶段 8 第五个 PR 切片“订单应用服务 repository 与事务边界” | 新增 `orderRepository`,订单应用服务的订单/商品读写、用户归属、事务、凭证锁、续期 Cookie 和远端缺失清理均通过窄接口;平台 MTOP、运行时 Cookie 更新、自动化发货和通知编排仍由 Server 负责;订单列表、详情、导入、手动发货、单笔/批量刷新语义保持不变;Server 全量测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:发布应用服务 repository 与 worker 事务边界 | +| 2026-08-15 | 完成阶段 8 第六个 PR 切片“发布应用服务 repository 边界” | 新增 `itemPublishRepository`,单商品发布、类目推荐、预检批次创建、批次查询/取消/删除/失败重试及凭证 Cookie 持久化不再直接访问完整 `db.Store`;批量 worker 的租约状态机和后台生命周期暂保持原有 Server 接线,下一片整体迁移;单商品/批量发布测试、Go vet、lint、注释和全量门禁通过并合并为一个可回滚提交 | 阶段 8:发布 worker 租约状态机 repository 边界 | diff --git a/internal/server/application_services.go b/internal/server/application_services.go index c7165b2..a14f21a 100644 --- a/internal/server/application_services.go +++ b/internal/server/application_services.go @@ -18,7 +18,7 @@ type applicationServices struct { func newApplicationServices(server *Server) *applicationServices { return &applicationServices{ orders: &orderApplicationService{server: server, repository: newStoreOrderRepository(server.Store)}, - itemPublish: &itemPublishService{server: server}, + itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)}, accountLogin: &accountLoginService{server: server}, communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)}, analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)}, diff --git a/internal/server/item_publish_repository.go b/internal/server/item_publish_repository.go new file mode 100644 index 0000000..c15bf92 --- /dev/null +++ b/internal/server/item_publish_repository.go @@ -0,0 +1,138 @@ +package server + +import ( + "context" + + "xianyu-go/internal/db" +) + +// itemPublishRepository 定义发布应用服务处理商品与批次状态所需的最小持久化能力。 +type itemPublishRepository interface { + // LockCredentials 串行化账号凭证状态变更。 + LockCredentials(cookieID string) func() + // LoadCookiePlatformDetail 读取平台发布所需的最小账号凭证视图。 + LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*db.CookieDetail, error) + // UpdateCookieValueOwned 更新用户拥有账号的 Cookie。 + UpdateCookieValueOwned(ctx context.Context, cookieID, value string, userID int64) error + // UpsertItem 写入发布成功后的商品基础信息。 + UpsertItem(ctx context.Context, item *db.ItemInfoRow) error + // CreateBatch 创建批次及其明细行。 + CreateBatch(ctx context.Context, batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) error + // RecountBatch 重算批次统计。 + RecountBatch(ctx context.Context, batchID string) error + // GetBatch 查询用户拥有的批次。 + GetBatch(ctx context.Context, userID int64, batchID string) (*db.ItemPublishBatch, error) + // ClaimBatch 抢占批次 worker 租约。 + ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) + // PendingRows 查询批次待处理明细。 + PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]db.ItemPublishBatchRow, error) + // FinalizeBatch 完成批次状态收口。 + FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) + // ListBatchesForUser 查询用户批次列表。 + ListBatchesForUser(ctx context.Context, userID int64, limit int) ([]db.ItemPublishBatch, error) + // ListBatchRows 查询批次明细行。 + ListBatchRows(ctx context.Context, batchID string) ([]db.ItemPublishBatchRow, error) + // RequestCancel 请求取消批次。 + RequestCancel(ctx context.Context, batchID string) (string, bool, error) + // DeleteBatch 删除用户拥有的批次。 + DeleteBatch(ctx context.Context, userID int64, batchID string) error + // ResetFailed 重置批次失败明细。 + ResetFailed(ctx context.Context, batchID string) error +} + +// storeItemPublishRepository 将完整 Store 适配为发布应用服务窄 repository。 +type storeItemPublishRepository struct { + // store 保存数据库聚合入口,仅在适配器内部使用。 + store *db.Store +} + +// LockCredentials 委托账号凭证锁。 +func (r storeItemPublishRepository) LockCredentials(cookieID string) func() { + return r.store.LockAccountCredentials(cookieID) +} + +// LoadCookiePlatformDetail 委托平台发布凭证查询并转换为 Server 内部模型。 +func (r storeItemPublishRepository) LoadCookiePlatformDetail(ctx context.Context, cookieID string) (*db.CookieDetail, error) { + // data 和 err 保存平台运行视图查询结果。 + data, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) + if err != nil { + return nil, err + } + return &db.CookieDetail{ID: data.ID, UserID: data.UserID, Value: data.Value, MetadataJSON: data.MetadataJSON, ShowBrowser: data.ShowBrowser}, nil +} + +// UpdateCookieValueOwned 委托账号 Cookie 更新。 +func (r storeItemPublishRepository) UpdateCookieValueOwned(ctx context.Context, cookieID, value string, userID int64) error { + return r.store.Cookies.UpdateValueOwned(ctx, cookieID, value, userID) +} + +// UpsertItem 委托商品基础信息写入。 +func (r storeItemPublishRepository) UpsertItem(ctx context.Context, item *db.ItemInfoRow) error { + return r.store.Items.Upsert(ctx, item) +} + +// CreateBatch 委托批次创建。 +func (r storeItemPublishRepository) CreateBatch(ctx context.Context, batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) error { + return r.store.PublishBatches.Create(ctx, batch, rows) +} + +// RecountBatch 委托批次统计重算。 +func (r storeItemPublishRepository) RecountBatch(ctx context.Context, batchID string) error { + return r.store.PublishBatches.Recount(ctx, batchID) +} + +// GetBatch 委托用户批次查询。 +func (r storeItemPublishRepository) GetBatch(ctx context.Context, userID int64, batchID string) (*db.ItemPublishBatch, error) { + return r.store.PublishBatches.Get(ctx, userID, batchID) +} + +// ClaimBatch 委托批次租约抢占。 +func (r storeItemPublishRepository) ClaimBatch(ctx context.Context, batchID, workerToken string, leaseExpiresAt int64) (bool, error) { + return r.store.PublishBatches.ClaimBatch(ctx, batchID, workerToken, leaseExpiresAt) +} + +// PendingRows 委托批次待处理明细查询。 +func (r storeItemPublishRepository) PendingRows(ctx context.Context, batchID string, failedOnly bool) ([]db.ItemPublishBatchRow, error) { + return r.store.PublishBatches.PendingRows(ctx, batchID, failedOnly) +} + +// FinalizeBatch 委托批次完成状态收口。 +func (r storeItemPublishRepository) FinalizeBatch(ctx context.Context, batchID, workerToken string) (string, bool, error) { + return r.store.PublishBatches.FinalizeBatch(ctx, batchID, workerToken) +} + +// ListBatchesForUser 委托用户批次列表查询。 +func (r storeItemPublishRepository) ListBatchesForUser(ctx context.Context, userID int64, limit int) ([]db.ItemPublishBatch, error) { + return r.store.PublishBatches.ListForUser(ctx, userID, limit) +} + +// ListBatchRows 委托批次明细查询。 +func (r storeItemPublishRepository) ListBatchRows(ctx context.Context, batchID string) ([]db.ItemPublishBatchRow, error) { + return r.store.PublishBatches.Rows(ctx, batchID) +} + +// RequestCancel 委托批次取消请求。 +func (r storeItemPublishRepository) RequestCancel(ctx context.Context, batchID string) (string, bool, error) { + return r.store.PublishBatches.RequestCancel(ctx, batchID) +} + +// DeleteBatch 委托批次删除。 +func (r storeItemPublishRepository) DeleteBatch(ctx context.Context, userID int64, batchID string) error { + return r.store.PublishBatches.Delete(ctx, userID, batchID) +} + +// ResetFailed 委托失败明细重置。 +func (r storeItemPublishRepository) ResetFailed(ctx context.Context, batchID string) error { + return r.store.PublishBatches.ResetFailed(ctx, batchID) +} + +// newStoreItemPublishRepository 从完整 Store 构造发布应用服务窄 repository。 +func newStoreItemPublishRepository(store *db.Store) itemPublishRepository { + if store == nil || store.Cookies == nil || store.Items == nil || store.PublishBatches == nil { + return nil + } + return storeItemPublishRepository{store: store} +} + +// 确保 Store 适配器始终覆盖发布应用服务所需的全部能力。 +var _ itemPublishRepository = storeItemPublishRepository{} diff --git a/internal/server/item_publish_service.go b/internal/server/item_publish_service.go index a833a24..38460cb 100644 --- a/internal/server/item_publish_service.go +++ b/internal/server/item_publish_service.go @@ -81,6 +81,8 @@ type itemPublishPreviewInput struct { type itemPublishService struct { // server 提供数据库、MTOP 客户端、运行时 Cookie 和 worker 生命周期依赖。 server *Server + // repository 提供商品发布用例所需的最小持久化能力。 + repository itemPublishRepository } // itemPublishApplication 返回当前 Server 绑定的商品发布应用服务。 @@ -93,7 +95,7 @@ func (svc *itemPublishService) PublishSingle(ctx context.Context, input itemPubl // s 是当前商品发布应用服务依赖的 Server。 s := svc.server // unlock 释放当前账号的凭证串行化锁。 - unlock := s.Store.LockAccountCredentials(input.CookieID) + unlock := svc.repository.LockCredentials(input.CookieID) // err 和 latest 保存账号平台详情查询结果。 latest, err := s.loadCookiePlatformDetail(ctx, input.CookieID) if err != nil || latest == nil || latest.UserID != input.UserID || !hasStoredCookieCredential(latest) { @@ -128,7 +130,7 @@ func (svc *itemPublishService) PublishSingle(ctx context.Context, input itemPubl runtimeCookie = value } else if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != cookieValue { // saveErr 表示保存平台返回新 Cookie 的错误。 - if saveErr := s.Store.Cookies.UpdateValueOwned(ctx, input.CookieID, result.UpdatedCookies, input.UserID); saveErr != nil { + if saveErr := svc.repository.UpdateCookieValueOwned(ctx, input.CookieID, result.UpdatedCookies, input.UserID); saveErr != nil { persistErr = saveErr } else { runtimeCookie = result.UpdatedCookies @@ -153,7 +155,7 @@ func (svc *itemPublishService) PublishSingle(ctx context.Context, input itemPubl // detailJSON 是本地商品详情 JSON。 detailJSON, _ := json.Marshal(detail) // localErr 表示平台发布成功后本地商品落库的错误。 - localErr := s.Store.Items.Upsert(ctx, &db.ItemInfoRow{ + localErr := svc.repository.UpsertItem(ctx, &db.ItemInfoRow{ CookieID: input.CookieID, ItemID: result.ItemID, ItemTitle: result.Title, ItemDescription: input.Description, ItemCategory: result.CategoryID, ItemPrice: result.PriceText, ItemDetail: string(detailJSON), MultiQuantityDelivery: input.Quantity > 1, @@ -171,7 +173,7 @@ func (svc *itemPublishService) RecommendCategory(ctx context.Context, userID int return mtop.PublishCategory{}, errors.New("当前 MTOP 客户端不支持类目推荐") } // unlock 释放当前账号的凭证串行化锁。 - unlock := s.Store.LockAccountCredentials(cookieID) + unlock := svc.repository.LockCredentials(cookieID) // runtimeCookie 是需要在释放凭证锁后同步的刷新凭证。 runtimeCookie := "" defer func() { @@ -199,7 +201,7 @@ func (svc *itemPublishService) RecommendCategory(ctx context.Context, userID int } if !handled && updatedCookies != "" && updatedCookies != latest.Value { // err 表示保存平台返回新 Cookie 的错误。 - if err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil { + if err := svc.repository.UpdateCookieValueOwned(ctx, cookieID, updatedCookies, userID); err != nil { return mtop.PublishCategory{}, fmt.Errorf("保存账号登录状态失败: %w", err) } runtimeCookie = updatedCookies @@ -251,10 +253,10 @@ func (svc *itemPublishService) PersistPreview(ctx context.Context, input itemPub // locationBytes 是批次发货地配置的 JSON 表示。 locationBytes, _ := json.Marshal(input.Location) // err 表示批次及其明细的事务写入错误。 - if err := svc.server.Store.PublishBatches.Create(ctx, &db.ItemPublishBatch{ID: input.BatchID, UserID: input.UserID, DefaultCookieID: input.DefaultCookieID, Filename: input.Filename, UploadDir: input.UploadDir, LocationJSON: string(locationBytes), Status: "preview"}, rows); err != nil { + if err := svc.repository.CreateBatch(ctx, &db.ItemPublishBatch{ID: input.BatchID, UserID: input.UserID, DefaultCookieID: input.DefaultCookieID, Filename: input.Filename, UploadDir: input.UploadDir, LocationJSON: string(locationBytes), Status: "preview"}, rows); err != nil { return itemPublishBatchPreviewResponse{}, fmt.Errorf("保存预检结果失败: %w", err) } - _ = svc.server.Store.PublishBatches.Recount(ctx, input.BatchID) + _ = svc.repository.RecountBatch(ctx, input.BatchID) return itemPublishBatchPreviewResponse{Success: true, PreviewID: input.BatchID, Total: len(rows), Valid: valid, Invalid: invalid, Rows: previewRows}, nil } @@ -263,7 +265,7 @@ func (svc *itemPublishService) StartBatch(ctx context.Context, userID int64, bat // s 是当前商品发布应用服务依赖的 Server。 s := svc.server // batch 和 err 保存批次查询结果。 - batch, err := s.Store.PublishBatches.Get(ctx, userID, batchID) + batch, err := svc.repository.GetBatch(ctx, userID, batchID) if err != nil { return "", errItemPublishBatchNotFound } @@ -276,7 +278,7 @@ func (svc *itemPublishService) StartBatch(ctx context.Context, userID int64, bat // token 是本次 worker 租约的随机凭证。 token := randomHex(16) // claimed 和 err 保存批次租约声明结果。 - claimed, err := s.Store.PublishBatches.ClaimBatch(ctx, batch.ID, token, time.Now().UTC().Add(publishBatchLease).Unix()) + claimed, err := svc.repository.ClaimBatch(ctx, batch.ID, token, time.Now().UTC().Add(publishBatchLease).Unix()) if err != nil { return "", fmt.Errorf("启动任务失败: %w", err) } @@ -284,13 +286,13 @@ func (svc *itemPublishService) StartBatch(ctx context.Context, userID int64, bat return "", errItemPublishBatchConflict } // pending 和 err 保存待处理明细查询结果。 - pending, err := s.Store.PublishBatches.PendingRows(ctx, batch.ID, false) + pending, err := svc.repository.PendingRows(ctx, batch.ID, false) if err != nil { s.failClaimedPublishBatch(batch.ID, token) return "", fmt.Errorf("读取任务失败: %w", err) } if len(pending) == 0 { - _, _, _ = s.Store.PublishBatches.FinalizeBatch(ctx, batch.ID, token) + _, _, _ = svc.repository.FinalizeBatch(ctx, batch.ID, token) return "", errItemPublishBatchNoRows } s.startPublishBatchWorker(s.lifecycleContext(), userID, batch.ID, token) @@ -300,7 +302,7 @@ func (svc *itemPublishService) StartBatch(ctx context.Context, userID int64, bat // ListBatches 查询用户的批量任务并映射为 HTTP 无关的响应 DTO。 func (svc *itemPublishService) ListBatches(ctx context.Context, userID int64, limit int) ([]itemPublishBatchResponse, error) { // batches 和 err 保存用户批次列表查询结果。 - batches, err := svc.server.Store.PublishBatches.ListForUser(ctx, userID, limit) + batches, err := svc.repository.ListBatchesForUser(ctx, userID, limit) if err != nil { return nil, err } @@ -316,12 +318,12 @@ func (svc *itemPublishService) ListBatches(ctx context.Context, userID int64, li // GetBatch 查询用户拥有的批量任务及其明细行。 func (svc *itemPublishService) GetBatch(ctx context.Context, userID int64, batchID string) (itemPublishBatchResponse, error) { // batch 和 err 保存批次查询结果。 - batch, err := svc.server.Store.PublishBatches.Get(ctx, userID, batchID) + batch, err := svc.repository.GetBatch(ctx, userID, batchID) if err != nil { return itemPublishBatchResponse{}, errItemPublishBatchNotFound } // rows 和 err 保存批次明细查询结果。 - rows, err := svc.server.Store.PublishBatches.Rows(ctx, batch.ID) + rows, err := svc.repository.ListBatchRows(ctx, batch.ID) if err != nil { return itemPublishBatchResponse{}, err } @@ -333,11 +335,11 @@ func (svc *itemPublishService) CancelBatch(ctx context.Context, userID int64, ba // s 是当前商品发布应用服务依赖的 Server。 s := svc.server // err 表示批次所有权查询错误。 - if _, err := s.Store.PublishBatches.Get(ctx, userID, batchID); err != nil { + if _, err := svc.repository.GetBatch(ctx, userID, batchID); err != nil { return "", errItemPublishBatchNotFound } // token、running 和 err 保存取消请求及当前 worker 状态。 - token, running, err := s.Store.PublishBatches.RequestCancel(ctx, batchID) + token, running, err := svc.repository.RequestCancel(ctx, batchID) if err != nil { if errors.Is(err, db.ErrPublishBatchChanged) { return "", errItemPublishBatchConflict @@ -355,10 +357,8 @@ func (svc *itemPublishService) CancelBatch(ctx context.Context, userID int64, ba // DeleteBatch 删除非运行中的批量任务并返回其上传目录供适配层清理。 func (svc *itemPublishService) DeleteBatch(ctx context.Context, userID int64, batchID string) (string, error) { - // s 是当前商品发布应用服务依赖的 Server。 - s := svc.server // batch 和 err 保存批次查询结果。 - batch, err := s.Store.PublishBatches.Get(ctx, userID, batchID) + batch, err := svc.repository.GetBatch(ctx, userID, batchID) if err != nil { return "", errItemPublishBatchNotFound } @@ -366,7 +366,7 @@ func (svc *itemPublishService) DeleteBatch(ctx context.Context, userID int64, ba return "", errItemPublishBatchConflict } // err 表示批次删除错误。 - if err := s.Store.PublishBatches.Delete(ctx, userID, batchID); err != nil { + if err := svc.repository.DeleteBatch(ctx, userID, batchID); err != nil { return "", err } return batch.UploadDir, nil @@ -377,7 +377,7 @@ func (svc *itemPublishService) RetryFailedBatch(ctx context.Context, userID int6 // s 是当前商品发布应用服务依赖的 Server。 s := svc.server // batch 和 err 保存批次查询结果。 - batch, err := s.Store.PublishBatches.Get(ctx, userID, batchID) + batch, err := svc.repository.GetBatch(ctx, userID, batchID) if err != nil { return "", errItemPublishBatchNotFound } @@ -387,7 +387,7 @@ func (svc *itemPublishService) RetryFailedBatch(ctx context.Context, userID int6 // token 是本次重试 worker 的租约凭证。 token := randomHex(16) // claimed 和 err 保存重试租约声明结果。 - claimed, err := s.Store.PublishBatches.ClaimBatch(ctx, batchID, token, time.Now().UTC().Add(publishBatchLease).Unix()) + claimed, err := svc.repository.ClaimBatch(ctx, batchID, token, time.Now().UTC().Add(publishBatchLease).Unix()) if err != nil { return "", err } @@ -395,19 +395,19 @@ func (svc *itemPublishService) RetryFailedBatch(ctx context.Context, userID int6 return "", errItemPublishBatchConflict } // err 表示重置失败明细的错误。 - if err := s.Store.PublishBatches.ResetFailed(ctx, batchID); err != nil { + if err := svc.repository.ResetFailed(ctx, batchID); err != nil { s.failClaimedPublishBatch(batchID, token) return "", err } - _ = s.Store.PublishBatches.Recount(ctx, batchID) + _ = svc.repository.RecountBatch(ctx, batchID) // pending 和 err 保存可重试明细查询结果。 - pending, err := s.Store.PublishBatches.PendingRows(ctx, batchID, false) + pending, err := svc.repository.PendingRows(ctx, batchID, false) if err != nil { s.failClaimedPublishBatch(batchID, token) return "", err } if len(pending) == 0 { - _, _, _ = s.Store.PublishBatches.FinalizeBatch(ctx, batchID, token) + _, _, _ = svc.repository.FinalizeBatch(ctx, batchID, token) return "", errItemPublishBatchNoRows } s.startPublishBatchWorker(s.lifecycleContext(), userID, batchID, token)