Compare commits

...
Author SHA1 Message Date
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
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
7 changed files with 202 additions and 86 deletions
+6 -2
View File
@@ -17,6 +17,7 @@ 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/ratelimit" "github.com/baicai2026-baicai/goods/api/internal/ratelimit"
) )
@@ -70,9 +71,12 @@ func main() {
} }
authn := auth.New(username, passwordHash, secret, 12*time.Hour) authn := auth.New(username, passwordHash, secret, 12*time.Hour)
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).
WithCache(readCache)
srv := &http.Server{ srv := &http.Server{
Addr: addr, Addr: addr,
@@ -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:
}
}
+36
View File
@@ -3,9 +3,11 @@
package adminhandler package adminhandler
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"io/fs" "io/fs"
"log"
"net/http" "net/http"
"strings" "strings"
"time" "time"
@@ -28,6 +30,11 @@ type Handler struct {
spa fs.FS spa fs.FS
submitLimit *rateLimiter submitLimit *rateLimiter
usage *ratelimit.Limiter usage *ratelimit.Limiter
cache cacheBumper
}
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).
@@ -49,6 +56,34 @@ func (h *Handler) WithUsage(l *ratelimit.Limiter) *Handler {
return h 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)
}
})
}
// 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()
@@ -64,6 +99,7 @@ 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.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)
+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")
+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 变慢。
+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>
); );