Compare commits

...
Author SHA1 Message Date
lixu c9563a83d0 Merge pull request 'feat(bypos-collector): 跨次去重、重试、导入 Goods 等采集器改进(取代 #24)' (#59) from devin/1793411261-goods-24-collector-improvements into main 2026-10-31 09:51:55 +08:00
z8jd98andDevin AI a72366566e feat(bypos-collector): 跨次去重、重试、CSV 补全、端口自动选择、Windows 日志和一键导入(取代 #24)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 01:48:15 +00:00
lixu c163f2b741 Merge pull request 'docs: 完善 README,移除未使用的 MinIO,修正 openapi 路径 (#48)' (#58) from devin/1793408463-goods-48-docs-minio into main 2026-10-31 09:45:44 +08:00
lixu 08140d7c6b Merge pull request 'test(admin): 补充后台接口测试,修复 bypos 导入不认 JSON 数组 (#47)' (#57) from devin/1793408183-goods-47-admin-api-tests into main 2026-10-31 09:45:39 +08:00
lixu 44d0bfc217 Merge pull request 'feat(api): HTTP 服务补齐超时并支持优雅退出 (#46)' (#56) from devin/1793408086-goods-46-graceful-shutdown into main 2026-10-31 09:45:33 +08:00
lixu 17eb6c134e Merge pull request 'fix(api): 公开投稿限流器定期清理过期记录 (#44)' (#54) from devin/1793407948-goods-44-submission-rate-prune into main 2026-10-31 09:45:29 +08:00
z8jd98andDevin AI 8779f0fe81 docs: document trusted proxy configuration
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 01:40:02 +00:00
z8jd98 04112c4fd2 Merge remote-tracking branch 'origin/main' into devin/1793408463-goods-48-docs-minio 2026-10-31 01:39:53 +00:00
z8jd98 4901a9cb10 Merge remote-tracking branch 'origin/main' into devin/1793408183-goods-47-admin-api-tests 2026-10-31 01:39:51 +00:00
z8jd98 3172928306 Merge remote-tracking branch 'origin/main' into devin/1793408086-goods-46-graceful-shutdown
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

# Conflicts:
#	api/cmd/admin/main.go
#	api/cmd/server/main.go
2026-10-31 01:39:49 +00:00
z8jd98 62bc2c6fda Merge remote-tracking branch 'origin/main' into devin/1793407948-goods-44-submission-rate-prune 2026-10-31 01:39:20 +00:00
lixu 9ee2d39833 Merge pull request 'fix(api): 回流接口按 API key 限速,500 不再返回内部错误 (#43)' (#53) from devin/1793407831-goods-43-backflow-rate-safe-errors into main
Merge pull request 'fix(api): 回流接口按 API key 限速,500 不再返回内部错误 (#43)' (#53)
2026-10-31 09:30:54 +08:00
fu500fandDevin AI b6c463beab 合并最新 main
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 01:29:55 +00:00
lixu 1c78422ddd Merge pull request 'feat(admin): 登录防暴力破解、登录审计和服务端退出 (#42)' (#52) from devin/1793407649-goods-42-admin-login-hardening into main
Merge pull request 'feat(admin): 登录防暴力破解、登录审计和服务端退出 (#42)' (#52)
2026-10-31 09:28:50 +08:00
fu500fandDevin AI b4c3e22707 合并最新 main
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 01:27:10 +00:00
lixu 7693a80513 Merge pull request 'build(api): 升级 Go 1.27 与依赖,修复 5 个已知漏洞 (#41)' (#51) from devin/1793407570-goods-41-go-dependency-upgrade into main
Merge pull request 'build(api): 升级 Go 1.27 与依赖,修复 5 个已知漏洞 (#41)' (#51)
2026-10-31 09:26:27 +08:00
fu500f 8de947c4f2 合并最新 main 2026-10-31 01:24:55 +00:00
lixu f92d810605 Merge pull request 'fix(api): 后台写操作成功后刷新公开 API 缓存 (#40)' (#50) from devin/1793407455-goods-40-cache-invalidation into main
Merge pull request 'fix(api): 后台写操作成功后刷新公开 API 缓存 (#40)' (#50)
2026-10-31 09:24:34 +08:00
fu500fandDevin AI 9091dfd4c5 合并最新 main
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 01:23:44 +00:00
lixu 94549c8e2a Merge pull request 'fix(api): 客户端 IP 只信任可信代理设置的头 (#39)' (#49) from devin/1793407315-goods-39-trusted-proxy into main
Merge pull request 'fix(api): 客户端 IP 只信任可信代理设置的头 (#39)' (#49)
2026-10-31 09:22:44 +08:00
fu500f d33f74fe74 合并最新 main 2026-10-31 01:21:48 +00:00
lixu b043b9e91f Merge pull request 'fix(api): 限制公开搜索和品牌列表翻页深度 (#45)' (#55) from devin/1793407986-goods-45-search-result-window into main
Merge pull request 'fix(api): 限制公开搜索和品牌列表翻页深度 (#45)' (#55)
2026-10-31 09:20:15 +08:00
fu500fandDevin AI 007fc7b938 docs: 完善 README,移除未使用的 MinIO,修正 openapi 路径 (#48)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 01:01:59 +00:00
fu500fandDevin AI 2e88efd604 fix(admin): bypos 导入同时支持 JSON 数组和 JSONL (#47)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 01:00:55 +00:00
fu500fandDevin AI 003543d6e2 test(admin): 补充后台接口数据库测试 (#47)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:59:06 +00:00
fu500fandDevin AI 3aaa7b1d0c feat(api): 增加服务优雅关闭与超时配置 (#46)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:56:16 +00:00
fu500fandDevin AI 124f14b509 fix(api): 限制公开接口分页结果窗口 (#45)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:54:37 +00:00
fu500fandDevin AI 31e1a8977b fix(api): 清理投稿限流器的过期 IP 记录 (#44)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:52:56 +00:00
fu500fandDevin AI 8a29423451 fix(api): 限制回流频率并隐藏后台错误详情 (#43)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:52:20 +00:00
fu500fandDevin AI 065198f227 feat(admin): 增加登录限流、审计与令牌退出 (#42)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:50:23 +00:00
fu500fandDevin AI 45213805df build(api): 升级 Go 与依赖修复安全漏洞 (#41)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:47:21 +00:00
fu500fandDevin AI d0ad1b85f3 fix(api): 管理后台成功写入后递增缓存代次 (#40)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:45:55 +00:00
fu500fandDevin AI 667e6d0f00 fix(api): 仅信任配置的反向代理转发客户端 IP (#39)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-31 00:44:04 +00:00
lixu 36f9c95fa7 Merge pull request 'feat(public): 首页改为极简谷歌风格' (#38) from devin/1782372352-home-mobile-center into main
CI / Go (api) (push) Successful in 1m10s
CI / Python (ingestion) (push) Successful in 19s
CI / Migrations (postgres) (push) Successful in 26s
2026-06-25 18:11:18 +08:00
lixu 9ee83e3535 feat(public): 首页改为极简谷歌风格
CI / Go (api) (pull_request) Successful in 54s
CI / Python (ingestion) (pull_request) Successful in 16s
CI / Migrations (postgres) (pull_request) Successful in 27s
2026-06-25 10:08:56 +00:00
lixu 53ade9eeea Merge pull request 'feat(public): 首页搜索居中、移动端自适应,移除下方三卡片' (#37) from devin/1782372352-home-mobile-center into main
CI / Go (api) (push) Successful in 56s
CI / Python (ingestion) (push) Successful in 23s
CI / Migrations (postgres) (push) Successful in 27s
2026-06-25 15:28:54 +08:00
lixu 313bc84cb0 feat(public): 首页搜索居中、移动端自适应,移除下方三卡片
CI / Go (api) (pull_request) Successful in 52s
CI / Python (ingestion) (pull_request) Successful in 25s
CI / Migrations (postgres) (pull_request) Successful in 29s
2026-06-25 07:25:52 +00:00
lixu 8c8df2b8a2 Merge pull request 'fix(admin): 回流接口校验/规范化 GTIN' (#36) from devin/1782352663-backflow-gtin-validate into main
CI / Go (api) (push) Successful in 1m7s
CI / Python (ingestion) (push) Successful in 24s
CI / Migrations (postgres) (push) Successful in 25s
2026-06-25 10:00:29 +08:00
busenalbantoglu51424 f04891d0b9 fix(admin): 回流接口校验/规范化 GTIN,非法条码标记 invalid 而非中断批次
CI / Go (api) (pull_request) Successful in 56s
CI / Python (ingestion) (pull_request) Successful in 28s
CI / Migrations (postgres) (pull_request) Successful in 29s
2026-06-25 01:57:43 +00:00
lixu 3a5575f51b Merge pull request 'feat(admin): 新增档案回流接口 POST /api/public/backflow' (#35) from devin/1782350840-backflow-api into main
CI / Go (api) (push) Successful in 53s
CI / Python (ingestion) (push) Successful in 28s
CI / Migrations (postgres) (push) Successful in 47s
2026-06-25 09:52:43 +08:00
49 changed files with 2515 additions and 341 deletions
+5 -2
View File
@@ -3,10 +3,13 @@
POSTGRES_USER=opengoods POSTGRES_USER=opengoods
POSTGRES_PASSWORD=change-me POSTGRES_PASSWORD=change-me
POSTGRES_DB=opengoods POSTGRES_DB=opengoods
MINIO_ROOT_USER=opengoods
MINIO_ROOT_PASSWORD=change-me # Empty uses loopback and private-network defaults; use "none" to trust no proxies.
OPENGOODS_TRUSTED_PROXIES=
# Admin console (served at /ping). Set a strong password and a random JWT secret. # Admin console (served at /ping). Set a strong password and a random JWT secret.
GOODS_ADMIN_USER=admin GOODS_ADMIN_USER=admin
GOODS_ADMIN_PASSWORD=change-me GOODS_ADMIN_PASSWORD=change-me
GOODS_ADMIN_JWT_SECRET=change-me-to-a-long-random-string GOODS_ADMIN_JWT_SECRET=change-me-to-a-long-random-string
GOODS_BACKFLOW_RATE_PER_HOUR=30
GOODS_ADMIN_TOKEN_TTL=12h
+1 -1
View File
@@ -6,7 +6,7 @@ on:
pull_request: pull_request:
env: env:
GO_VERSION: "1.23.12" GO_VERSION: "1.27.3"
GOPROXY: "https://goproxy.cn,direct" GOPROXY: "https://goproxy.cn,direct"
jobs: jobs:
+108 -2
View File
@@ -1,2 +1,108 @@
# goods # OpenGoods
商品档案公开API
OpenGoods(天工·商品标签)提供公开、只读的商品事实 API,并配套运营后台和数据采集工具。项目整理商品名称、品牌、品类、条码、配料、营养成分、产地等客观信息,不提供购买或交易功能。
## 项目组成
- **公开 API**:Go 服务,提供商品搜索、品牌和商品详情等只读接口。
- **运营后台**:独立的 Go 管理服务,提供登录、商品维护、投稿审核、API Key 和导入功能。
- **数据采集**:`ingestion/` 是 Python 采集与 ETL 包;`tools/bypos-collector/` 包含 BYPOS 采集工具。
- **前端**:`public-frontend/` 是公开站点,`admin-frontend/` 是运营后台界面;两者均使用 React、Vite 和 TypeScript。
- **数据库迁移**:`migrations/` 保存 PostgreSQL schema 的正向与回滚迁移。
## API 与文档
- API 使用说明:[`docs/api.md`](docs/api.md)
- OpenAPI 规范源文件:[`api/internal/handler/openapi.json`](api/internal/handler/openapi.json)
- 数据契约:[`docs/data-contract.md`](docs/data-contract.md)
- 采集说明:[`docs/etl-openfoodfacts.md`](docs/etl-openfoodfacts.md) 和 [`docs/ingestion-management.md`](docs/ingestion-management.md)
- 部署指南:[`docs/deploy.md`](docs/deploy.md)
运行中的公开服务也通过 `GET /api/v1/openapi.json` 提供机器可读规范。
## 本地开发
需要 Go(版本要求见 `api/go.mod`)、Docker Compose、Node.js/npm,以及 Python 3.11 或更新版本(用于采集侧开发)。
启动 PostgreSQL 和 Redis:
```bash
docker compose up -d postgres redis
```
安装迁移工具并应用数据库迁移:
```bash
go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@v4.18.1
migrate -path migrations \
-database 'postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable' up
```
启动公开 API:
```bash
cd api
export OPENGOODS_DATABASE_URL='postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable'
export OPENGOODS_REDIS_URL='redis://localhost:6379/0'
go run ./cmd/server
```
在另一个终端启动运营后台(本地示例凭据请自行替换):
```bash
cd api
export OPENGOODS_DATABASE_URL='postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable'
export OPENGOODS_REDIS_URL='redis://localhost:6379/0'
export GOODS_ADMIN_ADDR=':8081'
export GOODS_ADMIN_USER='admin'
export GOODS_ADMIN_PASSWORD='local-development-password'
export GOODS_ADMIN_JWT_SECRET='local-development-secret-change-before-use'
go run ./cmd/admin
```
前端可在各自目录启动 Vite 开发服务器(分别在两个终端运行):
```bash
cd public-frontend
npm install
npm run dev
```
```bash
cd admin-frontend
npm install
npm run dev
```
## 测试与构建
Go API:
```bash
cd api
test -z "$(gofmt -l .)"
go vet ./...
go build ./...
go test ./...
```
Python 采集侧:
```bash
cd ingestion
pip install -e ".[dev]"
ruff check .
ruff format --check .
pytest -q
```
前端构建:
```bash
(cd public-frontend && npm install && npm run build)
(cd admin-frontend && npm install && npm run build)
```
生产部署步骤、环境变量和反向代理配置见[部署文档](docs/deploy.md)。
可信代理通过 `OPENGOODS_TRUSTED_PROXIES` 配置;支持格式与默认行为见部署指南。
+2 -1
View File
@@ -59,7 +59,8 @@ export default function App() {
setView({ name: "list" }); setView({ name: "list" });
} }
function logout() { async function logout() {
await api.logout().catch(() => undefined);
clearToken(); clearToken();
setAuthed(false); setAuthed(false);
setUsername(""); setUsername("");
+1
View File
@@ -50,6 +50,7 @@ export const api = {
method: "POST", method: "POST",
body: JSON.stringify({ username, password }), body: JSON.stringify({ username, password }),
}), }),
logout: () => request<void>("/logout", { method: "POST" }),
me: () => request<{ username: string }>("/me"), me: () => request<{ username: string }>("/me"),
listProducts: ( listProducts: (
q: string, q: string,
+1 -1
View File
@@ -1,5 +1,5 @@
# Build stage # Build stage
FROM golang:1.23-alpine AS build FROM golang:1.27-alpine AS build
WORKDIR /src WORKDIR /src
COPY go.mod go.sum ./ COPY go.mod go.sum ./
RUN go mod download RUN go mod download
+1 -1
View File
@@ -11,7 +11,7 @@ COPY admin-frontend/ ./
RUN npm run build RUN npm run build
# Stage 2: build the Go admin binary with the SPA embedded. # Stage 2: build the Go admin binary with the SPA embedded.
FROM golang:1.23-alpine AS build FROM golang:1.27-alpine AS build
ENV GOPROXY=https://goproxy.cn,direct ENV GOPROXY=https://goproxy.cn,direct
WORKDIR /src WORKDIR /src
COPY api/go.mod api/go.sum ./ COPY api/go.mod api/go.sum ./
+1 -1
View File
@@ -13,7 +13,7 @@ COPY public-frontend/ ./
RUN npm run build RUN npm run build
# Stage 2: build the Go server binary with the SPA embedded. # Stage 2: build the Go server binary with the SPA embedded.
FROM golang:1.23-alpine AS build FROM golang:1.27-alpine AS build
ENV GOPROXY=https://goproxy.cn,direct ENV GOPROXY=https://goproxy.cn,direct
WORKDIR /src WORKDIR /src
COPY api/go.mod api/go.sum ./ COPY api/go.mod api/go.sum ./
+60 -9
View File
@@ -8,6 +8,9 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"os/signal"
"strconv"
"syscall"
"time" "time"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
@@ -17,6 +20,8 @@ import (
"github.com/baicai2026-baicai/goods/api/internal/adminstore" "github.com/baicai2026-baicai/goods/api/internal/adminstore"
"github.com/baicai2026-baicai/goods/api/internal/adminweb" "github.com/baicai2026-baicai/goods/api/internal/adminweb"
"github.com/baicai2026-baicai/goods/api/internal/auth" "github.com/baicai2026-baicai/goods/api/internal/auth"
"github.com/baicai2026-baicai/goods/api/internal/cache"
"github.com/baicai2026-baicai/goods/api/internal/clientip"
"github.com/baicai2026-baicai/goods/api/internal/ratelimit" "github.com/baicai2026-baicai/goods/api/internal/ratelimit"
) )
@@ -32,6 +37,24 @@ func main() {
dbURL := getenv("OPENGOODS_DATABASE_URL", "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable") dbURL := getenv("OPENGOODS_DATABASE_URL", "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable")
basePath := getenv("GOODS_ADMIN_BASE_PATH", "/ping") basePath := getenv("GOODS_ADMIN_BASE_PATH", "/ping")
username := getenv("GOODS_ADMIN_USER", "admin") username := getenv("GOODS_ADMIN_USER", "admin")
backflowRate, err := strconv.Atoi(getenv("GOODS_BACKFLOW_RATE_PER_HOUR", "30"))
if err != nil || backflowRate < 1 {
log.Fatalf("invalid GOODS_BACKFLOW_RATE_PER_HOUR: must be a positive integer")
}
tokenTTL := 12 * time.Hour
if value := os.Getenv("GOODS_ADMIN_TOKEN_TTL"); value != "" {
parsed, err := time.ParseDuration(value)
if err != nil || parsed <= 0 {
log.Fatalf("invalid GOODS_ADMIN_TOKEN_TTL %q: expected a positive duration", value)
}
tokenTTL = parsed
}
clientIPs, err := clientip.Parse(getenv("OPENGOODS_TRUSTED_PROXIES", ""))
if err != nil {
log.Fatalf("invalid OPENGOODS_TRUSTED_PROXIES: %v", err)
}
runCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// Password: prefer a bcrypt hash; otherwise hash a plaintext password. // Password: prefer a bcrypt hash; otherwise hash a plaintext password.
var passwordHash []byte var passwordHash []byte
@@ -56,31 +79,59 @@ func main() {
log.Print("warning: GOODS_ADMIN_JWT_SECRET not set; using a random secret (tokens invalidate on restart)") log.Print("warning: GOODS_ADMIN_JWT_SECRET not set; using a random secret (tokens invalidate on restart)")
} }
ctx := context.Background() pool, err := pgxpool.New(context.Background(), dbURL)
pool, err := pgxpool.New(ctx, dbURL)
if err != nil { if err != nil {
log.Fatalf("failed to create db pool: %v", err) log.Fatalf("failed to create db pool: %v", err)
} }
defer pool.Close()
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) pingCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() defer cancel()
if err := pool.Ping(pingCtx); err != nil { if err := pool.Ping(pingCtx); err != nil {
log.Printf("warning: database not reachable at startup: %v", err) log.Printf("warning: database not reachable at startup: %v", err)
} }
authn := auth.New(username, passwordHash, secret, 12*time.Hour) authn := auth.New(username, passwordHash, secret, tokenTTL)
usage := ratelimit.New(getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0")) redisURL := getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0")
usage := ratelimit.New(redisURL)
readCache := cache.New(redisURL)
h := adminhandler.New(adminstore.New(pool), authn, basePath, adminweb.Dist()). h := adminhandler.New(adminstore.New(pool), authn, basePath, adminweb.Dist()).
WithUsage(usage) WithUsage(usage).
WithBackflowRate(backflowRate).
WithCache(readCache).
WithClientIP(clientIPs)
srv := &http.Server{ srv := &http.Server{
Addr: addr, Addr: addr,
Handler: h.Router(), Handler: h.Router(),
ReadHeaderTimeout: 10 * time.Second, ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 120 * time.Second,
} }
log.Printf("OpenGoods admin console listening on %s (base path %s)", addr, basePath) log.Printf("OpenGoods admin console listening on %s (base path %s)", addr, basePath)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { serverErr := make(chan error, 1)
log.Fatalf("server error: %v", err) go func() {
serverErr <- srv.ListenAndServe()
}()
select {
case err := <-serverErr:
pool.Close()
if err != nil && err != http.ErrServerClosed {
log.Fatalf("server error: %v", err)
}
case <-runCtx.Done():
log.Print("shutdown signal received")
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 25*time.Second)
err := srv.Shutdown(shutdownCtx)
shutdownCancel()
if err != nil {
log.Printf("server shutdown: %v", err)
}
pool.Close()
if err := <-serverErr; err != nil && err != http.ErrServerClosed {
log.Printf("server error after shutdown: %v", err)
}
log.Print("OpenGoods admin console shutdown complete")
} }
} }
+41 -7
View File
@@ -5,11 +5,15 @@ import (
"context" "context"
"log" "log"
"net/http" "net/http"
"os"
"os/signal"
"syscall"
"time" "time"
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"github.com/baicai2026-baicai/goods/api/internal/cache" "github.com/baicai2026-baicai/goods/api/internal/cache"
"github.com/baicai2026-baicai/goods/api/internal/clientip"
"github.com/baicai2026-baicai/goods/api/internal/config" "github.com/baicai2026-baicai/goods/api/internal/config"
"github.com/baicai2026-baicai/goods/api/internal/handler" "github.com/baicai2026-baicai/goods/api/internal/handler"
"github.com/baicai2026-baicai/goods/api/internal/publicweb" "github.com/baicai2026-baicai/goods/api/internal/publicweb"
@@ -19,15 +23,19 @@ import (
func main() { func main() {
cfg := config.Load() cfg := config.Load()
clientIPs, err := clientip.Parse(cfg.TrustedProxies)
if err != nil {
log.Fatalf("invalid OPENGOODS_TRUSTED_PROXIES: %v", err)
}
runCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
ctx := context.Background() pool, err := pgxpool.New(context.Background(), cfg.DatabaseURL)
pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
if err != nil { if err != nil {
log.Fatalf("failed to create db pool: %v", err) log.Fatalf("failed to create db pool: %v", err)
} }
defer pool.Close()
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second) pingCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel() defer cancel()
if err := pool.Ping(pingCtx); err != nil { if err := pool.Ping(pingCtx); err != nil {
log.Printf("warning: database not reachable at startup: %v", err) log.Printf("warning: database not reachable at startup: %v", err)
@@ -44,16 +52,42 @@ func main() {
} }
h := handler.New(store.New(pool).WithCache(readCache), publicweb.Dist()). h := handler.New(store.New(pool).WithCache(readCache), publicweb.Dist()).
WithRateLimit(limiter, cfg.AnonRateLimitPerMin). WithRateLimit(limiter, cfg.AnonRateLimitPerMin).
WithQuotas(cfg.AnonTotalQuota, cfg.RegisteredRateLimitPerMin, cfg.RegisteredQuotaTotal) WithQuotas(cfg.AnonTotalQuota, cfg.RegisteredRateLimitPerMin, cfg.RegisteredQuotaTotal).
WithClientIP(clientIPs)
srv := &http.Server{ srv := &http.Server{
Addr: cfg.Addr, Addr: cfg.Addr,
Handler: h.Router(), Handler: h.Router(),
ReadHeaderTimeout: 10 * time.Second, ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 120 * time.Second,
} }
log.Printf("OpenGoods API listening on %s", cfg.Addr) log.Printf("OpenGoods API listening on %s", cfg.Addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { serverErr := make(chan error, 1)
log.Fatalf("server error: %v", err) go func() {
serverErr <- srv.ListenAndServe()
}()
select {
case err := <-serverErr:
pool.Close()
if err != nil && err != http.ErrServerClosed {
log.Fatalf("server error: %v", err)
}
case <-runCtx.Done():
log.Print("shutdown signal received")
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 25*time.Second)
err := srv.Shutdown(shutdownCtx)
shutdownCancel()
if err != nil {
log.Printf("server shutdown: %v", err)
}
pool.Close()
if err := <-serverErr; err != nil && err != http.ErrServerClosed {
log.Printf("server error after shutdown: %v", err)
}
log.Print("OpenGoods API shutdown complete")
} }
} }
+9 -9
View File
@@ -1,21 +1,21 @@
module github.com/baicai2026-baicai/goods/api module github.com/baicai2026-baicai/goods/api
go 1.23.4 go 1.27.0
require ( require (
github.com/go-chi/chi/v5 v5.1.0 github.com/go-chi/chi/v5 v5.5.0
github.com/jackc/pgx/v5 v5.7.2 github.com/jackc/pgx/v5 v5.11.0
github.com/redis/go-redis/v9 v9.18.0 github.com/redis/go-redis/v9 v9.23.0
golang.org/x/crypto v0.31.0 golang.org/x/crypto v0.58.0
) )
require ( require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect
go.uber.org/atomic v1.11.0 // indirect go.uber.org/atomic v1.12.0 // indirect
golang.org/x/sync v0.10.0 // indirect golang.org/x/sync v0.24.0 // indirect
golang.org/x/text v0.21.0 // indirect golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
) )
+24 -27
View File
@@ -5,42 +5,39 @@ github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= 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/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.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= 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/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI= github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= 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/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 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.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 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=
+3 -3
View File
@@ -21,7 +21,7 @@ type apiKeyView struct {
// ListAPIKeys returns all issued keys with usage stats merged in. // ListAPIKeys returns all issued keys with usage stats merged in.
func (h *Handler) ListAPIKeys(w http.ResponseWriter, r *http.Request) { func (h *Handler) ListAPIKeys(w http.ResponseWriter, r *http.Request) {
keys, err := h.store.ListAPIKeys(r.Context()) keys, err := h.store.ListAPIKeys(r.Context())
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
views := make([]apiKeyView, 0, len(keys)) views := make([]apiKeyView, 0, len(keys))
@@ -51,7 +51,7 @@ func (h *Handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) {
return return
} }
plaintext, row, err := h.store.CreateAPIKey(r.Context(), in, auth.UserFrom(r.Context())) plaintext, row, err := h.store.CreateAPIKey(r.Context(), in, auth.UserFrom(r.Context()))
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusCreated, map[string]any{ writeJSON(w, http.StatusCreated, map[string]any{
@@ -63,7 +63,7 @@ func (h *Handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) {
// RevokeAPIKey disables a key. Subsequent requests with it are rejected. // RevokeAPIKey disables a key. Subsequent requests with it are rejected.
func (h *Handler) RevokeAPIKey(w http.ResponseWriter, r *http.Request) { func (h *Handler) RevokeAPIKey(w http.ResponseWriter, r *http.Request) {
if err := h.store.RevokeAPIKey(r.Context(), chi.URLParam(r, "id")); h.handleErr(w, err) { if err := h.store.RevokeAPIKey(r.Context(), chi.URLParam(r, "id")); h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"status": "revoked"}) writeJSON(w, http.StatusOK, map[string]string{"status": "revoked"})
@@ -0,0 +1,93 @@
package adminhandler
import (
"bytes"
"context"
"errors"
"log"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/go-chi/chi/v5/middleware"
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
)
type fakeUsageLimiter struct {
result ratelimit.Result
key string
limit int
window time.Duration
}
func (f *fakeUsageLimiter) Allow(_ context.Context, key string, limit int, window time.Duration) ratelimit.Result {
f.key = key
f.limit = limit
f.window = window
return f.result
}
func (*fakeUsageLimiter) Usage(context.Context, string) ratelimit.UsageStat {
return ratelimit.UsageStat{}
}
func TestBackflowRateLimitReturnsRetryAfter(t *testing.T) {
usage := &fakeUsageLimiter{
result: ratelimit.Result{
Allowed: false,
ResetUnix: time.Now().Add(2 * time.Minute).Unix(),
},
}
h := New(nil, nil, "/ping", nil)
h.usage = usage
h.WithBackflowRate(7)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/public/backflow", nil)
if h.allowBackflow(recorder, req, "key-id") {
t.Fatal("allowBackflow returned true for a denied request")
}
if recorder.Code != http.StatusTooManyRequests {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusTooManyRequests)
}
retryAfter, err := strconv.Atoi(recorder.Header().Get("Retry-After"))
if err != nil || retryAfter <= 0 {
t.Fatalf("Retry-After = %q, want positive integer", recorder.Header().Get("Retry-After"))
}
if usage.key != "backflow:key-id" || usage.limit != 7 || usage.window != time.Hour {
t.Fatalf("Allow called with key=%q limit=%d window=%v", usage.key, usage.limit, usage.window)
}
}
func TestInternalErrorDoesNotExposeDetailsAndLogsRequestID(t *testing.T) {
var logs bytes.Buffer
previousOutput := log.Writer()
log.SetOutput(&logs)
t.Cleanup(func() { log.SetOutput(previousOutput) })
h := New(nil, nil, "/ping", nil)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/ping/api/products", nil)
req.Header.Set(middleware.RequestIDHeader, "request-123")
handler := middleware.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.handleErr(w, r, errors.New("sensitive database detail"))
}))
handler.ServeHTTP(recorder, req)
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusInternalServerError)
}
if strings.Contains(recorder.Body.String(), "sensitive database detail") {
t.Fatalf("response exposed internal error: %s", recorder.Body.String())
}
if !strings.Contains(recorder.Body.String(), "服务器内部错误") || !strings.Contains(recorder.Body.String(), "internal_error") {
t.Fatalf("response missing generic internal error: %s", recorder.Body.String())
}
if !strings.Contains(logs.String(), "sensitive database detail") || !strings.Contains(logs.String(), "request-123") {
t.Fatalf("log missing error or request ID: %s", logs.String())
}
}
@@ -0,0 +1,83 @@
package adminhandler
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
type fakeCacheBumper struct {
calls int
err error
contexts []context.Context
}
func (f *fakeCacheBumper) Bump(ctx context.Context) error {
f.calls++
f.contexts = append(f.contexts, ctx)
return f.err
}
func TestInvalidateCache(t *testing.T) {
tests := []struct {
name string
method string
status int
write bool
want int
}{
{name: "successful write", method: http.MethodPost, status: http.StatusCreated, write: true, want: 1},
{name: "implicit success", method: http.MethodPost, status: http.StatusOK, want: 1},
{name: "client error", method: http.MethodPost, status: http.StatusBadRequest, write: true},
{name: "server error", method: http.MethodPost, status: http.StatusInternalServerError, write: true},
{name: "get", method: http.MethodGet, status: http.StatusCreated, write: true},
{name: "head", method: http.MethodHead, status: http.StatusCreated, write: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
bumper := &fakeCacheBumper{}
h := New(nil, nil, "/ping", nil).WithCache(bumper)
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if tt.write {
w.WriteHeader(tt.status)
}
})
handler := h.invalidateCache(next)
req := httptest.NewRequest(tt.method, "/", nil)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if bumper.calls != tt.want {
t.Fatalf("Bump calls = %d, want %d", bumper.calls, tt.want)
}
})
}
}
func TestInvalidateCacheDoesNotFailResponseAndUsesUncancelledContext(t *testing.T) {
bumper := &fakeCacheBumper{err: errors.New("redis unavailable")}
h := New(nil, nil, "/ping", nil).WithCache(bumper)
handler := h.invalidateCache(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusCreated)
}))
ctx, cancel := context.WithCancel(context.Background())
cancel()
req := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != http.StatusCreated {
t.Fatalf("response status = %d, want %d", recorder.Code, http.StatusCreated)
}
if bumper.calls != 1 {
t.Fatalf("Bump calls = %d, want 1", bumper.calls)
}
select {
case <-bumper.contexts[0].Done():
t.Fatal("Bump context was canceled")
default:
}
}
+199 -61
View File
@@ -3,10 +3,14 @@
package adminhandler package adminhandler
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"io/fs" "io/fs"
"log"
"net"
"net/http" "net/http"
"strconv"
"strings" "strings"
"time" "time"
@@ -16,29 +20,46 @@ import (
"github.com/baicai2026-baicai/goods/api/internal/adminstore" "github.com/baicai2026-baicai/goods/api/internal/adminstore"
"github.com/baicai2026-baicai/goods/api/internal/apikey" "github.com/baicai2026-baicai/goods/api/internal/apikey"
"github.com/baicai2026-baicai/goods/api/internal/auth" "github.com/baicai2026-baicai/goods/api/internal/auth"
"github.com/baicai2026-baicai/goods/api/internal/clientip"
"github.com/baicai2026-baicai/goods/api/internal/gtin" "github.com/baicai2026-baicai/goods/api/internal/gtin"
"github.com/baicai2026-baicai/goods/api/internal/ratelimit" "github.com/baicai2026-baicai/goods/api/internal/ratelimit"
) )
// Handler holds the admin dependencies. // Handler holds the admin dependencies.
type Handler struct { type Handler struct {
store *adminstore.Store store *adminstore.Store
authn *auth.Authenticator authn *auth.Authenticator
basePath string basePath string
spa fs.FS spa fs.FS
submitLimit *rateLimiter submitLimit *rateLimiter
usage *ratelimit.Limiter loginLimit *loginLimiter
usage usageLimiter
backflowRate int
cache cacheBumper
clientIP *clientip.Resolver
}
type usageLimiter interface {
Allow(context.Context, string, int, time.Duration) ratelimit.Result
Usage(context.Context, string) ratelimit.UsageStat
}
type cacheBumper interface {
Bump(context.Context) error
} }
// New constructs an admin Handler. basePath is e.g. "/ping" (no trailing slash). // New constructs an admin Handler. basePath is e.g. "/ping" (no trailing slash).
func New(store *adminstore.Store, authn *auth.Authenticator, basePath string, spa fs.FS) *Handler { func New(store *adminstore.Store, authn *auth.Authenticator, basePath string, spa fs.FS) *Handler {
basePath = "/" + strings.Trim(basePath, "/") basePath = "/" + strings.Trim(basePath, "/")
return &Handler{ return &Handler{
store: store, store: store,
authn: authn, authn: authn,
basePath: basePath, basePath: basePath,
spa: spa, spa: spa,
submitLimit: newRateLimiter(5, 10*time.Minute), submitLimit: newRateLimiter(5, 10*time.Minute),
loginLimit: newLoginLimiter(10, 20, 15*time.Minute),
backflowRate: 30,
clientIP: clientip.Default(),
} }
} }
@@ -49,11 +70,54 @@ func (h *Handler) WithUsage(l *ratelimit.Limiter) *Handler {
return h return h
} }
// WithBackflowRate configures the per-key hourly backflow request limit.
func (h *Handler) WithBackflowRate(n int) *Handler {
h.backflowRate = n
return h
}
// WithCache attaches a cache epoch invalidator for successful admin writes.
func (h *Handler) WithCache(c cacheBumper) *Handler {
h.cache = c
return h
}
func (h *Handler) invalidateCache(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if h.cache == nil || r.Method == http.MethodGet || r.Method == http.MethodHead {
next.ServeHTTP(w, r)
return
}
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)
status := ww.Status()
if status == 0 {
status = http.StatusOK
}
if status < http.StatusOK || status >= http.StatusMultipleChoices {
return
}
if err := h.cache.Bump(context.WithoutCancel(r.Context())); err != nil {
log.Printf("admin cache invalidation failed: %v", err)
}
})
}
// WithClientIP sets the trusted-proxy resolver used to normalize request IPs.
func (h *Handler) WithClientIP(resolver *clientip.Resolver) *Handler {
if resolver == nil {
resolver = clientip.Default()
}
h.clientIP = resolver
return h
}
// Router builds the HTTP handler. // Router builds the HTTP handler.
func (h *Handler) Router() http.Handler { func (h *Handler) Router() http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
r.Use(middleware.RequestID) r.Use(middleware.RequestID)
r.Use(middleware.RealIP) r.Use(h.clientIP.Middleware)
r.Use(middleware.Recoverer) r.Use(middleware.Recoverer)
r.Route(h.basePath, func(r chi.Router) { r.Route(h.basePath, func(r chi.Router) {
@@ -64,6 +128,8 @@ func (h *Handler) Router() http.Handler {
r.Group(func(r chi.Router) { r.Group(func(r chi.Router) {
r.Use(h.authn.Middleware) r.Use(h.authn.Middleware)
r.Use(h.invalidateCache)
r.Post("/api/logout", h.Logout)
r.Get("/api/me", h.Me) r.Get("/api/me", h.Me)
r.Get("/api/stats", h.Stats) r.Get("/api/stats", h.Stats)
r.Get("/api/audit", h.ListAllAudit) r.Get("/api/audit", h.ListAllAudit)
@@ -154,14 +220,66 @@ func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "bad_request", "invalid body") writeError(w, http.StatusBadRequest, "bad_request", "invalid body")
return return
} }
ip := loginIP(r)
if blocked, wait := h.loginLimit.blocked(ip, body.Username); blocked {
seconds := int(wait / time.Second)
if wait%time.Second != 0 {
seconds++
}
if seconds < 1 {
seconds = 1
}
w.Header().Set("Retry-After", strconv.Itoa(seconds))
h.logAdminSession(r, body.Username, "login_blocked", ip)
writeError(w, http.StatusTooManyRequests, "too_many_requests", "登录尝试过于频繁,请稍后重试")
return
}
token, err := h.authn.Login(body.Username, body.Password) token, err := h.authn.Login(body.Username, body.Password)
if err != nil { if err != nil {
h.loginLimit.recordFailure(ip, body.Username)
h.logAdminSession(r, body.Username, "login_failure", ip)
writeError(w, http.StatusUnauthorized, "unauthorized", "用户名或密码错误") writeError(w, http.StatusUnauthorized, "unauthorized", "用户名或密码错误")
return return
} }
h.loginLimit.clearIP(ip)
h.logAdminSession(r, body.Username, "login_success", ip)
writeJSON(w, http.StatusOK, map[string]string{"token": token, "username": body.Username}) writeJSON(w, http.StatusOK, map[string]string{"token": token, "username": body.Username})
} }
// Logout revokes the current bearer token.
func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {
token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if token == "" {
writeError(w, http.StatusUnauthorized, "unauthorized", "令牌无效")
return
}
if err := h.authn.Revoke(token); err != nil {
writeError(w, http.StatusUnauthorized, "unauthorized", "令牌无效")
return
}
username := auth.UserFrom(r.Context())
h.logAdminSession(r, username, "logout", loginIP(r))
w.WriteHeader(http.StatusNoContent)
}
func loginIP(r *http.Request) string {
ip := realIP(r)
if host, _, err := net.SplitHostPort(ip); err == nil {
return host
}
return ip
}
func (h *Handler) logAdminSession(r *http.Request, username, action, ip string) {
if h.store == nil {
return
}
detail := map[string]any{"ip": ip, "username": username}
if err := h.store.LogAdminSession(r.Context(), username, action, detail); err != nil {
log.Printf("admin session audit write failed: %v", err)
}
}
// Me returns the current authenticated user. // Me returns the current authenticated user.
func (h *Handler) Me(w http.ResponseWriter, r *http.Request) { func (h *Handler) Me(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"username": auth.UserFrom(r.Context())}) writeJSON(w, http.StatusOK, map[string]string{"username": auth.UserFrom(r.Context())})
@@ -176,7 +294,7 @@ func (h *Handler) ListProducts(w http.ResponseWriter, r *http.Request) {
order := r.URL.Query().Get("order") order := r.URL.Query().Get("order")
page, size := pageParams(r) page, size := pageParams(r)
items, total, err := h.store.ListProducts(r.Context(), q, sort, order, size, (page-1)*size) items, total, err := h.store.ListProducts(r.Context(), q, sort, order, size, (page-1)*size)
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]any{ writeJSON(w, http.StatusOK, map[string]any{
@@ -188,7 +306,7 @@ func (h *Handler) ListProducts(w http.ResponseWriter, r *http.Request) {
// GetProduct returns full editable detail. // GetProduct returns full editable detail.
func (h *Handler) GetProduct(w http.ResponseWriter, r *http.Request) { func (h *Handler) GetProduct(w http.ResponseWriter, r *http.Request) {
d, err := h.store.GetProduct(r.Context(), chi.URLParam(r, "id")) d, err := h.store.GetProduct(r.Context(), chi.URLParam(r, "id"))
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, d) writeJSON(w, http.StatusOK, d)
@@ -211,7 +329,7 @@ func (h *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusConflict, "duplicate_gtin", "该条码(GTIN)已被其它商品使用") writeError(w, http.StatusConflict, "duplicate_gtin", "该条码(GTIN)已被其它商品使用")
return return
} }
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusCreated, d) writeJSON(w, http.StatusCreated, d)
@@ -220,7 +338,7 @@ func (h *Handler) CreateProduct(w http.ResponseWriter, r *http.Request) {
// Stats returns the dashboard overview counters. // Stats returns the dashboard overview counters.
func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) { func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
st, err := h.store.Stats(r.Context()) st, err := h.store.Stats(r.Context())
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, st) writeJSON(w, http.StatusOK, st)
@@ -230,7 +348,7 @@ func (h *Handler) Stats(w http.ResponseWriter, r *http.Request) {
func (h *Handler) ListAllAudit(w http.ResponseWriter, r *http.Request) { func (h *Handler) ListAllAudit(w http.ResponseWriter, r *http.Request) {
page, size := pageParams(r) page, size := pageParams(r)
items, total, err := h.store.ListAllAudit(r.Context(), size, (page-1)*size) items, total, err := h.store.ListAllAudit(r.Context(), size, (page-1)*size)
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]any{ writeJSON(w, http.StatusOK, map[string]any{
@@ -281,7 +399,7 @@ func (h *Handler) BulkProducts(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "bad_request", "未选择任何商品") writeError(w, http.StatusBadRequest, "bad_request", "未选择任何商品")
return return
} }
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "affected": affected}) writeJSON(w, http.StatusOK, map[string]any{"status": "ok", "affected": affected})
@@ -299,7 +417,7 @@ func (h *Handler) UpdateProduct(w http.ResponseWriter, r *http.Request) {
return return
} }
d, err := h.store.UpdateProduct(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in) d, err := h.store.UpdateProduct(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, d) writeJSON(w, http.StatusOK, d)
@@ -308,7 +426,7 @@ func (h *Handler) UpdateProduct(w http.ResponseWriter, r *http.Request) {
// ListAudit returns audit history for a product. // ListAudit returns audit history for a product.
func (h *Handler) ListAudit(w http.ResponseWriter, r *http.Request) { func (h *Handler) ListAudit(w http.ResponseWriter, r *http.Request) {
items, err := h.store.ListAudit(r.Context(), chi.URLParam(r, "id"), 100) items, err := h.store.ListAudit(r.Context(), chi.URLParam(r, "id"), 100)
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]any{"items": items}) writeJSON(w, http.StatusOK, map[string]any{"items": items})
@@ -325,7 +443,7 @@ func (h *Handler) AddImage(w http.ResponseWriter, r *http.Request) {
return return
} }
im, err := h.store.AddImage(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.URL, body.Kind) im, err := h.store.AddImage(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.URL, body.Kind)
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusCreated, im) writeJSON(w, http.StatusCreated, im)
@@ -334,7 +452,7 @@ func (h *Handler) AddImage(w http.ResponseWriter, r *http.Request) {
// DeleteImage removes an image. // DeleteImage removes an image.
func (h *Handler) DeleteImage(w http.ResponseWriter, r *http.Request) { func (h *Handler) DeleteImage(w http.ResponseWriter, r *http.Request) {
err := h.store.DeleteImage(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "imageID"), auth.UserFrom(r.Context())) err := h.store.DeleteImage(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "imageID"), auth.UserFrom(r.Context()))
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"}) writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
@@ -348,7 +466,7 @@ func (h *Handler) AddMSRP(w http.ResponseWriter, r *http.Request) {
return return
} }
m, err := h.store.AddMSRP(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in) m, err := h.store.AddMSRP(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusCreated, m) writeJSON(w, http.StatusCreated, m)
@@ -357,7 +475,7 @@ func (h *Handler) AddMSRP(w http.ResponseWriter, r *http.Request) {
// DeleteMSRP removes an MSRP snapshot. // DeleteMSRP removes an MSRP snapshot.
func (h *Handler) DeleteMSRP(w http.ResponseWriter, r *http.Request) { func (h *Handler) DeleteMSRP(w http.ResponseWriter, r *http.Request) {
err := h.store.DeleteMSRP(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "msrpID"), auth.UserFrom(r.Context())) err := h.store.DeleteMSRP(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "msrpID"), auth.UserFrom(r.Context()))
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"}) writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
@@ -375,7 +493,7 @@ func (h *Handler) AddBarcode(w http.ResponseWriter, r *http.Request) {
return return
} }
b, err := h.store.AddBarcode(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in) b, err := h.store.AddBarcode(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
if h.handleBarcodeErr(w, err) { if h.handleBarcodeErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusCreated, b) writeJSON(w, http.StatusCreated, b)
@@ -384,7 +502,7 @@ func (h *Handler) AddBarcode(w http.ResponseWriter, r *http.Request) {
// DeleteBarcode removes a barcode; a primary one is replaced automatically. // DeleteBarcode removes a barcode; a primary one is replaced automatically.
func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) { func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) {
err := h.store.DeleteBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context())) err := h.store.DeleteBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"}) writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
@@ -393,7 +511,7 @@ func (h *Handler) DeleteBarcode(w http.ResponseWriter, r *http.Request) {
// SetPrimaryBarcode marks one barcode primary and mirrors it to product.gtin. // SetPrimaryBarcode marks one barcode primary and mirrors it to product.gtin.
func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) { func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) {
b, err := h.store.SetPrimaryBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context())) b, err := h.store.SetPrimaryBarcode(r.Context(), chi.URLParam(r, "id"), chi.URLParam(r, "barcodeID"), auth.UserFrom(r.Context()))
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, b) writeJSON(w, http.StatusOK, b)
@@ -401,7 +519,7 @@ func (h *Handler) SetPrimaryBarcode(w http.ResponseWriter, r *http.Request) {
// handleBarcodeErr maps barcode-specific errors (GTIN validation, ownership // handleBarcodeErr maps barcode-specific errors (GTIN validation, ownership
// conflict) to client-facing statuses, falling back to handleErr otherwise. // conflict) to client-facing statuses, falling back to handleErr otherwise.
func (h *Handler) handleBarcodeErr(w http.ResponseWriter, err error) bool { func (h *Handler) handleBarcodeErr(w http.ResponseWriter, r *http.Request, err error) bool {
if err == nil { if err == nil {
return false return false
} }
@@ -422,13 +540,13 @@ func (h *Handler) handleBarcodeErr(w http.ResponseWriter, err error) bool {
writeError(w, http.StatusBadRequest, "invalid_gtin", err.Error()) writeError(w, http.StatusBadRequest, "invalid_gtin", err.Error())
return true return true
} }
return h.handleErr(w, err) return h.handleErr(w, r, err)
} }
// ListBrands returns brand options. // ListBrands returns brand options.
func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) { func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) {
items, err := h.store.ListBrands(r.Context()) items, err := h.store.ListBrands(r.Context())
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]any{"items": items}) writeJSON(w, http.StatusOK, map[string]any{"items": items})
@@ -442,7 +560,7 @@ func (h *Handler) ListKindFields(w http.ResponseWriter, r *http.Request) {
return return
} }
items, err := h.store.ListKindFields(r.Context(), kind) items, err := h.store.ListKindFields(r.Context(), kind)
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]any{"items": items, "kind": kind}) writeJSON(w, http.StatusOK, map[string]any{"items": items, "kind": kind})
@@ -451,7 +569,7 @@ func (h *Handler) ListKindFields(w http.ResponseWriter, r *http.Request) {
// ListCategories returns category options. // ListCategories returns category options.
func (h *Handler) ListCategories(w http.ResponseWriter, r *http.Request) { func (h *Handler) ListCategories(w http.ResponseWriter, r *http.Request) {
items, err := h.store.ListCategories(r.Context()) items, err := h.store.ListCategories(r.Context())
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]any{"items": items}) writeJSON(w, http.StatusOK, map[string]any{"items": items})
@@ -469,7 +587,7 @@ func (h *Handler) CreateCategory(w http.ResponseWriter, r *http.Request) {
return return
} }
c, err := h.store.CreateCategory(r.Context(), auth.UserFrom(r.Context()), in) c, err := h.store.CreateCategory(r.Context(), auth.UserFrom(r.Context()), in)
if h.handleCategoryErr(w, err) { if h.handleCategoryErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusCreated, c) writeJSON(w, http.StatusCreated, c)
@@ -487,7 +605,7 @@ func (h *Handler) UpdateCategory(w http.ResponseWriter, r *http.Request) {
return return
} }
c, err := h.store.UpdateCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in) c, err := h.store.UpdateCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in)
if h.handleCategoryErr(w, err) { if h.handleCategoryErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, c) writeJSON(w, http.StatusOK, c)
@@ -496,7 +614,7 @@ func (h *Handler) UpdateCategory(w http.ResponseWriter, r *http.Request) {
// DeleteCategory removes a leaf category that no product uses. // DeleteCategory removes a leaf category that no product uses.
func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) { func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) {
err := h.store.DeleteCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context())) err := h.store.DeleteCategory(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
if h.handleCategoryErr(w, err) { if h.handleCategoryErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"}) writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
@@ -504,7 +622,7 @@ func (h *Handler) DeleteCategory(w http.ResponseWriter, r *http.Request) {
// handleCategoryErr maps category-specific errors to client statuses, falling // handleCategoryErr maps category-specific errors to client statuses, falling
// back to handleErr otherwise. // back to handleErr otherwise.
func (h *Handler) handleCategoryErr(w http.ResponseWriter, err error) bool { func (h *Handler) handleCategoryErr(w http.ResponseWriter, r *http.Request, err error) bool {
if err == nil { if err == nil {
return false return false
} }
@@ -522,7 +640,7 @@ func (h *Handler) handleCategoryErr(w http.ResponseWriter, err error) bool {
writeError(w, http.StatusBadRequest, "invalid_parent", "上级分类无效(不存在或不能移动到自身/子级下)") writeError(w, http.StatusBadRequest, "invalid_parent", "上级分类无效(不存在或不能移动到自身/子级下)")
return true return true
} }
return h.handleErr(w, err) return h.handleErr(w, r, err)
} }
type brandInput struct { type brandInput struct {
@@ -545,7 +663,7 @@ func (h *Handler) CreateBrand(w http.ResponseWriter, r *http.Request) {
return return
} }
b, err := h.store.CreateBrand(r.Context(), auth.UserFrom(r.Context()), in.Name) b, err := h.store.CreateBrand(r.Context(), auth.UserFrom(r.Context()), in.Name)
if h.handleBrandErr(w, err) { if h.handleBrandErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusCreated, b) writeJSON(w, http.StatusCreated, b)
@@ -563,7 +681,7 @@ func (h *Handler) UpdateBrand(w http.ResponseWriter, r *http.Request) {
return return
} }
b, err := h.store.UpdateBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in.Name) b, err := h.store.UpdateBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), in.Name)
if h.handleBrandErr(w, err) { if h.handleBrandErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, b) writeJSON(w, http.StatusOK, b)
@@ -581,7 +699,7 @@ func (h *Handler) MergeBrands(w http.ResponseWriter, r *http.Request) {
return return
} }
b, err := h.store.MergeBrands(r.Context(), chi.URLParam(r, "id"), in.TargetID, auth.UserFrom(r.Context())) b, err := h.store.MergeBrands(r.Context(), chi.URLParam(r, "id"), in.TargetID, auth.UserFrom(r.Context()))
if h.handleBrandErr(w, err) { if h.handleBrandErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, b) writeJSON(w, http.StatusOK, b)
@@ -590,14 +708,14 @@ func (h *Handler) MergeBrands(w http.ResponseWriter, r *http.Request) {
// DeleteBrand removes a brand no product references. // DeleteBrand removes a brand no product references.
func (h *Handler) DeleteBrand(w http.ResponseWriter, r *http.Request) { func (h *Handler) DeleteBrand(w http.ResponseWriter, r *http.Request) {
err := h.store.DeleteBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context())) err := h.store.DeleteBrand(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
if h.handleBrandErr(w, err) { if h.handleBrandErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"}) writeJSON(w, http.StatusOK, map[string]string{"status": "deleted"})
} }
// handleBrandErr maps brand-specific errors to client statuses. // handleBrandErr maps brand-specific errors to client statuses.
func (h *Handler) handleBrandErr(w http.ResponseWriter, err error) bool { func (h *Handler) handleBrandErr(w http.ResponseWriter, r *http.Request, err error) bool {
if err == nil { if err == nil {
return false return false
} }
@@ -612,7 +730,7 @@ func (h *Handler) handleBrandErr(w http.ResponseWriter, err error) bool {
writeError(w, http.StatusBadRequest, "invalid_merge", "合并目标无效(不存在或与源品牌相同)") writeError(w, http.StatusBadRequest, "invalid_merge", "合并目标无效(不存在或与源品牌相同)")
return true return true
} }
return h.handleErr(w, err) return h.handleErr(w, r, err)
} }
// ---------- submissions ---------- // ---------- submissions ----------
@@ -634,7 +752,7 @@ func (h *Handler) CreateSubmission(w http.ResponseWriter, r *http.Request) {
} }
id, err := h.store.CreateSubmission(r.Context(), in, realIP(r)) id, err := h.store.CreateSubmission(r.Context(), in, realIP(r))
if err != nil { if err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", err.Error()) internalError(w, r, err)
return return
} }
writeJSON(w, http.StatusCreated, map[string]string{"id": id, "status": "pending"}) writeJSON(w, http.StatusCreated, map[string]string{"id": id, "status": "pending"})
@@ -653,12 +771,16 @@ func (h *Handler) Backflow(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 格式无效") writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 格式无效")
return return
} }
if _, err := h.store.APIKeyByHash(r.Context(), apikey.Hash(raw)); err != nil { key, err := h.store.APIKeyByHash(r.Context(), apikey.Hash(raw))
if err != nil {
if errors.Is(err, adminstore.ErrNotFound) { if errors.Is(err, adminstore.ErrNotFound) {
writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 无效或已吊销") writeError(w, http.StatusUnauthorized, "invalid_api_key", "API key 无效或已吊销")
return return
} }
writeError(w, http.StatusInternalServerError, "internal_error", err.Error()) internalError(w, r, err)
return
}
if !h.allowBackflow(w, r, key.ID) {
return return
} }
@@ -679,12 +801,29 @@ func (h *Handler) Backflow(w http.ResponseWriter, r *http.Request) {
sum, err := h.store.CreateBackflowSubmissions(r.Context(), items, realIP(r)) sum, err := h.store.CreateBackflowSubmissions(r.Context(), items, realIP(r))
if err != nil { if err != nil {
writeError(w, http.StatusInternalServerError, "internal_error", err.Error()) internalError(w, r, err)
return return
} }
writeJSON(w, http.StatusOK, sum) writeJSON(w, http.StatusOK, sum)
} }
func (h *Handler) allowBackflow(w http.ResponseWriter, r *http.Request, keyID string) bool {
if h.usage == nil {
return true
}
res := h.usage.Allow(r.Context(), "backflow:"+keyID, h.backflowRate, time.Hour)
if res.Allowed {
return true
}
retryAfter := res.ResetUnix - time.Now().Unix()
if retryAfter < 1 {
retryAfter = 1
}
w.Header().Set("Retry-After", strconv.FormatInt(retryAfter, 10))
writeError(w, http.StatusTooManyRequests, "rate_limited", "回流请求超过每小时限制")
return false
}
// presentedAPIKey extracts a public API key from X-API-Key or a Bearer token. // presentedAPIKey extracts a public API key from X-API-Key or a Bearer token.
func presentedAPIKey(r *http.Request) string { func presentedAPIKey(r *http.Request) string {
if v := strings.TrimSpace(r.Header.Get("X-API-Key")); v != "" { if v := strings.TrimSpace(r.Header.Get("X-API-Key")); v != "" {
@@ -701,7 +840,7 @@ func (h *Handler) ListSubmissions(w http.ResponseWriter, r *http.Request) {
status := r.URL.Query().Get("status") status := r.URL.Query().Get("status")
page, size := pageParams(r) page, size := pageParams(r)
items, total, err := h.store.ListSubmissions(r.Context(), status, size, (page-1)*size) items, total, err := h.store.ListSubmissions(r.Context(), status, size, (page-1)*size)
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
pending, _ := h.store.PendingSubmissionCount(r.Context()) pending, _ := h.store.PendingSubmissionCount(r.Context())
@@ -713,7 +852,7 @@ func (h *Handler) ListSubmissions(w http.ResponseWriter, r *http.Request) {
// GetSubmission returns full submission detail (admin). // GetSubmission returns full submission detail (admin).
func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) { func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) {
d, err := h.store.GetSubmission(r.Context(), chi.URLParam(r, "id")) d, err := h.store.GetSubmission(r.Context(), chi.URLParam(r, "id"))
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, d) writeJSON(w, http.StatusOK, d)
@@ -722,7 +861,7 @@ func (h *Handler) GetSubmission(w http.ResponseWriter, r *http.Request) {
// ApproveSubmission applies a contribution to the product store (admin). // ApproveSubmission applies a contribution to the product store (admin).
func (h *Handler) ApproveSubmission(w http.ResponseWriter, r *http.Request) { func (h *Handler) ApproveSubmission(w http.ResponseWriter, r *http.Request) {
d, err := h.store.ApproveSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context())) d, err := h.store.ApproveSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()))
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, d) writeJSON(w, http.StatusOK, d)
@@ -735,7 +874,7 @@ func (h *Handler) RejectSubmission(w http.ResponseWriter, r *http.Request) {
} }
_ = json.NewDecoder(r.Body).Decode(&body) _ = json.NewDecoder(r.Body).Decode(&body)
err := h.store.RejectSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.Note) err := h.store.RejectSubmission(r.Context(), chi.URLParam(r, "id"), auth.UserFrom(r.Context()), body.Note)
if h.handleErr(w, err) { if h.handleErr(w, r, err) {
return return
} }
writeJSON(w, http.StatusOK, map[string]string{"status": "rejected"}) writeJSON(w, http.StatusOK, map[string]string{"status": "rejected"})
@@ -744,19 +883,18 @@ func (h *Handler) RejectSubmission(w http.ResponseWriter, r *http.Request) {
// ---------- helpers ---------- // ---------- helpers ----------
func realIP(r *http.Request) string { func realIP(r *http.Request) string {
if ip := r.Header.Get("X-Forwarded-For"); ip != "" { if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
if i := strings.IndexByte(ip, ','); i >= 0 { return host
return strings.TrimSpace(ip[:i])
}
return strings.TrimSpace(ip)
}
if ip := r.Header.Get("X-Real-IP"); ip != "" {
return ip
} }
return r.RemoteAddr return r.RemoteAddr
} }
func (h *Handler) handleErr(w http.ResponseWriter, err error) bool { func internalError(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("adminhandler: internal error request_id=%s: %v", middleware.GetReqID(r.Context()), err)
writeError(w, http.StatusInternalServerError, "internal_error", "服务器内部错误")
}
func (h *Handler) handleErr(w http.ResponseWriter, r *http.Request, err error) bool {
if err == nil { if err == nil {
return false return false
} }
@@ -768,7 +906,7 @@ func (h *Handler) handleErr(w http.ResponseWriter, err error) bool {
writeError(w, http.StatusConflict, "conflict", "该投稿已被处理") writeError(w, http.StatusConflict, "conflict", "该投稿已被处理")
return true return true
} }
writeError(w, http.StatusInternalServerError, "internal_error", err.Error()) internalError(w, r, err)
return true return true
} }
@@ -0,0 +1,414 @@
package adminhandler
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"testing/fstest"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
"github.com/baicai2026-baicai/goods/api/internal/adminstore"
"github.com/baicai2026-baicai/goods/api/internal/auth"
)
func newTestAdminHandler(t *testing.T) (*Handler, *pgxpool.Pool, string, string, string) {
t.Helper()
dsn := os.Getenv("OPENGOODS_DATABASE_URL")
if dsn == "" {
dsn = "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable"
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
t.Skipf("no database: %v", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
t.Skipf("database not reachable: %v", err)
}
var migrated bool
if err := pool.QueryRow(ctx, `
SELECT to_regclass('public.audit_log') IS NOT NULL
AND to_regclass('public.submission') IS NOT NULL
AND to_regclass('public.api_key') IS NOT NULL`).Scan(&migrated); err != nil || !migrated {
pool.Close()
t.Skip("migrations not applied")
}
prefix := fmt.Sprintf("adminapi_%d_", time.Now().UnixNano())
username := prefix + "operator"
password := "admin-api-test-password"
passwordHash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
if err != nil {
pool.Close()
t.Fatalf("hash password: %v", err)
}
h := New(
adminstore.New(pool),
auth.New(username, passwordHash, []byte(prefix+"secret"), time.Hour),
"/ping",
fstest.MapFS{"index.html": &fstest.MapFile{Data: []byte("<html></html>")}},
)
t.Cleanup(func() {
cleanupAdminTestData(t, pool, prefix, username)
pool.Close()
})
return h, pool, prefix, username, password
}
func cleanupAdminTestData(t *testing.T, pool *pgxpool.Pool, prefix, actor string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
like := prefix + "%"
_, _ = pool.Exec(ctx, "DELETE FROM submission WHERE name LIKE $1", like)
_, _ = pool.Exec(ctx, "DELETE FROM audit_log WHERE actor=$1 OR entity_id IN (SELECT id FROM product WHERE name LIKE $2)", actor, like)
_, _ = pool.Exec(ctx, "DELETE FROM product WHERE name LIKE $1", like)
_, _ = pool.Exec(ctx, "DELETE FROM api_key WHERE name LIKE $1", like)
_, _ = pool.Exec(ctx, "DELETE FROM manufacturer WHERE name LIKE $1", like)
_, _ = pool.Exec(ctx, "DELETE FROM brand WHERE name LIKE $1", like)
}
func adminJSON(t *testing.T, h *Handler, method, path string, body any, token string) *httptest.ResponseRecorder {
t.Helper()
var data []byte
if body != nil {
var err error
data, err = json.Marshal(body)
if err != nil {
t.Fatalf("marshal request: %v", err)
}
}
req := httptest.NewRequest(method, path, bytes.NewReader(data))
req.RemoteAddr = "127.0.0.1:12345"
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
h.Router().ServeHTTP(rec, req)
return rec
}
func adminAPIKeyJSON(t *testing.T, h *Handler, path string, body any, key string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(mustJSON(t, body)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-API-Key", key)
req.RemoteAddr = "127.0.0.1:12345"
rec := httptest.NewRecorder()
h.Router().ServeHTTP(rec, req)
return rec
}
func adminRawJSON(t *testing.T, h *Handler, path, body, token string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
req.RemoteAddr = "127.0.0.1:12345"
rec := httptest.NewRecorder()
h.Router().ServeHTTP(rec, req)
return rec
}
func adminLogin(t *testing.T, h *Handler, username, password string) string {
t.Helper()
rec := adminJSON(t, h, http.MethodPost, "/ping/api/login", map[string]string{
"username": username,
"password": password,
}, "")
if rec.Code != http.StatusOK {
t.Fatalf("login status = %d, body = %s", rec.Code, rec.Body.String())
}
var response struct {
Token string `json:"token"`
}
if err := json.NewDecoder(rec.Body).Decode(&response); err != nil {
t.Fatalf("decode login response: %v", err)
}
if response.Token == "" {
t.Fatal("login response did not contain a token")
}
return response.Token
}
func TestAdminLoginAuthAndProductAudit(t *testing.T) {
h, pool, prefix, username, password := newTestAdminHandler(t)
if rec := adminJSON(t, h, http.MethodPost, "/ping/api/login", map[string]string{
"username": username,
"password": "wrong-password",
}, ""); rec.Code != http.StatusUnauthorized {
t.Fatalf("failed login status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
if rec := adminJSON(t, h, http.MethodGet, "/ping/api/products", nil, ""); rec.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated product status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
token := adminLogin(t, h, username, password)
productName := prefix + "product"
rec := adminJSON(t, h, http.MethodPost, "/ping/api/products", map[string]string{
"name": productName,
}, token)
if rec.Code != http.StatusCreated {
t.Fatalf("create product status = %d, body = %s", rec.Code, rec.Body.String())
}
var created adminstore.ProductDetail
if err := json.NewDecoder(rec.Body).Decode(&created); err != nil {
t.Fatalf("decode created product: %v", err)
}
var createAudits int
if err := pool.QueryRow(context.Background(), `
SELECT count(*) FROM audit_log
WHERE actor=$1 AND action='create' AND entity='product' AND entity_id=$2`,
username, created.ID).Scan(&createAudits); err != nil {
t.Fatalf("query create audit: %v", err)
}
if createAudits != 1 {
t.Fatalf("create audit count = %d, want 1", createAudits)
}
updatedName := prefix + "product-updated"
rec = adminJSON(t, h, http.MethodPut, "/ping/api/products/"+created.ID, map[string]string{
"name": updatedName,
}, token)
if rec.Code != http.StatusOK {
t.Fatalf("update product status = %d, body = %s", rec.Code, rec.Body.String())
}
var updateAudits int
if err := pool.QueryRow(context.Background(), `
SELECT count(*) FROM audit_log
WHERE actor=$1 AND action='update' AND entity='product' AND entity_id=$2`,
username, created.ID).Scan(&updateAudits); err != nil {
t.Fatalf("query update audit: %v", err)
}
if updateAudits != 1 {
t.Fatalf("update audit count = %d, want 1", updateAudits)
}
}
func TestAdminSubmissionApproval(t *testing.T) {
h, pool, prefix, username, password := newTestAdminHandler(t)
token := adminLogin(t, h, username, password)
name := prefix + "submission"
rec := adminJSON(t, h, http.MethodPost, "/api/public/submissions", adminstore.SubmissionInput{
Name: name,
}, "")
if rec.Code != http.StatusCreated {
t.Fatalf("submission status = %d, body = %s", rec.Code, rec.Body.String())
}
var submitted struct {
ID string `json:"id"`
}
if err := json.NewDecoder(rec.Body).Decode(&submitted); err != nil {
t.Fatalf("decode submission response: %v", err)
}
if submitted.ID == "" {
t.Fatal("submission response did not contain an id")
}
rec = adminJSON(t, h, http.MethodPost,
"/ping/api/submissions/"+submitted.ID+"/approve", nil, token)
if rec.Code != http.StatusOK {
t.Fatalf("approve status = %d, body = %s", rec.Code, rec.Body.String())
}
var status, productID string
if err := pool.QueryRow(context.Background(), `
SELECT status, result_product_id::text FROM submission WHERE id=$1`,
submitted.ID).Scan(&status, &productID); err != nil {
t.Fatalf("query approved submission: %v", err)
}
if status != "approved" || productID == "" {
t.Fatalf("submission status/product = %q/%q", status, productID)
}
var productCount int
if err := pool.QueryRow(context.Background(),
"SELECT count(*) FROM product WHERE id=$1 AND name=$2", productID, name).Scan(&productCount); err != nil {
t.Fatalf("query approved product: %v", err)
}
if productCount != 1 {
t.Fatalf("approved product count = %d, want 1", productCount)
}
}
func TestAdminBackflowAuthenticationAndQueue(t *testing.T) {
h, pool, prefix, username, _ := newTestAdminHandler(t)
store := adminstore.New(pool)
ctx := context.Background()
key, row, err := store.CreateAPIKey(ctx, adminstore.APIKeyInput{Name: prefix + "key-one"}, username)
if err != nil {
t.Fatalf("create API key: %v", err)
}
if rec := adminAPIKeyJSON(t, h, "/api/public/backflow", []adminstore.SubmissionInput{}, ""); rec.Code != http.StatusUnauthorized {
t.Fatalf("missing key status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
if rec := adminAPIKeyJSON(t, h, "/api/public/backflow", []adminstore.SubmissionInput{}, "og_live_invalidkey123"); rec.Code != http.StatusUnauthorized {
t.Fatalf("invalid key status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
items := make([]adminstore.SubmissionInput, 1001)
for i := range items {
items[i].Name = fmt.Sprintf("%s-too-many-%d", prefix, i)
}
rec := adminAPIKeyJSON(t, h, "/api/public/backflow", items, key)
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "too_many") {
t.Fatalf("too-many response = %d %s", rec.Code, rec.Body.String())
}
if err := store.RevokeAPIKey(ctx, row.ID); err != nil {
t.Fatalf("revoke API key: %v", err)
}
rec = adminAPIKeyJSON(t, h, "/api/public/backflow", []adminstore.SubmissionInput{}, key)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("revoked key status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
activeKey, _, err := store.CreateAPIKey(ctx, adminstore.APIKeyInput{Name: prefix + "key-two"}, username)
if err != nil {
t.Fatalf("create active API key: %v", err)
}
name := prefix + "backflow"
rec = adminAPIKeyJSON(t, h, "/api/public/backflow", []adminstore.SubmissionInput{{Name: name}}, activeKey)
if rec.Code != http.StatusOK {
t.Fatalf("backflow status = %d, body = %s", rec.Code, rec.Body.String())
}
var summary struct {
Queued int `json:"queued"`
}
if err := json.NewDecoder(rec.Body).Decode(&summary); err != nil {
t.Fatalf("decode backflow response: %v", err)
}
if summary.Queued != 1 {
t.Fatalf("backflow queued = %d, want 1", summary.Queued)
}
var queued int
if err := pool.QueryRow(ctx, `
SELECT count(*) FROM submission
WHERE name=$1 AND payload->>'source'='backflow'`, name).Scan(&queued); err != nil {
t.Fatalf("query backflow submission: %v", err)
}
if queued != 1 {
t.Fatalf("backflow submission count = %d, want 1", queued)
}
}
func TestAdminByposImport(t *testing.T) {
h, pool, prefix, username, password := newTestAdminHandler(t)
token := adminLogin(t, h, username, password)
records := []adminstore.ByposRecord{
{
Barcode: "6901234567892",
Name: prefix + "bypos",
Spec: "500",
Unit: "g",
Status: "hit",
},
{
Barcode: "not-a-barcode",
Name: prefix + "invalid",
Status: "invalid",
RetMsg: "非国标条码",
},
}
rec := adminJSON(t, h, http.MethodPost, "/ping/api/import/bypos", records, token)
if rec.Code != http.StatusOK {
t.Fatalf("bypos status = %d, body = %s", rec.Code, rec.Body.String())
}
var result adminstore.ImportByposResult
if err := json.NewDecoder(rec.Body).Decode(&result); err != nil {
t.Fatalf("decode bypos response: %v", err)
}
if result.Loaded != 1 || result.Skipped != 1 || result.Errored != 0 {
t.Fatalf("bypos result = %+v", result)
}
var loaded, invalid int
if err := pool.QueryRow(context.Background(),
"SELECT count(*) FROM product WHERE name=$1", prefix+"bypos").Scan(&loaded); err != nil {
t.Fatalf("query bypos product: %v", err)
}
if err := pool.QueryRow(context.Background(),
"SELECT count(*) FROM product WHERE name=$1", prefix+"invalid").Scan(&invalid); err != nil {
t.Fatalf("query invalid bypos product: %v", err)
}
if loaded != 1 || invalid != 0 {
t.Fatalf("bypos products loaded/invalid = %d/%d", loaded, invalid)
}
}
func TestAdminByposImportJSONLAndMalformed(t *testing.T) {
h, pool, prefix, username, password := newTestAdminHandler(t)
token := adminLogin(t, h, username, password)
records := []adminstore.ByposRecord{
{
Barcode: "6901234567885",
Name: prefix + "jsonl",
Status: "hit",
},
{
Barcode: "invalid",
Name: prefix + "jsonl-invalid",
Status: "invalid",
},
}
var lines strings.Builder
for _, record := range records {
lines.Write(mustJSON(t, record))
lines.WriteByte('\n')
}
rec := adminRawJSON(t, h, "/ping/api/import/bypos", lines.String(), token)
if rec.Code != http.StatusOK {
t.Fatalf("JSONL bypos status = %d, body = %s", rec.Code, rec.Body.String())
}
var result adminstore.ImportByposResult
if err := json.NewDecoder(rec.Body).Decode(&result); err != nil {
t.Fatalf("decode JSONL bypos response: %v", err)
}
if result.Loaded != 1 || result.Skipped != 1 || result.Errored != 0 {
t.Fatalf("JSONL bypos result = %+v", result)
}
malformed := fmt.Sprintf(
"{\"barcode\":\"6901234567885\",\"name\":%q,\"status\":\"hit\"}\n{\"barcode\":",
prefix+"malformed",
)
rec = adminRawJSON(t, h, "/ping/api/import/bypos", malformed, token)
if rec.Code != http.StatusBadRequest ||
!strings.Contains(rec.Body.String(), `"code":"bad_request"`) ||
!strings.Contains(rec.Body.String(), "请求体应为 JSON 数组或 JSONL") {
t.Fatalf("malformed JSONL response = %d, body = %s", rec.Code, rec.Body.String())
}
var inserted int
if err := pool.QueryRow(context.Background(),
"SELECT count(*) FROM product WHERE name=$1", prefix+"malformed").Scan(&inserted); err != nil {
t.Fatalf("query malformed import product: %v", err)
}
if inserted != 0 {
t.Fatalf("malformed import inserted %d products, want 0", inserted)
}
}
func mustJSON(t *testing.T, value any) []byte {
t.Helper()
data, err := json.Marshal(value)
if err != nil {
t.Fatalf("marshal JSON: %v", err)
}
return data
}
+54 -8
View File
@@ -1,7 +1,10 @@
package adminhandler package adminhandler
import ( import (
"bufio"
"encoding/json" "encoding/json"
"errors"
"io"
"net/http" "net/http"
"github.com/baicai2026-baicai/goods/api/internal/adminstore" "github.com/baicai2026-baicai/goods/api/internal/adminstore"
@@ -9,22 +12,65 @@ import (
func (h *Handler) ImportBypos(w http.ResponseWriter, r *http.Request) { func (h *Handler) ImportBypos(w http.ResponseWriter, r *http.Request) {
var records []adminstore.ByposRecord var records []adminstore.ByposRecord
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 50<<20)) reader := bufio.NewReader(http.MaxBytesReader(w, r.Body, 50<<20))
for dec.More() { first, err := firstNonWhitespace(reader)
var rec adminstore.ByposRecord if errors.Is(err, io.EOF) {
if err := dec.Decode(&rec); err != nil { writeError(w, http.StatusBadRequest, "empty", "没有可导入的记录")
continue return
}
if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组或 JSONL")
return
}
dec := json.NewDecoder(reader)
if first == '[' {
if err := dec.Decode(&records); err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组或 JSONL")
return
}
var trailing any
if err := dec.Decode(&trailing); !errors.Is(err, io.EOF) {
writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组或 JSONL")
return
}
} else {
for {
var record adminstore.ByposRecord
if err := dec.Decode(&record); errors.Is(err, io.EOF) {
break
} else if err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "请求体应为 JSON 数组或 JSONL")
return
}
records = append(records, record)
} }
records = append(records, rec)
} }
if len(records) == 0 { if len(records) == 0 {
writeError(w, http.StatusBadRequest, "empty", "\u6ca1\u6709\u53ef\u5bfc\u5165\u7684\u8bb0\u5f55") writeError(w, http.StatusBadRequest, "empty", "没有可导入的记录")
return return
} }
result, err := h.store.ImportByposRecords(r.Context(), records) result, err := h.store.ImportByposRecords(r.Context(), records)
if err != nil { if err != nil {
writeError(w, http.StatusInternalServerError, "import_error", err.Error()) internalError(w, r, err)
return return
} }
writeJSON(w, http.StatusOK, result) writeJSON(w, http.StatusOK, result)
} }
func firstNonWhitespace(reader *bufio.Reader) (byte, error) {
for {
b, err := reader.ReadByte()
if err != nil {
return 0, err
}
switch b {
case ' ', '\t', '\r', '\n':
continue
default:
if err := reader.UnreadByte(); err != nil {
return 0, err
}
return b, nil
}
}
}
+127
View File
@@ -0,0 +1,127 @@
package adminhandler
import (
"strings"
"sync"
"time"
)
type loginLimiter struct {
mu sync.Mutex
ipFailures map[string][]time.Time
usernameFailures map[string][]time.Time
ipLimit int
usernameLimit int
window time.Duration
lastPrune time.Time
}
func newLoginLimiter(ipLimit, usernameLimit int, window time.Duration) *loginLimiter {
return &loginLimiter{
ipFailures: make(map[string][]time.Time),
usernameFailures: make(map[string][]time.Time),
ipLimit: ipLimit,
usernameLimit: usernameLimit,
window: window,
}
}
func loginUsernameKey(username string) string {
return strings.ToLower(strings.TrimSpace(username))
}
func pruneLoginFailures(failures []time.Time, cutoff time.Time) []time.Time {
kept := failures[:0]
for _, failure := range failures {
if failure.After(cutoff) {
kept = append(kept, failure)
}
}
return kept
}
func (l *loginLimiter) pruneExpired(now time.Time) {
if !l.lastPrune.IsZero() && now.Sub(l.lastPrune) < l.window {
return
}
cutoff := now.Add(-l.window)
for key, failures := range l.ipFailures {
kept := pruneLoginFailures(failures, cutoff)
if len(kept) == 0 {
delete(l.ipFailures, key)
} else {
l.ipFailures[key] = kept
}
}
for key, failures := range l.usernameFailures {
kept := pruneLoginFailures(failures, cutoff)
if len(kept) == 0 {
delete(l.usernameFailures, key)
} else {
l.usernameFailures[key] = kept
}
}
l.lastPrune = now
}
func retryAfter(failures []time.Time, limit int, now time.Time, window time.Duration) time.Duration {
if len(failures) < limit || len(failures) == 0 {
return 0
}
remaining := failures[0].Add(window).Sub(now)
if remaining < 0 {
return 0
}
return remaining
}
func (l *loginLimiter) blocked(ip, username string) (bool, time.Duration) {
now := time.Now()
cutoff := now.Add(-l.window)
username = loginUsernameKey(username)
l.mu.Lock()
defer l.mu.Unlock()
l.pruneExpired(now)
ipFailures := pruneLoginFailures(l.ipFailures[ip], cutoff)
if len(ipFailures) == 0 {
delete(l.ipFailures, ip)
} else {
l.ipFailures[ip] = ipFailures
}
userFailures := pruneLoginFailures(l.usernameFailures[username], cutoff)
if len(userFailures) == 0 {
delete(l.usernameFailures, username)
} else {
l.usernameFailures[username] = userFailures
}
ipRetry := retryAfter(ipFailures, l.ipLimit, now, l.window)
userRetry := retryAfter(userFailures, l.usernameLimit, now, l.window)
if userRetry > ipRetry {
ipRetry = userRetry
}
return ipRetry > 0, ipRetry
}
func (l *loginLimiter) recordFailure(ip, username string) {
now := time.Now()
cutoff := now.Add(-l.window)
username = loginUsernameKey(username)
l.mu.Lock()
defer l.mu.Unlock()
l.pruneExpired(now)
ipFailures := pruneLoginFailures(l.ipFailures[ip], cutoff)
l.ipFailures[ip] = append(ipFailures, now)
userFailures := pruneLoginFailures(l.usernameFailures[username], cutoff)
l.usernameFailures[username] = append(userFailures, now)
}
func (l *loginLimiter) clearIP(ip string) {
l.mu.Lock()
delete(l.ipFailures, ip)
l.mu.Unlock()
}
+141
View File
@@ -0,0 +1,141 @@
package adminhandler
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/baicai2026-baicai/goods/api/internal/auth"
"golang.org/x/crypto/bcrypt"
)
func TestLoginLimiterBlocksByIPAndUsername(t *testing.T) {
limiter := newLoginLimiter(2, 3, time.Minute)
limiter.recordFailure("192.0.2.1", "Admin")
limiter.recordFailure("192.0.2.1", "admin")
blocked, retry := limiter.blocked("192.0.2.1", "admin")
if !blocked || retry <= 0 {
t.Fatalf("IP limit: blocked=%v retry=%v, want blocked with retry", blocked, retry)
}
limiter.recordFailure("192.0.2.2", "admin")
blocked, retry = limiter.blocked("192.0.2.2", "ADMIN")
if !blocked || retry <= 0 {
t.Fatalf("username limit: blocked=%v retry=%v, want blocked with retry", blocked, retry)
}
}
func TestLoginBlockedReturnsRetryAfterWithoutCheckingPassword(t *testing.T) {
h := New(nil, nil, "/ping", nil)
h.loginLimit = newLoginLimiter(1, 1, 2*time.Second)
h.loginLimit.recordFailure("192.0.2.10", "admin")
req := httptest.NewRequest(http.MethodPost, "/ping/api/login", strings.NewReader(
`{"username":"admin","password":"irrelevant"}`,
))
req.RemoteAddr = "192.0.2.10:1234"
recorder := httptest.NewRecorder()
h.Login(recorder, req)
if recorder.Code != http.StatusTooManyRequests {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusTooManyRequests)
}
if retryAfter := recorder.Header().Get("Retry-After"); retryAfter != "2" && retryAfter != "1" {
t.Fatalf("Retry-After = %q, want 1 or 2 seconds", retryAfter)
}
}
func TestLoginFailureRecordsIPAndUsername(t *testing.T) {
passwordHash, err := bcrypt.GenerateFromPassword([]byte("s3cret"), bcrypt.MinCost)
if err != nil {
t.Fatalf("hash password: %v", err)
}
h := New(nil, auth.New("admin", passwordHash, []byte("secret"), time.Hour), "/ping", nil)
req := httptest.NewRequest(http.MethodPost, "/ping/api/login", strings.NewReader(
`{"username":"admin","password":"wrong"}`,
))
req.RemoteAddr = "192.0.2.15:1234"
recorder := httptest.NewRecorder()
h.Login(recorder, req)
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusUnauthorized)
}
if got := len(h.loginLimit.ipFailures["192.0.2.15"]); got != 1 {
t.Fatalf("IP failure count = %d, want 1", got)
}
if got := len(h.loginLimit.usernameFailures["admin"]); got != 1 {
t.Fatalf("username failure count = %d, want 1", got)
}
}
func TestLoginSuccessClearsIPFailures(t *testing.T) {
passwordHash, err := bcrypt.GenerateFromPassword([]byte("s3cret"), bcrypt.MinCost)
if err != nil {
t.Fatalf("hash password: %v", err)
}
h := New(nil, auth.New("admin", passwordHash, []byte("secret"), time.Hour), "/ping", nil)
h.loginLimit.recordFailure("192.0.2.20", "admin")
h.loginLimit.recordFailure("192.0.2.20", "admin")
req := httptest.NewRequest(http.MethodPost, "/ping/api/login", strings.NewReader(
`{"username":"admin","password":"s3cret"}`,
))
req.RemoteAddr = "192.0.2.20:1234"
recorder := httptest.NewRecorder()
h.Login(recorder, req)
if recorder.Code != http.StatusOK {
t.Fatalf("status = %d, want %d: %s", recorder.Code, http.StatusOK, recorder.Body.String())
}
if blocked, _ := h.loginLimit.blocked("192.0.2.20", "admin"); blocked {
t.Fatal("successful login did not clear IP failures")
}
}
func TestLoginLimiterRecoversAfterWindow(t *testing.T) {
limiter := newLoginLimiter(1, 1, 20*time.Millisecond)
limiter.recordFailure("192.0.2.30", "admin")
if blocked, _ := limiter.blocked("192.0.2.30", "admin"); !blocked {
t.Fatal("expected login to be blocked before window expires")
}
time.Sleep(30 * time.Millisecond)
if blocked, _ := limiter.blocked("192.0.2.30", "admin"); blocked {
t.Fatal("login remained blocked after window expired")
}
limiter.mu.Lock()
defer limiter.mu.Unlock()
if len(limiter.ipFailures) != 0 || len(limiter.usernameFailures) != 0 {
t.Fatalf("expired entries remain: ip=%d username=%d",
len(limiter.ipFailures), len(limiter.usernameFailures))
}
}
func TestLogoutRevokesCurrentToken(t *testing.T) {
passwordHash, err := bcrypt.GenerateFromPassword([]byte("s3cret"), bcrypt.MinCost)
if err != nil {
t.Fatalf("hash password: %v", err)
}
authn := auth.New("admin", passwordHash, []byte("secret"), time.Hour)
token, err := authn.Login("admin", "s3cret")
if err != nil {
t.Fatalf("login: %v", err)
}
h := New(nil, authn, "/ping", nil)
req := httptest.NewRequest(http.MethodPost, "/ping/api/logout", nil)
req.Header.Set("Authorization", "Bearer "+token)
recorder := httptest.NewRecorder()
h.Router().ServeHTTP(recorder, req)
if recorder.Code != http.StatusNoContent {
t.Fatalf("logout status = %d, want %d", recorder.Code, http.StatusNoContent)
}
if _, err := authn.Verify(token); err == nil {
t.Fatal("logout did not revoke token")
}
}
+26 -8
View File
@@ -8,10 +8,11 @@ import (
// rateLimiter is a simple fixed-window per-key limiter used to throttle // rateLimiter is a simple fixed-window per-key limiter used to throttle
// anonymous public submissions (basic anti-spam; captcha can be added later). // anonymous public submissions (basic anti-spam; captcha can be added later).
type rateLimiter struct { type rateLimiter struct {
mu sync.Mutex mu sync.Mutex
hits map[string][]time.Time hits map[string][]time.Time
limit int limit int
window time.Duration window time.Duration
lastPrune time.Time
} }
func newRateLimiter(limit int, window time.Duration) *rateLimiter { func newRateLimiter(limit int, window time.Duration) *rateLimiter {
@@ -26,12 +27,19 @@ func (r *rateLimiter) allow(key string) bool {
r.mu.Lock() r.mu.Lock()
defer r.mu.Unlock() defer r.mu.Unlock()
kept := r.hits[key][:0] if now.Sub(r.lastPrune) > r.window {
for _, t := range r.hits[key] { for expiredKey, hits := range r.hits {
if t.After(cutoff) { kept := pruneRateLimitHits(hits, cutoff)
kept = append(kept, t) if len(kept) == 0 {
delete(r.hits, expiredKey)
} else {
r.hits[expiredKey] = kept
}
} }
r.lastPrune = now
} }
kept := pruneRateLimitHits(r.hits[key], cutoff)
if len(kept) >= r.limit { if len(kept) >= r.limit {
r.hits[key] = kept r.hits[key] = kept
return false return false
@@ -39,3 +47,13 @@ func (r *rateLimiter) allow(key string) bool {
r.hits[key] = append(kept, now) r.hits[key] = append(kept, now)
return true return true
} }
func pruneRateLimitHits(hits []time.Time, cutoff time.Time) []time.Time {
kept := hits[:0]
for _, hit := range hits {
if hit.After(cutoff) {
kept = append(kept, hit)
}
}
return kept
}
@@ -0,0 +1,31 @@
package adminhandler
import (
"testing"
"time"
)
func TestRateLimiterPrunesExpiredKeysAndPreservesLiveLimits(t *testing.T) {
window := time.Minute
now := time.Now()
limiter := newRateLimiter(2, window)
limiter.hits["expired"] = []time.Time{now.Add(-2 * window)}
limiter.hits["live"] = []time.Time{now.Add(-time.Second)}
limiter.lastPrune = now.Add(-2 * window)
if !limiter.allow("live") {
t.Fatal("allow rejected a live key below its limit")
}
if _, ok := limiter.hits["expired"]; ok {
t.Fatal("expired key was not pruned")
}
if got := len(limiter.hits["live"]); got != 2 {
t.Fatalf("live key hit count = %d, want 2", got)
}
if limiter.allow("live") {
t.Fatal("allow accepted a live key at its limit")
}
if got := len(limiter.hits["live"]); got != 2 {
t.Fatalf("live key hit count after rejection = %d, want 2", got)
}
}
+15 -2
View File
@@ -6,6 +6,7 @@ import (
"errors" "errors"
"strings" "strings"
"github.com/baicai2026-baicai/goods/api/internal/gtin"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
) )
@@ -76,8 +77,20 @@ func (s *Store) CreateBackflowSubmissions(ctx context.Context, items []Submissio
if g == "" { if g == "" {
in.GTIN = nil in.GTIN = nil
} else { } else {
in.GTIN = &g // Validate/normalize so a malformed barcode is reported as an
res.GTIN = &g // invalid item instead of aborting the batch (the gtin column
// is varchar(14) and only GS1 codes are archived).
norm, err := gtin.Normalize(g)
if err != nil {
res.GTIN = &g
res.Status = "invalid"
res.Reason = err.Error()
sum.Invalid++
sum.Results = append(sum.Results, res)
continue
}
in.GTIN = &norm
res.GTIN = &norm
} }
} }
+5
View File
@@ -327,6 +327,11 @@ VALUES ($1,$2,$3,$4,$5,$6,$7)`, actor, action, entity, entityID, fields, bj, aj)
return err return err
} }
// LogAdminSession records an admin authentication event without an entity ID.
func (s *Store) LogAdminSession(ctx context.Context, actor, action string, detail map[string]any) error {
return s.writeAudit(ctx, actor, action, "admin_session", nil, nil, nil, detail)
}
// ---------- images ---------- // ---------- images ----------
// AddImage inserts an image URL (manual source) and recomputes quality. // AddImage inserts an image URL (manual source) and recomputes quality.
+61 -9
View File
@@ -6,12 +6,15 @@ package auth
import ( import (
"context" "context"
"crypto/hmac" "crypto/hmac"
"crypto/rand"
"crypto/sha256" "crypto/sha256"
"encoding/base64" "encoding/base64"
"encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
"net/http" "net/http"
"strings" "strings"
"sync"
"time" "time"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
@@ -23,11 +26,16 @@ type Authenticator struct {
passwordHash []byte passwordHash []byte
secret []byte secret []byte
ttl time.Duration ttl time.Duration
mu sync.RWMutex
revoked map[string]int64
} }
// New builds an Authenticator. passwordHash must be a bcrypt hash. // New builds an Authenticator. passwordHash must be a bcrypt hash.
func New(username string, passwordHash, secret []byte, ttl time.Duration) *Authenticator { func New(username string, passwordHash, secret []byte, ttl time.Duration) *Authenticator {
return &Authenticator{username: username, passwordHash: passwordHash, secret: secret, ttl: ttl} return &Authenticator{
username: username, passwordHash: passwordHash, secret: secret, ttl: ttl,
revoked: make(map[string]int64),
}
} }
// ErrInvalidCredentials is returned when login fails. // ErrInvalidCredentials is returned when login fails.
@@ -49,6 +57,7 @@ func (a *Authenticator) Login(username, password string) (string, error) {
type claims struct { type claims struct {
Sub string `json:"sub"` Sub string `json:"sub"`
Exp int64 `json:"exp"` Exp int64 `json:"exp"`
JTI string `json:"jti"`
} }
func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) } func b64(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
@@ -61,7 +70,15 @@ func (a *Authenticator) sign(signingInput string) string {
func (a *Authenticator) issue(sub string) (string, error) { func (a *Authenticator) issue(sub string) (string, error) {
header := b64([]byte(`{"alg":"HS256","typ":"JWT"}`)) header := b64([]byte(`{"alg":"HS256","typ":"JWT"}`))
payloadJSON, err := json.Marshal(claims{Sub: sub, Exp: time.Now().Add(a.ttl).Unix()}) randomID := make([]byte, 16)
if _, err := rand.Read(randomID); err != nil {
return "", err
}
payloadJSON, err := json.Marshal(claims{
Sub: sub,
Exp: time.Now().Add(a.ttl).Unix(),
JTI: hex.EncodeToString(randomID),
})
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -70,30 +87,65 @@ func (a *Authenticator) issue(sub string) (string, error) {
return signingInput + "." + a.sign(signingInput), nil return signingInput + "." + a.sign(signingInput), nil
} }
// Verify checks a token's signature and expiry, returning the subject. func (a *Authenticator) verifyClaims(token string) (claims, error) {
func (a *Authenticator) Verify(token string) (string, error) {
parts := strings.Split(token, ".") parts := strings.Split(token, ".")
if len(parts) != 3 { if len(parts) != 3 {
return "", errors.New("malformed token") return claims{}, errors.New("malformed token")
} }
signingInput := parts[0] + "." + parts[1] signingInput := parts[0] + "." + parts[1]
if !hmac.Equal([]byte(a.sign(signingInput)), []byte(parts[2])) { if !hmac.Equal([]byte(a.sign(signingInput)), []byte(parts[2])) {
return "", errors.New("bad signature") return claims{}, errors.New("bad signature")
} }
payload, err := base64.RawURLEncoding.DecodeString(parts[1]) payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil { if err != nil {
return "", err return claims{}, err
} }
var c claims var c claims
if err := json.Unmarshal(payload, &c); err != nil { if err := json.Unmarshal(payload, &c); err != nil {
return "", err return claims{}, err
} }
if time.Now().Unix() >= c.Exp { if time.Now().Unix() >= c.Exp {
return "", errors.New("token expired") return claims{}, errors.New("token expired")
}
if c.JTI == "" {
return claims{}, errors.New("token missing jti")
}
return c, nil
}
// Verify checks a token's signature, expiry, and revocation status.
func (a *Authenticator) Verify(token string) (string, error) {
c, err := a.verifyClaims(token)
if err != nil {
return "", err
}
a.mu.RLock()
exp, revoked := a.revoked[c.JTI]
a.mu.RUnlock()
if revoked && time.Now().Unix() < exp {
return "", errors.New("token revoked")
} }
return c.Sub, nil return c.Sub, nil
} }
// Revoke verifies a token and records its identifier until it expires.
func (a *Authenticator) Revoke(token string) error {
c, err := a.verifyClaims(token)
if err != nil {
return err
}
now := time.Now().Unix()
a.mu.Lock()
defer a.mu.Unlock()
for jti, exp := range a.revoked {
if exp <= now {
delete(a.revoked, jti)
}
}
a.revoked[c.JTI] = c.Exp
return nil
}
type ctxKey int type ctxKey int
const userKey ctxKey = 0 const userKey ctxKey = 0
+90
View File
@@ -1,6 +1,12 @@
package auth package auth
import ( import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing" "testing"
"time" "time"
@@ -60,3 +66,87 @@ func TestVerifyRejectsExpired(t *testing.T) {
t.Fatal("expected expired token error") t.Fatal("expected expired token error")
} }
} }
func TestIssuedTokensHaveUniqueRandomJTI(t *testing.T) {
a := newTestAuth(t, time.Hour)
first, err := a.Login("admin", "s3cret")
if err != nil {
t.Fatalf("first login: %v", err)
}
second, err := a.Login("admin", "s3cret")
if err != nil {
t.Fatalf("second login: %v", err)
}
readJTI := func(token string) string {
t.Helper()
parts := strings.Split(token, ".")
if len(parts) != 3 {
t.Fatalf("token has %d parts, want 3", len(parts))
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
t.Fatalf("decode payload: %v", err)
}
var c claims
if err := json.Unmarshal(payload, &c); err != nil {
t.Fatalf("unmarshal claims: %v", err)
}
randomID, err := hex.DecodeString(c.JTI)
if err != nil {
t.Fatalf("decode jti: %v", err)
}
if len(randomID) != 16 {
t.Fatalf("jti length = %d bytes, want 16", len(randomID))
}
return c.JTI
}
if firstID, secondID := readJTI(first), readJTI(second); firstID == secondID {
t.Fatal("issued tokens have the same jti")
}
}
func TestRevokeRejectsTokenInVerifyAndMiddleware(t *testing.T) {
a := newTestAuth(t, time.Hour)
token, err := a.Login("admin", "s3cret")
if err != nil {
t.Fatalf("login: %v", err)
}
if err := a.Revoke(token); err != nil {
t.Fatalf("revoke: %v", err)
}
if _, err := a.Verify(token); err == nil {
t.Fatal("Verify accepted revoked token")
}
nextCalled := false
handler := a.Middleware(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
nextCalled = true
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Authorization", "Bearer "+token)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusUnauthorized)
}
if nextCalled {
t.Fatal("middleware called next for revoked token")
}
}
func TestRevokePrunesExpiredEntries(t *testing.T) {
a := newTestAuth(t, time.Hour)
a.revoked["expired"] = time.Now().Add(-time.Minute).Unix()
token, err := a.Login("admin", "s3cret")
if err != nil {
t.Fatalf("login: %v", err)
}
if err := a.Revoke(token); err != nil {
t.Fatalf("revoke: %v", err)
}
if _, ok := a.revoked["expired"]; ok {
t.Fatal("Revoke retained an expired revocation")
}
}
+24 -4
View File
@@ -6,9 +6,9 @@
// so the cache can never take the API down or serve stale data after Redis loss. // so the cache can never take the API down or serve stale data after Redis loss.
// //
// Invalidation is global and O(1): keys are namespaced by an epoch counter // Invalidation is global and O(1): keys are namespaced by an epoch counter
// stored in Redis (og:cache:epoch). The Python ingestion bumps that counter // stored in Redis (og:cache:epoch). Python ingestion and successful admin
// after a write run, which logically invalidates every cached entry at once // writes bump that counter, logically invalidating cached entries at once while
// while old keys age out via their TTL. The epoch is read at most once per // old keys age out via their TTL. The epoch is read at most once per
// refresh interval per process, so it adds no per-request round trip. // refresh interval per process, so it adds no per-request round trip.
package cache package cache
@@ -35,7 +35,7 @@ const epochRefresh = 10 * time.Second
const opTimeout = 150 * time.Millisecond const opTimeout = 150 * time.Millisecond
// Cache wraps a Redis client. A nil-backed Cache (Redis unconfigured) disables // Cache wraps a Redis client. A nil-backed Cache (Redis unconfigured) disables
// caching: every Get misses and every Set is a no-op. // caching: every Get misses, every Set is a no-op, and Bump succeeds.
type Cache struct { type Cache struct {
rdb *redis.Client rdb *redis.Client
@@ -59,6 +59,26 @@ func New(redisURL string) *Cache {
// Enabled reports whether a Redis backend is configured. // Enabled reports whether a Redis backend is configured.
func (c *Cache) Enabled() bool { return c != nil && c.rdb != nil } func (c *Cache) Enabled() bool { return c != nil && c.rdb != nil }
// Bump increments the global cache epoch to invalidate existing entries.
func (c *Cache) Bump(ctx context.Context) error {
if !c.Enabled() {
return nil
}
cctx, cancel := context.WithTimeout(ctx, opTimeout)
defer cancel()
epoch, err := c.rdb.Incr(cctx, epochKey).Result()
if err != nil {
return err
}
c.mu.Lock()
c.epoch = epoch
c.epochSetAt = time.Now()
c.epochOK = true
c.mu.Unlock()
return nil
}
// epochNow returns the current cache generation, reading it from Redis at most // epochNow returns the current cache generation, reading it from Redis at most
// once per epochRefresh. On any Redis error it keeps the last known value and // once per epochRefresh. On any Redis error it keeps the last known value and
// throttles re-reads so a down backend cannot slow the hot path. // throttles re-reads so a down backend cannot slow the hot path.
+11 -7
View File
@@ -22,6 +22,15 @@ func TestDisabledFailsOpen(t *testing.T) {
} }
} }
func TestBumpDisabledCache(t *testing.T) {
if err := (*Cache)(nil).Bump(context.Background()); err != nil {
t.Fatalf("nil cache Bump(): %v", err)
}
if err := (&Cache{}).Bump(context.Background()); err != nil {
t.Fatalf("disabled cache Bump(): %v", err)
}
}
func testCache(t *testing.T) *Cache { func testCache(t *testing.T) *Cache {
t.Helper() t.Helper()
url := os.Getenv("OPENGOODS_REDIS_URL") url := os.Getenv("OPENGOODS_REDIS_URL")
@@ -69,14 +78,9 @@ func TestEpochInvalidation(t *testing.T) {
t.Fatal("expected hit before epoch bump") t.Fatal("expected hit before epoch bump")
} }
// Simulate an ingestion write bumping the global epoch. if err := c.Bump(ctx); err != nil {
if err := c.rdb.Incr(ctx, epochKey).Err(); err != nil { t.Fatalf("bump epoch: %v", err)
t.Fatalf("incr epoch: %v", err)
} }
// Force the process to re-read the epoch rather than use its cached value.
c.mu.Lock()
c.epochOK = false
c.mu.Unlock()
if c.GetJSON(ctx, suffix, &dst) { if c.GetJSON(ctx, suffix, &dst) {
t.Fatal("entry should be invisible after epoch bump") t.Fatal("entry should be invisible after epoch bump")
+140
View File
@@ -0,0 +1,140 @@
package clientip
import (
"fmt"
"net"
"net/http"
"strings"
)
// Resolver resolves client addresses using configured trusted proxy ranges.
type Resolver struct {
trusted []*net.IPNet
}
var defaultResolver = &Resolver{trusted: []*net.IPNet{
mustCIDR("127.0.0.0/8"),
mustCIDR("::1/128"),
mustCIDR("10.0.0.0/8"),
mustCIDR("172.16.0.0/12"),
mustCIDR("192.168.0.0/16"),
mustCIDR("fc00::/7"),
}}
// Parse creates a resolver from comma-separated CIDRs or bare IP addresses.
func Parse(spec string) (*Resolver, error) {
spec = strings.TrimSpace(spec)
if spec == "" {
return Default(), nil
}
if strings.EqualFold(spec, "none") {
return &Resolver{}, nil
}
resolver := &Resolver{}
for _, item := range strings.Split(spec, ",") {
item = strings.TrimSpace(item)
if item == "" {
return nil, fmt.Errorf("empty trusted proxy entry")
}
if ip := net.ParseIP(item); ip != nil {
if ipv4 := ip.To4(); ipv4 != nil {
resolver.trusted = append(resolver.trusted, &net.IPNet{
IP: ipv4,
Mask: net.CIDRMask(32, 32),
})
} else {
resolver.trusted = append(resolver.trusted, &net.IPNet{
IP: ip,
Mask: net.CIDRMask(128, 128),
})
}
continue
}
_, network, err := net.ParseCIDR(item)
if err != nil {
return nil, fmt.Errorf("invalid trusted proxy entry %q: %w", item, err)
}
resolver.trusted = append(resolver.trusted, network)
}
return resolver, nil
}
// Default trusts loopback, private IPv4, and unique-local IPv6 proxies.
func Default() *Resolver {
return defaultResolver
}
// ClientIP returns the resolved client IP without a port.
func (r *Resolver) ClientIP(req *http.Request) string {
if req == nil {
return ""
}
if r == nil {
r = Default()
}
peer, peerIP := remoteIP(req.RemoteAddr)
if peerIP == nil || !r.isTrusted(peerIP) {
return peer
}
if ip := net.ParseIP(strings.TrimSpace(req.Header.Get("X-Real-IP"))); ip != nil {
return ip.String()
}
var forwarded []string
for _, value := range req.Header.Values("X-Forwarded-For") {
forwarded = append(forwarded, strings.Split(value, ",")...)
}
for i := len(forwarded) - 1; i >= 0; i-- {
ip := net.ParseIP(strings.TrimSpace(forwarded[i]))
if ip != nil && !r.isTrusted(ip) {
return ip.String()
}
}
return peer
}
// Middleware normalizes RemoteAddr to the resolved client IP.
func (r *Resolver) Middleware(next http.Handler) http.Handler {
if r == nil {
r = Default()
}
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
req.RemoteAddr = r.ClientIP(req)
next.ServeHTTP(w, req)
})
}
func (r *Resolver) isTrusted(ip net.IP) bool {
for _, network := range r.trusted {
if network.Contains(ip) {
return true
}
}
return false
}
func remoteIP(remoteAddr string) (string, net.IP) {
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
host = remoteAddr
}
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = host[1 : len(host)-1]
}
ip := net.ParseIP(host)
if ip == nil {
return host, nil
}
return ip.String(), ip
}
func mustCIDR(value string) *net.IPNet {
_, network, err := net.ParseCIDR(value)
if err != nil {
panic(err)
}
return network
}
+148
View File
@@ -0,0 +1,148 @@
package clientip
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestClientIP(t *testing.T) {
tests := []struct {
name string
spec string
remoteAddr string
realIP string
trueIP string
forwarded []string
want string
}{
{
name: "untrusted peer ignores spoofed headers",
spec: "10.0.0.0/8",
remoteAddr: "203.0.113.20:1234",
realIP: "198.51.100.10",
trueIP: "198.51.100.12",
forwarded: []string{"198.51.100.11"},
want: "203.0.113.20",
},
{
name: "ignores True-Client-IP",
spec: "10.0.0.0/8",
remoteAddr: "10.0.0.2:1234",
trueIP: "198.51.100.12",
want: "10.0.0.2",
},
{
name: "trusted peer accepts X-Real-IP",
spec: "10.0.0.0/8",
remoteAddr: "10.0.0.2:1234",
realIP: "198.51.100.10",
forwarded: []string{"198.51.100.11"},
want: "198.51.100.10",
},
{
name: "walks forwarded chain from the right",
spec: "10.0.0.0/8",
remoteAddr: "10.0.0.3:1234",
forwarded: []string{"198.51.100.10, 10.0.0.1", "10.0.0.2"},
want: "198.51.100.10",
},
{
name: "ignores invalid header values",
spec: "10.0.0.0/8",
remoteAddr: "10.0.0.3:1234",
realIP: "not-an-ip",
forwarded: []string{"not-an-ip, 198.51.100.10, 10.0.0.1"},
want: "198.51.100.10",
},
{
name: "falls back to peer when forwarded values are invalid or trusted",
spec: "10.0.0.0/8",
remoteAddr: "10.0.0.3:1234",
realIP: "not-an-ip",
forwarded: []string{"bad, 10.0.0.1"},
want: "10.0.0.3",
},
{
name: "none trusts no proxy",
spec: "none",
remoteAddr: "10.0.0.2:1234",
realIP: "198.51.100.10",
forwarded: []string{"198.51.100.11"},
want: "10.0.0.2",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resolver, err := Parse(tt.spec)
if err != nil {
t.Fatalf("Parse(%q): %v", tt.spec, err)
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = tt.remoteAddr
if tt.realIP != "" {
req.Header.Set("X-Real-IP", tt.realIP)
}
if tt.trueIP != "" {
req.Header.Set("True-Client-IP", tt.trueIP)
}
for _, value := range tt.forwarded {
req.Header.Add("X-Forwarded-For", value)
}
if got := resolver.ClientIP(req); got != tt.want {
t.Fatalf("ClientIP() = %q, want %q", got, tt.want)
}
})
}
}
func TestParseEmptyUsesDefaultNetworks(t *testing.T) {
resolver, err := Parse("")
if err != nil {
t.Fatalf("Parse(): %v", err)
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "10.1.2.3:1234"
req.Header.Set("X-Real-IP", "198.51.100.10")
if got := resolver.ClientIP(req); got != "198.51.100.10" {
t.Fatalf("ClientIP() = %q, want %q", got, "198.51.100.10")
}
}
func TestParseBareIPs(t *testing.T) {
resolver, err := Parse("192.0.2.10, 2001:db8::10")
if err != nil {
t.Fatalf("Parse(): %v", err)
}
if !resolver.isTrusted([]byte{192, 0, 2, 10}) {
t.Fatal("bare IPv4 address was not trusted")
}
if !resolver.isTrusted([]byte{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10}) {
t.Fatal("bare IPv6 address was not trusted")
}
}
func TestParseRejectsInvalidEntry(t *testing.T) {
if _, err := Parse("10.0.0.0/8, invalid"); err == nil {
t.Fatal("Parse() accepted an invalid entry")
}
}
func TestMiddlewareNormalizesRemoteAddr(t *testing.T) {
resolver, err := Parse("10.0.0.0/8")
if err != nil {
t.Fatalf("Parse(): %v", err)
}
var got string
handler := resolver.Middleware(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
got = r.RemoteAddr
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.RemoteAddr = "10.0.0.2:1234"
req.Header.Set("X-Real-IP", "198.51.100.10")
handler.ServeHTTP(httptest.NewRecorder(), req)
if got != "198.51.100.10" {
t.Fatalf("normalized RemoteAddr = %q, want %q", got, "198.51.100.10")
}
}
+2
View File
@@ -12,6 +12,7 @@ type Config struct {
Addr string Addr string
DatabaseURL string DatabaseURL string
RedisURL string RedisURL string
TrustedProxies string
AnonRateLimitPerMin int AnonRateLimitPerMin int
AnonTotalQuota int AnonTotalQuota int
RegisteredRateLimitPerMin int RegisteredRateLimitPerMin int
@@ -24,6 +25,7 @@ func Load() Config {
Addr: getenv("OPENGOODS_ADDR", ":8080"), Addr: getenv("OPENGOODS_ADDR", ":8080"),
DatabaseURL: getenv("OPENGOODS_DATABASE_URL", "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable"), DatabaseURL: getenv("OPENGOODS_DATABASE_URL", "postgres://opengoods:opengoods@localhost:5432/opengoods?sslmode=disable"),
RedisURL: getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0"), RedisURL: getenv("OPENGOODS_REDIS_URL", "redis://localhost:6379/0"),
TrustedProxies: getenv("OPENGOODS_TRUSTED_PROXIES", ""),
AnonRateLimitPerMin: getenvInt("OPENGOODS_ANON_RATE_LIMIT_PER_MIN", 60), AnonRateLimitPerMin: getenvInt("OPENGOODS_ANON_RATE_LIMIT_PER_MIN", 60),
AnonTotalQuota: getenvInt("OPENGOODS_ANON_TOTAL_QUOTA", 1000), AnonTotalQuota: getenvInt("OPENGOODS_ANON_TOTAL_QUOTA", 1000),
RegisteredRateLimitPerMin: getenvInt("OPENGOODS_REGISTERED_RATE_LIMIT_PER_MIN", 300), RegisteredRateLimitPerMin: getenvInt("OPENGOODS_REGISTERED_RATE_LIMIT_PER_MIN", 300),
+10
View File
@@ -0,0 +1,10 @@
package config
import "testing"
func TestLoadTrustedProxies(t *testing.T) {
t.Setenv("OPENGOODS_TRUSTED_PROXIES", "10.0.0.0/8")
if got := Load().TrustedProxies; got != "10.0.0.0/8" {
t.Fatalf("TrustedProxies = %q, want %q", got, "10.0.0.0/8")
}
}
+26 -1
View File
@@ -16,6 +16,7 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware" "github.com/go-chi/chi/v5/middleware"
"github.com/baicai2026-baicai/goods/api/internal/clientip"
"github.com/baicai2026-baicai/goods/api/internal/ratelimit" "github.com/baicai2026-baicai/goods/api/internal/ratelimit"
"github.com/baicai2026-baicai/goods/api/internal/store" "github.com/baicai2026-baicai/goods/api/internal/store"
) )
@@ -33,6 +34,7 @@ const QualifiedMinScore = 0.6
const ( const (
defaultPageSize = 20 defaultPageSize = 20
maxPageSize = 100 maxPageSize = 100
maxResultWindow = 10000
// defaultAnonLimit is the per-minute request budget for unauthenticated // defaultAnonLimit is the per-minute request budget for unauthenticated
// callers (identified by client IP) when none is configured. // callers (identified by client IP) when none is configured.
@@ -57,6 +59,7 @@ type Handler struct {
store *store.Store store *store.Store
spa fs.FS spa fs.FS
limiter *ratelimit.Limiter limiter *ratelimit.Limiter
clientIP *clientip.Resolver
anonLimit int anonLimit int
anonTotalQuota int64 anonTotalQuota int64
regRatePerMin int regRatePerMin int
@@ -69,6 +72,7 @@ func New(s *store.Store, spa fs.FS) *Handler {
return &Handler{ return &Handler{
store: s, store: s,
spa: spa, spa: spa,
clientIP: clientip.Default(),
anonLimit: defaultAnonLimit, anonLimit: defaultAnonLimit,
anonTotalQuota: defaultAnonTotalQuota, anonTotalQuota: defaultAnonTotalQuota,
regRatePerMin: defaultRegRatePerMin, regRatePerMin: defaultRegRatePerMin,
@@ -87,6 +91,15 @@ func (h *Handler) WithRateLimit(l *ratelimit.Limiter, anonPerMin int) *Handler {
return h return h
} }
// WithClientIP sets the trusted-proxy resolver used to normalize request IPs.
func (h *Handler) WithClientIP(resolver *clientip.Resolver) *Handler {
if resolver == nil {
resolver = clientip.Default()
}
h.clientIP = resolver
return h
}
// WithQuotas configures the cumulative free quota for anonymous callers and the // WithQuotas configures the cumulative free quota for anonymous callers and the
// per-minute rate + cumulative quota self-registered keys receive. Non-positive // per-minute rate + cumulative quota self-registered keys receive. Non-positive
// values keep the defaults. // values keep the defaults.
@@ -107,7 +120,7 @@ func (h *Handler) WithQuotas(anonTotal, regPerMin, regTotal int) *Handler {
func (h *Handler) Router() http.Handler { func (h *Handler) Router() http.Handler {
r := chi.NewRouter() r := chi.NewRouter()
r.Use(middleware.RequestID) r.Use(middleware.RequestID)
r.Use(middleware.RealIP) r.Use(h.clientIP.Middleware)
r.Use(middleware.Recoverer) r.Use(middleware.Recoverer)
r.Get("/healthz", h.Healthz) r.Get("/healthz", h.Healthz)
@@ -221,6 +234,10 @@ func (h *Handler) SearchProducts(w http.ResponseWriter, r *http.Request) {
Country: strings.TrimSpace(qv.Get("country")), Country: strings.TrimSpace(qv.Get("country")),
} }
page, size := pageParams(r) page, size := pageParams(r)
if pageTooDeep(page, size) {
writeError(w, r, http.StatusBadRequest, "page_too_deep", "分页结果不能超过 10000 条")
return
}
items, total, err := h.store.SearchProducts(r.Context(), filters, size, (page-1)*size) items, total, err := h.store.SearchProducts(r.Context(), filters, size, (page-1)*size)
if h.handleErr(w, r, err) { if h.handleErr(w, r, err) {
@@ -258,6 +275,10 @@ func (h *Handler) ProductMSRP(w http.ResponseWriter, r *http.Request) {
// ListBrands returns a paginated list of brands. // ListBrands returns a paginated list of brands.
func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) { func (h *Handler) ListBrands(w http.ResponseWriter, r *http.Request) {
page, size := pageParams(r) page, size := pageParams(r)
if pageTooDeep(page, size) {
writeError(w, r, http.StatusBadRequest, "page_too_deep", "分页结果不能超过 10000 条")
return
}
items, total, err := h.store.ListBrands(r.Context(), size, (page-1)*size) items, total, err := h.store.ListBrands(r.Context(), size, (page-1)*size)
if h.handleErr(w, r, err) { if h.handleErr(w, r, err) {
return return
@@ -328,6 +349,10 @@ func pageParams(r *http.Request) (page, size int) {
return page, size return page, size
} }
func pageTooDeep(page, size int) bool {
return size > 0 && page > maxResultWindow/size
}
func atoiDefault(s string, fallback int) int { func atoiDefault(s string, fallback int) int {
if s == "" { if s == "" {
return fallback return fallback
+13
View File
@@ -116,6 +116,19 @@ func TestSearchProducts(t *testing.T) {
} }
} }
func TestPaginationResultWindowBoundary(t *testing.T) {
h, _ := newTestHandler(t)
for _, path := range []string{
"/api/" + APIVersion + "/products/search?page=100&size=100",
"/api/" + APIVersion + "/brands?page=100&size=100",
} {
rec := doGET(t, h, path)
if rec.Code != http.StatusOK {
t.Fatalf("%s: status = %d, body = %s", path, rec.Code, rec.Body.String())
}
}
}
func TestSearchFuzzyAndFilters(t *testing.T) { func TestSearchFuzzyAndFilters(t *testing.T) {
h, _ := newTestHandler(t) h, _ := newTestHandler(t)
ctx := context.Background() ctx := context.Background()
+37
View File
@@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings"
"testing" "testing"
) )
@@ -46,3 +47,39 @@ func TestPageParams(t *testing.T) {
} }
} }
} }
func TestPageTooDeep(t *testing.T) {
tests := []struct {
name string
page, size int
want bool
}{
{name: "boundary", page: 100, size: 100, want: false},
{name: "over boundary", page: 101, size: 100, want: true},
{name: "small page", page: 1, size: 20, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := pageTooDeep(tt.page, tt.size); got != tt.want {
t.Fatalf("pageTooDeep(%d, %d) = %v, want %v",
tt.page, tt.size, got, tt.want)
}
})
}
}
func TestDeepPaginationReturns400BeforeStoreAccess(t *testing.T) {
h := New(nil, nil)
for _, path := range []string{
"/api/" + APIVersion + "/products/search?page=101&size=100",
"/api/" + APIVersion + "/brands?page=101&size=100",
} {
rec := doGET(t, h, path)
if rec.Code != http.StatusBadRequest {
t.Fatalf("%s: status = %d, want %d", path, rec.Code, http.StatusBadRequest)
}
if !strings.Contains(rec.Body.String(), "page_too_deep") {
t.Fatalf("%s: response missing page_too_deep: %s", path, rec.Body.String())
}
}
}
+1 -1
View File
@@ -133,7 +133,7 @@ func presentedKey(r *http.Request) string {
return "" return ""
} }
// clientIP returns the caller IP, preferring chi's RealIP-normalized RemoteAddr. // clientIP returns the caller IP from the trusted-proxy-normalized RemoteAddr.
func clientIP(r *http.Request) string { func clientIP(r *http.Request) string {
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil { if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return host return host
+13 -5
View File
@@ -25,8 +25,8 @@
{ "name": "category", "in": "query", "schema": { "type": "string" }, "description": "Category code (matches the subtree), e.g. food.beverages." }, { "name": "category", "in": "query", "schema": { "type": "string" }, "description": "Category code (matches the subtree), e.g. food.beverages." },
{ "name": "brand", "in": "query", "schema": { "type": "string" }, "description": "Brand name (fuzzy)." }, { "name": "brand", "in": "query", "schema": { "type": "string" }, "description": "Brand name (fuzzy)." },
{ "name": "country", "in": "query", "schema": { "type": "string" }, "description": "Country of origin (case-insensitive prefix)." }, { "name": "country", "in": "query", "schema": { "type": "string" }, "description": "Country of origin (case-insensitive prefix)." },
{ "name": "page", "in": "query", "schema": { "type": "integer", "default": 1, "minimum": 1 } }, { "name": "page", "in": "query", "schema": { "type": "integer", "default": 1, "minimum": 1 }, "description": "Page number; page × size must not exceed 10000." },
{ "name": "size", "in": "query", "schema": { "type": "integer", "default": 20, "maximum": 100 } } { "name": "size", "in": "query", "schema": { "type": "integer", "default": 20, "maximum": 100 }, "description": "Page size; page × size must not exceed 10000." }
], ],
"responses": { "responses": {
"200": { "200": {
@@ -50,6 +50,7 @@
} }
} }
}, },
"400": { "$ref": "#/components/responses/PageTooDeep" },
"401": { "$ref": "#/components/responses/InvalidApiKey" }, "401": { "$ref": "#/components/responses/InvalidApiKey" },
"429": { "$ref": "#/components/responses/RateLimited" } "429": { "$ref": "#/components/responses/RateLimited" }
} }
@@ -99,10 +100,13 @@
"tags": ["catalog"], "tags": ["catalog"],
"summary": "List brands", "summary": "List brands",
"parameters": [ "parameters": [
{ "name": "page", "in": "query", "schema": { "type": "integer", "default": 1 } }, { "name": "page", "in": "query", "schema": { "type": "integer", "default": 1, "minimum": 1 }, "description": "Page number; page × size must not exceed 10000." },
{ "name": "size", "in": "query", "schema": { "type": "integer", "default": 20, "maximum": 100 } } { "name": "size", "in": "query", "schema": { "type": "integer", "default": 20, "maximum": 100 }, "description": "Page size; page × size must not exceed 10000." }
], ],
"responses": { "200": { "description": "Paged brands" } } "responses": {
"200": { "description": "Paged brands" },
"400": { "$ref": "#/components/responses/PageTooDeep" }
}
} }
}, },
"/categories": { "/categories": {
@@ -164,6 +168,10 @@
"InvalidApiKey": { "InvalidApiKey": {
"description": "API key invalid or revoked.", "description": "API key invalid or revoked.",
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
},
"PageTooDeep": {
"description": "The requested page exceeds the 10000-result window.",
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } }
} }
}, },
"schemas": { "schemas": {
+2 -16
View File
@@ -24,26 +24,12 @@ services:
timeout: 5s timeout: 5s
retries: 10 retries: 10
minio:
image: minio/minio:latest
restart: unless-stopped
command: server /data --console-address ":9001"
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
volumes:
- miniodata:/data
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 5s
timeout: 5s
retries: 10
api: api:
build: build:
context: . context: .
dockerfile: api/Dockerfile.prod dockerfile: api/Dockerfile.prod
restart: unless-stopped restart: unless-stopped
stop_grace_period: 30s
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
@@ -61,6 +47,7 @@ services:
context: . context: .
dockerfile: api/Dockerfile.admin dockerfile: api/Dockerfile.admin
restart: unless-stopped restart: unless-stopped
stop_grace_period: 30s
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
@@ -76,4 +63,3 @@ services:
volumes: volumes:
pgdata: pgdata:
miniodata:
-18
View File
@@ -25,23 +25,6 @@ services:
timeout: 5s timeout: 5s
retries: 5 retries: 5
minio:
image: minio/minio:latest
command: server /data --console-address ":9001"
environment:
MINIO_ROOT_USER: opengoods
MINIO_ROOT_PASSWORD: opengoods123
ports:
- "9000:9000"
- "9001:9001"
volumes:
- miniodata:/data
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 5s
timeout: 5s
retries: 5
api: api:
build: ./api build: ./api
depends_on: depends_on:
@@ -58,4 +41,3 @@ services:
volumes: volumes:
pgdata: pgdata:
miniodata:
+2 -1
View File
@@ -47,7 +47,7 @@ curl -H "Authorization: Bearer og_live_xxxxxxxx" \
## 分页 ## 分页
列表类接口支持 `page`(默认 `1`)与 `size`(默认 `20`,最大 `100`),响应含 `page`/`size`/`total`。 列表类接口支持 `page`(默认 `1`)与 `size`(默认 `20`,最大 `100`),响应含 `page`/`size`/`total`。搜索和品牌列表的 `page × size` 不得超过 `10000`;超出时返回 `400`(错误码 `page_too_deep`)。
## 端点 ## 端点
@@ -119,6 +119,7 @@ curl "https://goods.tangshasha.com/api/v1/products/barcode/5449000000996"
### `POST /api/public/backflow` — 批量回流未收录商品 ### `POST /api/public/backflow` — 批量回流未收录商品
- 鉴权:请求头携带 `X-API-Key: og_live_xxxxxxxx`(或 `Authorization: Bearer og_live_xxxxxxxx`)。缺失/无效/已吊销返回 `401`。 - 鉴权:请求头携带 `X-API-Key: og_live_xxxxxxxx`(或 `Authorization: Bearer og_live_xxxxxxxx`)。缺失/无效/已吊销返回 `401`。
- 限速:按 API key 使用每小时固定窗口,默认每小时 30 次,可通过 `GOODS_BACKFLOW_RATE_PER_HOUR` 配置。超限返回 `429` 和 `Retry-After`;Redis 不可用时按现有策略放行。
- 请求体:商品对象**数组**(与公众投稿同结构),单次最多 `1000` 条。常用字段: - 请求体:商品对象**数组**(与公众投稿同结构),单次最多 `1000` 条。常用字段:
| 字段 | 必填 | 说明 | | 字段 | 必填 | 说明 |
+1 -1
View File
@@ -33,4 +33,4 @@
- 对外 API 在 `sources` 中透明返回来源与其许可。 - 对外 API 在 `sources` 中透明返回来源与其许可。
## 6. 版本 ## 6. 版本
- 本契约随 schema 演进版本化;任何 schema 变更需同步更新:迁移(SQL) + 本契约 + `docs/openapi.yaml`。 - 本契约随 schema 演进版本化;任何 schema 变更需同步更新:迁移(SQL) + 本契约 + `api/internal/handler/openapi.json`。
+28 -4
View File
@@ -2,7 +2,7 @@
用 `docker-compose.prod.yml` 部署,与本地 `docker-compose.yml` 的区别: 用 `docker-compose.prod.yml` 部署,与本地 `docker-compose.yml` 的区别:
- 仅 `api` 映射宿主端口,且绑定 `127.0.0.1:8120`(由外层 nginx 反代 + HTTPS);`postgres`/`redis`/`minio` 不对外暴露端口,仅容器内网互通。 - 仅 `api` 映射宿主端口,且绑定 `127.0.0.1:8120`(由外层 nginx 反代 + HTTPS);`postgres`/`redis` 不对外暴露端口,仅容器内网互通。
- 所有服务 `restart: unless-stopped`。 - 所有服务 `restart: unless-stopped`。
- 凭据从 `.env` 注入(见 `.env.example`),不写入仓库。 - 凭据从 `.env` 注入(见 `.env.example`),不写入仓库。
- `api` 使用 `api/Dockerfile.prod`:运行镜像用 `scratch`(从构建镜像拷贝 ca-certs),适用于 `gcr.io/distroless` 不可达的环境;Go 模块走 `goproxy.cn`。 - `api` 使用 `api/Dockerfile.prod`:运行镜像用 `scratch`(从构建镜像拷贝 ca-certs),适用于 `gcr.io/distroless` 不可达的环境;Go 模块走 `goproxy.cn`。
@@ -25,10 +25,34 @@ curl -s http://127.0.0.1:8120/healthz # {"status":"ok"}
nginx 反代(子域 + HTTPS):80 端口 301 跳转到 443,443 `proxy_pass http://127.0.0.1:8120`,证书用 acme.sh 签发并配 `--reloadcmd "nginx -s reload"` 自动续期。 nginx 反代(子域 + HTTPS):80 端口 301 跳转到 443,443 `proxy_pass http://127.0.0.1:8120`,证书用 acme.sh 签发并配 `--reloadcmd "nginx -s reload"` 自动续期。
运营后台 `/ping`(同域复用证书):在 443 server 块内加一段 在 443 server 块内配置反代头;公开 API 走 8120,运营后台 `/ping` 与公开投稿 `/api/public/` 走 8121:
```nginx ```nginx
location /ping { proxy_pass http://127.0.0.1:8121; } location / {
proxy_pass http://127.0.0.1:8120;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /ping {
proxy_pass http://127.0.0.1:8121;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api/public/ {
proxy_pass http://127.0.0.1:8121;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
``` ```
后台凭据见 `.env` 的 `GOODS_ADMIN_USER` / `GOODS_ADMIN_PASSWORD` / `GOODS_ADMIN_JWT_SECRET`。新增迁移 `0005_admin`(`audit_log` 表 + `manual` 来源)随 `migrate ... up` 自动应用。 后台凭据见 `.env` 的 `GOODS_ADMIN_USER` / `GOODS_ADMIN_PASSWORD` / `GOODS_ADMIN_JWT_SECRET`;令牌有效期可通过 `GOODS_ADMIN_TOKEN_TTL` 设置(Go duration 格式,默认 `12h`)。登录失败按 IP(15 分钟 10 次)和用户名(15 分钟 20 次)限流,并将成功、失败和被限流的登录写入审计日志。退出会在当前进程内吊销令牌;服务重启后进程内吊销记录会丢失。若配置了持久的 `GOODS_ADMIN_JWT_SECRET`,未过期令牌仍有效至其过期;若未配置,服务每次启动会生成随机密钥,令牌会在重启后失效。新增迁移 `0005_admin`(`audit_log` 表 + `manual` 来源)随 `migrate ... up` 自动应用。
`OPENGOODS_TRUSTED_PROXIES` 用逗号分隔的 CIDR 或 IP 配置可信代理;留空时信任 loopback、私有 IPv4 与唯一本地 IPv6 网段,设置为 `none` 则不信任任何代理。Nginx 配置应保留上述反代头。
+2 -1
View File
@@ -70,6 +70,7 @@
- **常用筛选复合索引**:如 `(category_id, quality_score DESC)`、 - **常用筛选复合索引**:如 `(category_id, quality_score DESC)`、
`(archive_kind, quality_score DESC)` 配合域内列表。 `(archive_kind, quality_score DESC)` 配合域内列表。
- **Redis 缓存**(已在技术栈内):缓存热门搜索结果与商品详情,挡住重复读。 - **Redis 缓存**(已在技术栈内):缓存热门搜索结果与商品详情,挡住重复读。
- 管理后台的成功写操作会递增缓存 epoch,使公开 API 后续读取切换到新缓存代次。
### 阶段 1 — 千万级以上:读扩展 + 调优 ### 阶段 1 — 千万级以上:读扩展 + 调优
触发:单库读 QPS 升高、P99 变慢。 触发:单库读 QPS 升高、P99 变慢。
@@ -109,4 +110,4 @@
## 6. 版本 ## 6. 版本
- 本路线图随规模演进更新;任何落地改动需同步:迁移(SQL) + 本文档 +(涉及对外字段时) - 本路线图随规模演进更新;任何落地改动需同步:迁移(SQL) + 本文档 +(涉及对外字段时)
`docs/data-contract.md` / `docs/openapi.yaml`。 `docs/data-contract.md` / `api/internal/handler/openapi.json`。
+41 -73
View File
@@ -1,28 +1,8 @@
import { useState } from "react"; import { useState } from "react";
import { Search, PlusCircle, Code2, ScanBarcode, ShieldCheck, ArrowRight } from "lucide-react"; import { Search, PlusCircle, ArrowRight } from "lucide-react";
import { api } from "../api"; import { api } from "../api";
import type { ProductSummary } from "../types"; import type { ProductSummary } from "../types";
const EXAMPLES = ["可乐", "Nutella", "牛奶", "5449000000996"];
const FEATURES = [
{
icon: Search,
title: "客观可查",
desc: "按名称或条码检索商品的成分、营养、规格等官方事实。",
},
{
icon: ShieldCheck,
title: "可溯源",
desc: "每条资料标注数据来源与质量分,公开透明、人人可核。",
},
{
icon: Code2,
title: "开放 API",
desc: "免鉴权只读 REST 接口,开发者可直接接入商品档案。",
},
];
export default function Home({ export default function Home({
onOpen, onOpen,
onContribute, onContribute,
@@ -57,47 +37,47 @@ export default function Home({
return ( return (
<div className="animate-fade-up"> <div className="animate-fade-up">
<section className="relative overflow-hidden rounded-3xl border border-gray-100 bg-gradient-to-b from-white to-brand-50/40 px-6 py-14 text-center shadow-card"> <section
<div className={`flex flex-col items-center px-4 text-center ${
aria-hidden searched
className="pointer-events-none absolute -top-24 left-1/2 h-72 w-[42rem] -translate-x-1/2 rounded-full bg-brand-200/30 blur-3xl" ? "pt-2 pb-6"
/> : "min-h-[calc(100vh-12rem)] justify-center"
<div className="relative"> }`}
<span className="inline-flex items-center gap-1.5 rounded-full border border-brand-200 bg-white/70 px-3 py-1 text-xs font-medium text-brand-700"> >
<ShieldCheck className="w-3.5 h-3.5" /> 公益 · 开放 · 可溯源 <h1
</span> className={`font-medium tracking-tight text-gray-800 ${
<h1 className="mt-5 text-4xl sm:text-5xl font-extrabold tracking-tight text-gray-900"> searched ? "text-3xl" : "text-6xl sm:text-7xl"
天<span className="bg-gradient-to-r from-brand-600 to-emerald-500 bg-clip-text text-transparent">工</span> }`}
</h1> >
<p className="mx-auto mt-3 max-w-xl text-gray-500"> 天<span className="text-brand-600">工</span>
输入商品名称或条码,检索客观、可溯源的商品资料。人人可查,人人可贡献。 </h1>
</p>
<form onSubmit={(e) => run(undefined, e)} className="mx-auto mt-7 flex max-w-2xl gap-2"> <form
<div className="flex flex-1 items-center gap-2 rounded-xl border border-gray-200 bg-white px-3.5 shadow-sm transition focus-within:border-brand-400 focus-within:ring-4 focus-within:ring-brand-500/10"> onSubmit={(e) => run(undefined, e)}
<Search className="h-5 w-5 shrink-0 text-gray-400" /> className="mx-auto mt-8 w-full max-w-xl"
<input >
autoFocus <div className="flex items-center gap-3 rounded-full border border-gray-200 bg-white px-5 py-3 shadow-sm transition hover:shadow-md focus-within:shadow-md">
value={q} <Search className="h-5 w-5 shrink-0 text-gray-400" />
onChange={(e) => setQ(e.target.value)} <input
placeholder="例如:可乐、Nutella、5449000000996" autoFocus
className="flex-1 bg-transparent py-3.5 outline-none" value={q}
/> onChange={(e) => setQ(e.target.value)}
</div> placeholder="搜索商品名称或条码"
<button type="submit" disabled={loading} className="btn-primary px-7"> className="flex-1 bg-transparent outline-none"
{loading ? "检索中…" : "检索"} />
</button>
</form>
<div className="mt-4 flex flex-wrap items-center justify-center gap-2">
<span className="text-xs text-gray-400">试试:</span>
{EXAMPLES.map((ex) => (
<button key={ex} type="button" className="chip" onClick={() => run(ex)}>
<ScanBarcode className="w-3 h-3" /> {ex}
</button>
))}
</div> </div>
</div> {!searched && (
<div className="mt-8">
<button
type="submit"
disabled={loading}
className="rounded-md border border-gray-200 bg-gray-50 px-6 py-2.5 text-sm text-gray-700 transition hover:border-gray-300 hover:shadow-sm"
>
{loading ? "检索中…" : "检索"}
</button>
</div>
)}
</form>
</section> </section>
{error && ( {error && (
@@ -106,7 +86,7 @@ export default function Home({
</div> </div>
)} )}
{searched ? ( {searched && (
<div className="mt-8"> <div className="mt-8">
<div className="mb-3 text-sm text-gray-500"> <div className="mb-3 text-sm text-gray-500">
共 <span className="font-semibold text-gray-700">{total}</span> 条结果 共 <span className="font-semibold text-gray-700">{total}</span> 条结果
@@ -154,18 +134,6 @@ export default function Home({
</ul> </ul>
)} )}
</div> </div>
) : (
<div className="mt-8 grid gap-4 sm:grid-cols-3">
{FEATURES.map(({ icon: Icon, title, desc }) => (
<div key={title} className="card p-5 transition hover:shadow-card-hover">
<span className="grid h-10 w-10 place-items-center rounded-xl bg-brand-50 text-brand-600">
<Icon className="h-5 w-5" />
</span>
<h3 className="mt-3 font-semibold text-gray-800">{title}</h3>
<p className="mt-1 text-sm leading-relaxed text-gray-500">{desc}</p>
</div>
))}
</div>
)} )}
</div> </div>
); );
+4 -3
View File
@@ -58,9 +58,10 @@ GET http://zc.bypos.net/byGoodsService/byMessage.asmx/GetGoodsinfo
## 配置 ## 配置
- `sdogid`:中心库账号 id(本项目所属云店账号的授权 id)。默认值见 - `sdogid`:中心库账号 id(本项目所属云店账号的授权 id)。
`collect.go` 的 `defaultSdogID`,也可用 `-sdogid` 参数或控制台覆盖。 优先从环境变量 `BYPOS_SDOGID` 读取,其次是命令行 `-sdogid` 参数,
**这是账号级凭证**——若本仓库对外公开,建议改为从环境变量/外部配置读取。 也可以在 Web 控制台的输入框中填写。**三者都未设时启动会警告、开始采集时会报错。**
- 网络错误自动重试(最多 3 次,指数退避 500ms/1s/2s)。
## 导入 goods/天工库 ## 导入 goods/天工库
+105 -39
View File
@@ -1,6 +1,7 @@
package main package main
import ( import (
"bufio"
"context" "context"
"crypto/md5" "crypto/md5"
"encoding/hex" "encoding/hex"
@@ -20,12 +21,21 @@ import (
) )
// ---- upstream config ---- // ---- upstream config ----
// sdogid is the 云店 account license id observed in the live request. It is
// configurable so the tool is not tied to a single account.
const defaultSdogID = "137966"
const endpoint = "http://zc.bypos.net/byGoodsService/byMessage.asmx/GetGoodsinfo" const endpoint = "http://zc.bypos.net/byGoodsService/byMessage.asmx/GetGoodsinfo"
// maxRetries is the number of retry attempts for transient network errors.
const maxRetries = 3
// resolveSdogID reads the account id from $BYPOS_SDOGID, falling back to the
// explicit argument (CLI flag or Web UI input). Returns empty if neither set.
func resolveSdogID(explicit string) string {
if v := os.Getenv("BYPOS_SDOGID"); v != "" {
return v
}
return explicit
}
var stringTagRe = regexp.MustCompile(`(?s)<string[^>]*>(.*)</string>`) var stringTagRe = regexp.MustCompile(`(?s)<string[^>]*>(.*)</string>`)
// Product is the normalized record we persist (one JSON object per line). // Product is the normalized record we persist (one JSON object per line).
@@ -87,8 +97,8 @@ func ean13Check(body string) (string, bool) {
return body + strconv.Itoa(chk), true return body + strconv.Itoa(chk), true
} }
// lookup queries the upstream central library for one barcode. // lookupOnce performs a single HTTP request to the upstream central library.
func (c *Collector) lookup(ctx context.Context, barcode string) (*Product, error) { func (c *Collector) lookupOnce(ctx context.Context, barcode string) (*Product, error) {
tsMs := strconv.FormatInt(time.Now().Unix()*1000, 10) // always ends in 000 tsMs := strconv.FormatInt(time.Now().Unix()*1000, 10) // always ends in 000
sparm1 := md5hex(c.sdogID) sparm1 := md5hex(c.sdogID)
sparm2 := md5hex(barcode + tsMs) sparm2 := md5hex(barcode + tsMs)
@@ -147,21 +157,48 @@ func (c *Collector) lookup(ctx context.Context, barcode string) (*Product, error
return p, nil return p, nil
} }
// lookup queries the upstream with up to maxRetries retries on transient errors.
func (c *Collector) lookup(ctx context.Context, barcode string) (*Product, error) {
var lastErr error
for attempt := 0; attempt <= maxRetries; attempt++ {
if ctx.Err() != nil {
return nil, ctx.Err()
}
p, err := c.lookupOnce(ctx, barcode)
if err == nil {
return p, nil
}
lastErr = err
if attempt < maxRetries {
backoff := time.Duration(1<<uint(attempt)) * 500 * time.Millisecond
select {
case <-time.After(backoff):
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
return nil, lastErr
}
// ---- job / collector state ---- // ---- job / collector state ----
const collectedFile = "collected.txt"
type Stats struct { type Stats struct {
Running bool `json:"running"` Running bool `json:"running"`
Total int64 `json:"total"` Total int64 `json:"total"`
Done int64 `json:"done"` Done int64 `json:"done"`
Hits int64 `json:"hits"` Hits int64 `json:"hits"`
Miss int64 `json:"miss"` Miss int64 `json:"miss"`
Invalid int64 `json:"invalid"` Invalid int64 `json:"invalid"`
Errors int64 `json:"errors"` Errors int64 `json:"errors"`
Skipped int64 `json:"skipped"` Skipped int64 `json:"skipped"`
Current string `json:"current"` Current string `json:"current"`
OutFile string `json:"out_file"` OutFile string `json:"out_file"`
StartedAt string `json:"started_at"` StartedAt string `json:"started_at"`
Message string `json:"message"` Message string `json:"message"`
HistoryCount int `json:"history_count"`
} }
type Collector struct { type Collector struct {
@@ -182,20 +219,20 @@ type Collector struct {
startedAt string startedAt string
message string message string
seen map[string]struct{} // barcodes already in output (dedupe / resume) seen map[string]struct{} // barcodes already collected (dedupe)
recent []Product // ring of last results for UI collectedFp *os.File // persistent history file handle
recent []Product // ring of last results for UI
} }
func NewCollector(sdogID string) *Collector { func NewCollector(sdogID string) *Collector {
if sdogID == "" { sdogID = resolveSdogID(sdogID)
sdogID = defaultSdogID
}
c := &Collector{ c := &Collector{
client: &http.Client{Timeout: 25 * time.Second}, client: &http.Client{Timeout: 25 * time.Second},
sdogID: sdogID, sdogID: sdogID,
seen: map[string]struct{}{}, seen: map[string]struct{}{},
} }
c.current.Store("") c.current.Store("")
c.loadCollected()
return c return c
} }
@@ -207,20 +244,22 @@ func (c *Collector) snapshot() Stats {
msg := c.message msg := c.message
out := c.outPath out := c.outPath
started := c.startedAt started := c.startedAt
hist := len(c.seen)
c.mu.Unlock() c.mu.Unlock()
return Stats{ return Stats{
Running: c.isRunning(), Running: c.isRunning(),
Total: atomic.LoadInt64(&c.total), Total: atomic.LoadInt64(&c.total),
Done: atomic.LoadInt64(&c.done), Done: atomic.LoadInt64(&c.done),
Hits: atomic.LoadInt64(&c.hits), Hits: atomic.LoadInt64(&c.hits),
Miss: atomic.LoadInt64(&c.miss), Miss: atomic.LoadInt64(&c.miss),
Invalid: atomic.LoadInt64(&c.invalid), Invalid: atomic.LoadInt64(&c.invalid),
Errors: atomic.LoadInt64(&c.errors), Errors: atomic.LoadInt64(&c.errors),
Skipped: atomic.LoadInt64(&c.skipped), Skipped: atomic.LoadInt64(&c.skipped),
Current: cur, Current: cur,
OutFile: out, OutFile: out,
StartedAt: started, StartedAt: started,
Message: msg, Message: msg,
HistoryCount: hist,
} }
} }
@@ -241,9 +280,24 @@ func (c *Collector) pushRecent(p Product) {
c.mu.Unlock() c.mu.Unlock()
} }
// loadSeen reads an existing output file to build the dedupe set (for resume). // loadCollected reads the persistent history file (one barcode per line).
func (c *Collector) loadCollected() {
f, err := os.Open(collectedFile)
if err != nil {
return
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
bc := strings.TrimSpace(sc.Text())
if bc != "" {
c.seen[bc] = struct{}{}
}
}
}
// loadSeen reads an existing output file and adds to the dedupe set (for resume).
func (c *Collector) loadSeen(path string) error { func (c *Collector) loadSeen(path string) error {
c.seen = map[string]struct{}{}
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
@@ -308,6 +362,9 @@ func (c *Collector) Start(req JobReq) error {
if req.SdogID != "" { if req.SdogID != "" {
c.sdogID = req.SdogID c.sdogID = req.SdogID
} }
if c.sdogID == "" {
return fmt.Errorf("未指定 sdogid,请通过控制台输入框、环境变量 $BYPOS_SDOGID 或 -sdogid 参数配置")
}
// Build the list of barcodes to query. // Build the list of barcodes to query.
var barcodes []string var barcodes []string
@@ -353,6 +410,7 @@ func (c *Collector) Start(req JobReq) error {
} }
c.outFile = f c.outFile = f
c.outPath = abs c.outPath = abs
c.collectedFp, _ = os.OpenFile(collectedFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
// reset counters // reset counters
atomic.StoreInt64(&c.total, int64(len(barcodes))) atomic.StoreInt64(&c.total, int64(len(barcodes)))
@@ -390,6 +448,11 @@ func (c *Collector) run(ctx context.Context, barcodes []string, req JobReq) {
c.outFile.Close() c.outFile.Close()
c.outFile = nil c.outFile = nil
} }
if c.collectedFp != nil {
c.collectedFp.Sync()
c.collectedFp.Close()
c.collectedFp = nil
}
c.current.Store("") c.current.Store("")
}() }()
@@ -438,14 +501,17 @@ func (c *Collector) run(ctx context.Context, barcodes []string, req JobReq) {
} }
atomic.AddInt64(&c.done, 1) atomic.AddInt64(&c.done, 1)
c.pushRecent(*p) c.pushRecent(*p)
writeMu.Lock()
if p.Status == "hit" || req.LogMiss { if p.Status == "hit" || req.LogMiss {
line, _ := json.Marshal(p) line, _ := json.Marshal(p)
writeMu.Lock()
c.outFile.Write(line) c.outFile.Write(line)
c.outFile.Write([]byte("\n")) c.outFile.Write([]byte("\n"))
c.seen[bc] = struct{}{}
writeMu.Unlock()
} }
c.seen[bc] = struct{}{}
if c.collectedFp != nil {
c.collectedFp.WriteString(bc + "\n")
}
writeMu.Unlock()
} }
} }
+113
View File
@@ -0,0 +1,113 @@
package main
import (
"os"
"testing"
)
func TestEan13Check_valid(t *testing.T) {
tests := []struct {
body string
want string
}{
{"692045990501", "6920459905012"},
{"690100000000", "6901000000004"},
{"690100000099", "6901000000998"},
}
for _, tt := range tests {
got, ok := ean13Check(tt.body)
if !ok {
t.Errorf("ean13Check(%q) returned not ok", tt.body)
continue
}
if got != tt.want {
t.Errorf("ean13Check(%q) = %q, want %q", tt.body, got, tt.want)
}
}
}
func TestEan13Check_invalid(t *testing.T) {
cases := []string{"", "12345", "12345678901", "1234567890123", "69010000a000"}
for _, body := range cases {
_, ok := ean13Check(body)
if ok {
t.Errorf("ean13Check(%q) should return not ok", body)
}
}
}
func TestMd5hex(t *testing.T) {
got := md5hex("137966")
if len(got) != 32 {
t.Errorf("md5hex should return 32-char hex, got len=%d", len(got))
}
if got != md5hex("137966") {
t.Error("md5hex should be deterministic")
}
if got == md5hex("other") {
t.Error("md5hex should differ for different inputs")
}
}
func TestSanitizeBarcodes(t *testing.T) {
got := sanitizeBarcodes("6920459905012\n6901028941068 123")
want := []string{"6920459905012", "6901028941068", "123"}
if len(got) != len(want) {
t.Fatalf("len = %d, want %d", len(got), len(want))
}
for i := range want {
if got[i] != want[i] {
t.Errorf("got[%d] = %q, want %q", i, got[i], want[i])
}
}
}
func TestSanitizeBarcodes_empty(t *testing.T) {
got := sanitizeBarcodes(" \n\t ")
if len(got) != 0 {
t.Errorf("expected empty, got %v", got)
}
}
func TestResolveSdogID_envOverride(t *testing.T) {
os.Setenv("BYPOS_SDOGID", "999999")
defer os.Unsetenv("BYPOS_SDOGID")
got := resolveSdogID("111111")
if got != "999999" {
t.Errorf("expected env var override, got %q", got)
}
}
func TestResolveSdogID_fallback(t *testing.T) {
os.Unsetenv("BYPOS_SDOGID")
got := resolveSdogID("111111")
if got != "111111" {
t.Errorf("expected fallback to explicit, got %q", got)
}
}
func TestResolveSdogID_empty(t *testing.T) {
os.Unsetenv("BYPOS_SDOGID")
got := resolveSdogID("")
if got != "" {
t.Errorf("expected empty, got %q", got)
}
}
func TestNewCollector_sdogFromEnv(t *testing.T) {
os.Setenv("BYPOS_SDOGID", "888888")
defer os.Unsetenv("BYPOS_SDOGID")
c := NewCollector("")
if c.sdogID != "888888" {
t.Errorf("expected sdogID from env, got %q", c.sdogID)
}
}
func TestStartRejectsEmptySdogID(t *testing.T) {
os.Unsetenv("BYPOS_SDOGID")
c := NewCollector("")
err := c.Start(JobReq{Mode: "list", List: "6920459905012"})
if err == nil {
t.Fatal("expected error for empty sdogid")
}
}
+129 -12
View File
@@ -1,6 +1,8 @@
package main package main
import ( import (
"bufio"
"bytes"
"embed" "embed"
"encoding/csv" "encoding/csv"
"encoding/json" "encoding/json"
@@ -14,24 +16,55 @@ import (
"os" "os"
"os/exec" "os/exec"
"runtime" "runtime"
"strings"
"time" "time"
) )
//go:embed web/* //go:embed web/*
var webFS embed.FS var webFS embed.FS
var collector = NewCollector("") var collector *Collector
// waitExit keeps the console window open on Windows so the user can read errors.
func waitExit() {
if runtime.GOOS == "windows" {
fmt.Println("\n按回车键退出...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
}
func main() { func main() {
addr := flag.String("addr", "127.0.0.1:8765", "本地监听地址") // Log to file so crashes are diagnosable even if console closes.
noOpen := flag.Bool("no-open", false, "不自动打开浏览器") lf, lfErr := os.OpenFile("bypos-collector.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
sdog := flag.String("sdogid", "", "中心库账号 id(默认使用内置值)") if lfErr == nil {
flag.Parse() log.SetOutput(io.MultiWriter(os.Stderr, lf))
if *sdog != "" { defer lf.Close()
collector.sdogID = *sdog
} }
sub, _ := fs.Sub(webFS, "web") defer func() {
if r := recover(); r != nil {
log.Printf("程序崩溃: %v", r)
waitExit()
}
}()
log.Println("bypos-collector 启动中...")
addr := flag.String("addr", "127.0.0.1:8765", "本地监听地址")
noOpen := flag.Bool("no-open", false, "不自动打开浏览器")
sdog := flag.String("sdogid", "", "中心库账号 id(优先读 $BYPOS_SDOGID 环境变量)")
flag.Parse()
collector = NewCollector(*sdog)
if collector.sdogID == "" {
log.Println("警告: 未配置 sdogid,请通过 $BYPOS_SDOGID 环境变量、-sdogid 参数或控制台输入框指定")
}
sub, err := fs.Sub(webFS, "web")
if err != nil {
log.Printf("错误: 无法加载内嵌 web 资源: %v", err)
waitExit()
return
}
mux := http.NewServeMux() mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(sub))) mux.Handle("/", http.FileServer(http.FS(sub)))
mux.HandleFunc("/api/start", handleStart) mux.HandleFunc("/api/start", handleStart)
@@ -39,10 +72,17 @@ func main() {
mux.HandleFunc("/api/stats", handleStats) mux.HandleFunc("/api/stats", handleStats)
mux.HandleFunc("/api/download", handleDownload) mux.HandleFunc("/api/download", handleDownload)
mux.HandleFunc("/api/export.csv", handleExportCSV) mux.HandleFunc("/api/export.csv", handleExportCSV)
mux.HandleFunc("/api/import", handleImport)
ln, err := net.Listen("tcp", *addr) ln, err := net.Listen("tcp", *addr)
if err != nil { if err != nil {
log.Fatalf("无法监听 %s: %v", *addr, err) log.Printf("端口 %s 被占用,自动选择可用端口...", *addr)
ln, err = net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Printf("错误: 无法监听: %v", err)
waitExit()
return
}
} }
realAddr := ln.Addr().String() realAddr := ln.Addr().String()
urlStr := "http://" + realAddr + "/" urlStr := "http://" + realAddr + "/"
@@ -51,10 +91,14 @@ func main() {
fmt.Println(" 控制台: " + urlStr) fmt.Println(" 控制台: " + urlStr)
fmt.Println(" 关闭本窗口即停止程序") fmt.Println(" 关闭本窗口即停止程序")
fmt.Println("==============================================") fmt.Println("==============================================")
log.Printf("监听地址: %s", realAddr)
if !*noOpen { if !*noOpen {
go openBrowser(urlStr) go openBrowser(urlStr)
} }
log.Fatal(http.Serve(ln, mux)) if err := http.Serve(ln, mux); err != nil {
log.Printf("HTTP 服务异常退出: %v", err)
waitExit()
}
} }
func openBrowser(url string) { func openBrowser(url string) {
@@ -127,6 +171,79 @@ func handleDownload(w http.ResponseWriter, r *http.Request) {
io.Copy(w, f) io.Copy(w, f)
} }
func handleImport(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "method", 405)
return
}
var req struct {
APIURL string `json:"api_url"`
Username string `json:"username"`
Password string `json:"password"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, 400, map[string]string{"error": "请求格式错误"})
return
}
req.APIURL = strings.TrimRight(req.APIURL, "/")
if req.APIURL == "" || req.Username == "" || req.Password == "" {
writeJSON(w, 400, map[string]string{"error": "请填写完整的 API 地址、用户名和密码"})
return
}
s := collector.snapshot()
if s.OutFile == "" {
writeJSON(w, 400, map[string]string{"error": "没有采集数据可导入"})
return
}
client := &http.Client{Timeout: 60 * time.Second}
loginBody, _ := json.Marshal(map[string]string{"username": req.Username, "password": req.Password})
loginResp, err := client.Post(req.APIURL+"/api/login", "application/json", bytes.NewReader(loginBody))
if err != nil {
writeJSON(w, 502, map[string]string{"error": "无法连接 Goods 系统: " + err.Error()})
return
}
defer loginResp.Body.Close()
var loginResult struct {
Token string `json:"token"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
json.NewDecoder(loginResp.Body).Decode(&loginResult)
if loginResp.StatusCode != 200 || loginResult.Token == "" {
msg := "登录失败"
if loginResult.Error != nil {
msg = loginResult.Error.Message
}
writeJSON(w, 401, map[string]string{"error": msg})
return
}
jsonlData, err := os.ReadFile(s.OutFile)
if err != nil {
writeJSON(w, 500, map[string]string{"error": "读取采集文件失败: " + err.Error()})
return
}
importReq, _ := http.NewRequest("POST", req.APIURL+"/api/import/bypos", bytes.NewReader(jsonlData))
importReq.Header.Set("Content-Type", "application/x-ndjson")
importReq.Header.Set("Authorization", "Bearer "+loginResult.Token)
importResp, err := client.Do(importReq)
if err != nil {
writeJSON(w, 502, map[string]string{"error": "导入请求失败: " + err.Error()})
return
}
defer importResp.Body.Close()
respBody, _ := io.ReadAll(importResp.Body)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(importResp.StatusCode)
w.Write(respBody)
}
func handleExportCSV(w http.ResponseWriter, r *http.Request) { func handleExportCSV(w http.ResponseWriter, r *http.Request) {
s := collector.snapshot() s := collector.snapshot()
if s.OutFile == "" { if s.OutFile == "" {
@@ -143,14 +260,14 @@ func handleExportCSV(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Disposition", "attachment; filename=products.csv") w.Header().Set("Content-Disposition", "attachment; filename=products.csv")
w.Write([]byte{0xEF, 0xBB, 0xBF}) // UTF-8 BOM so Excel reads Chinese correctly w.Write([]byte{0xEF, 0xBB, 0xBF}) // UTF-8 BOM so Excel reads Chinese correctly
cw := csv.NewWriter(w) cw := csv.NewWriter(w)
cw.Write([]string{"barcode", "name", "spec", "unit", "area", "manufacturer", "license", "in_price", "sell_price", "status", "fetched_at"}) cw.Write([]string{"barcode", "name", "spec", "unit", "area", "manufacturer", "license", "in_price", "sell_price", "status", "retmsg", "fetched_at", "source"})
dec := json.NewDecoder(f) dec := json.NewDecoder(f)
for { for {
var p Product var p Product
if err := dec.Decode(&p); err != nil { if err := dec.Decode(&p); err != nil {
break break
} }
cw.Write([]string{p.Barcode, p.Name, p.Spec, p.Unit, p.Area, p.Manufacturer, p.License, p.InPrice, p.SellPrice, p.Status, p.FetchedAt}) cw.Write([]string{p.Barcode, p.Name, p.Spec, p.Unit, p.Area, p.Manufacturer, p.License, p.InPrice, p.SellPrice, p.Status, p.RetMsg, p.FetchedAt, p.Source})
} }
cw.Flush() cw.Flush()
} }
+67 -3
View File
@@ -37,6 +37,11 @@
.hit { color:#2da44e; } .miss { color:#999; } .invalid { color:#d1242f; } .error { color:#bf8700; } .hit { color:#2da44e; } .miss { color:#999; } .invalid { color:#d1242f; } .error { color:#bf8700; }
.hint { font-size:12px; color:#888; margin-top:6px; line-height:1.5; } .hint { font-size:12px; color:#888; margin-top:6px; line-height:1.5; }
.est { font-size:13px; color:#1f6feb; margin-top:6px; } .est { font-size:13px; color:#1f6feb; margin-top:6px; }
.history-badge { display:inline-block; background:#e8f0fe; color:#1f6feb; padding:4px 12px; border-radius:12px; font-size:13px; font-weight:600; margin-bottom:10px; }
.import-result { margin-top:10px; padding:10px; border-radius:6px; font-size:13px; }
.import-result.ok { background:#dcfce7; color:#166534; }
.import-result.fail { background:#fee2e2; color:#991b1b; }
input[type=password] { width:100%; padding:8px 10px; border:1px solid #cdd5e0; border-radius:6px; font-size:14px; }
</style> </style>
</head> </head>
<body> <body>
@@ -79,6 +84,10 @@
<div class="card"> <div class="card">
<h3>② 采集参数</h3> <h3>② 采集参数</h3>
<div class="row"> <div class="row">
<div>
<label>中心库账号 sdogid</label>
<input type="text" id="sdogid" placeholder="留空则使用环境变量或启动参数"/>
</div>
<div> <div>
<label>并发数</label> <label>并发数</label>
<input type="number" id="concurrency" value="3" min="1" max="20"/> <input type="number" id="concurrency" value="3" min="1" max="20"/>
@@ -93,11 +102,12 @@
</div> </div>
</div> </div>
<label style="margin-top:12px"><input type="checkbox" id="logmiss"/> 同时记录未命中/无效条码(默认只存命中)</label> <label style="margin-top:12px"><input type="checkbox" id="logmiss"/> 同时记录未命中/无效条码(默认只存命中)</label>
<div class="hint">速度越快越容易触发上游频控。建议并发 3、间隔 300ms 起步,稳定后再调。已采过的条码会自动跳过(断点续采)。</div> <div class="hint">速度越快越容易触发上游频控。建议并发 3、间隔 300ms 起步,稳定后再调。已采过的条码会自动跳过(跨次去重)。</div>
</div> </div>
<div class="card"> <div class="card">
<h3>③ 运行</h3> <h3>③ 运行</h3>
<div class="history-badge" id="history-badge">历史已采集: 0 个条码</div>
<div style="margin-bottom:12px"> <div style="margin-bottom:12px">
<button class="primary" id="btnStart" onclick="start()">开始采集</button> <button class="primary" id="btnStart" onclick="start()">开始采集</button>
<button class="danger" id="btnStop" onclick="stop()" disabled>停止</button> <button class="danger" id="btnStop" onclick="stop()" disabled>停止</button>
@@ -112,13 +122,36 @@
<div class="stat"><div class="n miss" id="s-miss">0</div><div class="l">未命中</div></div> <div class="stat"><div class="n miss" id="s-miss">0</div><div class="l">未命中</div></div>
<div class="stat"><div class="n invalid" id="s-invalid">0</div><div class="l">无效</div></div> <div class="stat"><div class="n invalid" id="s-invalid">0</div><div class="l">无效</div></div>
<div class="stat"><div class="n error" id="s-errors">0</div><div class="l">错误</div></div> <div class="stat"><div class="n error" id="s-errors">0</div><div class="l">错误</div></div>
<div class="stat"><div class="n" id="s-skipped">0</div><div class="l">跳过</div></div> <div class="stat"><div class="n" id="s-skipped">0</div><div class="l">跳过(已采)</div></div>
</div> </div>
<div class="hint" id="msg"></div> <div class="hint" id="msg"></div>
</div> </div>
<div class="card"> <div class="card">
<h3>④ 实时结果(最近 60 条)</h3> <h3>④ 导入到 Goods 系统</h3>
<div class="hint" style="margin-top:0;margin-bottom:10px">采集完成后,将数据一键导入到 OpenGoods 商品档案系统。</div>
<div class="row">
<div>
<label>Goods 管理后台地址</label>
<input type="text" id="import-url" placeholder="如 http://192.168.1.100:8080/ping"/>
</div>
<div>
<label>管理员用户名</label>
<input type="text" id="import-user" placeholder="admin"/>
</div>
<div>
<label>管理员密码</label>
<input type="password" id="import-pass"/>
</div>
</div>
<div style="margin-top:12px">
<button class="primary" id="btnImport" onclick="doImport()">导入到 Goods</button>
</div>
<div id="import-result"></div>
</div>
<div class="card">
<h3>⑤ 实时结果(最近 60 条)</h3>
<div style="max-height:340px; overflow:auto"> <div style="max-height:340px; overflow:auto">
<table> <table>
<thead><tr><th>条码</th><th>品名</th><th>规格</th><th>单位</th><th>产地</th><th>进价</th><th>零售价</th><th>状态</th></tr></thead> <thead><tr><th>条码</th><th>品名</th><th>规格</th><th>单位</th><th>产地</th><th>进价</th><th>零售价</th><th>状态</th></tr></thead>
@@ -165,6 +198,7 @@ async function start(){
start_body: document.getElementById('start').value.trim(), start_body: document.getElementById('start').value.trim(),
end_body: document.getElementById('end').value.trim(), end_body: document.getElementById('end').value.trim(),
list: document.getElementById('list').value, list: document.getElementById('list').value,
sdog_id: document.getElementById('sdogid').value.trim(),
concurrency: parseInt(document.getElementById('concurrency').value)||3, concurrency: parseInt(document.getElementById('concurrency').value)||3,
delay_ms: parseInt(document.getElementById('delay').value)||0, delay_ms: parseInt(document.getElementById('delay').value)||0,
log_miss: document.getElementById('logmiss').checked, log_miss: document.getElementById('logmiss').checked,
@@ -191,6 +225,7 @@ async function poll(){
document.getElementById('s-skipped').textContent = s.skipped; document.getElementById('s-skipped').textContent = s.skipped;
let pct = s.total>0 ? Math.floor(s.done*100/s.total) : 0; let pct = s.total>0 ? Math.floor(s.done*100/s.total) : 0;
document.getElementById('prog').style.width = pct + '%'; document.getElementById('prog').style.width = pct + '%';
document.getElementById('history-badge').textContent = '历史已采集: ' + (s.history_count||0) + ' 个条码';
document.getElementById('msg').textContent = (s.running? ('采集中… 当前 '+s.current) : (s.message||'空闲')); document.getElementById('msg').textContent = (s.running? ('采集中… 当前 '+s.current) : (s.message||'空闲'));
document.getElementById('btnStart').disabled = s.running; document.getElementById('btnStart').disabled = s.running;
document.getElementById('btnStop').disabled = !s.running; document.getElementById('btnStop').disabled = !s.running;
@@ -201,6 +236,35 @@ async function poll(){
}catch(e){} }catch(e){}
} }
setInterval(poll, 1000); poll(); setInterval(poll, 1000); poll();
async function doImport(){
let url = document.getElementById('import-url').value.trim();
let user = document.getElementById('import-user').value.trim();
let pass = document.getElementById('import-pass').value;
if(!url || !user || !pass){ alert('请填写完整的 Goods 系统地址、用户名和密码'); return; }
let btn = document.getElementById('btnImport');
let res = document.getElementById('import-result');
btn.disabled = true;
btn.textContent = '导入中...';
res.innerHTML = '';
try {
let r = await fetch('/api/import', {
method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({api_url:url, username:user, password:pass})
});
let j = await r.json();
if(j.error){
res.innerHTML = '<div class="import-result fail">导入失败: '+esc(j.error.message||j.error)+'</div>';
} else {
res.innerHTML = '<div class="import-result ok">导入完成: 成功 '+j.loaded+' 条, 跳过 '+j.skipped+' 条, 失败 '+j.errored+' 条</div>';
}
} catch(e){
res.innerHTML = '<div class="import-result fail">导入失败: '+esc(e.message)+'</div>';
}
btn.disabled = false;
btn.textContent = '导入到 Goods';
}
</script> </script>
</body> </body>
</html> </html>