RPGTheory/aeternalis-portal had diverged from this repo (the git/CI/CD copy) with an in-progress control portal feature that was never synced back here, so none of it had gone through CI or been deployed: - New site/game/control routing split: index.html becomes a world directory landing page (site.ts), game.html is the renamed former index.html (main.ts), control.html is a new admin panel (control.ts, portal-shared.ts, portal.css). - Server: new internal/store/portal.go (character/world registry, command queue, admin grants) and internal/transport/control.go (portal API routes), plus a new internal/gitops package that lets the portal provision new worlds via a GitOps repo commit. - game.World gains BornAt/DiedAt/DeathReason and an operator Control() path (close/open admissions, awaken boss, end world, per-character rename/heal/unstuck/retire); death no longer reuses the same character id on rejoin, matching the "new life" permadeath model in Plan.md rather than the old bypass-prevention test's expectations. - deploy/: new control-egress network policy and portal/control values (admin role, GitOps repo/branch/values file/CIDRs). - New e2e coverage: tests/portal.spec.ts, tools/capture-world.mjs. Verified this repo's own independent commits (800ms movement-staleness window, 20s boss-attack poll, SRS/TLS deploy values, ubuntu-22.04 runner pin, DOCKER_HOST fix) were already present in the portal copy before merging, so nothing here regresses them. `tsc --noEmit`, the vite client build, and the protocol contract check all pass; no go.mod changes. Could not run `go build`/`go test` locally (no Go toolchain on PATH, Docker daemon not running) — every new/changed Go symbol was manually cross-referenced and resolves, but this should still be built and tested in CI before merging to master. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
301 lines
11 KiB
Go
301 lines
11 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"aeternalis/server/internal/game"
|
|
)
|
|
|
|
var ErrLivingCharacter = errors.New("you already have a living character; continue that character or use its survivor passage")
|
|
|
|
type CharacterRecord struct {
|
|
ID string `json:"id"`
|
|
Account string `json:"account"`
|
|
WorldID string `json:"worldId"`
|
|
Name string `json:"name"`
|
|
State string `json:"state"`
|
|
Character *game.Character `json:"character"`
|
|
}
|
|
type WorldRecord struct {
|
|
ID string `json:"id"`
|
|
Phase string `json:"phase"`
|
|
Living int `json:"living"`
|
|
Dead int `json:"dead"`
|
|
Capacity int `json:"capacity"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
BossAt time.Time `json:"bossAt"`
|
|
Closed bool `json:"closed"`
|
|
Available bool `json:"available"`
|
|
Revision int64 `json:"revision"`
|
|
}
|
|
type Command struct {
|
|
ID string `json:"id"`
|
|
WorldID string `json:"worldId"`
|
|
Actor string `json:"actor"`
|
|
Op string `json:"op"`
|
|
Target string `json:"target"`
|
|
Value string `json:"value"`
|
|
Reason string `json:"reason"`
|
|
Status string `json:"status"`
|
|
Result string `json:"result"`
|
|
CreatedAt int64 `json:"createdAt"`
|
|
CompletedAt int64 `json:"completedAt"`
|
|
}
|
|
|
|
// Versioned, transactional backfill. Conflicting legacy lives fail closed rather
|
|
// than choosing which player's character to destroy during an upgrade.
|
|
func (d *DB) migrate(ctx context.Context) error {
|
|
tx, err := d.sql.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
if d.postgres {
|
|
if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(7362771)`); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
for _, stmt := range []string{
|
|
`CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)`,
|
|
`CREATE TABLE IF NOT EXISTS character_records(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, world_id TEXT NOT NULL, name TEXT NOT NULL, state TEXT NOT NULL, character TEXT NOT NULL)`,
|
|
`CREATE UNIQUE INDEX IF NOT EXISTS one_living_character ON character_records(account_id) WHERE state IN ('alive','eligible')`,
|
|
`CREATE INDEX IF NOT EXISTS characters_world ON character_records(world_id)`,
|
|
`CREATE TABLE IF NOT EXISTS admin_sessions(token_hash TEXT PRIMARY KEY, expires BIGINT NOT NULL)`,
|
|
`CREATE TABLE IF NOT EXISTS control_commands(id TEXT PRIMARY KEY, world_id TEXT NOT NULL, actor TEXT NOT NULL, op TEXT NOT NULL, target TEXT NOT NULL, value TEXT NOT NULL, reason TEXT NOT NULL, status TEXT NOT NULL, result TEXT NOT NULL, created_at BIGINT NOT NULL, completed_at BIGINT NOT NULL DEFAULT 0)`,
|
|
`CREATE INDEX IF NOT EXISTS commands_pending ON control_commands(world_id,status,created_at)`,
|
|
} {
|
|
if _, err = tx.ExecContext(ctx, stmt); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
var version int
|
|
err = tx.QueryRowContext(ctx, `SELECT version FROM schema_migrations WHERE version=1`).Scan(&version)
|
|
if err == nil {
|
|
return tx.Commit()
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
return err
|
|
}
|
|
rows, err := tx.QueryContext(ctx, `SELECT snapshot FROM worlds ORDER BY id`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var worlds []*game.World
|
|
for rows.Next() {
|
|
var raw string
|
|
if err = rows.Scan(&raw); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
var w game.World
|
|
if err = json.Unmarshal([]byte(raw), &w); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
worlds = append(worlds, &w)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, w := range worlds {
|
|
for _, c := range w.Characters {
|
|
var source string
|
|
var claimed sql.NullString
|
|
err = tx.QueryRowContext(ctx, d.q(`SELECT source_world,claimed_world FROM passages WHERE character_id=?`), c.View.Entity.ID).Scan(&source, &claimed)
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return err
|
|
}
|
|
if err == nil && ((claimed.Valid && claimed.String != w.ID) || (!claimed.Valid && source != w.ID)) {
|
|
continue
|
|
}
|
|
if err = d.writeCharacter(ctx, tx, w.ID, c, false); err != nil {
|
|
return fmt.Errorf("character migration conflict in world %s: %w; stop all old world pods and resolve duplicate living characters before upgrading", w.ID, err)
|
|
}
|
|
}
|
|
}
|
|
if _, err = tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES(1)`); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
func (d *DB) writeCharacter(ctx context.Context, tx *sql.Tx, world string, c *game.Character, claim bool) error {
|
|
raw, err := json.Marshal(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
where := "character_records.world_id=excluded.world_id"
|
|
if claim {
|
|
where = "character_records.account_id=excluded.account_id"
|
|
}
|
|
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO character_records(character_id,account_id,world_id,name,state,character) VALUES(?,?,?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET world_id=excluded.world_id,name=excluded.name,state=excluded.state,character=excluded.character WHERE `+where), c.View.Entity.ID, c.Account, world, c.View.Entity.Name, c.View.Entity.State, string(raw))
|
|
if err != nil && (strings.Contains(err.Error(), "one_living_character") || strings.Contains(err.Error(), "character_records.account_id")) {
|
|
return ErrLivingCharacter
|
|
}
|
|
return err
|
|
}
|
|
func (d *DB) syncCharacters(ctx context.Context, tx *sql.Tx, w *game.World, claim string) error {
|
|
// Release dead lives before reserving their replacements, independent of map order.
|
|
characters := make([]*game.Character, 0, len(w.Characters))
|
|
for _, c := range w.Characters {
|
|
characters = append(characters, c)
|
|
}
|
|
sort.Slice(characters, func(i, j int) bool {
|
|
a, b := characters[i], characters[j]
|
|
if (a.View.Entity.State == "dead") != (b.View.Entity.State == "dead") {
|
|
return a.View.Entity.State == "dead"
|
|
}
|
|
return a.View.Entity.ID < b.View.Entity.ID
|
|
})
|
|
for _, c := range characters {
|
|
if err := d.writeCharacter(ctx, tx, w.ID, c, c.View.Entity.ID == claim && claim != ""); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
func (d *DB) ActiveCharacter(ctx context.Context, account string) (*CharacterRecord, error) {
|
|
var r CharacterRecord
|
|
var raw string
|
|
err := d.sql.QueryRowContext(ctx, d.q(`SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE account_id=? AND state IN ('alive','eligible')`), account).Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err = json.Unmarshal([]byte(raw), &r.Character); err != nil {
|
|
return nil, err
|
|
}
|
|
return &r, nil
|
|
}
|
|
func (d *DB) Characters(ctx context.Context, account, world string) ([]CharacterRecord, error) {
|
|
query := `SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE 1=1`
|
|
args := []any{}
|
|
if account != "" {
|
|
query += " AND account_id=?"
|
|
args = append(args, account)
|
|
}
|
|
if world != "" {
|
|
query += " AND world_id=?"
|
|
args = append(args, world)
|
|
}
|
|
query += " ORDER BY world_id,name,character_id LIMIT 500"
|
|
rows, err := d.sql.QueryContext(ctx, d.q(query), args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []CharacterRecord{}
|
|
for rows.Next() {
|
|
var r CharacterRecord
|
|
var raw string
|
|
if err = rows.Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw); err != nil {
|
|
return nil, err
|
|
}
|
|
if err = json.Unmarshal([]byte(raw), &r.Character); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, r)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
func (d *DB) Worlds(ctx context.Context) ([]WorldRecord, error) {
|
|
rows, err := d.sql.QueryContext(ctx, `SELECT snapshot,revision,CASE WHEN owner<>'' AND lease_until>=`+d.now()+` THEN 1 ELSE 0 END FROM worlds ORDER BY id LIMIT 200`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []WorldRecord{}
|
|
for rows.Next() {
|
|
var raw string
|
|
var r WorldRecord
|
|
var available int
|
|
if err = rows.Scan(&raw, &r.Revision, &available); err != nil {
|
|
return nil, err
|
|
}
|
|
var w game.World
|
|
if err = json.Unmarshal([]byte(raw), &w); err != nil {
|
|
return nil, err
|
|
}
|
|
r.ID = w.ID
|
|
r.Phase = w.Phase
|
|
r.Living = w.LivingCount()
|
|
r.Dead = len(w.Characters) - r.Living
|
|
r.Capacity = w.Balance.MaxPlayers
|
|
r.CreatedAt = w.CreatedAt
|
|
r.BossAt = w.CreatedAt.Add(time.Duration(w.Balance.SeasonSeconds) * time.Second)
|
|
r.Closed = w.AdmissionsClosed
|
|
r.Available = available == 1
|
|
out = append(out, r)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
func (d *DB) GrantAdmin(ctx context.Context, token string, seconds int64) error {
|
|
_, err := d.sql.ExecContext(ctx, d.q(`INSERT INTO admin_sessions(token_hash,expires) VALUES(?,`+d.now()+`+?) ON CONFLICT(token_hash) DO UPDATE SET expires=excluded.expires`), token, seconds)
|
|
return err
|
|
}
|
|
func (d *DB) IsAdmin(ctx context.Context, token string) bool {
|
|
var n int
|
|
err := d.sql.QueryRowContext(ctx, d.q(`SELECT 1 FROM admin_sessions a JOIN sessions s ON s.token_hash=a.token_hash WHERE a.token_hash=? AND a.expires>`+d.now()+` AND s.expires>`+d.now()), token).Scan(&n)
|
|
return err == nil && n == 1
|
|
}
|
|
func (d *DB) Enqueue(ctx context.Context, c Command) error {
|
|
_, err := d.sql.ExecContext(ctx, d.q(`INSERT INTO control_commands(id,world_id,actor,op,target,value,reason,status,result,created_at) VALUES(?,?,?,?,?,?,?,'pending','',`+d.now()+`) ON CONFLICT(id) DO NOTHING`), c.ID, c.WorldID, c.Actor, c.Op, c.Target, c.Value, c.Reason)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var existing Command
|
|
err = d.sql.QueryRowContext(ctx, d.q(`SELECT actor,world_id,op,target,value,reason FROM control_commands WHERE id=?`), c.ID).Scan(&existing.Actor, &existing.WorldID, &existing.Op, &existing.Target, &existing.Value, &existing.Reason)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if existing.Actor != c.Actor || existing.WorldID != c.WorldID || existing.Op != c.Op || existing.Target != c.Target || existing.Value != c.Value || existing.Reason != c.Reason {
|
|
return errors.New("request ID already used")
|
|
}
|
|
return nil
|
|
}
|
|
func (d *DB) Commands(ctx context.Context, world string, pending bool) ([]Command, error) {
|
|
query := `SELECT id,world_id,actor,op,target,value,reason,status,result,created_at,completed_at FROM control_commands WHERE 1=1`
|
|
args := []any{}
|
|
if world != "" {
|
|
query += " AND world_id=?"
|
|
args = append(args, world)
|
|
}
|
|
if pending {
|
|
query += " AND status='pending' ORDER BY created_at,id LIMIT 10"
|
|
} else {
|
|
query += " ORDER BY created_at DESC,id LIMIT 100"
|
|
}
|
|
rows, err := d.sql.QueryContext(ctx, d.q(query), args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []Command{}
|
|
for rows.Next() {
|
|
var c Command
|
|
if err = rows.Scan(&c.ID, &c.WorldID, &c.Actor, &c.Op, &c.Target, &c.Value, &c.Reason, &c.Status, &c.Result, &c.CreatedAt, &c.CompletedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, c)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
func (d *DB) FinishProvision(ctx context.Context, id, result string, success bool) error {
|
|
status := "rejected"
|
|
if success {
|
|
status = "completed"
|
|
}
|
|
_, err := d.sql.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND status='pending' AND op='create-world'`), status, result, id)
|
|
return err
|
|
}
|