Files

338 lines
9.9 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
}
if err = db.ensureCatalog(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 {
return l.save(ctx, w, claimID, command, outcome, nil, nil, nil)
}
func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt, revival *reviveClaim, housing *houseMutation) error {
live := w
w = stageTitleWorld(w)
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 revival != nil {
if err = d.checkRevival(ctx, tx, revival); err != nil {
return err
}
}
if receipt != nil {
if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO craft_receipts(id,account_id,character_id,request_json,result_json) VALUES(?,?,?,?,?)`), receipt.ID, receipt.Account, receipt.CharacterID, receipt.Request, receipt.Result); err != nil {
return err
}
}
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 err = d.syncPassages(ctx, tx, w); err != nil {
return err
}
if err = d.syncCharacters(ctx, tx, w, claimID); err != nil {
return err
}
if command != nil && outcome == "" && game.IsContentCommand(command.Op) {
outcome, err = d.applyContentCommand(ctx, tx, w, command)
if err != nil {
return err
}
}
if err = d.syncHousing(ctx, tx, w); err != nil {
return err
}
if housing != nil {
if err = d.applyHouse(ctx, tx, w, housing); err != nil {
return err
}
if err = d.syncHouseRooms(ctx, tx, w); err != nil {
return err
}
}
if err = d.syncTitles(ctx, tx, w); err != nil {
return err
}
if command != nil && outcome == "" && command.Op == "grant-title" {
found := false
for _, award := range w.Characters[command.Target].View.Titles {
if award.ID == command.Value {
found = true
}
}
if !found {
outcome = "title's first claim belongs to another player"
}
}
// Rewrite the final payloads after the immutable award claims have resolved.
// The transaction already holds the owner, passage and character row locks.
data, err = json.Marshal(w)
if err != nil {
return err
}
if _, err = tx.ExecContext(ctx, d.q(`UPDATE worlds SET snapshot=? WHERE id=? AND owner=?`), string(data), l.WorldID, l.Owner); err != nil {
return err
}
if err = d.syncPassages(ctx, tx, w); 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++
for id, c := range w.Characters {
if game.HouseID(live.Characters[id]) != game.HouseID(c) {
live.Characters[id].MoveX = 0
live.Characters[id].MoveZ = 0
live.Characters[id].JumpVelocity = 0
}
live.Characters[id].View = c.View
live.Characters[id].HouseRoom = c.HouseRoom
}
live.PendingTitles = nil
live.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
}