推进P1应用端口生命周期与发货补偿
This commit is contained in:
1 parent
2cd3c946fc
commit
bcdc163306
11 files changed
+534
-120
No files matched your search
@@ -785,6 +785,9 @@ npm --prefix frontend run build
|
||||
| 2026-08-15 | P2 React ItemList 普通商品动作协调器 feature 化 | 已完成本切片 | 新增 `frontend/app/features/items/itemActions.ts` 和 `itemActions.test.tsx`,将商品同步、编辑、删除、手动添加、普通发布、图片预览、模板下载和发货地定位从 `ItemList` 根组件迁入 items feature;批量发布 Hook 保持独立,更新图片预览静态契约;前端全量 62 个测试文件/369 个用例、类型检查、中文注释门禁、生产构建和仓库 `make check` 通过。ItemList 真实页面组合覆盖、页面级 Provider 组合和阶段 7 总体验收仍未完成 |
|
||||
| 2026-08-15 | P0 敏感配置调用方与运维输出脱敏代码切片 | 已完成本子切片 | 新增 `Store.ReadSensitiveSetting`/`ReadSensitiveSettingForAccount`,AI API Key、远程验证码密钥、系统 SMTP 密码和 AI 模型查询均在解密前写入不含秘密值的访问审计;新增 `logsafe.Error/Text`,dbverify/dbseed/init-admin/server/spike 及关键 URL/错误日志不再直接输出凭证、查询参数或解密消息正文;三库矩阵新增严格 `REQUIRE_MULTIDB=1` 门禁和 `make test-multidb`,无外部 URL 时明确跳过/失败而不伪造证据。定向 Go 测试、`make check`、前端 369 测试/类型检查/构建和注释门禁通过;受影响包全量 race 曾命中既有订单并发测试一次,聚焦重复验证通过,外部三库证据在后续验收子切片补齐 |
|
||||
| 2026-08-15 | P0 父切片三库实测与集中式日志/凭证边界验收 | 已完成 | `.github/workflows/ci.yml` 新增 MySQL 8.4/PostgreSQL 17 service job,`docs/architecture/multidb-test-runbook.md` 提供本地复现方式;本机 Docker 实际执行 `make test-multidb`,SQLite/MySQL/PostgreSQL 全部多库测试通过并在结束后清理容器与数据卷;移除无人调用的批量解密 API,集中式 `slog` handler 递归清理敏感属性,Server/spike 的 logger fallback 也统一接入,审计边界与剩余 P1 风险已更新 |
|
||||
| 2026-08-15 | P1 单商品发布应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `internal/application/items` 的发布输入、结果、平台 Port 和商品仓储 Port;`publishItem` 仅在 Server 边界完成 HTTP/MTOP/DB 模型转换,单商品平台发布与本地商品落库编排已移出 Server;新增应用服务构造、平台失败和成功落库测试,架构门禁、中文注释门禁、Server 回归及聚焦 race 通过。批量发布、商品同步及其他 Server 应用服务仍待迁移;现有商品发布凭证锁覆盖远端 I/O 的风险保留给后续凭证协调切片 |
|
||||
| 2026-08-15 | P1 续期调度器 Context-aware Stop 切片 | 已完成本切片 | `internal/renewal.Scheduler` 新增私有运行 Context、`StopContext` 和兼容 `Stop`,主动停止会取消登录续期/API 续期 worker 并在调用方 Context 内等待 watcher 收束;重复停止保持幂等;新增主动取消与超时回归,续期测试、全量门禁和聚焦 race 通过。浏览器、Engine 内部任务、账号删除任务登记和统一生命周期清单仍未完成 |
|
||||
| 2026-08-15 | P1 发货本地事实补偿闭环切片 | 已完成本切片 | 自动化发货远端成功但本地订单状态或事件时间写入失败时创建 `manual_status_ship` pending 补偿记录;补偿记录创建失败会并入 uncertain 错误,不再吞错;扩展远端成功/本地失败回归并实际运行 reconciliation worker 恢复订单状态、清理 pending。其他不可逆自动化动作、退避策略和统一运维查询仍待治理 |
|
||||
|
||||
### 11.2 执行纠偏审计(2026-08-15)
|
||||
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// Package items 提供商品发布相关的应用用例与消费者定义的端口。
|
||||
package items
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Image 是商品发布所需的图片内容;图片字节只在当前用例生命周期内由端口消费。
|
||||
type Image struct {
|
||||
// Filename 是上传到平台时使用的原始文件名。
|
||||
Filename string
|
||||
// ContentType 是经过请求校验的 MIME 类型。
|
||||
ContentType string
|
||||
// Data 是图片二进制内容,禁止写入日志或响应。
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// Location 是平台发布所需的发货地信息,不依赖外部平台包的 DTO。
|
||||
type Location struct {
|
||||
// Area 是发货地的区县名称。
|
||||
Area string
|
||||
// City 是发货地的城市名称。
|
||||
City string
|
||||
// DivisionID 是平台行政区划标识。
|
||||
DivisionID string
|
||||
// Longitude 是发货地经度。
|
||||
Longitude float64
|
||||
// Latitude 是发货地纬度。
|
||||
Latitude float64
|
||||
// POIID 是地图服务返回的兴趣点标识。
|
||||
POIID string
|
||||
// POIName 是地图服务返回的兴趣点名称。
|
||||
POIName string
|
||||
// Province 是发货地的省份名称。
|
||||
Province string
|
||||
}
|
||||
|
||||
// PublishInput 是单商品发布用例输入,携带已由 HTTP 层验证的业务字段。
|
||||
type PublishInput struct {
|
||||
// UserID 是发起发布操作的用户标识。
|
||||
UserID int64
|
||||
// CookieID 是执行发布的账号标识。
|
||||
CookieID string
|
||||
// Title 是商品标题。
|
||||
Title string
|
||||
// Description 是商品描述。
|
||||
Description string
|
||||
// PriceCents 是商品售价,单位为分。
|
||||
PriceCents int64
|
||||
// OriginalPriceCents 是商品原价,单位为分。
|
||||
OriginalPriceCents int64
|
||||
// Quantity 是商品库存数量。
|
||||
Quantity int
|
||||
// PostageMode 是邮费模式,例如 free 或 fixed。
|
||||
PostageMode string
|
||||
// PostageCents 是邮费金额,单位为分。
|
||||
PostageCents int64
|
||||
// Location 是可选的发货地。
|
||||
Location *Location
|
||||
// Images 是待上传的商品图片。
|
||||
Images []Image
|
||||
}
|
||||
|
||||
// PublishResult 是平台返回的商品结果,经过端口转换后不暴露平台 DTO。
|
||||
type PublishResult struct {
|
||||
// ItemID 是平台商品标识。
|
||||
ItemID string
|
||||
// ItemURL 是平台商品详情地址。
|
||||
ItemURL string
|
||||
// Title 是平台最终确认的商品标题。
|
||||
Title string
|
||||
// PriceText 是平台格式化后的商品价格。
|
||||
PriceText string
|
||||
// CategoryID 是平台商品类目标识。
|
||||
CategoryID string
|
||||
// CategoryName 是平台商品类目名称。
|
||||
CategoryName string
|
||||
// ImageURL 是平台主图地址。
|
||||
ImageURL string
|
||||
// Quantity 是平台确认的库存数量。
|
||||
Quantity int
|
||||
// RawData 是平台原始结果的结构化副本,仅供本地详情持久化。
|
||||
RawData map[string]any
|
||||
}
|
||||
|
||||
// PublishOutcome 是发布端口结果及响应 Cookie 持久化风险。
|
||||
type PublishOutcome struct {
|
||||
// Result 是平台返回的商品结果;平台未返回结果时为空。
|
||||
Result *PublishResult
|
||||
// ResponseCookieErr 是平台响应 Cookie 未能持久化时的错误。
|
||||
ResponseCookieErr error
|
||||
// LocalSaveErr 是本地商品落库失败时的错误,由应用服务补充。
|
||||
LocalSaveErr error
|
||||
}
|
||||
|
||||
// PublishPort 是商品发布基础设施端口;实现方负责平台会话和凭证更新。
|
||||
type PublishPort interface {
|
||||
// Publish 调用外部平台并返回已脱离平台 DTO 的结果。
|
||||
Publish(context.Context, PublishInput) (PublishOutcome, error)
|
||||
}
|
||||
|
||||
// ItemRecord 是商品发布成功后写入本地商品表的最小模型。
|
||||
type ItemRecord struct {
|
||||
// CookieID 是发布所用账号标识。
|
||||
CookieID string
|
||||
// ItemID 是平台商品标识。
|
||||
ItemID string
|
||||
// ItemTitle 是商品标题。
|
||||
ItemTitle string
|
||||
// ItemDescription 是商品描述。
|
||||
ItemDescription string
|
||||
// ItemCategory 是平台类目标识。
|
||||
ItemCategory string
|
||||
// ItemPrice 是平台格式化后的价格文本。
|
||||
ItemPrice string
|
||||
// ItemDetail 是供后续详情页使用的 JSON 字符串。
|
||||
ItemDetail string
|
||||
// MultiQuantityDelivery 表示该商品是否启用多库存交付。
|
||||
MultiQuantityDelivery bool
|
||||
}
|
||||
|
||||
// ItemRepository 是商品本地持久化端口。
|
||||
type ItemRepository interface {
|
||||
// Upsert 保存或更新已在平台发布成功的商品。
|
||||
Upsert(context.Context, ItemRecord) error
|
||||
}
|
||||
|
||||
// Service 是单商品发布应用服务,负责平台结果与本地商品状态的编排。
|
||||
type Service struct {
|
||||
// publisher 执行平台发布及响应凭证持久化。
|
||||
publisher PublishPort
|
||||
// repository 保存平台成功后的本地商品记录。
|
||||
repository ItemRepository
|
||||
}
|
||||
|
||||
// NewService 创建单商品发布应用服务,并校验必需端口。
|
||||
func NewService(publisher PublishPort, repository ItemRepository) (*Service, error) {
|
||||
if publisher == nil {
|
||||
return nil, errors.New("商品发布端口不能为空")
|
||||
}
|
||||
if repository == nil {
|
||||
return nil, errors.New("商品仓储端口不能为空")
|
||||
}
|
||||
return &Service{publisher: publisher, repository: repository}, nil
|
||||
}
|
||||
|
||||
// PublishSingle 执行发布用例;平台成功但本地保存失败时保留远端结果供 HTTP 层提示补偿。
|
||||
func (svc *Service) PublishSingle(ctx context.Context, input PublishInput) (PublishOutcome, error) {
|
||||
// outcome 保存平台端口返回的远端结果;err 保存平台调用或凭证持久化错误。
|
||||
outcome, err := svc.publisher.Publish(ctx, input)
|
||||
if err != nil || outcome.Result == nil || strings.TrimSpace(outcome.Result.ItemID) == "" {
|
||||
return outcome, err
|
||||
}
|
||||
// detail 是供商品详情页使用的本地扩展信息;其中 RawData 仅进入受控数据库字段。
|
||||
detail := map[string]any{
|
||||
"item_image": outcome.Result.ImageURL,
|
||||
"web_url": outcome.Result.ItemURL,
|
||||
"category_name": outcome.Result.CategoryName,
|
||||
"quantity": outcome.Result.Quantity,
|
||||
"publish_raw": outcome.Result.RawData,
|
||||
}
|
||||
// detailJSON 是商品扩展信息的 JSON 表示;序列化失败不应阻断远端结果回传。
|
||||
detailJSON, _ := json.Marshal(detail)
|
||||
// localErr 是平台成功后本地商品落库错误,交由调用方呈现补偿提示。
|
||||
localErr := svc.repository.Upsert(ctx, ItemRecord{
|
||||
CookieID: input.CookieID, ItemID: outcome.Result.ItemID, ItemTitle: outcome.Result.Title,
|
||||
ItemDescription: input.Description, ItemCategory: outcome.Result.CategoryID,
|
||||
ItemPrice: outcome.Result.PriceText, ItemDetail: string(detailJSON),
|
||||
MultiQuantityDelivery: input.Quantity > 1,
|
||||
})
|
||||
outcome.LocalSaveErr = localErr
|
||||
return outcome, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package items
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakePublisher 是可控的平台端口替身,用于验证应用服务不会泄露平台 DTO。
|
||||
type fakePublisher struct {
|
||||
// outcome 保存桩平台返回的业务结果。
|
||||
outcome PublishOutcome
|
||||
// err 保存桩平台返回的调用错误。
|
||||
err error
|
||||
}
|
||||
|
||||
// Publish 返回预设的平台结果或错误。
|
||||
func (p fakePublisher) Publish(_ context.Context, _ PublishInput) (PublishOutcome, error) {
|
||||
return p.outcome, p.err
|
||||
}
|
||||
|
||||
// fakeItemRepository 是记录最后一次商品写入的本地仓储替身。
|
||||
type fakeItemRepository struct {
|
||||
// record 保存最后一次收到的商品记录。
|
||||
record ItemRecord
|
||||
// err 保存桩仓储返回的写入错误。
|
||||
err error
|
||||
}
|
||||
|
||||
// Upsert 保存记录并返回预设错误。
|
||||
func (r *fakeItemRepository) Upsert(_ context.Context, record ItemRecord) error {
|
||||
r.record = record
|
||||
return r.err
|
||||
}
|
||||
|
||||
// TestServicePublishSinglePersistsRemoteResult 验证平台成功后应用层写入本地商品。
|
||||
func TestServicePublishSinglePersistsRemoteResult(t *testing.T) {
|
||||
// repository 是记录写入内容的本地仓储桩。
|
||||
repository := &fakeItemRepository{}
|
||||
// service 是使用平台和仓储替身构造的应用服务。
|
||||
service, err := NewService(fakePublisher{outcome: PublishOutcome{Result: &PublishResult{
|
||||
ItemID: "item-1", ItemURL: "https://example.invalid/item-1", Title: "标题",
|
||||
PriceText: "12.00", CategoryID: "cat-1", CategoryName: "资料", ImageURL: "image",
|
||||
Quantity: 2, RawData: map[string]any{"trace": "opaque"},
|
||||
}}}, repository)
|
||||
if err != nil {
|
||||
t.Fatalf("NewService error: %v", err)
|
||||
}
|
||||
// outcome 是应用服务返回的远端结果及本地状态。
|
||||
outcome, err := service.PublishSingle(context.Background(), PublishInput{CookieID: "acc-1", Description: "描述", Quantity: 2})
|
||||
if err != nil || outcome.Result == nil || outcome.Result.ItemID != "item-1" {
|
||||
t.Fatalf("unexpected outcome: %+v, err=%v", outcome, err)
|
||||
}
|
||||
if repository.record.ItemID != "item-1" || !repository.record.MultiQuantityDelivery {
|
||||
t.Fatalf("unexpected local record: %+v", repository.record)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServicePublishSingleKeepsRemoteError 验证平台失败时不写入本地商品。
|
||||
func TestServicePublishSingleKeepsRemoteError(t *testing.T) {
|
||||
// repository 是记录是否被调用的本地仓储桩。
|
||||
repository := &fakeItemRepository{}
|
||||
// remoteErr 是平台调用失败的代表性错误。
|
||||
remoteErr := errors.New("platform unavailable")
|
||||
// service 是配置平台错误桩的应用服务。
|
||||
service, err := NewService(fakePublisher{err: remoteErr}, repository)
|
||||
if err != nil {
|
||||
t.Fatalf("NewService error: %v", err)
|
||||
}
|
||||
// outcome 是平台失败后应用服务保留的空结果。
|
||||
outcome, callErr := service.PublishSingle(context.Background(), PublishInput{})
|
||||
if !errors.Is(callErr, remoteErr) || outcome.Result != nil || repository.record.ItemID != "" {
|
||||
t.Fatalf("unexpected failure outcome: %+v, err=%v, record=%+v", outcome, callErr, repository.record)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewServiceRejectsMissingPort 验证必需应用端口不能在运行时缺失。
|
||||
func TestNewServiceRejectsMissingPort(t *testing.T) {
|
||||
// repository 是满足仓储端口的最小替身。
|
||||
repository := &fakeItemRepository{}
|
||||
// err 保存缺少发布端口时的构造错误。
|
||||
if _, err := NewService(nil, repository); err == nil {
|
||||
t.Fatal("缺少发布端口时应返回错误")
|
||||
}
|
||||
// err 保存缺少仓储端口时的构造错误。
|
||||
if _, err := NewService(fakePublisher{}, nil); err == nil {
|
||||
t.Fatal("缺少仓储端口时应返回错误")
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func (e *automationActionExecutor) confirmShipment(ctx context.Context, task Tas
|
||||
return e.confirmShipmentAttempt(ctx, task, true)
|
||||
}
|
||||
|
||||
// confirmShipmentAttempt 在凭证锁内调用 Consign,并处理 Cookie 合并、凭证恢复和本地状态收口。
|
||||
// confirmShipmentAttempt 在凭证锁内调用 Consign,处理 Cookie 合并、凭证恢复和本地状态收口;远端成功但订单事实落库失败时创建可重试补偿记录。
|
||||
func (e *automationActionExecutor) confirmShipmentAttempt(ctx context.Context, task Task, allowCredentialRecovery bool) error {
|
||||
// credentialUnlock 是账号凭证锁的释放函数。
|
||||
credentialUnlock := e.store.LockAccountCredentials(task.AccountID)
|
||||
@@ -127,6 +127,8 @@ func (e *automationActionExecutor) confirmShipmentAttempt(ctx context.Context, t
|
||||
consignOK, ret, updated, callErr := e.mtop().ConsignContext(mtopCtx, cookieStr, task.OrderID)
|
||||
// persistenceErrs 收集远端动作完成后本地状态写入失败。
|
||||
var persistenceErrs []error
|
||||
// shipmentStateNeedsReconciliation 标记订单发货事实是否需要异步补偿。
|
||||
shipmentStateNeedsReconciliation := false
|
||||
// runtimeCookie 保存需要同步到在线发送器的最新 Cookie。
|
||||
runtimeCookie := ""
|
||||
// runtimeCookieChanged 表示在线运行时是否需要替换 Cookie。
|
||||
@@ -222,12 +224,34 @@ func (e *automationActionExecutor) confirmShipmentAttempt(ctx context.Context, t
|
||||
SystemShipped: &sysShip,
|
||||
}); upsertErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存本地订单发货状态: %w", upsertErr))
|
||||
shipmentStateNeedsReconciliation = true
|
||||
}
|
||||
// eventErr 保存订单发货事实写入错误。
|
||||
if eventErr := e.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "shipped_at"); eventErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存订单发货时间: %w", eventErr))
|
||||
shipmentStateNeedsReconciliation = true
|
||||
}
|
||||
if len(persistenceErrs) > 0 {
|
||||
if shipmentStateNeedsReconciliation {
|
||||
if e.store == nil || e.store.Reconciliations == nil {
|
||||
persistenceErrs = append(persistenceErrs, errors.New("创建订单发货补偿记录: 补偿存储未初始化"))
|
||||
} else {
|
||||
// reconciliationID 保存本地订单状态补偿记录的幂等追踪标识;当前运行由 triggerKey 保证同一事件不会重复执行。
|
||||
// reconciliationErr 保存补偿记录写入失败原因。
|
||||
reconciliationID, reconciliationErr := e.store.Reconciliations.CreatePending(
|
||||
ctx,
|
||||
task.OrderID,
|
||||
task.AccountID,
|
||||
"manual_status_ship",
|
||||
"闲鱼已确认发货,但本地订单状态写入失败: "+errors.Join(persistenceErrs...).Error(),
|
||||
)
|
||||
if reconciliationErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("创建订单发货补偿记录: %w", reconciliationErr))
|
||||
} else {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("订单发货补偿记录 %s 已创建", reconciliationID))
|
||||
}
|
||||
}
|
||||
}
|
||||
return uncertainAction(fmt.Errorf("闲鱼已确认发货,但本地状态保存失败: %w", errors.Join(persistenceErrs...)))
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/reconciliation"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
@@ -324,6 +325,35 @@ func TestConfirmShipmentQuarantinesKnownRemoteSuccessWhenLocalPersistenceFails(t
|
||||
if order.SystemShipped {
|
||||
t.Fatal("failed local write must not be reported as persisted")
|
||||
}
|
||||
// pendingReconciliations 保存远端成功后创建的本地订单补偿记录。
|
||||
pendingReconciliations, listErr := store.Reconciliations.ListPending(ctx, 10)
|
||||
if listErr != nil {
|
||||
t.Fatal(listErr)
|
||||
}
|
||||
if len(pendingReconciliations) != 1 || pendingReconciliations[0].OrderID != "persist-failure" || pendingReconciliations[0].Kind != "manual_status_ship" {
|
||||
t.Fatalf("远端发货成功后必须创建订单补偿记录: %+v", pendingReconciliations)
|
||||
}
|
||||
// err 表示移除一次性故障触发器时产生的数据库错误。
|
||||
if _, err := store.DB.ExecContext(ctx, `DROP TRIGGER reject_shipped_state`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// err 表示补偿 worker 首次重试时返回的扫描级错误。
|
||||
if err := reconciliation.New(store, nil).RunOnce(ctx); err != nil {
|
||||
t.Fatalf("RunOnce: %v", err)
|
||||
}
|
||||
// reconciledOrder、getErr 保存补偿后的订单状态及查询错误。
|
||||
reconciledOrder, getErr := store.Orders.Get(ctx, "persist-failure")
|
||||
if getErr != nil || reconciledOrder == nil || !reconciledOrder.SystemShipped || reconciledOrder.OrderStatus != "shipped" {
|
||||
t.Fatalf("补偿 worker 未修复订单状态: order=%+v err=%v", reconciledOrder, getErr)
|
||||
}
|
||||
// remainingReconciliations 保存补偿完成后仍待处理的记录。
|
||||
remainingReconciliations, listErr := store.Reconciliations.ListPending(ctx, 10)
|
||||
if listErr != nil {
|
||||
t.Fatal(listErr)
|
||||
}
|
||||
if len(remainingReconciliations) != 0 {
|
||||
t.Fatalf("补偿完成后不应残留 pending 记录: %+v", remainingReconciliations)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfirmShipmentKeepsAuthoritativeSnapshotWhenSessionUnchanged 负责TestConfirmShipmentKeepsAuthoritativeSnapshotWhen会话Unchanged相关处理。
|
||||
|
||||
@@ -56,6 +56,7 @@ type PasswordRefresher interface {
|
||||
|
||||
// Scheduler 保存Scheduler,供当前处理流程使用
|
||||
type Scheduler struct {
|
||||
mu sync.Mutex
|
||||
store *db.Store
|
||||
starter AccountStarter
|
||||
refresher PasswordRefresher
|
||||
@@ -68,6 +69,8 @@ type Scheduler struct {
|
||||
done chan struct{}
|
||||
workers sync.WaitGroup
|
||||
watchers sync.WaitGroup
|
||||
// runCancel 取消当前调度器派生的运行上下文;只有 Run 成功登记后才非空。
|
||||
runCancel context.CancelFunc
|
||||
}
|
||||
|
||||
// RenewalNotifier 保存RenewalNotifier,供当前处理流程使用
|
||||
@@ -103,13 +106,22 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
if s == nil || s.store == nil {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
s.runOnce.Do(func() {
|
||||
// runCtx、cancel 将父生命周期转换为调度器私有的可主动停止上下文。
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
s.mu.Lock()
|
||||
s.runCancel = cancel
|
||||
s.mu.Unlock()
|
||||
go func() {
|
||||
defer close(s.done)
|
||||
defer cancel()
|
||||
s.workers.Add(2)
|
||||
go func() {
|
||||
defer s.workers.Done()
|
||||
s.runFixed(ctx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
|
||||
s.runFixed(runCtx, "login_renew", loginRenewEnabledSetting, loginRenewIntervalSetting, false, loginRenewInterval, s.executeLoginRenew)
|
||||
}()
|
||||
// 官网静默插件在账号启动时执行,并由此任务按保守频率持续检查;闲鱼
|
||||
// 下发的 sdkSilent 疲劳窗口仍会在请求前阻止重复续期。
|
||||
@@ -117,7 +129,7 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
// goroutine,否则同时开启时会重复续期并连续重启同一账号。
|
||||
go func() {
|
||||
defer s.workers.Done()
|
||||
s.runAPICookieRenewFixed(ctx)
|
||||
s.runAPICookieRenewFixed(runCtx)
|
||||
}()
|
||||
s.workers.Wait()
|
||||
s.watchers.Wait()
|
||||
@@ -125,6 +137,30 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// StopContext 主动取消续期调度器并在 ctx 允许的时间内等待所有任务和迟到响应 watcher 收束。
|
||||
// 调用可重复执行;已经停止或尚未启动的调度器视为成功完成。
|
||||
func (s *Scheduler) StopContext(ctx context.Context) error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
s.mu.Lock()
|
||||
// cancel 是调度器运行上下文的取消函数快照,避免持锁执行取消回调。
|
||||
cancel := s.runCancel
|
||||
s.mu.Unlock()
|
||||
if cancel != nil {
|
||||
cancel()
|
||||
}
|
||||
return s.WaitContext(ctx)
|
||||
}
|
||||
|
||||
// Stop 主动停止调度器并无限期等待,兼容旧调用方的无错误返回签名。
|
||||
func (s *Scheduler) Stop() {
|
||||
_ = s.StopContext(context.Background())
|
||||
}
|
||||
|
||||
// Wait 等待定时循环和迟到响应 watcher 完成。
|
||||
func (s *Scheduler) Wait() {
|
||||
_ = s.WaitContext(context.Background())
|
||||
|
||||
@@ -349,6 +349,30 @@ func TestRenewalSchedulerWaitContextHonorsDeadline(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenewalSchedulerStopContextCancelsRun 验证主动停止会取消调度器私有上下文并等待 worker 退出。
|
||||
func TestRenewalSchedulerStopContextCancelsRun(t *testing.T) {
|
||||
// store、cleanup 保存调度器所需的本地测试数据库及其清理函数。
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
// scheduler 保存待验证主动停止语义的续期调度器。
|
||||
scheduler := NewScheduler(store, nil, nil, nil)
|
||||
scheduler.Run(context.Background())
|
||||
// stopCtx、cancel 限制停止等待时间,防止回归测试在 worker 异常时永久阻塞。
|
||||
stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
// err 表示首次主动停止调度器时的收束结果。
|
||||
if err := scheduler.StopContext(stopCtx); err != nil {
|
||||
t.Fatalf("StopContext error=%v", err)
|
||||
}
|
||||
// repeatCtx、repeatCancel 验证重复停止保持幂等且不会重新启动 worker。
|
||||
repeatCtx, repeatCancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer repeatCancel()
|
||||
// err 表示重复主动停止调度器时的幂等收束结果。
|
||||
if err := scheduler.StopContext(repeatCtx); err != nil {
|
||||
t.Fatalf("重复 StopContext error=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPendingAPIRenewRestartFailureIsFinalFailure 负责TestPendingAPIRenewRestartFailureIsFinalFailure相关处理。
|
||||
func TestPendingAPIRenewRestartFailureIsFinalFailure(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import orderapp "xianyu-go/internal/application/orders"
|
||||
import itemapp "xianyu-go/internal/application/items"
|
||||
|
||||
// applicationServices 聚合 Server 使用的应用服务实例,统一管理共享基础设施依赖。
|
||||
type applicationServices struct {
|
||||
@@ -8,6 +9,8 @@ type applicationServices struct {
|
||||
orders *orderHTTPAdapter
|
||||
// itemPublish 是商品发布应用服务。
|
||||
itemPublish *itemPublishService
|
||||
// itemSinglePublish 是仅负责单商品发布用例的纯应用服务。
|
||||
itemSinglePublish *itemapp.Service
|
||||
// accountLogin 是账号登录应用服务。
|
||||
accountLogin *accountLoginService
|
||||
// communication 是聊天、通知和账号任务应用服务。
|
||||
@@ -25,11 +28,12 @@ func newApplicationServices(server *Server) *applicationServices {
|
||||
// orderServices 保存应用层统一构造的订单业务服务集合。
|
||||
orderServices := orderapp.NewServiceSet(orderRepository, orderRepository, orderRuntime, orderRuntime, newStoreOrderRefreshJobRepository(server.Store), refreshOrderChunkSize)
|
||||
return &applicationServices{
|
||||
orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository},
|
||||
itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)},
|
||||
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store)},
|
||||
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
|
||||
analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)},
|
||||
orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository},
|
||||
itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)},
|
||||
itemSinglePublish: newItemPublishApplication(server),
|
||||
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store)},
|
||||
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
|
||||
analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ func TestNewServerAssemblesApplicationServices(t *testing.T) {
|
||||
}
|
||||
// services 是统一应用服务集合。
|
||||
services := srv.applicationServiceSet()
|
||||
if services.orders == nil || services.itemPublish == nil || services.accountLogin == nil || services.communication == nil || services.analytics == nil {
|
||||
if services.orders == nil || services.itemPublish == nil || services.itemSinglePublish == nil || services.accountLogin == nil || services.communication == nil || services.analytics == nil {
|
||||
t.Fatal("应用服务集合存在未装配的服务")
|
||||
}
|
||||
if services.orders.services == nil || services.orders.services.List == nil || services.orders.services.Detail == nil || services.orders.services.Refresh == nil || services.orders.services.RefreshJobs == nil {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
itemapp "xianyu-go/internal/application/items"
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
@@ -115,10 +116,26 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
selectedLocation = &location
|
||||
}
|
||||
// outcome、callErr 保存outcome、callErr,供当前处理流程使用
|
||||
outcome, callErr := s.itemPublishApplication().PublishSingle(r.Context(), itemPublishInput{
|
||||
// applicationLocation 是 HTTP DTO 转换后的应用发货地模型。
|
||||
var applicationLocation *itemapp.Location
|
||||
if selectedLocation != nil {
|
||||
applicationLocation = &itemapp.Location{
|
||||
Area: selectedLocation.Area, City: selectedLocation.City, DivisionID: selectedLocation.DivisionID,
|
||||
Longitude: selectedLocation.Longitude, Latitude: selectedLocation.Latitude, POIID: selectedLocation.POIID,
|
||||
POIName: selectedLocation.POIName, Province: selectedLocation.Province,
|
||||
}
|
||||
}
|
||||
// applicationImages 是 HTTP 上传图片转换后的应用图片模型。
|
||||
applicationImages := make([]itemapp.Image, 0, len(images))
|
||||
// image 表示当前待转换的 HTTP 上传图片。
|
||||
for _, image := range images {
|
||||
applicationImages = append(applicationImages, itemapp.Image{Filename: image.Filename, ContentType: image.ContentType, Data: image.Data})
|
||||
}
|
||||
// outcome、callErr 保存应用服务返回的发布结果及调用错误。
|
||||
outcome, callErr := s.itemSinglePublishApplication().PublishSingle(r.Context(), itemapp.PublishInput{
|
||||
UserID: userID, CookieID: cookieID, Title: title, Description: description,
|
||||
PriceCents: priceCents, OriginalPriceCents: origCents, Quantity: quantity,
|
||||
PostageMode: postageMode, PostageCents: postageCents, Location: selectedLocation, Images: images,
|
||||
PostageMode: postageMode, PostageCents: postageCents, Location: applicationLocation, Images: applicationImages,
|
||||
})
|
||||
// res 保存响应,供当前处理流程使用
|
||||
res := outcome.Result
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
itemapp "xianyu-go/internal/application/items"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
@@ -23,42 +24,6 @@ var (
|
||||
errItemPublishBatchNoRows = errors.New("商品批量任务没有可处理的明细行")
|
||||
)
|
||||
|
||||
// itemPublishInput 是单个商品发布用例的业务输入,不包含 HTTP 请求对象。
|
||||
type itemPublishInput struct {
|
||||
// UserID 是发起发布操作的用户标识。
|
||||
UserID int64
|
||||
// CookieID 是执行商品发布的账号标识。
|
||||
CookieID string
|
||||
// Title 是商品标题。
|
||||
Title string
|
||||
// Description 是商品描述。
|
||||
Description string
|
||||
// PriceCents 是商品售价,单位为分。
|
||||
PriceCents int64
|
||||
// OriginalPriceCents 是商品原价,单位为分。
|
||||
OriginalPriceCents int64
|
||||
// Quantity 是商品库存数量。
|
||||
Quantity int
|
||||
// PostageMode 是邮费模式。
|
||||
PostageMode string
|
||||
// PostageCents 是邮费金额,单位为分。
|
||||
PostageCents int64
|
||||
// Location 是可选的发货地。
|
||||
Location *mtop.PublishLocation
|
||||
// Images 是待上传的商品图片。
|
||||
Images []mtop.PublishImage
|
||||
}
|
||||
|
||||
// itemPublishOutcome 是单个商品发布用例的结果及发布后的持久化风险。
|
||||
type itemPublishOutcome struct {
|
||||
// Result 是平台返回的商品信息。
|
||||
Result *mtop.PublishItemResult
|
||||
// ResponseCookieErr 是平台响应 Cookie 未能持久化时的错误。
|
||||
ResponseCookieErr error
|
||||
// LocalSaveErr 是平台成功后本地商品落库失败时的错误。
|
||||
LocalSaveErr error
|
||||
}
|
||||
|
||||
// itemPublishPreviewInput 是批量发布预检结果持久化所需的业务输入。
|
||||
type itemPublishPreviewInput struct {
|
||||
// UserID 是创建批次的用户标识。
|
||||
@@ -90,84 +55,16 @@ func (s *Server) itemPublishApplication() *itemPublishService {
|
||||
return s.applicationServiceSet().itemPublish
|
||||
}
|
||||
|
||||
// itemSinglePublishApplication 返回只负责单商品发布用例的应用服务。
|
||||
func (s *Server) itemSinglePublishApplication() *itemapp.Service {
|
||||
return s.applicationServiceSet().itemSinglePublish
|
||||
}
|
||||
|
||||
// itemPublishRepositoryForServer 返回当前 Server 装配的发布持久化边界。
|
||||
func (s *Server) itemPublishRepositoryForServer() itemPublishRepository {
|
||||
return s.itemPublishApplication().repository
|
||||
}
|
||||
|
||||
// PublishSingle 执行单商品发布、响应 Cookie 持久化和本地商品落库。
|
||||
func (svc *itemPublishService) PublishSingle(ctx context.Context, input itemPublishInput) (itemPublishOutcome, error) {
|
||||
// s 是当前商品发布应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// unlock 释放当前账号的凭证串行化锁。
|
||||
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) {
|
||||
unlock()
|
||||
return itemPublishOutcome{}, errors.New("账号凭证已变化,请重试")
|
||||
}
|
||||
// cookieValue 是本次 MTOP 调用使用的账号凭证。
|
||||
cookieValue := latest.Value
|
||||
// requestCtx 和 cancel 控制单商品发布的最长执行时间。
|
||||
requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
defer cancel()
|
||||
// client 是平台发布客户端。
|
||||
client := s.mtopClient()
|
||||
// mtopCtx 和 cookieSession 保存带 Cookie 快照的平台调用上下文。
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(requestCtx, latest)
|
||||
// result 和 callErr 是平台发布结果及调用错误。
|
||||
result, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
|
||||
Title: input.Title, Description: input.Description, PriceCents: input.PriceCents,
|
||||
OriginalPriceCents: input.OriginalPriceCents, Quantity: input.Quantity,
|
||||
PostageMode: input.PostageMode, PostageCents: input.PostageCents, Virtual: true,
|
||||
Location: input.Location, Images: input.Images,
|
||||
})
|
||||
// runtimeCookie 是需要同步到运行时账号的刷新凭证。
|
||||
runtimeCookie := ""
|
||||
// value、valueChanged、handled 和 persistErr 描述 Cookie Jar 持久化结果。
|
||||
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
if persistErr != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", input.CookieID, "err", persistErr)
|
||||
}
|
||||
} else if handled && valueChanged {
|
||||
runtimeCookie = value
|
||||
} else if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != cookieValue {
|
||||
// saveErr 表示保存平台返回新 Cookie 的错误。
|
||||
if saveErr := svc.repository.UpdateCookieValueOwned(ctx, input.CookieID, result.UpdatedCookies, input.UserID); saveErr != nil {
|
||||
persistErr = saveErr
|
||||
} else {
|
||||
runtimeCookie = result.UpdatedCookies
|
||||
}
|
||||
}
|
||||
unlock()
|
||||
if runtimeCookie != "" {
|
||||
s.updateRunningCookie(ctx, input.CookieID, runtimeCookie)
|
||||
}
|
||||
if callErr != nil {
|
||||
if persistErr != nil {
|
||||
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr))
|
||||
}
|
||||
s.recoverExpiredMTOPSession(ctx, input.CookieID, callErr)
|
||||
return itemPublishOutcome{ResponseCookieErr: persistErr}, callErr
|
||||
}
|
||||
if result == nil || strings.TrimSpace(result.ItemID) == "" {
|
||||
return itemPublishOutcome{Result: result, ResponseCookieErr: persistErr}, nil
|
||||
}
|
||||
// detail 保存平台商品附加信息。
|
||||
detail := map[string]any{"item_image": result.ImageURL, "web_url": result.ItemURL, "category_name": result.CategoryName, "quantity": result.Quantity, "publish_raw": result.RawData}
|
||||
// detailJSON 是本地商品详情 JSON。
|
||||
detailJSON, _ := json.Marshal(detail)
|
||||
// localErr 表示平台发布成功后本地商品落库的错误。
|
||||
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,
|
||||
})
|
||||
return itemPublishOutcome{Result: result, ResponseCookieErr: persistErr, LocalSaveErr: localErr}, nil
|
||||
}
|
||||
|
||||
// RecommendCategory 调用平台类目推荐并持久化刷新后的账号登录状态。
|
||||
func (svc *itemPublishService) RecommendCategory(ctx context.Context, userID int64, cookieID, keyword string) (mtop.PublishCategory, error) {
|
||||
// s 是当前商品发布应用服务依赖的 Server。
|
||||
@@ -418,3 +315,117 @@ func (svc *itemPublishService) RetryFailedBatch(ctx context.Context, userID int6
|
||||
s.startPublishBatchWorker(s.lifecycleContext(), userID, batchID, token)
|
||||
return batchID, nil
|
||||
}
|
||||
|
||||
// serverItemPublishPort 将 MTOP、Cookie 会话与运行时同步适配为应用商品发布端口。
|
||||
type serverItemPublishPort struct {
|
||||
// server 保存平台调用和账号凭证适配所需的 Server 依赖。
|
||||
server *Server
|
||||
// repository 提供账号锁、平台凭证查询和 Cookie 写回能力。
|
||||
repository itemPublishRepository
|
||||
}
|
||||
|
||||
// Publish 执行单商品平台发布及响应 Cookie 持久化,不向应用层泄露 MTOP 类型。
|
||||
func (p serverItemPublishPort) Publish(ctx context.Context, input itemapp.PublishInput) (itemapp.PublishOutcome, error) {
|
||||
// unlock 释放当前账号的凭证串行化锁;锁覆盖现有平台会话不变量。
|
||||
unlock := p.repository.LockCredentials(input.CookieID)
|
||||
// latest 保存加锁后读取的平台运行凭证视图。
|
||||
latest, err := p.server.loadCookiePlatformDetail(ctx, input.CookieID)
|
||||
if err != nil || latest == nil || latest.UserID != input.UserID || !hasStoredCookieCredential(latest) {
|
||||
unlock()
|
||||
return itemapp.PublishOutcome{}, errors.New("账号凭证已变化,请重试")
|
||||
}
|
||||
// requestCtx 和 cancel 控制单商品平台发布的最长执行时间。
|
||||
requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
|
||||
defer cancel()
|
||||
// images 保存应用图片 DTO 转换后的平台图片请求。
|
||||
images := make([]mtop.PublishImage, 0, len(input.Images))
|
||||
// image 表示当前待转换的应用图片。
|
||||
for _, image := range input.Images {
|
||||
images = append(images, mtop.PublishImage{Filename: image.Filename, ContentType: image.ContentType, Data: image.Data})
|
||||
}
|
||||
// location 保存应用发货地 DTO 转换后的平台位置请求。
|
||||
var location *mtop.PublishLocation
|
||||
if input.Location != nil {
|
||||
location = &mtop.PublishLocation{
|
||||
Area: input.Location.Area, City: input.Location.City, DivisionID: input.Location.DivisionID,
|
||||
Longitude: input.Location.Longitude, Latitude: input.Location.Latitude, POIID: input.Location.POIID,
|
||||
POIName: input.Location.POIName, Province: input.Location.Province,
|
||||
}
|
||||
}
|
||||
// mtopCtx 和 cookieSession 保存带 Cookie 快照的平台调用上下文。
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(requestCtx, latest)
|
||||
// result 和 callErr 保存平台发布结果及调用错误。
|
||||
result, callErr := p.server.mtopClient().PublishItem(mtopCtx, latest.Value, mtop.PublishItemRequest{
|
||||
Title: input.Title, Description: input.Description, PriceCents: input.PriceCents,
|
||||
OriginalPriceCents: input.OriginalPriceCents, Quantity: input.Quantity,
|
||||
PostageMode: input.PostageMode, PostageCents: input.PostageCents, Virtual: true,
|
||||
Location: location, Images: images,
|
||||
})
|
||||
// runtimeCookie 保存需要在释放凭证锁后同步到运行时的刷新 Cookie。
|
||||
runtimeCookie := ""
|
||||
// value、valueChanged、handled 和 persistErr 描述 Cookie Jar 持久化结果。
|
||||
value, valueChanged, handled, persistErr := p.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
if persistErr != nil {
|
||||
if p.server.Logger != nil {
|
||||
p.server.Logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", input.CookieID, "err", persistErr)
|
||||
}
|
||||
} else if handled && valueChanged {
|
||||
runtimeCookie = value
|
||||
} else if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != latest.Value {
|
||||
// saveErr 表示保存平台返回新 Cookie 的错误。
|
||||
if saveErr := p.repository.UpdateCookieValueOwned(ctx, input.CookieID, result.UpdatedCookies, input.UserID); saveErr != nil {
|
||||
persistErr = saveErr
|
||||
} else {
|
||||
runtimeCookie = result.UpdatedCookies
|
||||
}
|
||||
}
|
||||
unlock()
|
||||
if runtimeCookie != "" {
|
||||
p.server.updateRunningCookie(ctx, input.CookieID, runtimeCookie)
|
||||
}
|
||||
if callErr != nil {
|
||||
if persistErr != nil {
|
||||
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr))
|
||||
}
|
||||
p.server.recoverExpiredMTOPSession(ctx, input.CookieID, callErr)
|
||||
return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, callErr
|
||||
}
|
||||
if result == nil || strings.TrimSpace(result.ItemID) == "" {
|
||||
return itemapp.PublishOutcome{ResponseCookieErr: persistErr}, nil
|
||||
}
|
||||
return itemapp.PublishOutcome{Result: &itemapp.PublishResult{
|
||||
ItemID: result.ItemID, ItemURL: result.ItemURL, Title: result.Title, PriceText: result.PriceText,
|
||||
CategoryID: result.CategoryID, CategoryName: result.CategoryName, ImageURL: result.ImageURL,
|
||||
Quantity: result.Quantity, RawData: result.RawData,
|
||||
}, ResponseCookieErr: persistErr}, nil
|
||||
}
|
||||
|
||||
// storeItemPublishItemRepository 将商品数据库写入适配为应用层商品仓储端口。
|
||||
type storeItemPublishItemRepository struct {
|
||||
// store 保存数据库聚合入口,仅在 Server 适配器内部使用。
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
// Upsert 保存应用层商品记录,并在边界转换为数据库行模型。
|
||||
func (r storeItemPublishItemRepository) Upsert(ctx context.Context, record itemapp.ItemRecord) error {
|
||||
return r.store.Items.Upsert(ctx, &db.ItemInfoRow{
|
||||
CookieID: record.CookieID, ItemID: record.ItemID, ItemTitle: record.ItemTitle,
|
||||
ItemDescription: record.ItemDescription, ItemCategory: record.ItemCategory,
|
||||
ItemPrice: record.ItemPrice, ItemDetail: record.ItemDetail,
|
||||
MultiQuantityDelivery: record.MultiQuantityDelivery,
|
||||
})
|
||||
}
|
||||
|
||||
// newItemPublishApplication 创建单商品发布应用服务并绑定 Server 适配器。
|
||||
func newItemPublishApplication(server *Server) *itemapp.Service {
|
||||
// publisher 是商品发布平台端口适配器。
|
||||
publisher := serverItemPublishPort{server: server, repository: newStoreItemPublishRepository(server.Store)}
|
||||
// repository 是商品本地持久化端口适配器。
|
||||
repository := storeItemPublishItemRepository{store: server.Store}
|
||||
// service 和 err 保存应用服务构造结果。
|
||||
service, err := itemapp.NewService(publisher, repository)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("商品发布应用服务装配失败: %v", err))
|
||||
}
|
||||
return service
|
||||
}
|
||||
Reference in new issue
Block a user