Files
aeternalis/server/internal/store/store.go
T
dingoandClaude Sonnet 5 5df2f1b681 Merge control portal work from RPGTheory/aeternalis-portal
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>
2026-09-06 11:08:44 -04:00

275 lines
8.1 KiB
Go

package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
"aeternalis/server/internal/game"
_ "github.com/jackc/pgx/v5/stdlib"
_ "modernc.org/sqlite"
)
var ErrOwnership = errors.New("world ownership or revision lost")
type DB struct {
sql *sql.DB
postgres bool
}
type Lease struct {
DB *DB
WorldID string
Owner string
Revision int64
}
type Passage struct {
CharacterID string `json:"characterId"`
SourceWorld string `json:"sourceWorld"`
Name string `json:"name"`
}
func Open(ctx context.Context, dsn string) (*DB, error) {
postgres := strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://")
driver := "sqlite"
if postgres {
driver = "pgx"
}
conn, err := sql.Open(driver, dsn)
if err != nil {
return nil, err
}
conn.SetMaxOpenConns(8)
if !postgres {
conn.SetMaxOpenConns(1)
}
db := &DB{conn, postgres}
if err = conn.PingContext(ctx); err != nil {
conn.Close()
return nil, err
}
if !postgres {
if _, err = conn.ExecContext(ctx, "PRAGMA journal_mode=WAL"); err != nil {
conn.Close()
return nil, err
}
_, _ = conn.ExecContext(ctx, "PRAGMA busy_timeout=5000")
}
for _, stmt := range []string{
`CREATE TABLE IF NOT EXISTS worlds(id TEXT PRIMARY KEY, owner TEXT NOT NULL, lease_until BIGINT NOT NULL, revision BIGINT NOT NULL, snapshot TEXT NOT NULL)`,
`CREATE TABLE IF NOT EXISTS passages(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, source_world TEXT NOT NULL, character TEXT NOT NULL, claimed_world TEXT)`,
`CREATE INDEX IF NOT EXISTS passages_account ON passages(account_id)`,
`CREATE TABLE IF NOT EXISTS sessions(token_hash TEXT PRIMARY KEY, account_id TEXT NOT NULL, expires BIGINT NOT NULL)`,
`CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires)`,
} {
if _, err = conn.ExecContext(ctx, stmt); err != nil {
conn.Close()
return nil, err
}
}
if err = db.migrate(ctx); err != nil {
conn.Close()
return nil, err
}
return db, nil
}
func (d *DB) Close() error { return d.sql.Close() }
func (d *DB) q(query string) string {
if !d.postgres {
return query
}
i := 0
var b strings.Builder
for _, c := range query {
if c == '?' {
i++
fmt.Fprintf(&b, "$%d", i)
} else {
b.WriteRune(c)
}
}
return b.String()
}
func (d *DB) now() string {
if d.postgres {
return "CAST(EXTRACT(EPOCH FROM clock_timestamp()) AS BIGINT)"
}
return "unixepoch()"
}
func (d *DB) Acquire(ctx context.Context, w *game.World) (*Lease, []byte, error) {
data, err := json.Marshal(w)
if err != nil {
return nil, nil, err
}
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return nil, nil, err
}
defer tx.Rollback()
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO worlds(id,owner,lease_until,revision,snapshot) VALUES(?,'',0,0,?) ON CONFLICT(id) DO NOTHING`), w.ID, string(data))
if err != nil {
return nil, nil, err
}
owner := game.ID()
result, err := tx.ExecContext(ctx, d.q(`UPDATE worlds SET owner=?,lease_until=`+d.now()+`+30 WHERE id=? AND (owner='' OR lease_until<`+d.now()+`)`), owner, w.ID)
if err != nil {
return nil, nil, err
}
n, _ := result.RowsAffected()
if n != 1 {
return nil, nil, ErrOwnership
}
var snapshot string
var revision int64
if err = tx.QueryRowContext(ctx, d.q(`SELECT revision,snapshot FROM worlds WHERE id=?`), w.ID).Scan(&revision, &snapshot); err != nil {
return nil, nil, err
}
if err = tx.Commit(); err != nil {
return nil, nil, err
}
return &Lease{d, w.ID, owner, revision}, []byte(snapshot), nil
}
func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
return l.SaveCommand(ctx, w, claimID, nil, "")
}
func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, command *Command, outcome string) error {
data, err := json.Marshal(w)
if err != nil {
return err
}
d := l.DB
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
result, err := tx.ExecContext(ctx, d.q(`UPDATE worlds SET snapshot=?,revision=revision+1,lease_until=`+d.now()+`+30 WHERE id=? AND owner=? AND revision=? AND lease_until>=`+d.now()), string(data), l.WorldID, l.Owner, l.Revision)
if err != nil {
return err
}
n, _ := result.RowsAffected()
if n != 1 {
return ErrOwnership
}
if claimID != "" {
c := w.Characters[claimID]
if c == nil {
return errors.New("claimed character absent from target")
}
result, err = tx.ExecContext(ctx, d.q(`UPDATE passages SET claimed_world=? WHERE character_id=? AND account_id=? AND claimed_world IS NULL AND source_world<>?`), w.ID, claimID, c.Account, w.ID)
if err != nil {
return err
}
n, _ = result.RowsAffected()
if n != 1 {
return errors.New("passage already redeemed or unavailable")
}
}
if w.Phase == "won" {
for _, c := range w.Characters {
if c.View.Entity.State != "eligible" {
continue
}
encoded, err := json.Marshal(c)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO passages(character_id,account_id,source_world,character) VALUES(?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET source_world=excluded.source_world,character=excluded.character,claimed_world=NULL WHERE passages.claimed_world=excluded.source_world`), c.View.Entity.ID, c.Account, w.ID, string(encoded))
if err != nil {
return err
}
}
}
if err = d.syncCharacters(ctx, tx, w, claimID); err != nil {
return err
}
if command != nil {
status := "completed"
if outcome != "" {
status = "rejected"
}
r, err := tx.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND world_id=? AND status='pending'`), status, outcome, command.ID, w.ID)
if err != nil {
return err
}
n, _ := r.RowsAffected()
if n != 1 {
return errors.New("command already processed")
}
if command.Op == "revoke-sessions" && outcome == "" {
if _, err = tx.ExecContext(ctx, d.q(`DELETE FROM sessions WHERE account_id=?`), command.Target); err != nil {
return err
}
}
}
if err = tx.Commit(); err != nil {
return err
}
l.Revision++
w.Saved()
return nil
}
func (l *Lease) Release(ctx context.Context) error {
_, err := l.DB.sql.ExecContext(ctx, l.DB.q(`UPDATE worlds SET owner='',lease_until=0 WHERE id=? AND owner=?`), l.WorldID, l.Owner)
return err
}
func (d *DB) Passages(ctx context.Context, account string) ([]Passage, error) {
rows, err := d.sql.QueryContext(ctx, d.q(`SELECT character_id,source_world,character FROM passages WHERE account_id=? AND claimed_world IS NULL`), account)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Passage{}
for rows.Next() {
var p Passage
var raw string
if err = rows.Scan(&p.CharacterID, &p.SourceWorld, &raw); err != nil {
return nil, err
}
var c game.Character
if err = json.Unmarshal([]byte(raw), &c); err != nil {
return nil, err
}
p.Name = c.View.Entity.Name
out = append(out, p)
}
return out, rows.Err()
}
func (d *DB) ReadPassage(ctx context.Context, id, account string) (*game.Character, error) {
var raw string
err := d.sql.QueryRowContext(ctx, d.q(`SELECT character FROM passages WHERE character_id=? AND account_id=? AND claimed_world IS NULL`), id, account).Scan(&raw)
if err != nil {
return nil, err
}
var c game.Character
if err = json.Unmarshal([]byte(raw), &c); err != nil {
return nil, err
}
return &c, nil
}
func (d *DB) CreateSession(ctx context.Context, hash, account string) error {
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err = tx.ExecContext(ctx, `DELETE FROM sessions WHERE expires<`+d.now()); err != nil {
return err
}
if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO sessions(token_hash,account_id,expires) VALUES(?,?,`+d.now()+`+86400)`), hash, account); err != nil {
return err
}
return tx.Commit()
}
func (d *DB) Session(ctx context.Context, hash string) (string, error) {
var account string
err := d.sql.QueryRowContext(ctx, d.q(`SELECT account_id FROM sessions WHERE token_hash=? AND expires>`+d.now()), hash).Scan(&account)
return account, err
}
func (d *DB) DeleteSession(ctx context.Context, hash string) error {
_, err := d.sql.ExecContext(ctx, d.q(`DELETE FROM sessions WHERE token_hash=?`), hash)
return err
}