mirror of
https://ids-dev.idsbuybuybuy.com/ids-ecommerce/ids-svc-product.git
synced 2026-11-29 16:57:41 +08:00
Merge pull request 'dev2' (#2) from dev2 into main
Reviewed-on: https://llms.idsbuybuybuy.com:3003/ids-ecommerce/ids-svc-product/pulls/2
This commit is contained in:
commit
1573e7393b
20
.env.example
20
.env.example
@ -1,16 +1,18 @@
|
||||
SERVER_PORT=:50051
|
||||
SERVER_PORT=:50052
|
||||
POSTGRES_HOST=localhost
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_USER=postgres
|
||||
POSTGRES_PASSWORD=<db_password>
|
||||
POSTGRES_DB=<db_name>
|
||||
TEMPORAL_HOST_PORT=localhost:7233
|
||||
POSTGRES_PASSWORD=postgres
|
||||
POSTGRES_DB=ids_ecommerce
|
||||
POSTGRES_SCHEMA=product
|
||||
POSTGRES_SSLMODE=disable
|
||||
NATS_URL=nats://localhost:4222
|
||||
|
||||
METRICS_PORT=:9102
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
|
||||
OTEL_EXPORTER_OTLP_INSECURE=true
|
||||
DEPLOYMENT_ENVIRONMENT=development
|
||||
SNOWFLAKE_WORKER_ID=1
|
||||
|
||||
# Optional
|
||||
# POSTGRES_SCHEMA=order_schema
|
||||
# POSTGRES_SSLMODE=disable
|
||||
# POSTGRES_DSN=postgres://... # full DSN override (skips assembly above)
|
||||
# TEMPORAL_NAMESPACE=default
|
||||
# TEMPORAL_TASK_QUEUE=ids-order-task-queue
|
||||
# ORDER_PAYMENT_TIMEOUT_MINS=15
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@ -1,3 +1,4 @@
|
||||
.env
|
||||
/bin/
|
||||
*.exe
|
||||
.DS_Store
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
|
||||
- 本服务 Go Module 名: `llms.idsbuybuybuy.com/ecommerce/ids-svc-product`
|
||||
- 外部依赖契约: `llms.idsbuybuybuy.com/ecommerce/ids-proto`(已通过 `go.mod` 中的本地 `replace` 关联到 `../ids-proto`)
|
||||
- 数据库命名空间: PostgreSQL 的 `product_schema`
|
||||
- 数据库命名空间: PostgreSQL 的 `product`
|
||||
- Proto 契约路径: `ids-proto/proto/ids/product/v1/product.proto`(包名 `ids.product.v1`,Go 包 `productv1`)
|
||||
|
||||
# Task 1: 依赖对齐与本地拦截 (`go.mod`)
|
||||
@ -29,7 +29,7 @@ replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto
|
||||
|
||||
```env
|
||||
SERVER_PORT=:50052
|
||||
POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product_schema
|
||||
POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product
|
||||
NATS_URL=nats://localhost:4222
|
||||
```
|
||||
|
||||
@ -45,15 +45,14 @@ NATS_URL=nats://localhost:4222
|
||||
|
||||
## 3.1 `internal/repository/product_repository.go`
|
||||
|
||||
- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product_schema.products`(SPU)和 `product_schema.skus` 的底座 CRUD
|
||||
- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.product_items` 的底座 CRUD
|
||||
- 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属的 SKU 列表
|
||||
- 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用
|
||||
- **【红线 ARC-001】**:严禁在这里编写任何跨 Schema 的 JOIN 查询
|
||||
|
||||
## 3.2 `internal/server/product_server.go`(gRPC Server)
|
||||
|
||||
- 引入 `llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/product/v1`(别名为 `productv1`)
|
||||
- 实现 `productv1.ProductServiceServer` 接口中的 `GetProduct` 和 `BatchGetProducts` 方法
|
||||
- 实现 `productv1.ProductServiceServer` 接口中的 `CreateProduct`、`GetProduct` 和 `ListCategoryProducts` 方法
|
||||
- 职责:解析入参 → 调用 repository 获取数据 → 组装并映射为 `productv1.Product` 和 `productv1.SKU` 强类型结构体返回
|
||||
- 所有价格字段(`price`)必须严格映射为 `int64`(单位:分)
|
||||
|
||||
|
||||
223
README.md
223
README.md
@ -1,6 +1,6 @@
|
||||
# ids-svc-product
|
||||
|
||||
IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据与价格读取,为 `ids-svc-order` 算价链路提供稳定的 gRPC 商品快照查询能力。
|
||||
IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类商品查询与价格读取。
|
||||
|
||||
**设计原则:** 轻、快、稳、灵 · Doc-First · Schema-per-Service
|
||||
|
||||
@ -8,18 +8,173 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据与价格
|
||||
|
||||
| RPC | 说明 | 主要调用方 |
|
||||
|-----|------|-----------|
|
||||
| `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 / 订单服务 |
|
||||
| `BatchGetProducts` | 批量拉取商品快照,减少算价阶段 N 次 RPC | `ids-svc-order` |
|
||||
| `CreateProduct` | 创建商品 SPU 及可选 SKU 列表 | 后台 / 运营系统 |
|
||||
| `GetProduct` | 按 `product_id` 返回 SPU 及下属 SKU 列表 | BFF / 后台 |
|
||||
| `ListProducts` | 分页返回全部未软删除商品列表 | Admin API |
|
||||
| `SearchProducts` | 按标题关键字分页返回前台可见商品 | 小程序 / H5 BFF |
|
||||
| `UpdateProduct` | 更新 SPU 字段,并更新或替换 SKU 集合 | Admin API |
|
||||
| `UpdateProductStatus` | 显式变更仓库中、上架、已售罄状态 | Admin API |
|
||||
| `ListCategoryProducts` | 按 `category_id` 分页返回分类下商品列表 | BFF / 商城前台 |
|
||||
| `ListCategoryTree` | 返回商品分类树,子节点挂载在父节点 `children` 下 | 微信小程序分类页 / BFF |
|
||||
|
||||
契约定义见 [`ids-proto`](https://llms.idsbuybuybuy.com/ecommerce/ids-proto) 的 `proto/ids/product/v1/product.proto`。
|
||||
|
||||
## 接口清单
|
||||
|
||||
商品服务对外接口的 REST 路径由 `google.api.http` 注解提供给 APISIX gRPC-Transcode 使用。
|
||||
|
||||
| RPC | REST | 请求 | 响应 | 说明 |
|
||||
|---|---|---|---|---|
|
||||
| `CreateProduct` | `POST /v1/products` | `CreateProductRequest` | `CreateProductResponse` | 创建商品 SPU,可同时提交 SKU 列表 |
|
||||
| `GetProduct` | `GET /v1/products/{product_id}` | `GetProductRequest` | `GetProductResponse` | 按商品 ID 查询商品详情,返回 SPU 与 SKU 列表 |
|
||||
| `ListProducts` | `GET /v1/products?page=1&page_size=20` | `ListProductsRequest` | `ListProductsResponse` | 分页查询全部未软删除商品 |
|
||||
| `SearchProducts` | gRPC only | `SearchProductsRequest` | `ListCategoryProductsResponse` | 按标题关键字分页查询前台可见商品,响应与分类商品列表一致 |
|
||||
| `UpdateProduct` | `PATCH /v1/products/{product_id}` | `UpdateProductRequest` | `UpdateProductResponse` | 原子更新 SPU 字段,并补丁更新或整体替换 SKU |
|
||||
| `UpdateProductStatus` | `PATCH /v1/products/{product_id}/status` | `UpdateProductStatusRequest` | `UpdateProductStatusResponse` | 使用乐观锁更新商品状态 |
|
||||
| `ListCategoryProducts` | `GET /v1/categories/{category_id}/products?page=1&page_size=20` | `ListCategoryProductsRequest` | `ListCategoryProductsResponse` | 按分类/分组 ID 分页查询商品列表 |
|
||||
| `ListCategoryTree` | `GET /v1/categories/tree?only_visible=true` | `ListCategoryTreeRequest` | `ListCategoryTreeResponse` | 查询 `node_type = 0` 的商品分类,并按父子层级返回树 |
|
||||
|
||||
### `CreateProduct`
|
||||
|
||||
创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。
|
||||
|
||||
当前创建接口不再接收 `product_id`、`sku_id`、`inventory_id` 和 SKU `name`:`product_id`、`sku_id`、`inventory_id` 由商品服务应用层生成雪花 ID,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。
|
||||
|
||||
创建商品时,调用方只提交商品业务字段和 SKU 业务字段。服务会在入库前生成:
|
||||
|
||||
| ID | 生成方式 | 写入位置 |
|
||||
|---|---|---|
|
||||
| `product_id` | 服务内 Snowflake 生成 | `product.products.id` |
|
||||
| `sku_id` | 服务内 Snowflake 生成,每个 SKU 一个 | `product.product_items.id` |
|
||||
| `inventory_id` | 服务内 Snowflake 生成,每个 SKU 库存行一个 | `product.product_item_inventory.id` |
|
||||
| 分类绑定 ID | 每个 `leaf_category_ids` 项由服务内 Snowflake 生成 | `product.product_category_bindings.id` |
|
||||
|
||||
常用请求字段:
|
||||
|
||||
| 字段 | 必填 | 说明 |
|
||||
|---|---:|---|
|
||||
| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 |
|
||||
| `title` | 是 | 商品标题 |
|
||||
| `selling_point` | 否 | 商品卖点 |
|
||||
| `leaf_category_ids` | 否 | 已存在的二级分类 ID 列表;传入后会写入全部分类绑定 |
|
||||
| `image_ids` | 否 | 商品图片 ID 列表 |
|
||||
| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID |
|
||||
| `status` | 否 | 未传时默认 `PRODUCT_STATUS_INVENTORY`;可取 `INVENTORY`、`ON_SALE`、`OFF_SALE` |
|
||||
| `goods_type` | 否 | 未传时默认 `1` |
|
||||
| `freight_charge_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `freight_template_id` |
|
||||
| `sale_time_type` | 否 | 未传时默认 `1`;为 `2` 时必须传 `scheduled_sale_time` |
|
||||
| `skus` | 否 | SKU 列表 |
|
||||
|
||||
`skus` 中每个 SKU 至少需要一组规格 `k1/v1`,价格和库存必须大于等于 0。SKU 可显式提供 `name`;未提供时由规格值拼接,例如 `500g 原味`。
|
||||
|
||||
最小示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"spu_no": "SPU202607100001",
|
||||
"title": "澳洲和牛家庭装",
|
||||
"selling_point": "原切谷饲,冷链到家",
|
||||
"leaf_category_ids": ["726390485721088000"],
|
||||
"skus": [
|
||||
{
|
||||
"sku_no": "SKU20260710000101",
|
||||
"price": 12800,
|
||||
"stock_quantity": 100,
|
||||
"k1": "规格",
|
||||
"v1": "1kg"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
响应只返回创建结果摘要,字段结构如下:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"item_id": 726390485721088000,
|
||||
"title": "澳洲和牛家庭装"
|
||||
},
|
||||
"success": true,
|
||||
"code": 0,
|
||||
"message": "success"
|
||||
}
|
||||
```
|
||||
|
||||
其中 `data.item_id` 是服务生成后的商品主键 ID,`data.title` 是商品标题。
|
||||
|
||||
### `GetProduct`
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `product_id` | `string` | 是 | 商品 SPU ID |
|
||||
|
||||
响应 `product` 包含 SPU 基础信息、SKU 列表、`created_at`、`updated_at`。时间字段统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
|
||||
|
||||
### `ListProducts`
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 |
|
||||
| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` |
|
||||
|
||||
返回全部 `deleted_at IS NULL` 的商品,不按商品状态筛选,按 `created_at DESC, id DESC` 稳定排序。响应字段和聚合规则与 `ListCategoryProducts` 相同:`price` 为未归档 SKU 的最低售价(分),`sold_quantity` 为未归档 SKU 的累计销量。
|
||||
|
||||
### `ListCategoryProducts`
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `category_id` | `string` | 是 | 分类/分组节点 ID,对应 `product.product_category.id` |
|
||||
| `page` | `int32` | 否 | 页码,从 `1` 开始;未传或小于 `1` 时按 `1` 处理 |
|
||||
| `page_size` | `int32` | 否 | 每页数量;未传或小于 `1` 时按 `20` 处理,大于 `100` 时截断为 `100` |
|
||||
| `only_visible` | `bool` | 否 | 为 `true` 时返回 `ON_SALE` 和 `OFF_SALE` 商品;小程序 BFF 固定传 `true`,Admin 不传以查看全部状态 |
|
||||
|
||||
分页响应字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `products` | `Product[]` | 当前页商品列表 |
|
||||
| `page` | `int32` | 当前页码 |
|
||||
| `page_size` | `int32` | 当前每页数量 |
|
||||
| `total` | `int64` | 分类/分组下商品总数 |
|
||||
| `total_pages` | `int32` | 总页数 |
|
||||
|
||||
`products[]` 返回商品摘要以及全部未归档 SKU 的聚合数据:`price` 为最低售价(单位:分),`sold_quantity` 为累计已售数量之和;不再返回 `skus` 列表。没有有效 SKU 或库存记录时,两个聚合字段均为 `0`。
|
||||
|
||||
### `UpdateProduct` 与 `UpdateProductStatus`
|
||||
|
||||
完整的输入输出及状态/SKU 规则见 [`docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md`](docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md)。重点约束:更新请求必须携带 SPU、SKU 和库存的乐观锁版本;`PATCH_EXISTING` 可更新 SKU `name`;`REPLACE_ALL` 仅允许在 `INVENTORY` 或 `OFF_SALE` 状态执行,并归档而不删除旧 SKU(即使存在锁定库存)。库存耗尽仅会自动将 `ON_SALE` 转为 `OFF_SALE`,补库存不会自动上架。
|
||||
|
||||
`products[].created_at`、`products[].updated_at` 统一返回 13 位 Unix 毫秒时间戳字符串,前端展示时按 `Asia/Shanghai` 渲染。
|
||||
|
||||
### `ListCategoryTree`
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `only_visible` | `bool` | 否 | 为 `true` 时只返回 `status = 1` 的分类;为 `false` 时返回全部 `node_type = 0` 分类 |
|
||||
|
||||
响应 `categories` 为树形分类列表。一级分类位于最外层,子分类挂载在父分类的 `children` 下。
|
||||
|
||||
`CategoryNode` 字段:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `category_id` | `string` | 分类节点 ID,对应 `product.product_category.id` |
|
||||
| `name` | `string` | 分类展示名称 |
|
||||
| `parent_id` | `string` | 父级分类 ID;一级分类为空字符串 |
|
||||
| `level` | `int32` | 分类层级 |
|
||||
| `image_json` | `string` | 分类图片 JSON,原样返回 |
|
||||
| `sort_num` | `int32` | 同级排序值 |
|
||||
| `status` | `int32` | 节点状态:`0` 隐藏,`1` 显示 |
|
||||
| `children` | `CategoryNode[]` | 子分类列表 |
|
||||
|
||||
## 技术栈
|
||||
|
||||
| 项 | 选型 |
|
||||
|---|---|
|
||||
| 语言 | Go 1.26 |
|
||||
| RPC | gRPC (`google.golang.org/grpc`) |
|
||||
| 数据库 | PostgreSQL `product_schema`(`github.com/jackc/pgx/v5`) |
|
||||
| 数据库 | PostgreSQL `product`(`github.com/jackc/pgx/v5`) |
|
||||
| 配置 | 环境变量 + 可选本地 `.env`(`github.com/joho/godotenv`) |
|
||||
| 契约 | `llms.idsbuybuybuy.com/ecommerce/ids-proto`(本地 `replace ../ids-proto`) |
|
||||
|
||||
@ -30,7 +185,7 @@ ids-svc-product/
|
||||
├── cmd/main.go # 服务入口
|
||||
├── internal/
|
||||
│ ├── config/config.go # 配置加载
|
||||
│ ├── repository/product_repository.go # product_schema 数据访问
|
||||
│ ├── repository/product_repository.go # product 数据访问
|
||||
│ └── server/product_server.go # gRPC 契约实现
|
||||
├── docs/
|
||||
│ ├── ARCHITECTURE.md # 架构白皮书
|
||||
@ -64,9 +219,26 @@ cp .env.example .env
|
||||
| `POSTGRES_USER` | `postgres` | 数据库用户 |
|
||||
| `POSTGRES_PASSWORD` | `postgres` | 数据库密码 |
|
||||
| `POSTGRES_DB` | `ids_ecommerce` | 数据库名 |
|
||||
| `POSTGRES_SCHEMA` | `product_schema` | 搜索路径 |
|
||||
| `POSTGRES_SCHEMA` | `product` | 搜索路径 |
|
||||
| `POSTGRES_SSLMODE` | `disable` | SSL 模式 |
|
||||
| `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址(首版查询链路不依赖) |
|
||||
| `METRICS_PORT` | `:9102` | Prometheus 指标与 HTTP 健康检查监听地址 |
|
||||
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTLP HTTP trace exporter 地址 |
|
||||
| `OTEL_EXPORTER_OTLP_INSECURE` | `true` | OTLP exporter 是否使用明文连接 |
|
||||
| `DEPLOYMENT_ENVIRONMENT` | `development` | Trace resource 中的部署环境标签 |
|
||||
| `SNOWFLAKE_WORKER_ID` | `1` | Snowflake worker ID;同一部署环境内不同服务实例必须使用不同值 |
|
||||
|
||||
### 可观测性
|
||||
|
||||
| 能力 | 入口 / 指标 | 说明 |
|
||||
|---|---|---|
|
||||
| HTTP 健康检查 | `GET /healthz`, `GET /readyz` | 返回 200 前会检查 PostgreSQL 连通性 |
|
||||
| gRPC 健康检查 | `grpc.health.v1.Health/Check` | 注册标准 gRPC Health Checking |
|
||||
| Prometheus 指标 | `GET /metrics` | 暴露 Go runtime、process、RPC 与商品业务指标 |
|
||||
| RPC 指标 | `ids_product_grpc_requests_total`, `ids_product_grpc_request_duration_seconds` | 按 `method`、`code` 维度统计请求数和耗时 |
|
||||
| 商品业务指标 | `ids_product_products_created_total`, `ids_product_product_lists_total`, `ids_product_category_product_lists_total`, `ids_product_category_tree_lists_total` | 统计商品创建成功数、全商品查询成功数、分类商品查询成功数和分类树查询成功数 |
|
||||
| 链路追踪 | OTLP HTTP | gRPC 自动 span,并为商品创建、商品查询、全商品查询、分类商品查询补充业务 span |
|
||||
| 结构化日志 | stdout | access log 与错误日志包含 `trace_id`、`span_id`、`correlation_id` |
|
||||
|
||||
### 构建与运行
|
||||
|
||||
@ -85,25 +257,34 @@ go run ./cmd
|
||||
grpcurl -plaintext localhost:50052 list
|
||||
|
||||
# 查询单个商品
|
||||
grpcurl -plaintext -d '{"product_id":"<uuid>"}' \
|
||||
grpcurl -plaintext -d '{"product_id":"<snowflake-id>"}' \
|
||||
localhost:50052 ids.product.v1.ProductService/GetProduct
|
||||
|
||||
# 批量查询
|
||||
grpcurl -plaintext -d '{"product_ids":["<uuid-1>","<uuid-2>"]}' \
|
||||
localhost:50052 ids.product.v1.ProductService/BatchGetProducts
|
||||
# 创建商品;product_id 和 sku_id 由服务生成
|
||||
grpcurl -plaintext -d '{"spu_no":"<spu-no>","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_INVENTORY","skus":[]}' \
|
||||
localhost:50052 ids.product.v1.ProductService/CreateProduct
|
||||
|
||||
# 分页查询分类商品
|
||||
grpcurl -plaintext -d '{"category_id":"<snowflake-category-id>","page":1,"page_size":20}' \
|
||||
localhost:50052 ids.product.v1.ProductService/ListCategoryProducts
|
||||
|
||||
# 分页查询全部未软删除商品
|
||||
grpcurl -plaintext -d '{"page":1,"page_size":20}' \
|
||||
localhost:50052 ids.product.v1.ProductService/ListProducts
|
||||
```
|
||||
|
||||
## 数据模型
|
||||
|
||||
商品域采用 SPU/SKU 分层,**仅读写** `product_schema`:
|
||||
商品域采用 SPU/SKU 分层,**仅读写** `product`:
|
||||
|
||||
| 表 | 职责 |
|
||||
|---|---|
|
||||
| `product_schema.products` | SPU 主表(名称、描述、状态、扩展属性) |
|
||||
| `product_schema.skus` | SKU 明细(规格、价格、库存) |
|
||||
| `product.products` | SPU 主表(标题、卖点、状态、扩展属性) |
|
||||
| `product.product_items` | SKU 明细(规格、价格、属性) |
|
||||
| `product.product_item_inventory` | SKU 库存销量(可售、锁定、已售) |
|
||||
|
||||
- 价格字段统一为 `BIGINT` / Go `int64`,单位:**分**
|
||||
- 禁止跨 Schema JOIN(`order_schema`、`user_schema` 等)
|
||||
- 禁止跨 Schema JOIN(`trade`、`customer` 等)
|
||||
|
||||
## 架构约束
|
||||
|
||||
@ -116,22 +297,10 @@ grpcurl -plaintext -d '{"product_ids":["<uuid-1>","<uuid-2>"]}' \
|
||||
|
||||
| ID | 约束 |
|
||||
|---|---|
|
||||
| ARC-PROD-001 | 仅读写 `product_schema`,禁止跨 Schema JOIN |
|
||||
| ARC-PROD-003 | `BatchGetProducts` 对重复 ID 去重,缺失 ID 静默跳过 |
|
||||
| ARC-PROD-001 | 仅读写 `product`,禁止跨 Schema JOIN |
|
||||
| ARC-PROD-004 | 价格字段统一 `int64`(分) |
|
||||
| ARC-PROD-005 | 状态枚举强对齐 `productv1.ProductStatus` |
|
||||
|
||||
## 与订单域协作
|
||||
|
||||
```
|
||||
ids-svc-order (算价) ──BatchGetProducts──▶ ids-svc-product
|
||||
│
|
||||
▼
|
||||
PG product_schema
|
||||
```
|
||||
|
||||
订单服务通过 gRPC 批量拉取 SKU 价格,**不得**跨库查询商品表。
|
||||
|
||||
## 相关仓库
|
||||
|
||||
| 仓库 | 关系 |
|
||||
|
||||
63
cmd/main.go
63
cmd/main.go
@ -4,23 +4,31 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"net"
|
||||
"net/http"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/health"
|
||||
healthpb "google.golang.org/grpc/health/grpc_health_v1"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||
|
||||
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/config"
|
||||
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/idgen"
|
||||
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/observability"
|
||||
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/server"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger, err := zap.NewProduction()
|
||||
logger, err := newLogger()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@ -31,9 +39,26 @@ func main() {
|
||||
logger.Fatal("load config failed", zap.Error(err))
|
||||
}
|
||||
|
||||
idGenerator, err := idgen.NewFromEnv()
|
||||
if err != nil {
|
||||
logger.Fatal("init snowflake id generator failed", zap.Error(err))
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
observer, shutdownTelemetry, err := observability.New(ctx, logger, cfg.OTLPEndpoint, cfg.OTELInsecure, cfg.Environment)
|
||||
if err != nil {
|
||||
logger.Fatal("init observability failed", zap.Error(err))
|
||||
}
|
||||
defer func() {
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := shutdownTelemetry(shutdownCtx); err != nil {
|
||||
logger.Error("shutdown telemetry failed", zap.Error(err))
|
||||
}
|
||||
}()
|
||||
|
||||
db, err := sql.Open("pgx", cfg.PostgresDSN)
|
||||
if err != nil {
|
||||
logger.Fatal("open postgres failed", zap.Error(err))
|
||||
@ -52,10 +77,27 @@ func main() {
|
||||
logger.Fatal("ensure product schema failed", zap.Error(err))
|
||||
}
|
||||
|
||||
productServer := server.NewProductServer(repo, logger)
|
||||
metricsServer := observability.MetricsServer(cfg.MetricsPort, db.PingContext)
|
||||
go func() {
|
||||
logger.Info("metrics server listening", zap.String("addr", cfg.MetricsPort))
|
||||
if err := metricsServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
logger.Error("metrics server failed", zap.Error(err))
|
||||
stop()
|
||||
}
|
||||
}()
|
||||
|
||||
grpcServer := grpc.NewServer()
|
||||
productServer := server.NewProductServer(repo, idGenerator, logger, observer)
|
||||
|
||||
grpcServer := grpc.NewServer(
|
||||
grpc.StatsHandler(otelgrpc.NewServerHandler()),
|
||||
grpc.UnaryInterceptor(observer.UnaryServerInterceptor()),
|
||||
)
|
||||
productv1.RegisterProductServiceServer(grpcServer, productServer)
|
||||
healthServer := health.NewServer()
|
||||
healthServer.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)
|
||||
healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_SERVING)
|
||||
healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_SERVING)
|
||||
healthpb.RegisterHealthServer(grpcServer, healthServer)
|
||||
reflection.Register(grpcServer)
|
||||
|
||||
lis, err := net.Listen("tcp", cfg.ServerPort)
|
||||
@ -72,5 +114,20 @@ func main() {
|
||||
|
||||
<-ctx.Done()
|
||||
logger.Info("shutting down")
|
||||
|
||||
healthServer.SetServingStatus("", healthpb.HealthCheckResponse_NOT_SERVING)
|
||||
healthServer.SetServingStatus(productv1.ProductService_ServiceDesc.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING)
|
||||
healthServer.SetServingStatus(observability.ServiceName, healthpb.HealthCheckResponse_NOT_SERVING)
|
||||
grpcServer.GracefulStop()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := metricsServer.Shutdown(shutdownCtx); err != nil {
|
||||
logger.Error("shutdown metrics server failed", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
func newLogger() (*zap.Logger, error) {
|
||||
cfg := zap.NewProductionConfig()
|
||||
cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
|
||||
return cfg.Build()
|
||||
}
|
||||
|
||||
@ -13,13 +13,19 @@ services:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres123}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-ids_ecommerce}
|
||||
POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-product_schema}
|
||||
POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-product}
|
||||
POSTGRES_SSLMODE: ${POSTGRES_SSLMODE:-disable}
|
||||
NATS_URL: nats://nats:4222
|
||||
METRICS_PORT: ":9102"
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://ids-tempo:4318
|
||||
OTEL_EXPORTER_OTLP_INSECURE: "true"
|
||||
DEPLOYMENT_ENVIRONMENT: ${DEPLOYMENT_ENVIRONMENT:-development}
|
||||
SNOWFLAKE_WORKER_ID: ${SNOWFLAKE_WORKER_ID:-1}
|
||||
GOMODCACHE: /go/pkg/mod
|
||||
GOCACHE: /root/.cache/go-build
|
||||
ports:
|
||||
- "${PRODUCT_GRPC_PORT:-50052}:50052"
|
||||
- "${PRODUCT_METRICS_PORT:-9102}:9102"
|
||||
volumes:
|
||||
- .:/workspace/ids-svc-product
|
||||
- ../ids-proto:/workspace/ids-proto:ro
|
||||
|
||||
@ -12,9 +12,9 @@
|
||||
|
||||
### 1.1 数据隔离红线 [ARC-PROD-001]
|
||||
|
||||
- 本服务**仅允许**读写 PostgreSQL 中的 `product_schema`。
|
||||
- 绝对禁止跨 Schema 去 `JOIN` `order_schema`、`user_schema` 或任何其他业务 Schema 的表。
|
||||
- 任何关于订单状态、用户会员权益、支付结果、库存锁定等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。
|
||||
- 本服务**仅允许**读写 PostgreSQL 中的 `product`。
|
||||
- 绝对禁止跨 Schema 去 `JOIN` `trade`、`customer` 或任何其他业务 Schema 的表。
|
||||
- 任何关于订单状态、客户会员权益、支付结果、库存锁定等跨域信息,**必须**由对应服务通过 gRPC 或事件契约提供,严禁在商品服务内通过跨库查询获取。
|
||||
|
||||
### 1.2 数据模型 (PostgreSQL)
|
||||
|
||||
@ -22,8 +22,8 @@
|
||||
|
||||
| 表 | 职责 |
|
||||
|---|---|
|
||||
| `product_schema.products` | SPU 主表,保存商品级公共信息、上下架状态与基础描述。 |
|
||||
| `product_schema.skus` | SKU 明细表,保存可售规格、价格、状态与 SPU 关联关系。 |
|
||||
| `product.products` | SPU 主表,保存商品级公共信息、上下架状态与基础描述。 |
|
||||
| `product.product_items` | SKU 明细表,保存可售规格、价格、状态与 SPU 关联关系。 |
|
||||
|
||||
所有价格字段(如 `price`)统一采用 `BIGINT` / Go `int64`,单位为**分**。禁止使用 `float32`、`float64` 或数据库浮点类型表达金额。
|
||||
|
||||
@ -49,7 +49,7 @@
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────┐
|
||||
│ PG product_schema │
|
||||
│ PG product │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
@ -59,28 +59,30 @@
|
||||
|---|---|---|
|
||||
| 启动信宿 | `cmd/main.go` | 服务启动信宿,负责加载配置、初始化 PostgreSQL 连接池、创建 repository,并拉起 gRPC 监听端口。 |
|
||||
| 契约实现层 | `internal/server/` | 实现 `ids-proto` 生成的 `ProductServiceServer` 接口。**禁止**在此处编写任何 SQL;主要职责是解析入参、调用 repository、映射 `productv1.Product` 与 `productv1.SKU` 强类型响应。 |
|
||||
| 数据持久层 | `internal/repository/` | 纯粹的数据访问层,封装面向 `product_schema.products` 与 `product_schema.skus` 的 CRUD 和批量查询能力。 |
|
||||
| 数据持久层 | `internal/repository/` | 纯粹的数据访问层,封装面向 `product.products` 与 `product.product_items` 的 CRUD 和批量查询能力。 |
|
||||
| 配置底座 | `internal/config/` | 轻量读取环境变量,优先加载本地 `.env`,生产环境无 `.env` 时静默降级到环境注入。 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 商品查询契约 [ADR-PROD-001]
|
||||
|
||||
商品服务是订单服务提单算价时的商品事实来源。`ids-svc-order` 不允许跨 Schema 查询商品表,而必须通过本服务 gRPC 接口获取商品与 SKU 快照。
|
||||
商品服务是商品 SPU/SKU 主数据与分类商品查询的事实来源。其他服务不允许跨 Schema 查询商品表。
|
||||
|
||||
### 3.1 核心 RPC
|
||||
|
||||
| RPC | 调用方 | 语义 |
|
||||
|---|---|---|
|
||||
| `GetProduct` | BFF / 后台 / 订单服务 | 根据单个 `product_id` 返回 SPU 及其 SKU 列表。 |
|
||||
| `BatchGetProducts` | `ids-svc-order` | 根据多个 `product_id` 批量返回商品及 SKU 列表,减少局域网算价阶段的 N 次调用。 |
|
||||
| `CreateProduct` | 后台 / 运营系统 | 创建商品 SPU 及可选 SKU 列表。 |
|
||||
| `GetProduct` | BFF / 后台 | 根据单个 `product_id` 返回 SPU 及其 SKU 列表。 |
|
||||
| `ListCategoryProducts` | BFF / 商城前台 | 根据分类/分组节点分页返回商品列表。 |
|
||||
| `ListCategoryTree` | 微信小程序分类页 / BFF | 返回 `node_type = 0` 的商品分类树,子分类挂载在父分类 `children` 下。 |
|
||||
|
||||
### 3.2 查询实现约束
|
||||
|
||||
1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product_schema.products` 与 `product_schema.skus` 之间做本域关联或分步查询,但不得访问其他 Schema。
|
||||
2. **[ARC-PROD-003] 批量查询必须稳定去重:** `BatchGetProducts` 应对重复 `product_id` 输入做安全处理,避免无意义 DB 放大,并保持返回结果语义清晰。
|
||||
3. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。
|
||||
4. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。
|
||||
1. **[ARC-PROD-002] SPU/SKU 只在本 Schema 内关联:** repository 可以在 `product.products` 与 `product.product_items` 之间做本域关联或分步查询,但不得访问其他 Schema。
|
||||
2. **[ARC-PROD-004] 价格单位强约束:** 所有 gRPC 响应里的 `price` 字段必须映射为 `int64`,单位为分。
|
||||
3. **[ARC-PROD-005] 状态枚举强对齐:** 商品和 SKU 状态必须使用 `productv1.ProductStatus` 等 proto 中定义的枚举类型,不得使用裸字符串向外泄露内部状态。
|
||||
4. **[ARC-PROD-007] 分类树组装边界:** repository 只查询 `product.product_category` 的扁平分类数据;父子层级组装由 `internal/server` 完成,不允许通过跨 Schema 查询补齐分类展示信息。
|
||||
|
||||
---
|
||||
|
||||
@ -91,8 +93,12 @@
|
||||
| 环境变量 | 默认值 | 说明 |
|
||||
|---|---|---|
|
||||
| `SERVER_PORT` | `:50052` | gRPC Server 监听地址。 |
|
||||
| `POSTGRES_DSN` | `postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product_schema` | PostgreSQL 连接字符串,必须包含 `product_schema` 搜索路径或由 SQL 显式限定 Schema。 |
|
||||
| `POSTGRES_DSN` | `postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product` | PostgreSQL 连接字符串,必须包含 `product` 搜索路径或由 SQL 显式限定 Schema。 |
|
||||
| `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址;当前商品查询主链路不依赖 NATS。 |
|
||||
| `METRICS_PORT` | `:9102` | Prometheus 指标与 HTTP 健康检查监听地址。 |
|
||||
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTLP HTTP trace exporter 地址。 |
|
||||
| `OTEL_EXPORTER_OTLP_INSECURE` | `true` | OTLP exporter 是否使用明文连接。 |
|
||||
| `DEPLOYMENT_ENVIRONMENT` | `development` | OpenTelemetry resource 的部署环境标签。 |
|
||||
|
||||
### 4.1 `.env` 加载策略 [ARC-PROD-006]
|
||||
|
||||
@ -110,8 +116,10 @@
|
||||
|---|---|
|
||||
| DB 连接失败 | `cmd/main.go` 启动阶段记录 DSN 之外的上下文并直接失败退出。 |
|
||||
| 单商品不存在 | repository 返回明确的 not found 语义,server 映射为 gRPC `NotFound`。 |
|
||||
| 批量商品部分缺失 | 返回已存在商品集合;调用方根据业务决定是否拒单或降级。 |
|
||||
| SQL 执行失败 | repository 包装 product id、操作名等上下文;server 记录并映射为 gRPC `Internal`。 |
|
||||
| 健康检查 | HTTP `/healthz`、`/readyz` 必须检查 PostgreSQL 连通性;gRPC 必须注册标准 Health Checking。 |
|
||||
| 指标 | `/metrics` 必须暴露 runtime、RPC 请求量/耗时和商品业务指标。 |
|
||||
| 链路追踪 | gRPC 自动 span 必须启用;关键业务路径补充业务 span 与错误状态。 |
|
||||
|
||||
---
|
||||
|
||||
@ -124,8 +132,7 @@
|
||||
3. 数据库操作必须收敛在 `internal/repository` 层,**严禁**在 `internal/server` 抛出 naked SQL。
|
||||
4. 严格按照 `ids-proto` 中 `ids.product.v1` / `productv1` 的结构体定义进行序列化与反序列化。
|
||||
5. 商品状态枚举必须强对齐 `productv1.ProductStatus`,不得在 gRPC 响应中暴露内部字符串状态。
|
||||
6. 跨域数据(订单、用户、支付、库存)必须通过 gRPC 或事件契约获取,严禁跨 Schema JOIN。
|
||||
7. `BatchGetProducts` 是订单算价链路的关键接口,应优先保证低延迟、批量查询与清晰错误语义。
|
||||
6. 跨域数据(订单、客户、支付、库存)必须通过 gRPC 或事件契约获取,严禁跨 Schema JOIN。
|
||||
|
||||
---
|
||||
|
||||
@ -133,9 +140,8 @@
|
||||
|
||||
| ID | 约束 |
|
||||
|---|---|
|
||||
| ARC-PROD-001 | 仅读写 `product_schema`,禁止跨 Schema JOIN |
|
||||
| ARC-PROD-001 | 仅读写 `product`,禁止跨 Schema JOIN |
|
||||
| ARC-PROD-002 | SPU/SKU 只允许在商品域 Schema 内关联 |
|
||||
| ARC-PROD-003 | `BatchGetProducts` 必须对重复输入做稳定处理 |
|
||||
| ARC-PROD-004 | 价格字段统一 `int64`,单位为分 |
|
||||
| ARC-PROD-005 | 状态枚举强对齐 `productv1` proto 枚举 |
|
||||
| ARC-PROD-006 | 配置加载优先 `.env`,生产无 `.env` 时静默降级 |
|
||||
|
||||
@ -20,7 +20,7 @@
|
||||
|---|---|
|
||||
| Go Module | `llms.idsbuybuybuy.com/ecommerce/ids-svc-product` |
|
||||
| 外部依赖契约 | `llms.idsbuybuybuy.com/ecommerce/ids-proto`(通过 `go.mod` 中 `replace` 关联到 `../ids-proto`) |
|
||||
| 数据库命名空间 | PostgreSQL `product_schema` |
|
||||
| 数据库命名空间 | PostgreSQL `product` |
|
||||
| Go 工具链 | **Go 1.26** |
|
||||
| Proto 契约路径 | `ids-proto/proto/ids/product/v1/product.proto` |
|
||||
| Proto 包名 | `ids.product.v1` |
|
||||
@ -59,8 +59,12 @@ replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto
|
||||
|
||||
```env
|
||||
SERVER_PORT=:50052
|
||||
POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product_schema
|
||||
POSTGRES_DSN=postgres://postgres:postgres@localhost:5432/ids_db?sslmode=disable&search_path=product
|
||||
NATS_URL=nats://localhost:4222
|
||||
METRICS_PORT=:9102
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
|
||||
OTEL_EXPORTER_OTLP_INSECURE=true
|
||||
DEPLOYMENT_ENVIRONMENT=development
|
||||
```
|
||||
|
||||
本地开发:`cp .env.example .env`,按 infra 实际凭证修改 DSN。
|
||||
@ -78,6 +82,10 @@ NATS_URL=nats://localhost:4222
|
||||
| `SERVER_PORT` | `ServerPort` | `:50052` |
|
||||
| `POSTGRES_DSN` | `PostgresDSN` | 见 `.env.example` |
|
||||
| `NATS_URL` | `NATSURL` | `nats://localhost:4222` |
|
||||
| `METRICS_PORT` | `MetricsPort` | `:9102` |
|
||||
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `OTLPEndpoint` | `http://localhost:4318` |
|
||||
| `OTEL_EXPORTER_OTLP_INSECURE` | `OTELInsecure` | `true` |
|
||||
| `DEPLOYMENT_ENVIRONMENT` | `Environment` | `development` |
|
||||
|
||||
> `NATS_URL` 当前作为后续商品事件广播的预留配置存在,首版查询链路不应强依赖 NATS 可用性。
|
||||
|
||||
@ -111,20 +119,18 @@ ids-svc-product/
|
||||
|
||||
### 3.1 `internal/repository/product_repository.go`
|
||||
|
||||
- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product_schema.products`(SPU)和 `product_schema.skus` 的底座 CRUD。
|
||||
- 基于 `database/sql`(或轻量级 `sqlx`),实现面向 `product.products`(SPU)和 `product.product_items` 的底座 CRUD。
|
||||
- 实现 `GetProduct(ctx, productId)`:查询 SPU 信息并关联查询出其所属 SKU 列表。
|
||||
- 实现 `BatchGetProducts(ctx, productIds)`:支持传入多个 ID 批量获取商品及 SKU 列表,供 `ids-svc-order` 算价时局域网调用。
|
||||
- `BatchGetProducts` 必须对重复 `product_id` 输入做稳定去重,避免 DB 查询放大。
|
||||
- 单商品不存在时应返回明确 not found 语义,便于 gRPC 层映射为 `codes.NotFound`。
|
||||
- **【红线 ARC-PROD-001】**:严禁编写任何跨 Schema 的 JOIN 查询。
|
||||
- **【红线 ARC-PROD-002】**:SPU/SKU 只允许在 `product_schema` 内关联或分步查询。
|
||||
- **【红线 ARC-PROD-002】**:SPU/SKU 只允许在 `product` 内关联或分步查询。
|
||||
|
||||
---
|
||||
|
||||
### 3.2 `internal/server/product_server.go`(gRPC Server)
|
||||
|
||||
- 引入 `llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/product/v1`(别名为 `productv1`)。
|
||||
- 实现 `productv1.ProductServiceServer` 接口中的 `GetProduct` 和 `BatchGetProducts` 方法。
|
||||
- 实现 `productv1.ProductServiceServer` 接口中的 `CreateProduct`、`GetProduct` 和 `ListCategoryProducts` 方法。
|
||||
- 职责链:
|
||||
1. 解析入参;
|
||||
2. 校验必要字段;
|
||||
@ -164,13 +170,12 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository
|
||||
|---|---|
|
||||
| 1 | 价格字段一律 `int64`(单位:分),**禁止** `float64` |
|
||||
| 2 | 状态枚举强对齐 `productv1.ProductStatus` |
|
||||
| 3 | repository 仅操作 `product_schema.products` 与 `product_schema.skus` |
|
||||
| 3 | repository 仅操作 `product.products` 与 `product.product_items` |
|
||||
| 4 | 禁止跨 Schema JOIN(**[ARC-PROD-001]**) |
|
||||
| 5 | `BatchGetProducts` 必须支持批量查询与重复输入去重(**[ARC-PROD-003]**) |
|
||||
| 6 | DB / gRPC 等底座错误须有完整日志包装(`log` 或 `slog`) |
|
||||
| 7 | 序列化/反序列化严格对齐 `ids-proto` 中的 `productv1` |
|
||||
| 8 | 配置加载优先 `godotenv.Load()`,生产环境无 `.env` 时须静默降级 |
|
||||
| 9 | `internal/server` 禁止 SQL;`internal/repository` 禁止 proto 响应拼装 |
|
||||
| 5 | DB / gRPC 等底座错误须有完整日志包装(`log` 或 `slog`) |
|
||||
| 6 | 序列化/反序列化严格对齐 `ids-proto` 中的 `productv1` |
|
||||
| 7 | 配置加载优先 `godotenv.Load()`,生产环境无 `.env` 时须静默降级 |
|
||||
| 8 | `internal/server` 禁止 SQL;`internal/repository` 禁止 proto 响应拼装 |
|
||||
|
||||
---
|
||||
|
||||
@ -190,10 +195,9 @@ LoadConfig() → 初始化 PG 连接池 → 创建 ProductRepository
|
||||
|
||||
| 开发任务 | 架构约束 |
|
||||
|---|---|
|
||||
| `repository` 仅操作 `product_schema` | [ARC-PROD-001] |
|
||||
| `repository` 仅操作 `product` | [ARC-PROD-001] |
|
||||
| SPU/SKU 只在商品域内关联 | [ARC-PROD-002] |
|
||||
| 批量商品查询去重与稳定返回 | [ARC-PROD-003] |
|
||||
| 价格字段统一 `int64` 分单位 | [ARC-PROD-004] |
|
||||
| 商品状态枚举强对齐 proto | [ARC-PROD-005] |
|
||||
| 配置优先 `.env` 并支持生产静默降级 | [ARC-PROD-006] |
|
||||
| 商品服务作为订单算价阶段商品事实来源 | [ADR-PROD-001] |
|
||||
| 商品服务作为商品主数据事实来源 | [ADR-PROD-001] |
|
||||
|
||||
288
docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md
Normal file
288
docs/PRODUCT_UPDATE_AND_SKU_ARCHIVE_DESIGN.md
Normal file
@ -0,0 +1,288 @@
|
||||
# 商品更新、状态与 SKU 归档设计
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
本设计新增以下管理端能力:
|
||||
|
||||
- 更新商品 SPU 信息和 SKU;
|
||||
- 更新商品经营状态;
|
||||
- SKU 规格整体替换时保留旧 SKU 与库存记录,不物理删除;
|
||||
- 历史订单继续展示下单时的商品与 SKU 快照。
|
||||
|
||||
商品域只读写 PostgreSQL 的 `product` schema。历史订单展示由订单域读取 `trade.order_items` 中的快照字段,不依赖当前 SKU 是否有效。
|
||||
|
||||
## 2. 状态模型
|
||||
|
||||
### 2.1 商品状态
|
||||
|
||||
`product.products.status` 使用以下值:
|
||||
|
||||
| 数据库存储值 | Proto / API 枚举 | 含义 | 小程序行为 |
|
||||
|---:|---|---|---|
|
||||
| `1` | `PRODUCT_STATUS_INVENTORY` | 在仓库 | 不展示、不可购买 |
|
||||
| `2` | `PRODUCT_STATUS_ON_SALE` | 已上架 | 展示、可购买 |
|
||||
| `3` | `PRODUCT_STATUS_OFF_SALE` | 已售罄 | 展示已售罄状态、不可购买 |
|
||||
|
||||
Proto 定义:
|
||||
|
||||
```proto
|
||||
enum ProductStatus {
|
||||
PRODUCT_STATUS_INVENTORY = 1;
|
||||
PRODUCT_STATUS_ON_SALE = 2;
|
||||
PRODUCT_STATUS_OFF_SALE = 3;
|
||||
}
|
||||
```
|
||||
|
||||
状态流转:
|
||||
|
||||
```text
|
||||
INVENTORY -> ON_SALE
|
||||
运营人员上架;至少存在一个可售 SKU。
|
||||
|
||||
ON_SALE -> OFF_SALE
|
||||
所有当前可售 SKU 的 stock_quantity - locked_quantity <= 0 时系统自动下架,
|
||||
或由运营人员主动下架。
|
||||
|
||||
OFF_SALE -> ON_SALE
|
||||
仅由运营人员主动重新上架;补货不会自动恢复上架。
|
||||
|
||||
ON_SALE 或 OFF_SALE -> INVENTORY
|
||||
运营人员放回仓库。
|
||||
```
|
||||
|
||||
### 2.2 SKU 状态与归档
|
||||
|
||||
`product.product_items.status` 保持现有含义:
|
||||
|
||||
| 值 | 含义 |
|
||||
|---:|---|
|
||||
| `0` | 暂停使用;管理端可见,可重新启用 |
|
||||
| `1` | 启用;可参与销售 |
|
||||
|
||||
为 SKU 增加:
|
||||
|
||||
```sql
|
||||
is_archived BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
archived_at TIMESTAMPTZ NULL
|
||||
```
|
||||
|
||||
并添加约束:
|
||||
|
||||
```sql
|
||||
CHECK (
|
||||
(is_archived = FALSE AND archived_at IS NULL)
|
||||
OR
|
||||
(is_archived = TRUE AND archived_at IS NOT NULL)
|
||||
)
|
||||
```
|
||||
|
||||
| `status` | `is_archived` | 含义 |
|
||||
|---:|---:|---|
|
||||
| `0` | `false` | 当前 SKU 暂停销售;运营人员可见、可恢复 |
|
||||
| `1` | `false` | 当前有效 SKU |
|
||||
| `0` | `true` | 历史 SKU;普通管理端不展示,不可销售、不可更新 |
|
||||
| `1` | `true` | 非法组合,服务端禁止 |
|
||||
|
||||
`is_archived` 是 SKU 生命周期字段,不能由管理端直接写入;仅 SKU 整体替换流程可以将旧 SKU 归档。
|
||||
|
||||
## 3. 管理端接口
|
||||
|
||||
### 3.1 更新商品与 SKU
|
||||
|
||||
```http
|
||||
PATCH /admin/v1/products/{product_id}
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
`expected_version` 必填。未传的 SPU 字段保持原值;数组字段传空数组代表清空。
|
||||
|
||||
```json
|
||||
{
|
||||
"expected_version": 12,
|
||||
"title": "中秋礼盒升级版",
|
||||
"selling_point": "限时优惠",
|
||||
"image_ids": ["726390485721088010"],
|
||||
"sku_change": {
|
||||
"mode": "PATCH_EXISTING",
|
||||
"items": [
|
||||
{
|
||||
"sku_id": "726390485721088101",
|
||||
"expected_sku_version": 3,
|
||||
"expected_inventory_version": 8,
|
||||
"name": "红色 M 码",
|
||||
"price": 9900,
|
||||
"stock_quantity": 50,
|
||||
"status": 1,
|
||||
"image_ids": ["726390485721088011"]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 可更新 SPU 字段
|
||||
|
||||
- `title`、`selling_point`;
|
||||
- `brand_id`、`supplier_id`;
|
||||
- `image_ids`、`detail_html`、`member_discount_enabled`、`service_guarantees`;
|
||||
- `cross_border_info`;
|
||||
- 运费、开售时间、商品类型相关字段。
|
||||
|
||||
不允许通过本接口更新 `spu_no`、商品 `status`、分类/分组绑定、`sold_quantity`、`locked_quantity`、`is_archived` 或 `archived_at`。
|
||||
|
||||
#### `PATCH_EXISTING`
|
||||
|
||||
仅更新已有 SKU 的可变字段:
|
||||
|
||||
- `price`;
|
||||
- `name`;
|
||||
- `stock_quantity`;
|
||||
- `status`;
|
||||
- `image_ids`。
|
||||
|
||||
不能修改 `sku_no`、`k1/v1` 至 `k3/v3`、销量或锁定库存。`name` 可单独覆盖,不影响 SKU 编号和规格组合。`stock_quantity` 是更新后的绝对数量,且不得小于 `locked_quantity`。
|
||||
|
||||
SKU 和库存均需要版本校验,防止后台操作覆盖下单锁库存。
|
||||
|
||||
#### `REPLACE_ALL`
|
||||
|
||||
用于 SKU 数量或规格结构变化,包括新增、移除、合并、拆分 SKU,或修改 `sku_no`、规格组合。
|
||||
|
||||
```json
|
||||
{
|
||||
"expected_version": 12,
|
||||
"sku_change": {
|
||||
"mode": "REPLACE_ALL",
|
||||
"items": [
|
||||
{
|
||||
"sku_no": "SKU-RED-M",
|
||||
"price": 9900,
|
||||
"stock_quantity": 20,
|
||||
"status": 1,
|
||||
"k1": "颜色",
|
||||
"v1": "红色",
|
||||
"k2": "尺寸",
|
||||
"v2": "M",
|
||||
"image_ids": ["726390485721088011"]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
即使旧 SKU 有 `locked_quantity > 0`,也允许整体替换。替换事务执行:
|
||||
|
||||
1. 锁定商品与当前 SKU 记录;
|
||||
2. 将旧 SKU 设为 `status = 0`、`is_archived = true`、`archived_at = NOW()`;
|
||||
3. 保留旧 SKU 的可售量、锁定量与销量,保证待支付订单、取消订单、支付完成等流程可继续按旧 SKU ID 结算;
|
||||
4. 新建全部目标 SKU 和库存记录;
|
||||
5. 禁止为已归档 SKU 创建新的库存锁定;
|
||||
6. 商品版本递增,并重新计算商品是否自动售罄。
|
||||
|
||||
仅在商品处于 `INVENTORY` 或 `OFF_SALE` 时允许 `REPLACE_ALL`;商品为 `ON_SALE` 时必须返回冲突错误,避免上架中替换规格影响购物车和下单。
|
||||
|
||||
成功响应:
|
||||
|
||||
```json
|
||||
{
|
||||
"product": {
|
||||
"product_id": "726390485721088003",
|
||||
"status": "PRODUCT_STATUS_INVENTORY",
|
||||
"version": 13,
|
||||
"skus": [
|
||||
{
|
||||
"sku_id": "726390485721088201",
|
||||
"sku_no": "SKU-RED-M",
|
||||
"price": 9900,
|
||||
"stock_quantity": 20,
|
||||
"status": 1,
|
||||
"is_archived": false,
|
||||
"version": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"sku_change_result": {
|
||||
"mode": "REPLACE_ALL",
|
||||
"created_sku_ids": ["726390485721088201"],
|
||||
"archived_sku_ids": ["726390485721088101"],
|
||||
"updated_sku_ids": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3.2 更新商品状态
|
||||
|
||||
```http
|
||||
PATCH /admin/v1/products/{product_id}/status
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "PRODUCT_STATUS_ON_SALE",
|
||||
"expected_version": 13
|
||||
}
|
||||
```
|
||||
|
||||
运营人员可以提交 `INVENTORY`、`ON_SALE`、`OFF_SALE`。无论商品是运营人员手动下架,还是因无可售库存自动切换为 `OFF_SALE`,都只能通过本接口显式重新设置为 `ON_SALE`;库存补充本身不会改变商品状态。
|
||||
|
||||
上架时必须存在至少一个启用、未归档且 `stock_quantity > locked_quantity` 的 SKU。
|
||||
|
||||
```json
|
||||
{
|
||||
"product_id": "726390485721088003",
|
||||
"previous_status": "PRODUCT_STATUS_ON_SALE",
|
||||
"status": "PRODUCT_STATUS_OFF_SALE",
|
||||
"version": 14,
|
||||
"updated_at": "1754388000000"
|
||||
}
|
||||
```
|
||||
|
||||
## 4. 所有商品接口的归档规则
|
||||
|
||||
| 接口 | 归档规则 |
|
||||
|---|---|
|
||||
| 创建商品 | 不接收归档字段;新 SKU 固定为 `is_archived=false`、`archived_at=null` |
|
||||
| 查询商品详情 | SKU 协议增加归档字段;普通管理端和小程序默认过滤归档 SKU |
|
||||
| 查询全部商品 | 仅用未归档 SKU 聚合最低价和销量 |
|
||||
| 查询分类商品 | 仅用未归档 SKU 聚合最低价和销量 |
|
||||
| 更新商品 | 已归档 SKU 不允许 `PATCH_EXISTING`;`REPLACE_ALL` 归档旧 SKU |
|
||||
| 更新状态 | 上架校验仅统计启用、未归档且有可售量的 SKU |
|
||||
| 锁库存 | 新订单仅可锁定启用且未归档 SKU |
|
||||
| 订单取消、支付、库存结算 | 必须支持处理已归档 SKU 的既有订单 |
|
||||
|
||||
SKU 协议需要增加 `is_archived`、`archived_at` 与版本字段。普通接口过滤已归档 SKU,因此普通运营人员不会看到历史 SKU;订单历史展示应使用订单快照。
|
||||
|
||||
## 5. 数据库迁移
|
||||
|
||||
现有商品状态迁移:
|
||||
|
||||
| 旧值 | 旧含义 | 新值 | 新含义 |
|
||||
|---:|---|---:|---|
|
||||
| `0` | DRAFT | `1` | INVENTORY |
|
||||
| `1` | ON_SALE | `2` | ON_SALE |
|
||||
| `3` | OFF_SALE | `3` | OFF_SALE |
|
||||
| `2` | 当前无有效语义 | `1` | INVENTORY |
|
||||
|
||||
迁移后,`status` 默认值为 `1`,约束为 `status IN (1, 2, 3)`。
|
||||
|
||||
SKU 编号唯一索引只约束当前有效 SKU:
|
||||
|
||||
```sql
|
||||
CREATE UNIQUE INDEX uq_product_items_sku_no_active
|
||||
ON product.product_items (sku_no)
|
||||
WHERE sku_no IS NOT NULL
|
||||
AND deleted_at IS NULL
|
||||
AND is_archived = FALSE;
|
||||
```
|
||||
|
||||
必须先创建新索引,再删除旧 `uq_product_items_sku_no` 索引;否则归档 SKU 仍会阻止复用原 `sku_no`。
|
||||
|
||||
## 6. 实施位置
|
||||
|
||||
- `ids-proto/proto/ids/product/v1/product.proto`:状态枚举、SKU 归档字段、版本字段、更新 RPC 与消息;
|
||||
- `ids-svc-product/internal/repository/product_repository.go`:状态映射、归档字段、SKU 替换,以及仅在已上架商品无可售库存时自动下架的计算;
|
||||
- `ids-svc-product/internal/server/product_server.go`:更新校验、状态流转与 gRPC 错误映射;
|
||||
- `ids-svc-product` SQL 初始化、重建和正式迁移脚本:字段、约束和索引;
|
||||
- `ids-admin-api/internal/handler`、`internal/service`:两个 PATCH 路由、DTO、Mapper、版本冲突映射与图片 URL 解析;
|
||||
- `admin接口描述.md`:管理端接口请求、响应、归档语义、自动售罄规则与错误码。
|
||||
37
go.mod
37
go.mod
@ -5,23 +5,46 @@ go 1.26.4
|
||||
replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto
|
||||
|
||||
require (
|
||||
github.com/bwmarrin/snowflake v0.3.0
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0
|
||||
go.opentelemetry.io/otel v1.43.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0
|
||||
go.opentelemetry.io/otel/sdk v1.43.0
|
||||
go.opentelemetry.io/otel/trace v1.43.0
|
||||
go.uber.org/zap v1.28.0
|
||||
google.golang.org/grpc v1.81.1
|
||||
google.golang.org/grpc v1.82.0
|
||||
google.golang.org/protobuf v1.36.11
|
||||
llms.idsbuybuybuy.com/ecommerce/ids-proto v0.0.0-00010101000000-000000000000
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.66.1 // indirect
|
||||
github.com/prometheus/procfs v0.16.1 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.43.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
||||
go.uber.org/multierr v1.10.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
golang.org/x/net v0.56.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260720155508-bb71a54f79dc // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260720155508-bb71a54f79dc // indirect
|
||||
)
|
||||
|
||||
69
go.sum
69
go.sum
@ -1,8 +1,15 @@
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0=
|
||||
github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
@ -13,6 +20,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
@ -23,8 +32,28 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
|
||||
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
|
||||
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
@ -32,8 +61,14 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0 h1:0Qx7VGBacMm9ZENQ7TnNObTYI4ShC+lHI16seduaxZo=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg=
|
||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 h1:3iZJKlCZufyRzPzlQhUIWVmfltrXuGyfjREgGP3UUjc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0/go.mod h1:/G+nUPfhq2e+qiXMGxMwumDrP5jtzU+mWN7/sjT2rak=
|
||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
||||
@ -42,33 +77,39 @@ go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfC
|
||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
|
||||
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
||||
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ=
|
||||
google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260720155508-bb71a54f79dc h1:fi+kqxHxmaxbnTnxOutQrJvK9ANhJIZAWkXwoTki6WM=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260720155508-bb71a54f79dc/go.mod h1:WRrQ7/7N19PypuT0fxLOL5Lq0waoiRri4FbtHDEKrGE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260720155508-bb71a54f79dc h1:3TtNq/QbJNrSY1nVdjcikfBw6ujnaNbdrd88wNr1OW4=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260720155508-bb71a54f79dc/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU=
|
||||
google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
@ -10,21 +10,28 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
defaultServerPort = ":50052"
|
||||
defaultPostgresHost = "localhost"
|
||||
defaultPostgresPort = "5432"
|
||||
defaultPostgresUser = "postgres"
|
||||
defaultPostgresPass = "postgres"
|
||||
defaultPostgresDB = "ids_ecommerce"
|
||||
defaultPostgresSchema = "product_schema"
|
||||
defaultNATSURL = "nats://localhost:4222"
|
||||
defaultServerPort = ":50052"
|
||||
defaultPostgresHost = "localhost"
|
||||
defaultPostgresPort = "5432"
|
||||
defaultPostgresUser = "postgres"
|
||||
defaultPostgresPass = "postgres"
|
||||
defaultPostgresDB = "ids_ecommerce"
|
||||
defaultPostgresSchema = "product"
|
||||
defaultNATSURL = "nats://localhost:4222"
|
||||
defaultMetricsPort = ":9102"
|
||||
defaultOTLPEndpoint = "http://localhost:4318"
|
||||
defaultEnvironment = "development"
|
||||
)
|
||||
|
||||
// Config holds runtime configuration loaded from environment variables.
|
||||
type Config struct {
|
||||
ServerPort string
|
||||
PostgresDSN string
|
||||
NATSURL string
|
||||
ServerPort string
|
||||
PostgresDSN string
|
||||
NATSURL string
|
||||
MetricsPort string
|
||||
OTLPEndpoint string
|
||||
OTELInsecure bool
|
||||
Environment string
|
||||
}
|
||||
|
||||
// LoadConfig loads .env when present and assembles configuration from environment variables.
|
||||
@ -39,9 +46,13 @@ func LoadConfig() (*Config, error) {
|
||||
}
|
||||
|
||||
return &Config{
|
||||
ServerPort: getEnv("SERVER_PORT", defaultServerPort),
|
||||
PostgresDSN: dsn,
|
||||
NATSURL: getEnv("NATS_URL", defaultNATSURL),
|
||||
ServerPort: getEnv("SERVER_PORT", defaultServerPort),
|
||||
PostgresDSN: dsn,
|
||||
NATSURL: getEnv("NATS_URL", defaultNATSURL),
|
||||
MetricsPort: getEnv("METRICS_PORT", defaultMetricsPort),
|
||||
OTLPEndpoint: getEnv("OTEL_EXPORTER_OTLP_ENDPOINT", defaultOTLPEndpoint),
|
||||
OTELInsecure: getEnv("OTEL_EXPORTER_OTLP_INSECURE", "true") == "true",
|
||||
Environment: getEnv("DEPLOYMENT_ENVIRONMENT", defaultEnvironment),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
41
internal/idgen/snowflake.go
Normal file
41
internal/idgen/snowflake.go
Normal file
@ -0,0 +1,41 @@
|
||||
package idgen
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/bwmarrin/snowflake"
|
||||
)
|
||||
|
||||
// Generator creates 64-bit, time-sortable Snowflake IDs.
|
||||
type Generator struct {
|
||||
node *snowflake.Node
|
||||
}
|
||||
|
||||
// NewFromEnv creates a generator using SNOWFLAKE_WORKER_ID, defaulting to 1.
|
||||
func NewFromEnv() (*Generator, error) {
|
||||
workerID := int64(1)
|
||||
if raw := os.Getenv("SNOWFLAKE_WORKER_ID"); raw != "" {
|
||||
parsed, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse SNOWFLAKE_WORKER_ID: %w", err)
|
||||
}
|
||||
workerID = parsed
|
||||
}
|
||||
node, err := snowflake.NewNode(workerID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create snowflake node: %w", err)
|
||||
}
|
||||
return &Generator{node: node}, nil
|
||||
}
|
||||
|
||||
// Next returns a new Snowflake ID.
|
||||
func (g *Generator) Next() int64 {
|
||||
return g.node.Generate().Int64()
|
||||
}
|
||||
|
||||
// NextString returns a decimal string representation of Next.
|
||||
func (g *Generator) NextString() string {
|
||||
return strconv.FormatInt(g.Next(), 10)
|
||||
}
|
||||
28
internal/idgen/snowflake_test.go
Normal file
28
internal/idgen/snowflake_test.go
Normal file
@ -0,0 +1,28 @@
|
||||
package idgen
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGeneratorNextString(t *testing.T) {
|
||||
t.Setenv("SNOWFLAKE_WORKER_ID", "1")
|
||||
|
||||
g, err := NewFromEnv()
|
||||
if err != nil {
|
||||
t.Fatalf("NewFromEnv() error = %v", err)
|
||||
}
|
||||
|
||||
id := g.NextString()
|
||||
if _, err := strconv.ParseInt(id, 10, 64); err != nil {
|
||||
t.Fatalf("NextString() = %q, want decimal int64: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFromEnvRejectsInvalidWorkerID(t *testing.T) {
|
||||
t.Setenv("SNOWFLAKE_WORKER_ID", "1024")
|
||||
|
||||
if _, err := NewFromEnv(); err == nil {
|
||||
t.Fatal("NewFromEnv() error = nil, want error")
|
||||
}
|
||||
}
|
||||
263
internal/observability/observability.go
Normal file
263
internal/observability/observability.go
Normal file
@ -0,0 +1,263 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.34.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const ServiceName = "ids-svc-product"
|
||||
|
||||
var (
|
||||
grpcRequestsTotal = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: "ids",
|
||||
Subsystem: "product",
|
||||
Name: "grpc_requests_total",
|
||||
Help: "Total number of product service gRPC requests.",
|
||||
},
|
||||
[]string{"method", "code"},
|
||||
)
|
||||
|
||||
grpcRequestDurationSeconds = promauto.NewHistogramVec(
|
||||
prometheus.HistogramOpts{
|
||||
Namespace: "ids",
|
||||
Subsystem: "product",
|
||||
Name: "grpc_request_duration_seconds",
|
||||
Help: "Product service gRPC request duration in seconds.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
},
|
||||
[]string{"method", "code"},
|
||||
)
|
||||
|
||||
productsCreatedTotal = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: "ids",
|
||||
Subsystem: "product",
|
||||
Name: "products_created_total",
|
||||
Help: "Total number of products created successfully.",
|
||||
},
|
||||
)
|
||||
|
||||
categoryProductListsTotal = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: "ids",
|
||||
Subsystem: "product",
|
||||
Name: "category_product_lists_total",
|
||||
Help: "Total number of successful category product list queries.",
|
||||
},
|
||||
)
|
||||
|
||||
productListsTotal = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: "ids",
|
||||
Subsystem: "product",
|
||||
Name: "product_lists_total",
|
||||
Help: "Total number of successful all-product list queries.",
|
||||
},
|
||||
)
|
||||
|
||||
productSearchesTotal = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: "ids",
|
||||
Subsystem: "product",
|
||||
Name: "product_searches_total",
|
||||
Help: "Total number of successful storefront product keyword searches.",
|
||||
},
|
||||
)
|
||||
|
||||
categoryTreeListsTotal = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Namespace: "ids",
|
||||
Subsystem: "product",
|
||||
Name: "category_tree_lists_total",
|
||||
Help: "Total number of successful category tree queries.",
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
// Observer wires OTLP tracing and trace-aware structured logging.
|
||||
type Observer struct {
|
||||
logger *zap.Logger
|
||||
tracer trace.Tracer
|
||||
}
|
||||
|
||||
// New initializes OTLP export and returns a shutdown function for the tracer provider.
|
||||
func New(ctx context.Context, logger *zap.Logger, endpoint string, insecure bool, environment string) (*Observer, func(context.Context) error, error) {
|
||||
if logger == nil {
|
||||
logger = zap.NewNop()
|
||||
}
|
||||
if environment == "" {
|
||||
environment = "development"
|
||||
}
|
||||
|
||||
opts := []otlptracehttp.Option{otlptracehttp.WithEndpointURL(endpoint)}
|
||||
if insecure {
|
||||
opts = append(opts, otlptracehttp.WithInsecure())
|
||||
}
|
||||
exporter, err := otlptracehttp.New(ctx, opts...)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create OTLP trace exporter: %w", err)
|
||||
}
|
||||
|
||||
res, err := resource.New(ctx,
|
||||
resource.WithAttributes(
|
||||
semconv.ServiceName(ServiceName),
|
||||
attribute.String("deployment.environment", environment),
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create trace resource: %w", err)
|
||||
}
|
||||
|
||||
provider := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithBatcher(exporter),
|
||||
sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())),
|
||||
)
|
||||
otel.SetTracerProvider(provider)
|
||||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{}, propagation.Baggage{},
|
||||
))
|
||||
|
||||
o := &Observer{
|
||||
logger: logger,
|
||||
tracer: provider.Tracer(ServiceName),
|
||||
}
|
||||
return o, provider.Shutdown, nil
|
||||
}
|
||||
|
||||
// NewNoop returns an observer that enriches logs and uses the global tracer provider.
|
||||
func NewNoop(logger *zap.Logger) *Observer {
|
||||
if logger == nil {
|
||||
logger = zap.NewNop()
|
||||
}
|
||||
return &Observer{
|
||||
logger: logger,
|
||||
tracer: otel.Tracer(ServiceName),
|
||||
}
|
||||
}
|
||||
|
||||
// Tracer returns the service tracer; nil-safe.
|
||||
func (o *Observer) Tracer() trace.Tracer {
|
||||
if o == nil {
|
||||
return otel.Tracer(ServiceName)
|
||||
}
|
||||
return o.tracer
|
||||
}
|
||||
|
||||
// Logger returns a logger enriched with trace_id, span_id, and correlation_id when present.
|
||||
func (o *Observer) Logger(ctx context.Context) *zap.Logger {
|
||||
if o == nil {
|
||||
return zap.NewNop()
|
||||
}
|
||||
|
||||
span := trace.SpanFromContext(ctx).SpanContext()
|
||||
logger := o.logger
|
||||
if logger == nil {
|
||||
logger = zap.NewNop()
|
||||
}
|
||||
if span.IsValid() {
|
||||
logger = logger.With(
|
||||
zap.String("trace_id", span.TraceID().String()),
|
||||
zap.String("span_id", span.SpanID().String()),
|
||||
)
|
||||
}
|
||||
if md, ok := metadata.FromIncomingContext(ctx); ok {
|
||||
for _, key := range []string{"x-request-id", "correlation-id"} {
|
||||
if values := md.Get(key); len(values) > 0 && values[0] != "" {
|
||||
logger = logger.With(zap.String("correlation_id", values[0]))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return logger
|
||||
}
|
||||
|
||||
// UnaryServerInterceptor records access logs and request metrics for every unary RPC.
|
||||
func (o *Observer) UnaryServerInterceptor() grpc.UnaryServerInterceptor {
|
||||
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
start := time.Now()
|
||||
resp, err := handler(ctx, req)
|
||||
duration := time.Since(start)
|
||||
code := status.Code(err).String()
|
||||
|
||||
grpcRequestsTotal.WithLabelValues(info.FullMethod, code).Inc()
|
||||
grpcRequestDurationSeconds.WithLabelValues(info.FullMethod, code).Observe(duration.Seconds())
|
||||
|
||||
logger := o.Logger(ctx).With(
|
||||
zap.String("grpc_method", info.FullMethod),
|
||||
zap.String("grpc_code", code),
|
||||
zap.Duration("duration", duration),
|
||||
)
|
||||
if err != nil {
|
||||
logger.Warn("grpc request completed", zap.Error(err))
|
||||
} else {
|
||||
logger.Info("grpc request completed")
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
|
||||
// IncProductsCreated records a successful product creation.
|
||||
func IncProductsCreated() {
|
||||
productsCreatedTotal.Inc()
|
||||
}
|
||||
|
||||
// IncCategoryProductLists records a successful category product list query.
|
||||
func IncCategoryProductLists() {
|
||||
categoryProductListsTotal.Inc()
|
||||
}
|
||||
|
||||
// IncProductLists records a successful all-product list query.
|
||||
func IncProductLists() {
|
||||
productListsTotal.Inc()
|
||||
}
|
||||
|
||||
// IncProductSearches records a successful storefront product keyword search.
|
||||
func IncProductSearches() {
|
||||
productSearchesTotal.Inc()
|
||||
}
|
||||
|
||||
// IncCategoryTreeLists records a successful category tree query.
|
||||
func IncCategoryTreeLists() {
|
||||
categoryTreeListsTotal.Inc()
|
||||
}
|
||||
|
||||
// MetricsServer exposes Prometheus scrape and health endpoints.
|
||||
func MetricsServer(addr string, healthCheck func(context.Context) error) *http.Server {
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/metrics", promhttp.Handler())
|
||||
healthHandler := func(w http.ResponseWriter, r *http.Request) {
|
||||
if healthCheck != nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := healthCheck(ctx); err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
mux.HandleFunc("/healthz", healthHandler)
|
||||
mux.HandleFunc("/readyz", healthHandler)
|
||||
return &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
39
internal/repository/product_repository_test.go
Normal file
39
internal/repository/product_repository_test.go
Normal file
@ -0,0 +1,39 @@
|
||||
package repository
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEscapeLikeLiteral(t *testing.T) {
|
||||
input := `100%_off\\bundle`
|
||||
if got, want := escapeLikeLiteral(input), `100\%\_off\\\\bundle`; got != want {
|
||||
t.Fatalf("escapeLikeLiteral(%q) = %q, want %q", input, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAggregateInventoryAdjustments(t *testing.T) {
|
||||
got, err := aggregateInventoryAdjustments([]InventoryAdjustment{
|
||||
{SKUID: "1002", Quantity: 3},
|
||||
{SKUID: "1001", Quantity: 1},
|
||||
{SKUID: "1001", Quantity: 2},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("len = %d, want 2", len(got))
|
||||
}
|
||||
if got[0] != (InventoryAdjustment{SKUID: "1001", Quantity: 3}) {
|
||||
t.Fatalf("first adjustment = %#v", got[0])
|
||||
}
|
||||
if got[1] != (InventoryAdjustment{SKUID: "1002", Quantity: 3}) {
|
||||
t.Fatalf("second adjustment = %#v", got[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestAggregateInventoryAdjustmentsRejectsInvalidSKUID(t *testing.T) {
|
||||
_, err := aggregateInventoryAdjustments([]InventoryAdjustment{
|
||||
{SKUID: "bad-sku", Quantity: 1},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid sku id error")
|
||||
}
|
||||
}
|
||||
31
internal/server/category_image_ids_test.go
Normal file
31
internal/server/category_image_ids_test.go
Normal file
@ -0,0 +1,31 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
|
||||
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
|
||||
)
|
||||
|
||||
func TestCategoryImageIDsRoundTripThroughExistingProtoField(t *testing.T) {
|
||||
imageIDs, err := normalizeNodeImageIDs(`[" image-1 ", "image-1", "image-2"]`)
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeNodeImageIDs: %v", err)
|
||||
}
|
||||
if len(imageIDs) != 2 || imageIDs[0] != "image-1" || imageIDs[1] != "image-2" {
|
||||
t.Fatalf("image ids = %#v", imageIDs)
|
||||
}
|
||||
|
||||
node := toProtoCategoryNode(&repository.CategoryRecord{ImageIDs: imageIDs})
|
||||
if got := node.GetImageJson(); got != `["image-1","image-2"]` {
|
||||
t.Fatalf("image_json = %q", got)
|
||||
}
|
||||
if _, err := protojson.Marshal(node); err != nil {
|
||||
t.Fatalf("marshal category node: %v", err)
|
||||
}
|
||||
|
||||
if _, err := normalizeNodeImageIDs(`{"image_id":"image-1"}`); err == nil {
|
||||
t.Fatal("expected non-array image_json to be rejected")
|
||||
}
|
||||
}
|
||||
19
internal/server/get_product_by_sku_test.go
Normal file
19
internal/server/get_product_by_sku_test.go
Normal file
@ -0,0 +1,19 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
|
||||
)
|
||||
|
||||
func TestGetProductBySkuRequiresID(t *testing.T) {
|
||||
s := NewProductServer(nil, nil, nil, nil)
|
||||
_, err := s.GetProductBySku(context.Background(), &productv1.GetProductBySkuRequest{})
|
||||
if status.Code(err) != codes.InvalidArgument {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
14
scripts/sql/create-inventory-adjustments.sql
Normal file
14
scripts/sql/create-inventory-adjustments.sql
Normal file
@ -0,0 +1,14 @@
|
||||
CREATE TABLE IF NOT EXISTS product.inventory_adjustments (
|
||||
order_id BIGINT NOT NULL,
|
||||
action VARCHAR(20) NOT NULL,
|
||||
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
|
||||
quantity INTEGER NOT NULL CHECK (quantity > 0),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (order_id, action, sku_id),
|
||||
CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release'))
|
||||
);
|
||||
|
||||
COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存';
|
||||
COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定';
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product;
|
||||
35
scripts/sql/migrate-category-image-ids.sql
Normal file
35
scripts/sql/migrate-category-image-ids.sql
Normal file
@ -0,0 +1,35 @@
|
||||
-- Migrate product.product_category.image_json (JSONB) to image_ids (VARCHAR[]).
|
||||
-- Safe to run multiple times. The ids-svc-product startup schema check performs
|
||||
-- the same migration for service-managed deployments.
|
||||
|
||||
ALTER TABLE product.product_category
|
||||
ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[];
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'product'
|
||||
AND table_name = 'product_category'
|
||||
AND column_name = 'image_json'
|
||||
) THEN
|
||||
EXECUTE $migration$
|
||||
UPDATE product.product_category
|
||||
SET image_ids = CASE
|
||||
WHEN jsonb_typeof(image_json) = 'array' THEN COALESCE(
|
||||
(SELECT array_agg(image_id)
|
||||
FROM jsonb_array_elements_text(image_json) AS image_id),
|
||||
'{}'::VARCHAR[]
|
||||
)
|
||||
ELSE '{}'::VARCHAR[]
|
||||
END
|
||||
WHERE image_json IS NOT NULL
|
||||
$migration$;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
ALTER TABLE product.product_category
|
||||
DROP COLUMN IF EXISTS image_json;
|
||||
|
||||
COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示';
|
||||
54
scripts/sql/migrate-product-status-and-sku-archive.sql
Normal file
54
scripts/sql/migrate-product-status-and-sku-archive.sql
Normal file
@ -0,0 +1,54 @@
|
||||
-- One-time migration for product lifecycle statuses and SKU archival.
|
||||
-- Run during a maintenance window before deploying the product-service code
|
||||
-- that uses PRODUCT_STATUS_INVENTORY / ON_SALE / OFF_SALE.
|
||||
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE product.product_items
|
||||
ADD COLUMN IF NOT EXISTS is_archived BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
|
||||
ALTER TABLE product.product_items
|
||||
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;
|
||||
|
||||
ALTER TABLE product.product_items
|
||||
DROP CONSTRAINT IF EXISTS chk_product_items_archived;
|
||||
|
||||
ALTER TABLE product.product_items
|
||||
ADD CONSTRAINT chk_product_items_archived
|
||||
CHECK ((is_archived = FALSE AND archived_at IS NULL) OR (is_archived = TRUE AND archived_at IS NOT NULL));
|
||||
|
||||
ALTER TABLE product.products
|
||||
DROP CONSTRAINT IF EXISTS chk_products_status;
|
||||
|
||||
-- Current values are 0=DRAFT, 1=ON_SALE, 3=OFF_SALE. Value 2 has no
|
||||
-- supported current meaning and is moved to INVENTORY as the safe state.
|
||||
UPDATE product.products
|
||||
SET status = CASE status
|
||||
WHEN 0 THEN 1
|
||||
WHEN 1 THEN 2
|
||||
WHEN 3 THEN 3
|
||||
ELSE 1
|
||||
END;
|
||||
|
||||
ALTER TABLE product.products
|
||||
ALTER COLUMN status SET DEFAULT 1;
|
||||
|
||||
ALTER TABLE product.products
|
||||
ADD CONSTRAINT chk_products_status CHECK (status IN (1, 2, 3));
|
||||
|
||||
COMMIT;
|
||||
|
||||
-- CREATE INDEX CONCURRENTLY cannot run inside the transaction above.
|
||||
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_product_items_sku_no_active
|
||||
ON product.product_items (sku_no)
|
||||
WHERE sku_no IS NOT NULL
|
||||
AND deleted_at IS NULL
|
||||
AND is_archived = FALSE;
|
||||
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_product_items_active_product_id
|
||||
ON product.product_items (product_id)
|
||||
WHERE deleted_at IS NULL
|
||||
AND is_archived = FALSE;
|
||||
|
||||
-- Drop the legacy index only after uq_product_items_sku_no_active is valid.
|
||||
DROP INDEX CONCURRENTLY IF EXISTS product.uq_product_items_sku_no;
|
||||
260
scripts/sql/recreate-product-tables.sql
Normal file
260
scripts/sql/recreate-product-tables.sql
Normal file
@ -0,0 +1,260 @@
|
||||
-- Manual one-shot SQL for recreating the 5 product-domain tables
|
||||
-- without rebuilding the PostgreSQL data volume.
|
||||
--
|
||||
-- Tables:
|
||||
-- product.products
|
||||
-- product.product_category
|
||||
-- product.product_category_bindings
|
||||
-- product.product_items
|
||||
-- product.product_item_inventory
|
||||
--
|
||||
-- Intended use:
|
||||
-- 1. Drop the product tables manually if they still exist.
|
||||
-- 2. Execute this file against the existing ids_ecommerce database.
|
||||
--
|
||||
-- Drop order, if needed:
|
||||
-- DROP TABLE IF EXISTS product.product_item_inventory;
|
||||
-- DROP TABLE IF EXISTS product.product_category_bindings;
|
||||
-- DROP TABLE IF EXISTS product.product_items;
|
||||
-- DROP TABLE IF EXISTS product.product_category;
|
||||
-- DROP TABLE IF EXISTS product.products;
|
||||
--
|
||||
-- Example from ids-svc-product/:
|
||||
-- docker cp scripts/sql/recreate-product-tables.sql ids-postgres:/tmp/recreate-product-tables.sql
|
||||
-- docker exec -it ids-postgres psql -U postgres -d ids_ecommerce -f /tmp/recreate-product-tables.sql
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS "pg_trgm";
|
||||
|
||||
CREATE SCHEMA IF NOT EXISTS product;
|
||||
|
||||
CREATE OR REPLACE FUNCTION public.set_updated_at()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = NOW();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.products (
|
||||
id BIGINT PRIMARY KEY,
|
||||
spu_no VARCHAR(100) NOT NULL,
|
||||
title VARCHAR(200) NOT NULL,
|
||||
selling_point VARCHAR(300),
|
||||
brand_id BIGINT,
|
||||
supplier_id BIGINT,
|
||||
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||
detail_html TEXT,
|
||||
member_discount_enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
goods_type SMALLINT NOT NULL DEFAULT 1,
|
||||
service_guarantees VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||
status SMALLINT NOT NULL DEFAULT 1,
|
||||
cross_border JSONB NOT NULL DEFAULT '{}'::JSONB,
|
||||
freight_charge_type SMALLINT NOT NULL DEFAULT 1,
|
||||
freight_fixed_amount BIGINT NOT NULL DEFAULT 0,
|
||||
freight_template_id BIGINT,
|
||||
sale_time_type SMALLINT NOT NULL DEFAULT 1,
|
||||
scheduled_sale_time TIMESTAMPTZ,
|
||||
version INTEGER NOT NULL DEFAULT 0,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT chk_products_goods_type
|
||||
CHECK (goods_type IN (1, 2, 3, 4)),
|
||||
CONSTRAINT chk_products_status
|
||||
CHECK (status IN (1, 2, 3)),
|
||||
CONSTRAINT chk_products_freight_charge_type
|
||||
CHECK (freight_charge_type IN (1, 2)),
|
||||
CONSTRAINT chk_products_freight_fixed_amount
|
||||
CHECK (freight_fixed_amount >= 0),
|
||||
CONSTRAINT chk_products_freight_template_required
|
||||
CHECK (freight_charge_type <> 2 OR freight_template_id IS NOT NULL),
|
||||
CONSTRAINT chk_products_sale_time_type
|
||||
CHECK (sale_time_type IN (1, 2)),
|
||||
CONSTRAINT chk_products_scheduled_sale_time_required
|
||||
CHECK (sale_time_type <> 2 OR scheduled_sale_time IS NOT NULL),
|
||||
CONSTRAINT chk_products_version
|
||||
CHECK (version >= 0)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE product.products IS '商品 SPU 主表:存储商品公共信息、分类分组、品牌、供应商、图片、商品类型、运费、开售配置和软删除状态';
|
||||
COMMENT ON COLUMN product.products.service_guarantees IS '服务保障展示快照;服务保障主数据变更时需通过业务流程刷新';
|
||||
COMMENT ON COLUMN product.products.detail_html IS '商品详情 HTML;写入或渲染前必须做 HTML Sanitization,列表接口不得读取该字段';
|
||||
COMMENT ON COLUMN product.products.version IS '乐观锁版本号,用于后台并发编辑冲突检测';
|
||||
COMMENT ON COLUMN product.products.deleted_at IS '软删除时间;NULL 表示未删除,商品禁止物理删除以保护订单和财务引用';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_products_title_trgm
|
||||
ON product.products USING GIN (title gin_trgm_ops);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_products_brand_status
|
||||
ON product.products (brand_id, status);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_products_status_goods_type
|
||||
ON product.products (status, goods_type)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_products_supplier_id
|
||||
ON product.products (supplier_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_products_goods_type
|
||||
ON product.products (goods_type);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_products_deleted_at
|
||||
ON product.products (deleted_at);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_products_active_created_id
|
||||
ON product.products (created_at DESC, id DESC)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no
|
||||
ON product.products (spu_no)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.product_category (
|
||||
id BIGINT PRIMARY KEY,
|
||||
node_type SMALLINT NOT NULL DEFAULT 1,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
parent_id BIGINT REFERENCES product.product_category(id),
|
||||
level SMALLINT NOT NULL,
|
||||
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||
sort_num INTEGER NOT NULL DEFAULT 0,
|
||||
status SMALLINT NOT NULL DEFAULT 1,
|
||||
version INTEGER NOT NULL DEFAULT 0,
|
||||
CONSTRAINT chk_product_category_node_type
|
||||
CHECK (node_type IN (1, 2)),
|
||||
CONSTRAINT chk_product_category_level
|
||||
CHECK (level > 0),
|
||||
CONSTRAINT chk_product_category_status
|
||||
CHECK (status IN (0, 1)),
|
||||
CONSTRAINT chk_product_category_version
|
||||
CHECK (version >= 0)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE product.product_category IS '商品类别表:存储商品分类和商品分组,通过 node_type 区分分类或分组';
|
||||
COMMENT ON COLUMN product.product_category.id IS '类别/分组节点主键';
|
||||
COMMENT ON COLUMN product.product_category.node_type IS '节点类型:1 分类,2 分组';
|
||||
COMMENT ON COLUMN product.product_category.name IS '节点展示名称';
|
||||
COMMENT ON COLUMN product.product_category.parent_id IS '上级节点 ID,顶级节点为空;子节点通过 parent_id 反向查询';
|
||||
COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、3';
|
||||
COMMENT ON COLUMN product.product_category.image_ids IS '图片 ID 列表,用于小程序分类入口、分组入口展示';
|
||||
COMMENT ON COLUMN product.product_category.sort_num IS '排序值,数值越小越靠前';
|
||||
COMMENT ON COLUMN product.product_category.status IS '节点状态:0 隐藏,1 显示';
|
||||
COMMENT ON COLUMN product.product_category.version IS '节点乐观锁版本号,更新时递增';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_product_category_parent_id
|
||||
ON product.product_category (parent_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_product_category_node_status_sort
|
||||
ON product.product_category (node_type, status, sort_num);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.product_category_bindings (
|
||||
id BIGINT PRIMARY KEY,
|
||||
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||
category_id BIGINT NOT NULL REFERENCES product.product_category(id) ON DELETE CASCADE,
|
||||
CONSTRAINT uq_product_category_bindings_product_category UNIQUE (product_id, category_id)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE product.product_category_bindings IS '商品类别/分组绑定表:存储商品 SPU 与分类/分组节点的多对多绑定关系';
|
||||
COMMENT ON COLUMN product.product_category_bindings.id IS '商品类别/分组绑定主键';
|
||||
COMMENT ON COLUMN product.product_category_bindings.product_id IS '绑定商品 SPU ID,对应 product.products.id';
|
||||
COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类/分组节点 ID,对应 product.product_category.id';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id
|
||||
ON product.product_category_bindings (category_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.product_items (
|
||||
id BIGINT PRIMARY KEY,
|
||||
product_id BIGINT NOT NULL REFERENCES product.products(id) ON DELETE CASCADE,
|
||||
sku_no VARCHAR(100),
|
||||
name VARCHAR(256) NOT NULL,
|
||||
price BIGINT NOT NULL CHECK (price >= 0),
|
||||
image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[],
|
||||
attributes JSONB NOT NULL DEFAULT '{}',
|
||||
status SMALLINT NOT NULL DEFAULT 1 CHECK (status IN (0, 1)),
|
||||
is_archived BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
archived_at TIMESTAMPTZ,
|
||||
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||
deleted_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT chk_product_items_archived
|
||||
CHECK ((is_archived = FALSE AND archived_at IS NULL) OR (is_archived = TRUE AND archived_at IS NOT NULL))
|
||||
);
|
||||
|
||||
COMMENT ON TABLE product.product_items IS '商品 SKU 明细表:存储具体可售规格、价格和规格属性;库存统一存储在 product.product_item_inventory';
|
||||
COMMENT ON COLUMN product.product_items.price IS 'SKU 售价,单位:分';
|
||||
COMMENT ON COLUMN product.product_items.image_ids IS 'SKU 图片 ID 列表';
|
||||
COMMENT ON COLUMN product.product_items.attributes IS 'SKU 规格属性 JSONB,如颜色、尺寸等';
|
||||
COMMENT ON COLUMN product.product_items.status IS 'SKU 状态:0 停用,1 启用';
|
||||
COMMENT ON COLUMN product.product_items.is_archived IS 'SKU 是否归档;归档 SKU 不参与当前运营、展示和新订单销售';
|
||||
COMMENT ON COLUMN product.product_items.archived_at IS 'SKU 归档时间;归档后仅保留供历史订单结算与展示';
|
||||
COMMENT ON COLUMN product.product_items.version IS 'SKU 乐观锁版本号';
|
||||
COMMENT ON COLUMN product.product_items.deleted_at IS 'SKU 软删除时间;NULL 表示未删除';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_product_items_product_id
|
||||
ON product.product_items (product_id)
|
||||
WHERE deleted_at IS NULL AND is_archived = FALSE;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_product_items_price
|
||||
ON product.product_items (price)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no_active
|
||||
ON product.product_items (sku_no)
|
||||
WHERE sku_no IS NOT NULL AND deleted_at IS NULL AND is_archived = FALSE;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.product_item_inventory (
|
||||
id BIGINT PRIMARY KEY,
|
||||
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
|
||||
spu_no VARCHAR(100),
|
||||
sku_no VARCHAR(100),
|
||||
stock_quantity INTEGER NOT NULL DEFAULT 0 CHECK (stock_quantity >= 0),
|
||||
locked_quantity INTEGER NOT NULL DEFAULT 0 CHECK (locked_quantity >= 0),
|
||||
sold_quantity INTEGER NOT NULL DEFAULT 0 CHECK (sold_quantity >= 0),
|
||||
version INTEGER NOT NULL DEFAULT 0 CHECK (version >= 0),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS product.inventory_adjustments (
|
||||
order_id BIGINT NOT NULL,
|
||||
action VARCHAR(20) NOT NULL,
|
||||
sku_id BIGINT NOT NULL REFERENCES product.product_items(id) ON DELETE CASCADE,
|
||||
quantity INTEGER NOT NULL CHECK (quantity > 0),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (order_id, action, sku_id),
|
||||
CONSTRAINT chk_inventory_adjustments_action CHECK (action IN ('confirm', 'release'))
|
||||
);
|
||||
|
||||
COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储库存池、锁定库存和已售数量';
|
||||
COMMENT ON COLUMN product.product_item_inventory.id IS '库存记录主键,由商品服务应用层生成雪花 ID';
|
||||
COMMENT ON COLUMN product.product_item_inventory.spu_no IS '商品 SPU 编码冗余字段,用于库存查询和对账';
|
||||
COMMENT ON COLUMN product.product_item_inventory.sku_no IS '商品 SKU 编码冗余字段,用于库存查询和对账';
|
||||
COMMENT ON COLUMN product.product_item_inventory.stock_quantity IS 'SKU 当前库存池数量,净可售=stock_quantity-locked_quantity';
|
||||
COMMENT ON COLUMN product.product_item_inventory.locked_quantity IS '待支付订单锁定库存';
|
||||
COMMENT ON COLUMN product.product_item_inventory.sold_quantity IS '支付成功后的累计销量';
|
||||
COMMENT ON COLUMN product.product_item_inventory.version IS '库存乐观锁版本号';
|
||||
COMMENT ON TABLE product.inventory_adjustments IS '订单库存动作幂等表:记录确认成交和释放锁定库存';
|
||||
COMMENT ON COLUMN product.inventory_adjustments.action IS '库存动作:confirm 支付成功确认成交;release 待支付取消/超时释放锁定';
|
||||
|
||||
DROP TRIGGER IF EXISTS set_products_updated_at ON product.products;
|
||||
CREATE TRIGGER set_products_updated_at
|
||||
BEFORE UPDATE ON product.products
|
||||
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
DROP TRIGGER IF EXISTS set_product_items_updated_at ON product.product_items;
|
||||
CREATE TRIGGER set_product_items_updated_at
|
||||
BEFORE UPDATE ON product.product_items
|
||||
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
DROP TRIGGER IF EXISTS set_product_item_inventory_updated_at ON product.product_item_inventory;
|
||||
CREATE TRIGGER set_product_item_inventory_updated_at
|
||||
BEFORE UPDATE ON product.product_item_inventory
|
||||
FOR EACH ROW EXECUTE FUNCTION public.set_updated_at();
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON product.products TO svc_product;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category TO svc_product;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_category_bindings TO svc_product;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_items TO svc_product;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON product.product_item_inventory TO svc_product;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON product.inventory_adjustments TO svc_product;
|
||||
5
scripts/sql/rename-inventory-stock-quantity.sql
Normal file
5
scripts/sql/rename-inventory-stock-quantity.sql
Normal file
@ -0,0 +1,5 @@
|
||||
ALTER TABLE product.product_item_inventory
|
||||
RENAME COLUMN available_quantity TO stock_quantity;
|
||||
|
||||
COMMENT ON TABLE product.product_item_inventory IS '商品 SKU 库存销量表:存储库存池、锁定库存和已售数量';
|
||||
COMMENT ON COLUMN product.product_item_inventory.stock_quantity IS 'SKU 当前库存池数量,净可售=stock_quantity-locked_quantity';
|
||||
Loading…
Reference in New Issue
Block a user