From 1c89c4a11fe8881980a0a13dca0a214067b89368 Mon Sep 17 00:00:00 2001 From: BXY0414 <1079823339@qq.com> Date: Fri, 10 Jul 2026 16:31:07 +0800 Subject: [PATCH] feat(product): switch product IDs to application snowflake generation --- .env.example | 1 + README.md | 56 +++++++++++++++++++++-- cmd/main.go | 10 ++-- docker-compose.yaml | 1 + internal/repository/product_repository.go | 31 ++++++------- internal/server/product_server.go | 3 ++ scripts/sql/recreate-product-tables.sql | 16 ++----- 7 files changed, 80 insertions(+), 38 deletions(-) diff --git a/.env.example b/.env.example index f804ea9..1d7d2e1 100644 --- a/.env.example +++ b/.env.example @@ -12,6 +12,7 @@ METRICS_PORT=:9102 OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 OTEL_EXPORTER_OTLP_INSECURE=true DEPLOYMENT_ENVIRONMENT=development +SNOWFLAKE_WORKER_ID=1 # Optional # POSTGRES_DSN=postgres://... # full DSN override (skips assembly above) diff --git a/README.md b/README.md index 07d1cb8..de22173 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,56 @@ IDS 电商矩阵中的**商品域微服务**,负责 SPU/SKU 主数据、分类 创建商品的完整字段、SKU 规格整理规则、跨境字段和入库表映射见 [`docs/CREATE_PRODUCT.md`](docs/CREATE_PRODUCT.md)。 -当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_id` 由数据库生成,SKU `name` 由后端按规格值 `v1/v2/v3` 拼接。 +当前创建接口不再接收 `product_id`、`sku_id` 和 SKU `name`:`product_id`、`sku_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` | 复用对应 `sku_id` | `product.product_item_inventory.id` | +| 分类绑定 ID | 传入 `leaf_category_id` 时服务内 Snowflake 生成 | `product.product_category_bindings.id` | + +常用请求字段: + +| 字段 | 必填 | 说明 | +|---|---:|---| +| `spu_no` | 是 | 商品业务编码,未删除商品内唯一 | +| `title` | 是 | 商品标题 | +| `selling_point` | 否 | 商品卖点 | +| `leaf_category_id` | 否 | 已存在的分类/分组节点 ID;传入后会写入分类绑定 | +| `image_ids` | 否 | 商品图片 ID 列表 | +| `brand_id` / `supplier_id` | 否 | 品牌、供应商 ID | +| `status` | 否 | 未传时默认草稿 | +| `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 名称由规格值拼接,例如 `500g 原味`。 + +最小示例: + +```json +{ + "spu_no": "SPU202607100001", + "title": "澳洲和牛家庭装", + "selling_point": "原切谷饲,冷链到家", + "leaf_category_id": "726390485721088000", + "skus": [ + { + "sku_no": "SKU20260710000101", + "price": 12800, + "available_quantity": 100, + "k1": "规格", + "v1": "1kg" + } + ] +} +``` + +响应中的 `product.product_id` 和 `product.skus[].sku_id` 是服务生成后的最终主键 ID。 ### `GetProduct` @@ -137,6 +186,7 @@ cp .env.example .env | `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;同一部署环境内不同服务实例必须使用不同值 | ### 可观测性 @@ -170,8 +220,8 @@ grpcurl -plaintext localhost:50052 list grpcurl -plaintext -d '{"product_id":""}' \ localhost:50052 ids.product.v1.ProductService/GetProduct -# 创建商品 -grpcurl -plaintext -d '{"product_id":"","spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \ +# 创建商品;product_id 和 sku_id 由服务生成 +grpcurl -plaintext -d '{"spu_no":"","title":"商品标题","selling_point":"商品卖点","status":"PRODUCT_STATUS_DRAFT","skus":[]}' \ localhost:50052 ids.product.v1.ProductService/CreateProduct # 分页查询分类商品 diff --git a/cmd/main.go b/cmd/main.go index 423fa95..69499ab 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -38,6 +38,11 @@ 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() @@ -71,11 +76,6 @@ func main() { logger.Fatal("ensure product schema failed", zap.Error(err)) } - idGenerator, err := idgen.NewFromEnv() - if err != nil { - logger.Fatal("init snowflake id generator failed", zap.Error(err)) - } - metricsServer := observability.MetricsServer(cfg.MetricsPort, db.PingContext) go func() { logger.Info("metrics server listening", zap.String("addr", cfg.MetricsPort)) diff --git a/docker-compose.yaml b/docker-compose.yaml index 124536c..c65f107 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -20,6 +20,7 @@ services: 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: diff --git a/internal/repository/product_repository.go b/internal/repository/product_repository.go index c9e55ad..59e44c4 100644 --- a/internal/repository/product_repository.go +++ b/internal/repository/product_repository.go @@ -41,6 +41,7 @@ type ProductRecord struct { SaleTimeType int32 ScheduledSaleTime *time.Time LeafCategoryID string + CategoryBindingID string DeletedAt *time.Time CreatedAt time.Time UpdatedAt time.Time @@ -126,21 +127,14 @@ func NewProductRepository(db *sql.DB) *ProductRepository { // EnsureSchema adds the SKU table when missing; products is provisioned by infra init-scripts. func (r *ProductRepository) EnsureSchema(ctx context.Context) error { const ddl = ` -CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; - ALTER TABLE product.products - ALTER COLUMN id SET DEFAULT nextval('product.products_id_seq'); + ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_category_bindings - ALTER COLUMN id SET DEFAULT nextval('product.product_category_bindings_id_seq'); - -SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); -SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); + ALTER COLUMN id DROP DEFAULT; CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), + 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, @@ -165,10 +159,9 @@ CREATE TABLE IF NOT EXISTS product.product_item_inventory ( CONSTRAINT uq_product_item_inventory_sku_id UNIQUE (sku_id) ); ALTER TABLE product.product_items - ALTER COLUMN id SET DEFAULT nextval('product.product_items_id_seq'); + ALTER COLUMN id DROP DEFAULT; ALTER TABLE product.product_items ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[]; -SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, false); CREATE INDEX IF NOT EXISTS idx_product_items_product_id ON product.product_items(product_id) WHERE deleted_at IS NULL; 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 ON product.product_items(sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; @@ -229,7 +222,7 @@ func (r *ProductRepository) CreateProductWithSKUs(ctx context.Context, product P } if product.LeafCategoryID != "" { - if err := insertCategoryBinding(ctx, tx, createdProduct.ID, product.LeafCategoryID); err != nil { + if err := insertCategoryBinding(ctx, tx, product.CategoryBindingID, createdProduct.ID, product.LeafCategoryID); err != nil { return nil, nil, err } } @@ -766,7 +759,11 @@ RETURNING id, sku_id, available_quantity, locked_quantity, sold_quantity, create return inventory, nil } -func insertCategoryBinding(ctx context.Context, tx *sql.Tx, productID, categoryID string) error { +func insertCategoryBinding(ctx context.Context, tx *sql.Tx, bindingID, productID, categoryID string) error { + parsedBindingID, err := parseID(bindingID, "category binding id") + if err != nil { + return err + } parsedProductID, err := parseID(productID, "product id") if err != nil { return err @@ -777,10 +774,10 @@ func insertCategoryBinding(ctx context.Context, tx *sql.Tx, productID, categoryI } _, err = tx.ExecContext(ctx, ` -INSERT INTO product.product_category_bindings (product_id, category_id) -VALUES ($1, $2) +INSERT INTO product.product_category_bindings (id, product_id, category_id) +VALUES ($1, $2, $3) ON CONFLICT (product_id, category_id) DO NOTHING -`, parsedProductID, parsedCategoryID) +`, parsedBindingID, parsedProductID, parsedCategoryID) if err != nil { return fmt.Errorf("insert category binding: %w", err) } diff --git a/internal/server/product_server.go b/internal/server/product_server.go index 3b262c7..3a5cfaf 100644 --- a/internal/server/product_server.go +++ b/internal/server/product_server.go @@ -73,6 +73,9 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create for i := range skus { skus[i].ID = s.idgen.NextString() } + if product.LeafCategoryID != "" { + product.CategoryBindingID = s.idgen.NextString() + } dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( attribute.String("product.spu_no", product.SPUNo), diff --git a/scripts/sql/recreate-product-tables.sql b/scripts/sql/recreate-product-tables.sql index 44490fc..43a2173 100644 --- a/scripts/sql/recreate-product-tables.sql +++ b/scripts/sql/recreate-product-tables.sql @@ -27,10 +27,6 @@ CREATE EXTENSION IF NOT EXISTS "pg_trgm"; CREATE SCHEMA IF NOT EXISTS product; -CREATE SEQUENCE IF NOT EXISTS product.products_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_items_id_seq; -CREATE SEQUENCE IF NOT EXISTS product.product_category_bindings_id_seq; - CREATE OR REPLACE FUNCTION public.set_updated_at() RETURNS TRIGGER AS $$ BEGIN @@ -40,7 +36,7 @@ END; $$ LANGUAGE plpgsql; CREATE TABLE IF NOT EXISTS product.products ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.products_id_seq'), + id BIGINT PRIMARY KEY, spu_no VARCHAR(100) NOT NULL, title VARCHAR(200) NOT NULL, selling_point VARCHAR(300), @@ -109,8 +105,6 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_products_spu_no ON product.products (spu_no) WHERE deleted_at IS NULL; -SELECT setval('product.products_id_seq', COALESCE((SELECT MAX(id) FROM product.products), 0) + 1, false); - CREATE TABLE IF NOT EXISTS product.product_category ( id BIGINT PRIMARY KEY, node_type SMALLINT NOT NULL DEFAULT 0, @@ -145,7 +139,7 @@ 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 DEFAULT nextval('product.product_category_bindings_id_seq'), + 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) @@ -159,10 +153,8 @@ COMMENT ON COLUMN product.product_category_bindings.category_id IS '绑定分类 CREATE INDEX IF NOT EXISTS idx_product_category_bindings_category_id ON product.product_category_bindings (category_id); -SELECT setval('product.product_category_bindings_id_seq', COALESCE((SELECT MAX(id) FROM product.product_category_bindings), 0) + 1, false); - CREATE TABLE IF NOT EXISTS product.product_items ( - id BIGINT PRIMARY KEY DEFAULT nextval('product.product_items_id_seq'), + 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, @@ -196,8 +188,6 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_product_items_sku_no ON product.product_items (sku_no) WHERE sku_no IS NOT NULL AND deleted_at IS NULL; -SELECT setval('product.product_items_id_seq', COALESCE((SELECT MAX(id) FROM product.product_items), 0) + 1, 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,