feat: integrate Snowflake ID generation for product and SKU creation

- Added a new ID generator using the Snowflake algorithm to create unique identifiers for products and SKUs.
- Updated the product server to utilize the ID generator for assigning IDs during product and SKU creation.
- Refactored the product repository to accommodate the new ID handling logic.
- Introduced unit tests for the ID generator to ensure correct functionality and error handling.
This commit is contained in:
robinj0726 2026-07-10 15:56:42 +08:00
parent 42419db604
commit 517f629d76
7 changed files with 112 additions and 12 deletions

View File

@ -20,6 +20,7 @@ import (
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" 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/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/observability"
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/server" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/server"
@ -70,6 +71,11 @@ func main() {
logger.Fatal("ensure product schema failed", zap.Error(err)) 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) metricsServer := observability.MetricsServer(cfg.MetricsPort, db.PingContext)
go func() { go func() {
logger.Info("metrics server listening", zap.String("addr", cfg.MetricsPort)) logger.Info("metrics server listening", zap.String("addr", cfg.MetricsPort))
@ -79,7 +85,7 @@ func main() {
} }
}() }()
productServer := server.NewProductServer(repo, logger, observer) productServer := server.NewProductServer(repo, idGenerator, logger, observer)
grpcServer := grpc.NewServer( grpcServer := grpc.NewServer(
grpc.StatsHandler(otelgrpc.NewServerHandler()), grpc.StatsHandler(otelgrpc.NewServerHandler()),

1
go.mod
View File

@ -5,6 +5,7 @@ go 1.26.4
replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto replace llms.idsbuybuybuy.com/ecommerce/ids-proto => ../ids-proto
require ( require (
github.com/bwmarrin/snowflake v0.3.0
github.com/jackc/pgx/v5 v5.10.0 github.com/jackc/pgx/v5 v5.10.0
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1
github.com/prometheus/client_golang v1.23.2 github.com/prometheus/client_golang v1.23.2

2
go.sum
View File

@ -1,5 +1,7 @@
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= 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/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 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= 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 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=

View 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)
}

View 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")
}
}

View File

@ -319,6 +319,10 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error
if err != nil { if err != nil {
return err return err
} }
skuID, err := parseID(sku.ID, "sku id")
if err != nil {
return err
}
tx, err := r.db.BeginTx(ctx, nil) tx, err := r.db.BeginTx(ctx, nil)
if err != nil { if err != nil {
@ -326,17 +330,16 @@ func (r *ProductRepository) CreateSKU(ctx context.Context, sku SKURecord) error
} }
defer tx.Rollback() defer tx.Rollback()
var id int64
err = tx.QueryRowContext(ctx, ` err = tx.QueryRowContext(ctx, `
INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status)
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)
RETURNING id RETURNING id
`, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&id) `, skuID, productID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)).Scan(&skuID)
if err != nil { if err != nil {
return fmt.Errorf("insert sku: %w", err) return fmt.Errorf("insert sku: %w", err)
} }
if _, err := upsertSKUInventory(ctx, tx, id, sku.AvailableQuantity); err != nil { if _, err := upsertSKUInventory(ctx, tx, skuID, sku.AvailableQuantity); err != nil {
return err return err
} }
@ -616,6 +619,10 @@ ORDER BY created_at ASC
} }
func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) { func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs []byte) (*ProductRecord, error) {
id, err := parseID(product.ID, "product id")
if err != nil {
return nil, err
}
brandID, err := nullableID(product.BrandID, "brand_id") brandID, err := nullableID(product.BrandID, "brand_id")
if err != nil { if err != nil {
return nil, err return nil, err
@ -630,6 +637,7 @@ func insertProduct(ctx context.Context, tx *sql.Tx, product ProductRecord, attrs
} }
row := tx.QueryRowContext(ctx, ` row := tx.QueryRowContext(ctx, `
INSERT INTO product.products ( INSERT INTO product.products (
id,
spu_no, spu_no,
title, title,
selling_point, selling_point,
@ -648,7 +656,7 @@ INSERT INTO product.products (
sale_time_type, sale_time_type,
scheduled_sale_time scheduled_sale_time
) )
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::jsonb, $13, $14, $15, $16, $17) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13::jsonb, $14, $15, $16, $17, $18)
RETURNING id, RETURNING id,
spu_no, spu_no,
title, title,
@ -670,7 +678,7 @@ RETURNING id,
deleted_at, deleted_at,
created_at, created_at,
updated_at updated_at
`, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs), `, id, product.SPUNo, product.Title, product.SellingPoint, brandID, supplierID, stringSliceOrEmpty(product.ImageIDs),
product.DetailHTML, product.MemberDiscountEnabled, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees), product.DetailHTML, product.MemberDiscountEnabled, int16(product.GoodsType), stringSliceOrEmpty(product.ServiceGuarantees),
statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID, statusToDB(product.Status), attrs, int16(product.FreightChargeType), product.FreightFixedAmount, freightTemplateID,
int16(product.SaleTimeType), product.ScheduledSaleTime) int16(product.SaleTimeType), product.ScheduledSaleTime)
@ -687,6 +695,10 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord)
if err != nil { if err != nil {
return nil, err return nil, err
} }
id, err := parseID(sku.ID, "sku id")
if err != nil {
return nil, err
}
parsedProductID, err := parseID(productID, "product id") parsedProductID, err := parseID(productID, "product id")
if err != nil { if err != nil {
@ -694,8 +706,8 @@ func insertSKU(ctx context.Context, tx *sql.Tx, productID string, sku SKURecord)
} }
row := tx.QueryRowContext(ctx, ` row := tx.QueryRowContext(ctx, `
INSERT INTO product.product_items (product_id, sku_no, name, price, image_ids, attributes, status) INSERT INTO product.product_items (id, product_id, sku_no, name, price, image_ids, attributes, status)
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8)
RETURNING id, RETURNING id,
product_id, product_id,
sku_no, sku_no,
@ -714,7 +726,7 @@ RETURNING id,
NULL::integer, NULL::integer,
NULL::timestamptz, NULL::timestamptz,
NULL::timestamptz NULL::timestamptz
`, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status)) `, id, parsedProductID, nullString(sku.SKUNo), sku.Name, sku.Price, stringSliceOrEmpty(sku.ImageIDs), attrs, int16(sku.Status))
createdSKU, err := scanSKU(row) createdSKU, err := scanSKU(row)
if err != nil { if err != nil {

View File

@ -20,6 +20,7 @@ import (
productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1" productv1 "llms.idsbuybuybuy.com/ecommerce/ids-proto/gen/go/ids/product/v1"
"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/observability"
"llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository" "llms.idsbuybuybuy.com/ecommerce/ids-svc-product/internal/repository"
) )
@ -34,12 +35,13 @@ type ProductServer struct {
productv1.UnimplementedProductServiceServer productv1.UnimplementedProductServiceServer
repo *repository.ProductRepository repo *repository.ProductRepository
idgen *idgen.Generator
logger *zap.Logger logger *zap.Logger
observer *observability.Observer observer *observability.Observer
} }
// NewProductServer constructs the gRPC product service handler. // NewProductServer constructs the gRPC product service handler.
func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger, observer *observability.Observer) *ProductServer { func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer) *ProductServer {
if logger == nil { if logger == nil {
logger = zap.NewNop() logger = zap.NewNop()
} }
@ -48,6 +50,7 @@ func NewProductServer(repo *repository.ProductRepository, logger *zap.Logger, ob
} }
return &ProductServer{ return &ProductServer{
repo: repo, repo: repo,
idgen: idGenerator,
logger: logger, logger: logger,
observer: observer, observer: observer,
} }
@ -63,6 +66,13 @@ func (s *ProductServer) CreateProduct(ctx context.Context, req *productv1.Create
if err != nil { if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error()) return nil, status.Error(codes.InvalidArgument, err.Error())
} }
if s.idgen == nil {
return nil, status.Error(codes.Internal, "id generator is not configured")
}
product.ID = s.idgen.NextString()
for i := range skus {
skus[i].ID = s.idgen.NextString()
}
dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes( dbCtx, dbSpan := s.observer.Tracer().Start(ctx, "product.create", trace.WithAttributes(
attribute.String("product.spu_no", product.SPUNo), attribute.String("product.spu_no", product.SPUNo),