Files
aeternalis/server/internal/store/titles.go
T

199 lines
6.2 KiB
Go

package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"maps"
"sort"
"aeternalis/server/internal/game"
p "aeternalis/server/internal/protocol"
)
// Title grants and their derived stats/equipment eligibility change in this staged view. The live simulation is untouched
// until its snapshot, claim ledger, character records and passages all commit.
func stageTitleWorld(w *game.World) *game.World {
staged := *w
staged.Characters = make(map[string]*game.Character, len(w.Characters))
for id, c := range w.Characters {
copy := *c
copy.View.Titles = append([]p.TitleAward{}, c.View.Titles...)
copy.View.Items = append([]p.ItemInstance{}, c.View.Items...)
copy.View.CraftedStacks = append([]p.CraftedStack{}, c.View.CraftedStacks...)
copy.View.Crafting = maps.Clone(c.View.Crafting)
copy.View.Powers = maps.Clone(c.View.Powers)
copy.View.Weapons = maps.Clone(c.View.Weapons)
copy.View.Inventory = maps.Clone(c.View.Inventory)
copy.View.StackNames = maps.Clone(c.View.StackNames)
copy.View.Equipment = maps.Clone(c.View.Equipment)
copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats)
copy.View.Stats = maps.Clone(c.View.Stats)
staged.Characters[id] = &copy
}
return &staged
}
func (d *DB) syncTitles(ctx context.Context, tx *sql.Tx, w *game.World) error {
// syncCharacters has already locked these rows. A stale source world may
// checkpoint itself, but it cannot grant titles for a transferred character.
owned := make(map[string]bool, len(w.Characters))
revoked := map[string]map[string]bool{}
for id, c := range w.Characters {
var account, world string
err := tx.QueryRowContext(ctx, d.q(`SELECT account_id,world_id FROM character_records WHERE character_id=?`), id).Scan(&account, &world)
if err != nil {
return err
}
owned[id] = account == c.Account && world == w.ID
if owned[id] && revoked[c.Account] == nil {
ids, err := d.revokedTitles(ctx, tx, c.Account)
if err != nil {
return err
}
revoked[c.Account] = ids
}
}
candidates := append([]game.TitleCandidate{}, w.PendingTitles...)
// All owners lock title IDs in the same order, even with different catalogs.
// Stable ordering preserves simulation event order for contenders for one ID.
sort.SliceStable(candidates, func(i, j int) bool { return candidates[i].Award.ID < candidates[j].Award.ID })
granted := map[string]map[string]bool{}
for _, candidate := range candidates {
c := w.Characters[candidate.CharacterID]
if c == nil || !owned[candidate.CharacterID] {
continue
}
award := candidate.Award
if revoked[c.Account][award.ID] {
continue
}
if award.ID == "" || award.WorldID != w.ID {
return errors.New("invalid title candidate identity")
}
key := ""
switch award.Scope {
case "personal":
key = c.Account
case "world":
key = w.ID
case "global":
key = "global"
default:
return errors.New("invalid title candidate scope")
}
raw, err := json.Marshal(award)
if err != nil {
return err
}
result, err := tx.ExecContext(ctx, d.q(`INSERT INTO title_awards(account_id,title_id,scope,scope_key,character_id,award) VALUES(?,?,?,?,?,?) ON CONFLICT DO NOTHING`), c.Account, award.ID, award.Scope, key, candidate.CharacterID, string(raw))
if err != nil {
return err
}
count, err := result.RowsAffected()
if err != nil {
return err
}
if count == 1 {
if granted[candidate.CharacterID] == nil {
granted[candidate.CharacterID] = map[string]bool{}
}
granted[candidate.CharacterID][award.ID] = true
}
}
byAccount := map[string][]p.TitleAward{}
for id, c := range w.Characters {
if !owned[id] {
continue
}
awards, loaded := byAccount[c.Account]
if !loaded {
var err error
awards, err = d.accountTitles(ctx, tx, c.Account)
if err != nil {
return err
}
byAccount[c.Account] = awards
}
if c.View.Entity.State != "dead" {
c.View.Titles = []p.TitleAward{}
for _, award := range awards {
if !revoked[c.Account][award.ID] {
c.View.Titles = append(c.View.Titles, award)
}
}
w.RefreshStats(c)
continue
}
// A historical dead life keeps its own record. Only awards from its death
// transaction are appended; titles from later lives do not rewrite history.
keep := map[string]bool{}
for _, award := range c.View.Titles {
keep[award.ID] = true
}
for title := range granted[id] {
keep[title] = true
}
c.View.Titles = []p.TitleAward{}
for _, award := range awards {
if keep[award.ID] {
c.View.Titles = append(c.View.Titles, award)
}
}
}
return nil
}
func (d *DB) accountTitles(ctx context.Context, tx *sql.Tx, account string) ([]p.TitleAward, error) {
rows, err := tx.QueryContext(ctx, d.q(`SELECT award FROM title_awards WHERE account_id=? ORDER BY title_id`), account)
if err != nil {
return nil, err
}
defer rows.Close()
awards := []p.TitleAward{}
for rows.Next() {
var raw string
var award p.TitleAward
if err = rows.Scan(&raw); err != nil {
return nil, err
}
if err = json.Unmarshal([]byte(raw), &award); err != nil {
return nil, err
}
if award.Effects.Modifiers == nil {
award.Effects.Modifiers = []p.StatModifier{}
}
awards = append(awards, award)
}
return awards, rows.Err()
}
func (d *DB) syncPassages(ctx context.Context, tx *sql.Tx, w *game.World) error {
if w.Phase != "won" {
return nil
}
// Stable row order also prevents competing owners from acquiring survivor
// passage locks in opposite map iteration order.
ids := make([]string, 0, len(w.Characters))
for id := range w.Characters {
ids = append(ids, id)
}
sort.Strings(ids)
for _, id := range ids {
c := w.Characters[id]
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 OR (passages.source_world=excluded.source_world AND passages.claimed_world IS NULL)`), c.View.Entity.ID, c.Account, w.ID, string(encoded))
if err != nil {
return err
}
}
return nil
}