feat(category): add batch category tree update with optimistic locking

This commit is contained in:
BXY 2026-08-12 09:35:46 +08:00
parent 0186633d73
commit d75d6e2112
3 changed files with 342 additions and 5 deletions

View File

@ -20,6 +20,8 @@ var ErrProductNotFound = errors.New("product not found")
// ErrCategoryNodeNotFound is returned when a category or product group node does not exist.
var ErrCategoryNodeNotFound = errors.New("category or group node not found")
var ErrCategoryVersionConflict = errors.New("category version conflict")
var ErrCategoryTreeConflict = errors.New("category tree conflict")
// ErrSKUNotFound is returned when a SKU does not exist.
var ErrSKUNotFound = errors.New("sku not found")
@ -214,6 +216,24 @@ type CategoryRecord struct {
ImageIDs []string
SortNum int32
Status int32
Version int32
}
// CategoryFieldUpdate selects mutable fields of one category node.
type CategoryFieldUpdate struct {
ID string
ExpectedVersion int32
Name *string
ImageIDs *[]string
SortNum *int32
Status *int32
}
// CategoryTreeUpdate groups an optional root update with direct-child updates.
type CategoryTreeUpdate struct {
CategoryID string
Category *CategoryFieldUpdate
Children []CategoryFieldUpdate
}
// ProductRepository provides CRUD access to product tables only [ARC-PROD-001].
@ -238,6 +258,21 @@ ALTER TABLE product.product_category_bindings
ALTER TABLE product.product_category
ADD COLUMN IF NOT EXISTS image_ids VARCHAR[] NOT NULL DEFAULT '{}'::VARCHAR[];
ALTER TABLE product.product_category
ADD COLUMN IF NOT EXISTS version INTEGER NOT NULL DEFAULT 0;
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'chk_product_category_version'
AND connamespace = 'product'::regnamespace
) THEN
ALTER TABLE product.product_category
ADD CONSTRAINT chk_product_category_version CHECK (version >= 0);
END IF;
END $$;
DO $$
BEGIN
IF EXISTS (
@ -428,6 +463,129 @@ func (r *ProductRepository) CreateCategoryNode(ctx context.Context, category Cat
return createdCategory, nil
}
// UpdateCategoryTrees applies all requested root and direct-child patches in a
// single transaction. Callers must supply already-validated patch fields.
func (r *ProductRepository) UpdateCategoryTrees(ctx context.Context, updates []CategoryTreeUpdate) error {
if len(updates) == 0 {
return errors.New("category_trees is required")
}
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin update category trees: %w", err)
}
defer tx.Rollback()
for _, tree := range updates {
root, err := loadCategoryForUpdate(ctx, tx, tree.CategoryID)
if err != nil {
return err
}
if root.NodeType != 0 || root.Level != 1 || root.ParentID != "" {
return ErrCategoryTreeConflict
}
if tree.Category != nil {
if tree.Category.ID != tree.CategoryID {
return ErrCategoryTreeConflict
}
if _, err := updateCategoryFields(ctx, tx, *tree.Category); err != nil {
return err
}
}
for _, child := range tree.Children {
current, err := loadCategoryForUpdate(ctx, tx, child.ID)
if err != nil {
return err
}
if current.NodeType != 0 || current.Level != 2 || current.ParentID != tree.CategoryID {
return ErrCategoryTreeConflict
}
if _, err := updateCategoryFields(ctx, tx, child); err != nil {
return err
}
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit update category trees: %w", err)
}
return nil
}
func loadCategoryForUpdate(ctx context.Context, tx *sql.Tx, categoryID string) (*CategoryRecord, error) {
id, err := parseID(categoryID, "category_id")
if err != nil {
return nil, err
}
row := tx.QueryRowContext(ctx, `
SELECT id, node_type, name, parent_id, level,
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version
FROM product.product_category
WHERE id = $1
FOR UPDATE`, id)
category, err := scanCategory(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrCategoryNodeNotFound
}
if err != nil {
return nil, fmt.Errorf("load category for update: %w", err)
}
return category, nil
}
func updateCategoryFields(ctx context.Context, tx *sql.Tx, update CategoryFieldUpdate) (*CategoryRecord, error) {
if update.Name == nil && update.ImageIDs == nil && update.SortNum == nil && update.Status == nil {
return nil, errors.New("category update has no fields")
}
id, err := parseID(update.ID, "category_id")
if err != nil {
return nil, err
}
row := tx.QueryRowContext(ctx, `
UPDATE product.product_category
SET name = CASE WHEN $3 THEN $4 ELSE name END,
image_ids = CASE WHEN $5 THEN $6 ELSE image_ids END,
sort_num = CASE WHEN $7 THEN $8 ELSE sort_num END,
status = CASE WHEN $9 THEN $10 ELSE status END,
version = version + 1
WHERE id = $1 AND version = $2
RETURNING id, node_type, name, parent_id, level,
COALESCE(to_json(image_ids)::text, '[]'), sort_num, status, version`,
id, update.ExpectedVersion,
update.Name != nil, stringValue(update.Name),
update.ImageIDs != nil, stringSliceOrEmpty(pointerStringSlice(update.ImageIDs)),
update.SortNum != nil, int32Value(update.SortNum),
update.Status != nil, int32Value(update.Status),
)
category, err := scanCategory(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrCategoryVersionConflict
}
if err != nil {
return nil, fmt.Errorf("update category fields: %w", err)
}
return category, nil
}
func stringValue(value *string) string {
if value == nil {
return ""
}
return *value
}
func int32Value(value *int32) int32 {
if value == nil {
return 0
}
return *value
}
func pointerStringSlice(value *[]string) []string {
if value == nil {
return nil
}
return *value
}
// AddProductsToGroup binds every product to the requested category or product group in one transaction.
// Existing bindings are retained and duplicate bindings are ignored.
func (r *ProductRepository) AddProductsToGroup(ctx context.Context, groupID string, bindingIDs, productIDs []string) error {
@ -1491,7 +1649,8 @@ SELECT id,
level,
COALESCE(to_json(image_ids)::text, '[]'),
sort_num,
status
status,
version
FROM product.product_category
WHERE node_type = 0
AND ($1 = false OR status = 1)
@ -1527,7 +1686,8 @@ SELECT id,
level,
COALESCE(to_json(image_ids)::text, '[]'),
sort_num,
status
status,
version
FROM product.product_category
WHERE node_type = 1
AND ($1 = false OR status = 1)
@ -1879,7 +2039,8 @@ RETURNING id,
level,
COALESCE(to_json(image_ids)::text, '[]'),
sort_num,
status
status,
version
`, id, int16(category.NodeType), category.Name, parentID, int16(category.Level), stringSliceOrEmpty(category.ImageIDs), category.SortNum, int16(category.Status))
createdCategory, err := scanCategory(row)
@ -2279,7 +2440,7 @@ func scanCategory(scanner rowScanner) (*CategoryRecord, error) {
status int16
)
if err := scanner.Scan(
&id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status,
&id, &nodeType, &rec.Name, &parentID, &level, &imageIDsJSON, &rec.SortNum, &status, &rec.Version,
); err != nil {
return nil, fmt.Errorf("scan category: %w", err)
}

View File

@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"time"
@ -17,6 +18,7 @@ import (
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/timestamppb"
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
@ -495,6 +497,51 @@ func (s *ProductServer) CreateCategoryTree(ctx context.Context, req *productv1.C
}, nil
}
// UpdateCategoryTrees atomically updates one or more top-level category trees.
func (s *ProductServer) UpdateCategoryTrees(ctx context.Context, req *productv1.UpdateCategoryTreesRequest) (*productv1.UpdateCategoryTreesResponse, error) {
if req == nil {
return nil, status.Error(codes.InvalidArgument, "request is required")
}
updates, rootIDs, err := categoryTreeUpdatesFromRequest(req)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.category_trees.update", trace.WithAttributes(attribute.Int("category.tree_count", len(updates))))
defer dbSpan.End()
if err := s.repo.UpdateCategoryTrees(dbCtx, updates); err != nil {
dbSpan.RecordError(err)
dbSpan.SetStatus(otelcodes.Error, err.Error())
switch {
case errors.Is(err, repository.ErrCategoryNodeNotFound):
return nil, status.Error(codes.NotFound, "category not found")
case errors.Is(err, repository.ErrCategoryVersionConflict):
return nil, status.Error(codes.Aborted, "category version conflict")
case errors.Is(err, repository.ErrCategoryTreeConflict):
return nil, status.Error(codes.FailedPrecondition, "child category does not belong to the specified top-level category")
default:
s.observer.Logger(ctx).Error("update category trees failed", zap.Error(err))
return nil, status.Error(codes.Internal, "update category trees")
}
}
all, err := s.repo.ListCategoryTreeNodes(dbCtx, false)
if err != nil {
return nil, status.Error(codes.Internal, "load updated category trees")
}
rootsByID := make(map[string]*productv1.CategoryNode)
for _, root := range buildCategoryTree(all) {
rootsByID[root.GetCategoryId()] = root
}
categories := make([]*productv1.CategoryNode, 0, len(rootIDs))
for _, rootID := range rootIDs {
root := rootsByID[rootID]
if root == nil {
return nil, status.Error(codes.Internal, "updated category tree is missing")
}
categories = append(categories, root)
}
return &productv1.UpdateCategoryTreesResponse{Categories: categories}, nil
}
// CreateGroup creates a top-level product group.
func (s *ProductServer) CreateGroup(ctx context.Context, req *productv1.CreateGroupRequest) (*productv1.CreateGroupResponse, error) {
if req == nil {
@ -751,6 +798,130 @@ func categoryTreeFromCreateRequest(req *productv1.CreateCategoryTreeRequest) (re
return parent, children, nil
}
func categoryTreeUpdatesFromRequest(req *productv1.UpdateCategoryTreesRequest) ([]repository.CategoryTreeUpdate, []string, error) {
if len(req.GetCategoryTrees()) == 0 {
return nil, nil, errors.New("category_trees is required")
}
updates := make([]repository.CategoryTreeUpdate, 0, len(req.GetCategoryTrees()))
rootIDs := make([]string, 0, len(req.GetCategoryTrees()))
seenRoots := make(map[string]struct{}, len(req.GetCategoryTrees()))
seenChildren := make(map[string]struct{})
for _, tree := range req.GetCategoryTrees() {
if tree == nil {
return nil, nil, errors.New("category_trees item is required")
}
rootID, err := normalizeCategoryID(tree.GetCategoryId(), "category_trees.category_id")
if err != nil {
return nil, nil, err
}
if _, exists := seenRoots[rootID]; exists {
return nil, nil, errors.New("category_trees.category_id must be unique")
}
seenRoots[rootID] = struct{}{}
update := repository.CategoryTreeUpdate{CategoryID: rootID}
if tree.GetCategory() != nil {
patch, err := categoryFieldUpdateFromProto(rootID, tree.GetCategory(), "category")
if err != nil {
return nil, nil, err
}
update.Category = patch
}
for _, child := range tree.GetChildCategories() {
if child == nil {
return nil, nil, errors.New("child_categories item is required")
}
childID, err := normalizeCategoryID(child.GetCategoryId(), "child_categories.category_id")
if err != nil {
return nil, nil, err
}
if _, exists := seenChildren[childID]; exists {
return nil, nil, errors.New("child category_id must not appear more than once")
}
seenChildren[childID] = struct{}{}
patch, err := categoryFieldUpdateFromProto(childID, child.GetPatch(), "child_categories.patch")
if err != nil {
return nil, nil, err
}
update.Children = append(update.Children, *patch)
}
if update.Category == nil && len(update.Children) == 0 {
return nil, nil, errors.New("category tree patch must update category or child_categories")
}
sort.Slice(update.Children, func(i, j int) bool { return update.Children[i].ID < update.Children[j].ID })
updates = append(updates, update)
rootIDs = append(rootIDs, rootID)
}
// A stable lock order avoids deadlocks when two edits overlap roots.
sort.Slice(updates, func(i, j int) bool { return updates[i].CategoryID < updates[j].CategoryID })
return updates, rootIDs, nil
}
func categoryFieldUpdateFromProto(id string, patch *productv1.CategoryFieldPatch, field string) (*repository.CategoryFieldUpdate, error) {
if patch == nil {
return nil, fmt.Errorf("%s is required", field)
}
paths, err := categoryUpdatePaths(patch.GetUpdateMask())
if err != nil {
return nil, fmt.Errorf("%s: %w", field, err)
}
if patch.GetExpectedVersion() < 0 {
return nil, fmt.Errorf("%s.expected_version must be non-negative", field)
}
update := &repository.CategoryFieldUpdate{ID: id, ExpectedVersion: patch.GetExpectedVersion()}
for _, path := range paths {
switch path {
case "name":
value, err := normalizeNodeName(patch.GetName(), field+".name")
if err != nil {
return nil, err
}
update.Name = &value
case "image_ids":
value := normalizeStringList(patch.GetImageIds())
update.ImageIDs = &value
case "sort_num":
value := patch.GetSortNum()
update.SortNum = &value
case "status":
value := patch.GetStatus()
if value != 0 && value != 1 {
return nil, fmt.Errorf("%s.status must be 0 or 1", field)
}
update.Status = &value
}
}
return update, nil
}
func categoryUpdatePaths(mask *fieldmaskpb.FieldMask) ([]string, error) {
if mask == nil || len(mask.GetPaths()) == 0 {
return nil, errors.New("update_mask is required")
}
allowed := map[string]struct{}{"name": {}, "image_ids": {}, "sort_num": {}, "status": {}}
paths := make([]string, 0, len(mask.GetPaths()))
seen := make(map[string]struct{}, len(mask.GetPaths()))
for _, path := range mask.GetPaths() {
if _, ok := allowed[path]; !ok {
return nil, fmt.Errorf("unsupported update path %q", path)
}
if _, duplicate := seen[path]; duplicate {
return nil, fmt.Errorf("duplicate update path %q", path)
}
seen[path] = struct{}{}
paths = append(paths, path)
}
return paths, nil
}
func normalizeCategoryID(value, field string) (string, error) {
trimmed := strings.TrimSpace(value)
id, err := strconv.ParseInt(trimmed, 10, 64)
if err != nil || id <= 0 {
return "", fmt.Errorf("%s must be a positive snowflake id", field)
}
return trimmed, nil
}
func groupFromCreateRequest(req *productv1.CreateGroupRequest) (repository.CategoryRecord, error) {
name, err := normalizeNodeName(req.GetName(), "name")
if err != nil {
@ -1455,6 +1626,7 @@ func toProtoCategoryNode(category *repository.CategoryRecord) *productv1.Categor
ImageJson: categoryImageIDsJSON(category.ImageIDs),
SortNum: category.SortNum,
Status: category.Status,
Version: category.Version,
Children: []*productv1.CategoryNode{},
}
}

View File

@ -118,12 +118,15 @@ CREATE TABLE IF NOT EXISTS product.product_category (
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 (0, 1)),
CONSTRAINT chk_product_category_level
CHECK (level > 0),
CONSTRAINT chk_product_category_status
CHECK (status IN (0, 1))
CHECK (status IN (0, 1)),
CONSTRAINT chk_product_category_version
CHECK (version >= 0)
);
COMMENT ON TABLE product.product_category IS '商品类别表:存储商品分类和商品分组,通过 node_type 区分分类或分组';
@ -135,6 +138,7 @@ COMMENT ON COLUMN product.product_category.level IS '节点层级,如 1、2、
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);