mirror of
https://github.com/IS1DI/x0gp.git
synced 2026-07-16 20:47:55 +00:00
This commit captures the full server code accumulated across
several development sessions. It includes the following layers,
applied in roughly this order during development:
1. Base infrastructure
- cmd/poc-server HTTP+WebSocket server, /health, /stats
- internal/transport wire types (Envelope + all message types)
- internal/catalog, internal/realtime, internal/stats
- internal/storage/postgres with migrations 001-004
- .env, .env.example, docker-compose, Dockerfile, scripts/
2. Swagger documentation
- go get github.com/swaggo/http-swagger
- swag init produces docs/docs.go
- /swagger/index.html UI, /swagger/doc.json spec
- annotations on health/stats/ws and catalog handlers
3. Races API
- internal/races/{store,service,keyset,types}.go
- migration 005_races.sql: finished_races, race_plans, race_queue
- GET /api/races with keyset pagination, status filter
- GET /api/races/upcoming
- POST /api/races/queue/join, GET, DELETE
- POST/GET /api/races/plans, DELETE /{id}
- lobby.RaceMeta simplification (no host_id/host_name)
4. Races seeder
- internal/races/seed with deterministic generator
- --seed-races / --reset CLI flags in main.go
- 30 finished + 5 live + 5 plans + 4 queue entries
5. Drivers and clans
- internal/drivers, internal/clans (CRUD, validation)
- migration 008_drivers_clans.sql
- /api/clans and /api/drivers endpoints
- 3-letter uppercase nickname/tag validation
- lobby.DriverMeta: Nickname, AvatarURL, ClanID, ClanTag
6. Podium
- internal/transport.RacePodiumEntry
- lobby.SetDriverProfile for in-memory metadata sync
- migration 007_podium.sql (podium JSONB column)
- seeder populates top-3 per finished race
7. Live races persistence
- migration 009_live_persistence.sql: live_races,
live_race_drivers, lobby_drivers
- internal/races/live_store.go: LiveStore with write-side
mirror for lobby.Service mutations
- Service.collectLive and Upcoming read from Postgres
- main.go RestoreFromDB rehydrates lobby on startup
8. Unify live + finished into one races table
- migration 010_unify_races.sql: rename finished_races to
races, expand status CHECK, merge live rows
- PgStore now hosts both write paths; LiveStore is a
thin facade implementing lobby.Persistence
- seeder resetAll drops only finished/cancelled rows and
race_plans / race_queue / lobby_drivers
Each layer is consistent on its own; cross-layer changes are
visible in the file history. A future refactor may split this
commit into the per-stage boundaries listed above.
172 lines
4.3 KiB
Go
172 lines
4.3 KiB
Go
// Package clans owns persistence and business logic for clans.
|
|
//
|
|
// A clan has a unique 3-letter tag (A-Z, uppercase, exactly 3 chars),
|
|
// a name, and an optional avatar URL. Drivers reference a clan via a
|
|
// nullable FK (see internal/drivers).
|
|
package clans
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"regexp"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// Errors returned by the service.
|
|
var (
|
|
ErrNotFound = errors.New("clan not found")
|
|
ErrInvalidInput = errors.New("invalid input")
|
|
ErrAlreadyExists = errors.New("clan already exists")
|
|
)
|
|
|
|
// tagRE enforces exactly 3 uppercase ASCII letters.
|
|
var tagRE = regexp.MustCompile(`^[A-Z]{3}$`)
|
|
|
|
// IsValidTag reports whether s is a valid clan/driver tag.
|
|
func IsValidTag(s string) bool { return tagRE.MatchString(s) }
|
|
|
|
// Clan is the canonical in-memory representation.
|
|
type Clan struct {
|
|
ID string
|
|
Tag string
|
|
Name string
|
|
AvatarURL string
|
|
CreatedMs int64
|
|
UpdatedMs int64
|
|
}
|
|
|
|
// PgStore is the Postgres-backed half of the package.
|
|
type PgStore struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
// NewPgStore wraps an open pgxpool.
|
|
func NewPgStore(pool *pgxpool.Pool) *PgStore {
|
|
return &PgStore{pool: pool}
|
|
}
|
|
|
|
// Exec exposes raw SQL for the seeder.
|
|
func (s *PgStore) Exec(ctx context.Context, sql string) (int64, error) {
|
|
tag, err := s.pool.Exec(ctx, sql)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return tag.RowsAffected(), nil
|
|
}
|
|
|
|
// Create inserts a clan.
|
|
func (s *PgStore) Create(ctx context.Context, c Clan) error {
|
|
now := time.Now().UnixMilli()
|
|
if c.CreatedMs == 0 {
|
|
c.CreatedMs = now
|
|
}
|
|
c.UpdatedMs = now
|
|
_, err := s.pool.Exec(ctx, `
|
|
INSERT INTO clans (id, tag, name, avatar_url, created_ms, updated_ms)
|
|
VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
c.ID, c.Tag, c.Name, c.AvatarURL, c.CreatedMs, c.UpdatedMs)
|
|
if err != nil {
|
|
return fmt.Errorf("insert clan: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Get loads a clan by id.
|
|
func (s *PgStore) Get(ctx context.Context, id string) (Clan, error) {
|
|
row := s.pool.QueryRow(ctx,
|
|
`SELECT id, tag, name, avatar_url, created_ms, updated_ms
|
|
FROM clans WHERE id = $1`, id)
|
|
var c Clan
|
|
if err := row.Scan(&c.ID, &c.Tag, &c.Name, &c.AvatarURL, &c.CreatedMs, &c.UpdatedMs); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return Clan{}, ErrNotFound
|
|
}
|
|
return Clan{}, err
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// GetByTag loads a clan by its 3-letter tag.
|
|
func (s *PgStore) GetByTag(ctx context.Context, tag string) (Clan, error) {
|
|
row := s.pool.QueryRow(ctx,
|
|
`SELECT id, tag, name, avatar_url, created_ms, updated_ms
|
|
FROM clans WHERE tag = $1`, tag)
|
|
var c Clan
|
|
if err := row.Scan(&c.ID, &c.Tag, &c.Name, &c.AvatarURL, &c.CreatedMs, &c.UpdatedMs); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return Clan{}, ErrNotFound
|
|
}
|
|
return Clan{}, err
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// List returns all clans, ordered by tag.
|
|
func (s *PgStore) List(ctx context.Context, limit, offset int) ([]Clan, error) {
|
|
if limit <= 0 || limit > 200 {
|
|
limit = 50
|
|
}
|
|
if offset < 0 {
|
|
offset = 0
|
|
}
|
|
rows, err := s.pool.Query(ctx,
|
|
`SELECT id, tag, name, avatar_url, created_ms, updated_ms
|
|
FROM clans ORDER BY tag ASC LIMIT $1 OFFSET $2`, limit, offset)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := make([]Clan, 0)
|
|
for rows.Next() {
|
|
var c Clan
|
|
if err := rows.Scan(&c.ID, &c.Tag, &c.Name, &c.AvatarURL, &c.CreatedMs, &c.UpdatedMs); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, c)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// Delete removes a clan by id.
|
|
func (s *PgStore) Delete(ctx context.Context, id string) error {
|
|
tag, err := s.pool.Exec(ctx, `DELETE FROM clans WHERE id = $1`, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Update applies a partial patch.
|
|
func (s *PgStore) Update(ctx context.Context, c Clan) error {
|
|
c.UpdatedMs = time.Now().UnixMilli()
|
|
tag, err := s.pool.Exec(ctx, `
|
|
UPDATE clans
|
|
SET name = $2, avatar_url = $3, updated_ms = $4
|
|
WHERE id = $1`,
|
|
c.ID, c.Name, c.AvatarURL, c.UpdatedMs)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
return ErrNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Count returns the total number of clans.
|
|
func (s *PgStore) Count(ctx context.Context) (int, error) {
|
|
var n int
|
|
row := s.pool.QueryRow(ctx, `SELECT COUNT(*) FROM clans`)
|
|
if err := row.Scan(&n); err != nil {
|
|
return 0, err
|
|
}
|
|
return n, nil
|
|
}
|