refactor(server): 重构服务层代码结构 feat(server): 添加基础设施、跨境电商、AI决策等核心服务 docs: 完善前端业务说明书和开发进度文档 style: 格式化代码和文档
10 KiB
10 KiB
服务设计文档 (Crawlful Hub)
定位:Crawlful Hub 后端服务设计文档 - 定义服务层架构、服务职责和实现规范。 更新日期: 2026-03-18 最高优先级参考: Business_ClosedLoops.md
1. 服务层架构
1.1 核心原则
- 每个业务操作对应一个 Service:前端的每个用户操作都必须有对应的后端 Service 处理
- 服务编排:通过 Service 层串联多个模块,实现业务流程的完整执行
- 单一职责:每个 Service 只负责一个核心业务领域
- 依赖注入:通过依赖注入实现服务间的解耦
- 事务管理:重要操作必须在事务中执行,确保数据一致性
1.2 服务层级结构
Controller → Service (核心编排) → Repository / External API → 数据库/外部系统
2. 核心服务列表
2.1 商品服务 (ProductService)
职责:管理商品全生命周期,包括创建、更新、查询、删除等操作
核心方法:
createProduct(): 创建商品updateProduct(): 更新商品信息updatePrice(): 更新商品价格,同时计算 ROIgetProductById(): 根据 ID 获取商品详情getProducts(): 获取商品列表deleteProduct(): 删除商品publishProduct(): 发布商品到平台unpublishProduct(): 从平台下架商品
依赖:
PricingService: 计算价格和 ROIInventoryService: 管理商品库存MediaService: 管理商品媒体资源
2.2 订单服务 (OrderService)
职责:管理订单全生命周期,包括创建、更新、查询、处理等操作
核心方法:
createOrder(): 创建订单updateOrderStatus(): 更新订单状态getOrderById(): 根据 ID 获取订单详情getOrders(): 获取订单列表processOrder(): 处理订单(包括库存扣减、物流安排等)splitOrder(): 拆分订单mergeOrders(): 合并订单handleExceptionOrder(): 处理异常订单
依赖:
InventoryService: 管理库存LogisticsService: 安排物流SettlementService: 处理结算
2.3 定价服务 (PricingService)
职责:负责商品定价和利润计算
核心方法:
calculatePrice(): 计算商品价格calculateROI(): 计算投资回报率calculateProfit(): 计算利润getPricingStrategy(): 获取定价策略updatePricingStrategy(): 更新定价策略
依赖:
CostService: 计算成本MarketService: 分析市场价格
2.4 库存服务 (InventoryService)
职责:管理库存,包括库存查询、扣减、预警等
核心方法:
getInventory(): 获取库存信息updateInventory(): 更新库存deductInventory(): 扣减库存reserveInventory(): 预留库存releaseInventory(): 释放预留库存getInventoryAlert(): 获取库存预警
依赖:
WarehouseService: 管理仓库
2.5 物流服务 (LogisticsService)
职责:管理物流,包括物流选择、追踪、费用计算等
核心方法:
selectLogisticsChannel(): 选择物流渠道calculateFreight(): 计算运费trackLogistics(): 追踪物流状态createShippingLabel(): 创建 shipping label
依赖:
ThirdPartyLogisticsAPI: 对接第三方物流 API
2.6 结算服务 (SettlementService)
职责:管理结算,包括收入计算、佣金扣除、打款等
核心方法:
calculateSettlement(): 计算结算金额processSettlement(): 处理结算createSettlementBill(): 创建结算账单processPayment(): 处理付款
依赖:
FinanceService: 财务管理PaymentService: 支付处理
2.7 商户服务 (MerchantService)
职责:管理商户,包括商户注册、认证、管理等
核心方法:
registerMerchant(): 注册商户verifyMerchant(): 验证商户资质getMerchantById(): 获取商户详情updateMerchant(): 更新商户信息suspendMerchant(): 暂停商户activateMerchant(): 激活商户
依赖:
VerificationService: 资质验证RBACService: 权限管理
2.8 权限服务 (RBACService)
职责:管理权限,包括角色定义、权限分配等
核心方法:
createRole(): 创建角色assignPermission(): 分配权限checkPermission(): 检查权限getUserRoles(): 获取用户角色
依赖:
UserService: 用户管理
2.9 数据服务 (DataPipelineService)
职责:管理数据采集、清洗、处理等
核心方法:
collectData(): 采集数据cleanData(): 清洗数据processData(): 处理数据analyzeData(): 分析数据
依赖:
PlatformApiService: 对接平台 APICrawlerService: 网页爬虫
2.10 AI 服务 (AIService)
职责:提供 AI 相关功能,如智能定价、智能分析等
核心方法:
predictPrice(): 预测价格analyzeMarket(): 分析市场optimizeStrategy(): 优化策略detectAnomaly(): 检测异常
依赖:
MachineLearningModel: 机器学习模型
3. 服务间调用规范
3.1 同步调用
适用场景:需要立即获取结果的操作
示例:
// ProductService 调用 PricingService
async updatePrice(productId: string, price: number): Promise<Product> {
const product = await this.productRepository.findById(productId);
const roi = await this.pricingService.calculateROI(product, price);
product.price = price;
product.roi = roi;
return await this.productRepository.save(product);
}
3.2 异步调用
适用场景:不需要立即获取结果的操作,如发送通知、数据处理等
示例:
// OrderService 调用 NotificationService
async processOrder(orderId: string): Promise<void> {
const order = await this.orderRepository.findById(orderId);
// 处理订单
await this.orderRepository.save(order);
// 异步发送通知
this.notificationService.sendOrderConfirmation(order).catch(err => {
this.logger.error('Failed to send order confirmation', err);
});
}
4. 事务管理
4.1 事务边界
定义:一组操作要么全部成功,要么全部失败
示例:
@Transactional()
async createOrder(orderData: OrderCreateDto): Promise<Order> {
// 1. 创建订单
const order = await this.orderRepository.create(orderData);
// 2. 扣减库存
await this.inventoryService.deductInventory(
orderData.productId,
orderData.quantity
);
// 3. 记录交易
await this.transactionRepository.create({
orderId: order.id,
amount: order.totalAmount,
type: 'ORDER_CREATED'
});
return order;
}
4.2 幂等性
定义:同一个请求执行多次,结果应该相同
实现:
- 使用唯一的
requestId - 记录已处理的请求
- 检查重复请求
示例:
async processPayment(paymentData: PaymentDto): Promise<Payment> {
// 检查是否已处理
const existingPayment = await this.paymentRepository.findByRequestId(paymentData.requestId);
if (existingPayment) {
return existingPayment;
}
// 处理支付
const payment = await this.paymentRepository.create(paymentData);
return payment;
}
5. 错误处理
5.1 业务错误
定义:业务逻辑错误,如库存不足、权限不足等
处理:
- 抛出业务异常
- 上层捕获并返回适当的错误信息
示例:
async deductInventory(productId: string, quantity: number): Promise<void> {
const inventory = await this.inventoryRepository.findByProductId(productId);
if (inventory.quantity < quantity) {
throw new BusinessException('Insufficient inventory');
}
inventory.quantity -= quantity;
await this.inventoryRepository.save(inventory);
}
5.2 系统错误
定义:系统级错误,如数据库连接失败、API 调用失败等
处理:
- 捕获系统异常
- 记录错误日志
- 尝试重试或降级策略
- 向上层返回适当的错误信息
示例:
async callExternalApi(endpoint: string, data: any): Promise<any> {
try {
const response = await this.httpClient.post(endpoint, data);
return response.data;
} catch (error) {
this.logger.error(`Failed to call external API: ${endpoint}`, error);
throw new SystemException('External API error');
}
}
6. 日志和监控
6.1 业务日志
定义:记录业务操作的日志
内容:
- 操作人
- 操作时间
- 操作类型
- 操作对象
- 操作结果
示例:
async updatePrice(productId: string, price: number): Promise<Product> {
this.logger.info(`Updating price for product ${productId} to ${price}`);
try {
const product = await this.productRepository.findById(productId);
const roi = await this.pricingService.calculateROI(product, price);
product.price = price;
product.roi = roi;
const updatedProduct = await this.productRepository.save(product);
this.logger.info(`Successfully updated price for product ${productId}`, {
oldPrice: product.oldPrice,
newPrice: price,
roi: roi
});
return updatedProduct;
} catch (error) {
this.logger.error(`Failed to update price for product ${productId}`, error);
throw error;
}
}
6.2 性能监控
定义:监控服务性能
指标:
- 响应时间
- 调用次数
- 错误率
- 资源使用情况
实现:
- 使用 Prometheus 等监控工具
- 定期分析性能数据
- 优化性能瓶颈
7. 服务版本管理
7.1 版本控制
定义:管理服务的版本
策略:
- 使用语义化版本号
- 向后兼容
- 版本迁移计划
7.2 API 版本控制
定义:管理 API 的版本
实现:
- 在 URL 中包含版本号
- 支持多个版本并存
- 逐步废弃旧版本
8. 部署和扩展性
8.1 部署策略
定义:服务的部署方式
选项:
- 单体应用
- 微服务
- 容器化部署
8.2 扩展性
定义:服务的扩展能力
实现:
- 水平扩展
- 负载均衡
- 缓存策略
- 异步处理
9. 相关文档
本文档基于业务闭环设计,最后更新: 2026-03-18