Adds the rest of the read-side endpoints to the Go tracker, all parity-checked
against the live Python service:
- DB reads: /stats/{c}, /portals, /spawns/heatmap, /server-health,
/character-stats/{c} (stats_data JSONB merged to top level),
/combat-stats[/{c}], /inventories, /inventory/{c}/search.
- 5-minute totals cache + /total-rares, /total-kills.
- Ingest-only state returned as Python's empty/default shapes (/quest-status,
/vital-sharing/peers, /equipment-cantrip-state/{c}); /issues (flat file),
/me (401 until cookie verification lands).
- Streaming reverse proxy to inventory-service (/inventory/{c},
/inventory-characters, /search/*, /sets/list, /inv/{path...} incl. the SSE
suitbuilder stream).
- compare/compare_endpoints.py: structural parity for all read endpoints +
exact-match check for /character-stats and /combat-stats on OFFLINE chars
(online chars legitimately differ — Python serves a richer live overlay that
Phase-1 Go lacks until ingest).
Verified live: 14/14 endpoints structural-match, 8/8 rich offline chars
exact-match on /character-stats.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
221 lines
7 KiB
Go
221 lines
7 KiB
Go
// Command tracker-go is a Go reimplementation of the MosswartOverlord
|
|
// "dereth-tracker" backend, deployed in parallel with the live Python service
|
|
// for side-by-side comparison (strangler-fig migration).
|
|
//
|
|
// Phase 1: read-side parity. Connects READ-ONLY to the existing dereth
|
|
// TimescaleDB and reimplements the HTTP read API, starting with the /live and
|
|
// /trails caches (the 5s _refresh_cache_loop). It never touches anything the
|
|
// Python service writes.
|
|
//
|
|
// Routes are declared WITHOUT the nginx-stripped "/go/" prefix, mirroring the
|
|
// Python service's "no /api/ prefix" convention. nginx's `location /go/` strips
|
|
// the prefix before proxying to this service on 127.0.0.1:8770.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// buildVersion is injected at build time via -ldflags "-X main.buildVersion=...".
|
|
// Mirrors the Python service's APP_VERSION / "/api-version" stamp.
|
|
var buildVersion = "dev"
|
|
|
|
// Server holds the shared dependencies for HTTP handlers.
|
|
type Server struct {
|
|
pool *pgxpool.Pool
|
|
cache *liveCache
|
|
totals *totalsCache
|
|
invProxy *httputil.ReverseProxy
|
|
staticDir string
|
|
log *slog.Logger
|
|
}
|
|
|
|
func main() {
|
|
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
|
slog.SetDefault(logger)
|
|
|
|
cfg := loadConfig()
|
|
logger.Info("starting tracker-go", "version", buildVersion, "addr", cfg.Addr)
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
srv := &Server{
|
|
cache: newLiveCache(),
|
|
totals: newTotalsCache(),
|
|
staticDir: cfg.StaticDir,
|
|
log: logger,
|
|
}
|
|
|
|
// Inventory-service reverse proxy (independent of the DB).
|
|
if err := srv.initInvProxy(cfg.InventoryURL); err != nil {
|
|
logger.Error("inventory proxy init failed", "err", err, "target", cfg.InventoryURL)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Connect to the dereth DB (read-only). If DATABASE_URL is unset we still
|
|
// serve health/version (Phase-0 mode) so the container is observable.
|
|
if cfg.DatabaseURL == "" {
|
|
logger.Warn("DATABASE_URL unset — running without DB; DB-backed endpoints will be empty")
|
|
} else {
|
|
connectCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
|
pool, err := newPool(connectCtx, cfg.DatabaseURL)
|
|
cancel()
|
|
if err != nil {
|
|
logger.Error("db pool init failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
defer pool.Close()
|
|
srv.pool = pool
|
|
go srv.runCacheLoop(ctx)
|
|
go srv.runTotalsLoop(ctx)
|
|
logger.Info("db connected; cache loops started", "live_interval", cacheInterval.String(), "totals_interval", totalsInterval.String())
|
|
}
|
|
|
|
mux := http.NewServeMux()
|
|
srv.registerRoutes(mux)
|
|
|
|
httpSrv := &http.Server{
|
|
Addr: cfg.Addr,
|
|
Handler: withRequestLogging(mux),
|
|
ReadHeaderTimeout: 10 * time.Second,
|
|
}
|
|
|
|
go func() {
|
|
if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
logger.Error("http server failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}()
|
|
logger.Info("listening", "addr", cfg.Addr)
|
|
|
|
<-ctx.Done()
|
|
logger.Info("shutdown signal received, draining")
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
if err := httpSrv.Shutdown(shutdownCtx); err != nil {
|
|
logger.Error("graceful shutdown failed", "err", err)
|
|
}
|
|
logger.Info("stopped")
|
|
}
|
|
|
|
// config holds runtime configuration sourced from environment variables,
|
|
// matching the Python service's env var names where they overlap.
|
|
type config struct {
|
|
Addr string // listen address, e.g. ":8770"
|
|
DatabaseURL string // dereth TimescaleDB DSN (read-only use)
|
|
InventoryURL string // inventory-service base URL
|
|
StaticDir string // directory for static assets / openissues.json
|
|
}
|
|
|
|
func loadConfig() config {
|
|
return config{
|
|
Addr: ":" + envOr("PORT", "8770"),
|
|
DatabaseURL: os.Getenv("DATABASE_URL"),
|
|
InventoryURL: envOr("INVENTORY_SERVICE_URL", "http://inventory-service:8000"),
|
|
StaticDir: envOr("STATIC_DIR", "static"),
|
|
}
|
|
}
|
|
|
|
func envOr(key, def string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
func (s *Server) registerRoutes(mux *http.ServeMux) {
|
|
mux.HandleFunc("GET /health", s.handleHealth)
|
|
// Mirrors Python's GET /api-version (hyphenated so nginx never strips it).
|
|
mux.HandleFunc("GET /api-version", s.handleVersion)
|
|
|
|
// Phase 1 read-side: the 5s caches.
|
|
mux.HandleFunc("GET /live", s.handleLive)
|
|
mux.HandleFunc("GET /live/", s.handleLive)
|
|
mux.HandleFunc("GET /trails", s.handleTrails)
|
|
mux.HandleFunc("GET /trails/", s.handleTrails)
|
|
|
|
// Totals (5-minute caches).
|
|
mux.HandleFunc("GET /total-rares", s.handleTotalRares)
|
|
mux.HandleFunc("GET /total-rares/", s.handleTotalRares)
|
|
mux.HandleFunc("GET /total-kills", s.handleTotalKills)
|
|
mux.HandleFunc("GET /total-kills/", s.handleTotalKills)
|
|
|
|
// Per-character & aggregate DB reads.
|
|
mux.HandleFunc("GET /stats/{character_name}", s.handleStats)
|
|
mux.HandleFunc("GET /portals", s.handlePortals)
|
|
mux.HandleFunc("GET /spawns/heatmap", s.handleSpawnHeatmap)
|
|
mux.HandleFunc("GET /server-health", s.handleServerHealth)
|
|
mux.HandleFunc("GET /character-stats/{name}", s.handleCharacterStats)
|
|
mux.HandleFunc("GET /combat-stats", s.handleCombatStatsAll)
|
|
mux.HandleFunc("GET /combat-stats/{character_name}", s.handleCombatStatsOne)
|
|
mux.HandleFunc("GET /inventories", s.handleInventories)
|
|
mux.HandleFunc("GET /inventory/{character_name}/search", s.handleInventorySearch)
|
|
|
|
// Ingest-only state (empty/default in Phase 1).
|
|
mux.HandleFunc("GET /quest-status", s.handleQuestStatus)
|
|
mux.HandleFunc("GET /vital-sharing/peers", s.handleVitalSharingPeers)
|
|
mux.HandleFunc("GET /equipment-cantrip-state/{name}", s.handleEquipmentCantrip)
|
|
mux.HandleFunc("GET /issues", s.handleIssues)
|
|
mux.HandleFunc("GET /me", s.handleMe)
|
|
|
|
// Inventory-service reverse proxies.
|
|
s.registerProxyRoutes(mux)
|
|
}
|
|
|
|
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"status": "ok",
|
|
"service": "tracker-go",
|
|
"version": buildVersion,
|
|
"db": s.pool != nil,
|
|
})
|
|
}
|
|
|
|
func (s *Server) handleVersion(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]any{"version": buildVersion})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
if err := json.NewEncoder(w).Encode(v); err != nil {
|
|
slog.Error("json encode failed", "err", err)
|
|
}
|
|
}
|
|
|
|
// withRequestLogging is a thin access-log middleware.
|
|
func withRequestLogging(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
sr := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
|
next.ServeHTTP(sr, r)
|
|
slog.Info("http",
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", sr.status,
|
|
"dur_ms", time.Since(start).Milliseconds(),
|
|
)
|
|
})
|
|
}
|
|
|
|
type statusRecorder struct {
|
|
http.ResponseWriter
|
|
status int
|
|
}
|
|
|
|
func (s *statusRecorder) WriteHeader(code int) {
|
|
s.status = code
|
|
s.ResponseWriter.WriteHeader(code)
|
|
}
|