a75318b811
Stage-0 caching from docs/scalability.md. The Go API now caches hot product-detail and search-result reads in Redis with a fail-open, epoch-versioned scheme; Python ingestion bumps the epoch after a write run to invalidate the cache globally in O(1). - api/internal/cache: fail-open Cache (GetJSON/SetJSON) namespaced by an epoch counter (og:cache:epoch); disabled when Redis is unconfigured. - store: ProductByID/ProductByGTIN (24h TTL) and SearchProducts (1h TTL) read-through the cache via WithCache. - ingestion: bump_cache_epoch() called after update_off/seed_off/ import_bypos/dedup commits when rows changed; best-effort, never fails a run. Adds redis dependency. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
60 lines
1.7 KiB
Go
60 lines
1.7 KiB
Go
// Command server starts the OpenGoods public read-only API.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"github.com/baicai2026-baicai/goods/api/internal/cache"
|
|
"github.com/baicai2026-baicai/goods/api/internal/config"
|
|
"github.com/baicai2026-baicai/goods/api/internal/handler"
|
|
"github.com/baicai2026-baicai/goods/api/internal/publicweb"
|
|
"github.com/baicai2026-baicai/goods/api/internal/ratelimit"
|
|
"github.com/baicai2026-baicai/goods/api/internal/store"
|
|
)
|
|
|
|
func main() {
|
|
cfg := config.Load()
|
|
|
|
ctx := context.Background()
|
|
pool, err := pgxpool.New(ctx, cfg.DatabaseURL)
|
|
if err != nil {
|
|
log.Fatalf("failed to create db pool: %v", err)
|
|
}
|
|
defer pool.Close()
|
|
|
|
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if err := pool.Ping(pingCtx); err != nil {
|
|
log.Printf("warning: database not reachable at startup: %v", err)
|
|
}
|
|
|
|
limiter := ratelimit.New(cfg.RedisURL)
|
|
if !limiter.Enabled() {
|
|
log.Print("warning: Redis not configured; public API rate limiting disabled")
|
|
}
|
|
|
|
readCache := cache.New(cfg.RedisURL)
|
|
if !readCache.Enabled() {
|
|
log.Print("warning: Redis not configured; public API read cache disabled")
|
|
}
|
|
h := handler.New(store.New(pool).WithCache(readCache), publicweb.Dist()).
|
|
WithRateLimit(limiter, cfg.AnonRateLimitPerMin).
|
|
WithQuotas(cfg.AnonTotalQuota, cfg.RegisteredRateLimitPerMin, cfg.RegisteredQuotaTotal)
|
|
|
|
srv := &http.Server{
|
|
Addr: cfg.Addr,
|
|
Handler: h.Router(),
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
}
|
|
|
|
log.Printf("OpenGoods API listening on %s", cfg.Addr)
|
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatalf("server error: %v", err)
|
|
}
|
|
}
|