feat: remove S3 public endpoint configuration and related logic from the project

This commit is contained in:
BXY 2026-10-09 16:46:27 +08:00
parent 86bdac8b72
commit e2e14ae337
7 changed files with 28 additions and 170 deletions

View File

@ -7,10 +7,6 @@ POSTGRES_DB=ids_ecommerce
POSTGRES_SCHEMA=product
POSTGRES_SSLMODE=disable
NATS_URL=nats://localhost:4222
# Must match ids-svc-storage's public signing endpoint. It is used only when
# returning storage-relative images embedded in product detail_html.
S3_PUBLIC_ENDPOINT=http://localhost:9000
METRICS_PORT=:9102
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
OTEL_EXPORTER_OTLP_INSECURE=true

View File

@ -250,7 +250,6 @@ cp .env.example .env
| `POSTGRES_SCHEMA` | `product` | 搜索路径 |
| `POSTGRES_SSLMODE` | `disable` | SSL 模式 |
| `NATS_URL` | `nats://localhost:4222` | 预留事件总线地址(首版查询链路不依赖) |
| `S3_PUBLIC_ENDPOINT` | `http://localhost:9000` | 存储服务对外媒体域名;须与 `ids-svc-storage` 同值。商品详情返回时会用它补全 `/ids-storage/...` 图片地址。 |
| `METRICS_PORT` | `:9102` | Prometheus 指标与 HTTP 健康检查监听地址 |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `http://localhost:4318` | OTLP HTTP trace exporter 地址 |
| `OTEL_EXPORTER_OTLP_INSECURE` | `true` | OTLP exporter 是否使用明文连接 |

View File

@ -86,9 +86,7 @@ func main() {
}
}()
productServer := server.NewProductServer(repo, idGenerator, logger, observer,
server.WithDetailHTMLAssetOrigin(cfg.S3PublicEndpoint),
)
productServer := server.NewProductServer(repo, idGenerator, logger, observer)
server.StartScheduledSaleWorker(ctx, repo, logger, time.Minute)
grpcServer := grpc.NewServer(

View File

@ -16,7 +16,6 @@ services:
POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-product}
POSTGRES_SSLMODE: ${POSTGRES_SSLMODE:-disable}
NATS_URL: nats://nats:4222
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT}
METRICS_PORT: ":9102"
OTEL_EXPORTER_OTLP_ENDPOINT: http://ids-tempo:4318
OTEL_EXPORTER_OTLP_INSECURE: "true"

View File

@ -5,7 +5,6 @@ import (
"fmt"
"net/url"
"os"
"strings"
"github.com/joho/godotenv"
)
@ -22,7 +21,6 @@ const (
defaultMetricsPort = ":9102"
defaultOTLPEndpoint = "http://localhost:4318"
defaultEnvironment = "development"
defaultS3PublicEndpoint = "http://localhost:9000"
)
// Config holds runtime configuration loaded from environment variables.
@ -34,9 +32,6 @@ type Config struct {
OTLPEndpoint string
OTELInsecure bool
Environment string
// S3PublicEndpoint is the public media origin used when product rich-text
// contains a storage-relative image URL. It must match ids-svc-storage.
S3PublicEndpoint string
}
// LoadConfig loads .env when present and assembles configuration from environment variables.
@ -49,11 +44,6 @@ func LoadConfig() (*Config, error) {
if err != nil {
return nil, err
}
s3PublicEndpoint, err := publicMediaOrigin(getEnv("S3_PUBLIC_ENDPOINT", defaultS3PublicEndpoint))
if err != nil {
return nil, fmt.Errorf("invalid S3_PUBLIC_ENDPOINT: %w", err)
}
return &Config{
ServerPort: getEnv("SERVER_PORT", defaultServerPort),
PostgresDSN: dsn,
@ -62,29 +52,9 @@ func LoadConfig() (*Config, error) {
OTLPEndpoint: getEnv("OTEL_EXPORTER_OTLP_ENDPOINT", defaultOTLPEndpoint),
OTELInsecure: getEnv("OTEL_EXPORTER_OTLP_INSECURE", "true") == "true",
Environment: getEnv("DEPLOYMENT_ENVIRONMENT", defaultEnvironment),
S3PublicEndpoint: s3PublicEndpoint,
}, nil
}
// publicMediaOrigin accepts an absolute HTTP(S) origin only. Relative paths,
// credentials, queries and fragments make signed media URL rewriting ambiguous.
func publicMediaOrigin(raw string) (string, error) {
parsed, err := url.Parse(strings.TrimSpace(raw))
if err != nil {
return "", err
}
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return "", errors.New("must use http or https")
}
if parsed.Host == "" {
return "", errors.New("host is required")
}
if parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") {
return "", errors.New("must be an origin without credentials, path, query, or fragment")
}
return strings.TrimRight(parsed.String(), "/"), nil
}
func buildPostgresDSN() (string, error) {
if dsn := os.Getenv("POSTGRES_DSN"); dsn != "" {
return dsn, nil

View File

@ -1,78 +0,0 @@
package server
import (
"io"
"strings"
"golang.org/x/net/html"
)
var detailHTMLStorageImagePrefixes = []string{
"/ids-storage/material-images/",
"/ids-storage/catalog/",
}
// completeDetailHTMLImageURLs completes only known storage-relative image
// paths. It deliberately leaves the query string untouched because it can
// contain a SigV4 signature whose encoding and parameter order are sensitive.
// Invalid HTML is returned unchanged so a read response never damages data.
func completeDetailHTMLImageURLs(raw, assetOrigin string) string {
assetOrigin = strings.TrimRight(strings.TrimSpace(assetOrigin), "/")
if raw == "" || assetOrigin == "" || !strings.Contains(strings.ToLower(raw), "<img") {
return raw
}
parser := html.NewTokenizer(strings.NewReader(raw))
var output strings.Builder
output.Grow(len(raw) + len(assetOrigin))
changed := false
for {
tokenType := parser.Next()
if tokenType == html.ErrorToken {
if parser.Err() == io.EOF && changed {
return output.String()
}
return raw
}
rawToken := parser.Raw()
if tokenType != html.StartTagToken && tokenType != html.SelfClosingTagToken {
output.Write(rawToken)
continue
}
token := parser.Token()
if !strings.EqualFold(token.Data, "img") {
output.Write(rawToken)
continue
}
tokenChanged := false
for index := range token.Attr {
if !strings.EqualFold(token.Attr[index].Key, "src") {
continue
}
if !isDetailHTMLStorageImagePath(token.Attr[index].Val) {
continue
}
token.Attr[index].Val = assetOrigin + token.Attr[index].Val
tokenChanged = true
changed = true
}
if tokenChanged {
output.WriteString(token.String())
} else {
output.Write(rawToken)
}
}
}
func isDetailHTMLStorageImagePath(src string) bool {
for _, prefix := range detailHTMLStorageImagePrefixes {
if strings.HasPrefix(src, prefix) {
return true
}
}
return false
}

View File

@ -53,40 +53,22 @@ type ProductServer struct {
idgen *idgen.Generator
logger *zap.Logger
observer *observability.Observer
detailHTMLAssetOrigin string
}
// ProductServerOption customizes ProductServer behavior.
type ProductServerOption func(*ProductServer)
// WithDetailHTMLAssetOrigin configures the public origin used to complete
// storage-relative image URLs in product detail_html response fields.
func WithDetailHTMLAssetOrigin(origin string) ProductServerOption {
return func(s *ProductServer) {
s.detailHTMLAssetOrigin = strings.TrimRight(strings.TrimSpace(origin), "/")
}
}
// NewProductServer constructs the gRPC product service handler.
func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer, options ...ProductServerOption) *ProductServer {
func NewProductServer(repo *repository.ProductRepository, idGenerator *idgen.Generator, logger *zap.Logger, observer *observability.Observer) *ProductServer {
if logger == nil {
logger = zap.NewNop()
}
if observer == nil {
observer = observability.NewNoop(logger)
}
server := &ProductServer{
return &ProductServer{
repo: repo,
idgen: idGenerator,
logger: logger,
observer: observer,
}
for _, option := range options {
if option != nil {
option(server)
}
}
return server
}
// CreateProduct creates a product SPU and optional SKU list.
@ -205,7 +187,7 @@ func (s *ProductServer) GetProduct(ctx context.Context, req *productv1.GetProduc
}
return &productv1.GetProductResponse{
Product: s.toProtoProduct(product, skus),
Product: toProtoProduct(product, skus),
}, nil
}
@ -282,7 +264,7 @@ func (s *ProductServer) GetProductBySku(ctx context.Context, req *productv1.GetP
}
return &productv1.GetProductResponse{
Product: s.toProtoProduct(product, skus),
Product: toProtoProduct(product, skus),
}, nil
}
@ -479,7 +461,7 @@ func (s *ProductServer) UpdateProduct(ctx context.Context, req *productv1.Update
return nil, status.Errorf(codes.Internal, "load updated product: %v", err)
}
return &productv1.UpdateProductResponse{
Product: s.toProtoProduct(updated, skus),
Product: toProtoProduct(updated, skus),
SkuChangeResult: toProtoSKUChangeResult(result),
}, nil
}
@ -2638,14 +2620,6 @@ func toProtoProduct(product *repository.ProductRecord, skus []repository.SKUReco
}
}
func (s *ProductServer) toProtoProduct(product *repository.ProductRecord, skus []repository.SKURecord) *productv1.Product {
result := toProtoProduct(product, skus)
if result != nil {
result.DetailHtml = completeDetailHTMLImageURLs(result.GetDetailHtml(), s.detailHTMLAssetOrigin)
}
return result
}
func toProtoCartItemProduct(lineID string, record repository.CartItemProductRecord) *productv1.CartItemProduct {
result := &productv1.CartItemProduct{
LineId: lineID,