Add spells, weapon abilities, and durable corpse resurrection
This commit is contained in:
@@ -17,6 +17,8 @@ var ErrCatalogInvalid = errors.New("invalid catalog change")
|
||||
var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
|
||||
|
||||
type CatalogChange struct {
|
||||
Power *content.PowerDefinition `json:"power,omitempty"`
|
||||
Weapon *content.GatheringSkill `json:"weapon,omitempty"`
|
||||
CraftRecipe *content.CraftRecipe `json:"craftRecipe,omitempty"`
|
||||
CraftProfession *content.GatheringSkill `json:"craftProfession,omitempty"`
|
||||
CraftMaterial *content.CraftMaterial `json:"craftMaterial,omitempty"`
|
||||
@@ -51,7 +53,7 @@ type CatalogResult struct {
|
||||
// Explicit definition IDs are reserved for trusted seed/import code. Browser
|
||||
// publications omit them; the server assigns an ID after resolving request replay.
|
||||
func (c CatalogChange) HasDefinitionID() bool {
|
||||
return (c.CraftRecipe != nil && c.CraftRecipe.ID != "") || (c.CraftProfession != nil && c.CraftProfession.ID != "") || (c.CraftMaterial != nil && c.CraftMaterial.ID != "") || (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "")
|
||||
return (c.Power != nil && c.Power.ID != "") || (c.Weapon != nil && c.Weapon.ID != "") || (c.CraftRecipe != nil && c.CraftRecipe.ID != "") || (c.CraftProfession != nil && c.CraftProfession.ID != "") || (c.CraftMaterial != nil && c.CraftMaterial.ID != "") || (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "")
|
||||
}
|
||||
|
||||
type CatalogAudit struct {
|
||||
@@ -129,6 +131,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) {
|
||||
}
|
||||
catalog.RestoreCrafting(defaults)
|
||||
}
|
||||
if catalog.Powers == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return catalog, e
|
||||
}
|
||||
catalog.RestorePowers(b)
|
||||
}
|
||||
return catalog, catalog.Validate()
|
||||
}
|
||||
func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) {
|
||||
@@ -164,12 +173,16 @@ func (c CatalogChange) validate() error {
|
||||
}
|
||||
valid := false
|
||||
count := 0
|
||||
for _, present := range []bool{c.CraftRecipe != nil, c.CraftProfession != nil, c.CraftMaterial != nil, c.CraftRules != nil, c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} {
|
||||
for _, present := range []bool{c.Power != nil, c.Weapon != nil, c.CraftRecipe != nil, c.CraftProfession != nil, c.CraftMaterial != nil, c.CraftRules != nil, c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} {
|
||||
if present {
|
||||
count++
|
||||
}
|
||||
}
|
||||
switch c.Op {
|
||||
case "create-power":
|
||||
valid = c.Power != nil
|
||||
case "create-weapon":
|
||||
valid = c.Weapon != nil
|
||||
case "create-craft-recipe", "update-craft-recipe":
|
||||
valid = c.CraftRecipe != nil
|
||||
case "create-craft-profession":
|
||||
|
||||
@@ -35,6 +35,12 @@ func (d *DB) PreviewCatalog(ctx context.Context, change CatalogChange) (CatalogP
|
||||
}
|
||||
// Preview validates a provisional identity but does not reserve or expose it.
|
||||
if !change.HasDefinitionID() {
|
||||
if resolved.Power != nil {
|
||||
resolved.Power.ID = ""
|
||||
}
|
||||
if resolved.Weapon != nil {
|
||||
resolved.Weapon.ID = ""
|
||||
}
|
||||
if resolved.CraftRecipe != nil && change.Op != "update-craft-recipe" {
|
||||
resolved.CraftRecipe.ID = ""
|
||||
}
|
||||
@@ -124,7 +130,32 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
|
||||
}
|
||||
crafting := *c.Crafting
|
||||
c.Crafting = &crafting
|
||||
if c.Powers == nil {
|
||||
b, e := content.Load()
|
||||
if e != nil {
|
||||
return invalid(e)
|
||||
}
|
||||
c.RestorePowers(b)
|
||||
}
|
||||
powers := *c.Powers
|
||||
c.Powers = &powers
|
||||
switch change.Op {
|
||||
case "create-power":
|
||||
v := *change.Power
|
||||
if v.ID == "" {
|
||||
v.ID = "power_" + game.ID()
|
||||
}
|
||||
c.Powers.Powers = append(slices.Clone(c.Powers.Powers), v)
|
||||
resolved.Power = &v
|
||||
target = v.ID
|
||||
case "create-weapon":
|
||||
v := *change.Weapon
|
||||
if v.ID == "" {
|
||||
v.ID = "weapon_" + game.ID()
|
||||
}
|
||||
c.Powers.Weapons = append(slices.Clone(c.Powers.Weapons), v)
|
||||
resolved.Weapon = &v
|
||||
target = v.ID
|
||||
case "create-craft-recipe", "update-craft-recipe":
|
||||
v := *change.CraftRecipe
|
||||
v.Revision = 1
|
||||
|
||||
@@ -73,7 +73,7 @@ func (l *Lease) Craft(ctx context.Context, live *game.World, account string, req
|
||||
request, _ := json.Marshal(req)
|
||||
out, _ := json.Marshal(result)
|
||||
receipt := &craftReceipt{req.ID, account, req.CharacterID, string(request), string(out)}
|
||||
if e = l.save(ctx, staged, "", nil, "", receipt); e != nil {
|
||||
if e = l.save(ctx, staged, "", nil, "", receipt, nil); e != nil {
|
||||
return p.CraftResult{}, e
|
||||
}
|
||||
// Retain character pointers captured by existing WebSocket handlers.
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// During a rolling upgrade an older world owner still inserts replacement lives.
|
||||
// Enforce the account pointer at the database boundary as well as in new writers,
|
||||
// so creating and losing a replacement on that owner cannot revive an older life.
|
||||
func (d *DB) migrateLifeTrigger(ctx context.Context, tx *sql.Tx) error {
|
||||
var version int
|
||||
err := tx.QueryRowContext(ctx, `SELECT version FROM schema_migrations WHERE version=7`).Scan(&version)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if d.postgres {
|
||||
if _, e := tx.ExecContext(ctx, `CREATE OR REPLACE FUNCTION aeternalis_current_life() RETURNS trigger AS $$ BEGIN
|
||||
INSERT INTO account_lives(account_id,character_id) VALUES(NEW.account_id,NEW.character_id)
|
||||
ON CONFLICT(account_id) DO UPDATE SET character_id=EXCLUDED.character_id;
|
||||
RETURN NEW;
|
||||
END; $$ LANGUAGE plpgsql`); e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e := tx.ExecContext(ctx, `DROP TRIGGER IF EXISTS aeternalis_new_life ON character_records`); e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e := tx.ExecContext(ctx, `CREATE TRIGGER aeternalis_new_life AFTER INSERT ON character_records FOR EACH ROW WHEN (NEW.state IN ('alive','eligible','transit')) EXECUTE FUNCTION aeternalis_current_life()`); e != nil {
|
||||
return e
|
||||
}
|
||||
} else {
|
||||
_, e := tx.ExecContext(ctx, `CREATE TRIGGER IF NOT EXISTS aeternalis_new_life AFTER INSERT ON character_records WHEN NEW.state IN ('alive','eligible','transit') BEGIN
|
||||
INSERT INTO account_lives(account_id,character_id) VALUES(NEW.account_id,NEW.character_id)
|
||||
ON CONFLICT(account_id) DO UPDATE SET character_id=excluded.character_id;
|
||||
END`)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES(7)`)
|
||||
return err
|
||||
}
|
||||
@@ -65,6 +65,8 @@ func (d *DB) migrate(ctx context.Context) error {
|
||||
}
|
||||
}
|
||||
for _, stmt := range []string{
|
||||
`CREATE TABLE IF NOT EXISTS account_lives(account_id TEXT PRIMARY KEY,character_id TEXT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS character_deaths(corpse_id TEXT PRIMARY KEY,character_id TEXT NOT NULL,world_id TEXT NOT NULL,character TEXT NOT NULL,revived INTEGER NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS craft_receipts(id TEXT NOT NULL,account_id TEXT NOT NULL,character_id TEXT NOT NULL,request_json TEXT NOT NULL,result_json TEXT NOT NULL,PRIMARY KEY(account_id,id))`,
|
||||
`CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)`,
|
||||
`CREATE TABLE IF NOT EXISTS title_awards(account_id TEXT NOT NULL, title_id TEXT NOT NULL, scope TEXT NOT NULL, scope_key TEXT NOT NULL, character_id TEXT NOT NULL, award TEXT NOT NULL, PRIMARY KEY(account_id,title_id), UNIQUE(scope,scope_key,title_id))`,
|
||||
@@ -83,7 +85,13 @@ func (d *DB) migrate(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `INSERT INTO account_lives(account_id,character_id) SELECT account_id,character_id FROM character_records WHERE state IN ('alive','eligible','transit') ON CONFLICT(account_id) DO NOTHING`); err != nil {
|
||||
return err
|
||||
}
|
||||
var version int
|
||||
if err = d.migrateLifeTrigger(ctx, tx); err != nil {
|
||||
return err
|
||||
}
|
||||
err = tx.QueryRowContext(ctx, `SELECT version FROM schema_migrations WHERE version=1`).Scan(&version)
|
||||
if err == nil {
|
||||
return tx.Commit()
|
||||
@@ -136,6 +144,9 @@ func (d *DB) migrate(ctx context.Context) error {
|
||||
return tx.Commit()
|
||||
}
|
||||
func (d *DB) writeCharacter(ctx context.Context, tx *sql.Tx, world string, c *game.Character, claim bool) error {
|
||||
if err := d.reserveCharacterLife(ctx, tx, world, c); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
)
|
||||
|
||||
var ErrRevival = errors.New("revival rejected")
|
||||
|
||||
type reviveClaim struct{ Account, Character, Corpse, World string }
|
||||
|
||||
// A permanent account pointer records the most recently created life, including
|
||||
// after its death. Repeated deaths never make an older life current again.
|
||||
func (d *DB) reserveCharacterLife(ctx context.Context, tx *sql.Tx, world string, c *game.Character) error {
|
||||
if _, e := tx.ExecContext(ctx, d.q(`INSERT INTO account_lives(account_id,character_id) VALUES(?,?) ON CONFLICT(account_id) DO NOTHING`), c.Account, c.View.Entity.ID); e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e := tx.ExecContext(ctx, d.q(`UPDATE account_lives SET character_id=character_id WHERE account_id=?`), c.Account); e != nil {
|
||||
return e
|
||||
}
|
||||
var current string
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT character_id FROM account_lives WHERE account_id=?`), c.Account).Scan(¤t); e != nil {
|
||||
return e
|
||||
}
|
||||
var state, oldWorld string
|
||||
e := tx.QueryRowContext(ctx, d.q(`SELECT state,world_id FROM character_records WHERE character_id=?`), c.View.Entity.ID).Scan(&state, &oldWorld)
|
||||
if e != nil && !errors.Is(e, sql.ErrNoRows) {
|
||||
return e
|
||||
}
|
||||
if errors.Is(e, sql.ErrNoRows) && c.View.Entity.State != "dead" {
|
||||
if _, e = tx.ExecContext(ctx, d.q(`UPDATE account_lives SET character_id=? WHERE account_id=?`), c.View.Entity.ID, c.Account); e != nil {
|
||||
return e
|
||||
}
|
||||
} else if e == nil && oldWorld == world && c.View.Entity.State != "dead" {
|
||||
if current != c.View.Entity.ID {
|
||||
return ErrLivingCharacter
|
||||
}
|
||||
if state == "dead" {
|
||||
var revived int
|
||||
if e = tx.QueryRowContext(ctx, d.q(`SELECT revived FROM character_deaths WHERE corpse_id=? AND character_id=?`), c.RevivalCorpse, c.View.Entity.ID).Scan(&revived); e != nil || revived != 1 {
|
||||
return ErrRevival
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.View.Entity.State == "dead" && c.RevivalCorpse != "" {
|
||||
raw, e := json.Marshal(c)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
_, e = tx.ExecContext(ctx, d.q(`INSERT INTO character_deaths(corpse_id,character_id,world_id,character,revived) VALUES(?,?,?,?,0) ON CONFLICT(corpse_id) DO NOTHING`), c.RevivalCorpse, c.View.Entity.ID, world, string(raw))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (d *DB) checkRevival(ctx context.Context, tx *sql.Tx, r *reviveClaim) error {
|
||||
if _, e := tx.ExecContext(ctx, d.q(`UPDATE account_lives SET character_id=character_id WHERE account_id=?`), r.Account); e != nil {
|
||||
return e
|
||||
}
|
||||
var current string
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT character_id FROM account_lives WHERE account_id=?`), r.Account).Scan(¤t); e != nil {
|
||||
return e
|
||||
}
|
||||
if current != r.Character {
|
||||
return fmt.Errorf("%w: a replacement character was created", ErrRevival)
|
||||
}
|
||||
var state, world, raw string
|
||||
if e := tx.QueryRowContext(ctx, d.q(`SELECT state,world_id,character FROM character_records WHERE character_id=? AND account_id=?`), r.Character, r.Account).Scan(&state, &world, &raw); e != nil {
|
||||
return e
|
||||
}
|
||||
var dead game.Character
|
||||
if e := json.Unmarshal([]byte(raw), &dead); e != nil {
|
||||
return e
|
||||
}
|
||||
if state != "dead" || world != r.World || dead.RevivalCorpse != r.Corpse || !dead.RevivalAllowed {
|
||||
return ErrRevival
|
||||
}
|
||||
result, e := tx.ExecContext(ctx, d.q(`UPDATE character_deaths SET revived=1 WHERE corpse_id=? AND character_id=? AND revived=0`), r.Corpse, r.Character)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
n, _ := result.RowsAffected()
|
||||
if n != 1 {
|
||||
return ErrRevival
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (d *DB) RevivalCurrent(ctx context.Context, account, id string) (bool, error) {
|
||||
var current string
|
||||
e := d.sql.QueryRowContext(ctx, d.q(`SELECT character_id FROM account_lives WHERE account_id=?`), account).Scan(¤t)
|
||||
if errors.Is(e, sql.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
return current == id, e
|
||||
}
|
||||
func (l *Lease) RevivalConsent(ctx context.Context, w *game.World, account, id string, allowed bool) error {
|
||||
c := w.Characters[id]
|
||||
if c == nil || c.Account != account || c.View.Entity.State != "dead" || c.RevivalCorpse == "" || w.Corpses[c.RevivalCorpse] == nil || w.Phase == "lost" {
|
||||
return ErrRevival
|
||||
}
|
||||
current, e := l.DB.RevivalCurrent(ctx, account, id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if !current {
|
||||
return ErrRevival
|
||||
}
|
||||
staged := stageTitleWorld(w)
|
||||
staged.Characters[id].RevivalAllowed = allowed
|
||||
if e = l.Save(ctx, staged, ""); e != nil {
|
||||
return e
|
||||
}
|
||||
for id, c := range staged.Characters {
|
||||
*w.Characters[id] = *c
|
||||
}
|
||||
w.Saved()
|
||||
return nil
|
||||
}
|
||||
func (l *Lease) Revive(ctx context.Context, w *game.World, account, corpse, power string) error {
|
||||
caster := w.ForAccount(account)
|
||||
if caster == nil {
|
||||
return ErrRevival
|
||||
}
|
||||
active, e := l.DB.ActiveCharacter(ctx, account)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if active == nil || active.ID != caster.View.Entity.ID || active.WorldID != w.ID {
|
||||
return ErrRevival
|
||||
}
|
||||
staged := stageTitleWorld(w)
|
||||
staged.Corpses = maps.Clone(w.Corpses)
|
||||
target, e := staged.Revive(staged.Characters[caster.View.Entity.ID], corpse, power)
|
||||
if e != nil {
|
||||
return fmt.Errorf("%w: %v", ErrRevival, e)
|
||||
}
|
||||
claim := &reviveClaim{target.Account, target.View.Entity.ID, corpse, w.ID}
|
||||
if e = l.save(ctx, staged, "", nil, "", nil, claim); e != nil {
|
||||
return e
|
||||
}
|
||||
for id, c := range staged.Characters {
|
||||
*w.Characters[id] = *c
|
||||
}
|
||||
w.Corpses = staged.Corpses
|
||||
w.PendingTitles = nil
|
||||
w.Saved()
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRevivalDurability(t *testing.T) {
|
||||
testRevivalDurability(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "revive.db")))
|
||||
}
|
||||
func TestPostgresRevivalDurability(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
testRevivalDurability(t, dsn)
|
||||
}
|
||||
func testRevivalDurability(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, e := Open(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
now := time.Now().UTC()
|
||||
w := game.New("revive-"+game.ID(), 1, now, b)
|
||||
l, _, e := db.Acquire(ctx, w)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c, _ := w.Join("victim-"+game.ID(), "Victim")
|
||||
rescuer, _ := w.Join("rescuer-"+game.ID(), "Rescuer")
|
||||
_ = w.Connect(rescuer.View.Entity.ID)
|
||||
rescuer.View.Entity.Position = c.View.Entity.Position
|
||||
rescuer.View.Inventory["revival_stone"] = 3
|
||||
if e = l.Save(ctx, w, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Create an actual new-system death without ending the world.
|
||||
c.View.Entity.HP = 0
|
||||
w.Advance(now.Add(time.Second), 1)
|
||||
corpse := c.RevivalCorpse
|
||||
if corpse == "" {
|
||||
t.Fatal("death missing corpse identity")
|
||||
}
|
||||
if e = l.Save(ctx, w, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = l.RevivalConsent(ctx, w, c.Account, c.View.Entity.ID, true); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = l.RevivalConsent(ctx, w, rescuer.Account, c.View.Entity.ID, true); !errors.Is(e, ErrRevival) {
|
||||
t.Fatal("rescuer set another account's consent", e)
|
||||
}
|
||||
before, _ := json.Marshal(w)
|
||||
stale := *l
|
||||
stale.Revision--
|
||||
if e = stale.Revive(ctx, w, rescuer.Account, corpse, "item"); !errors.Is(e, ErrOwnership) {
|
||||
t.Fatal("stale revival not fenced", e)
|
||||
}
|
||||
after, _ := json.Marshal(w)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("failed revival mutated live world")
|
||||
}
|
||||
if e = l.Revive(ctx, w, rescuer.Account, corpse, "item"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if c.View.Entity.State != "alive" || rescuer.View.Inventory["revival_stone"] != 2 {
|
||||
t.Fatal("revival not applied")
|
||||
}
|
||||
if e = l.Revive(ctx, w, rescuer.Account, corpse, "item"); !errors.Is(e, ErrRevival) {
|
||||
t.Fatal("duplicate revival accepted", e)
|
||||
}
|
||||
// Death events survive revival and restart; repeats create distinct corpses.
|
||||
var count int
|
||||
if e = db.sql.QueryRowContext(ctx, db.q(`SELECT COUNT(*) FROM character_deaths WHERE character_id=? AND revived=1`), c.View.Entity.ID).Scan(&count); e != nil || count != 1 {
|
||||
t.Fatal("death history missing", e)
|
||||
}
|
||||
c.View.Entity.HP = 0
|
||||
w.Advance(now.Add(2*time.Second), 1)
|
||||
if e = l.Save(ctx, w, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = l.RevivalConsent(ctx, w, c.Account, c.View.Entity.ID, true); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
corpse = c.RevivalCorpse
|
||||
other := game.New("replacement-"+game.ID(), 2, now, b)
|
||||
ol, _, e := db.Acquire(ctx, other)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
replacement, e := other.Join(c.Account, "Replacement")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Simulate an old world binary inserting a replacement during rolling upgrade.
|
||||
replacementJSON, _ := json.Marshal(replacement)
|
||||
if _, e = db.sql.ExecContext(ctx, db.q(`INSERT INTO character_records(character_id,account_id,world_id,name,state,character) VALUES(?,?,?,?,?,?)`), replacement.View.Entity.ID, replacement.Account, other.ID, "Replacement", "alive", string(replacementJSON)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Even killing the replacement cannot restore eligibility for the old life.
|
||||
replacement.View.Entity.HP = 0
|
||||
other.Advance(now.Add(time.Second), 1)
|
||||
if e = ol.Save(ctx, other, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = l.Revive(ctx, w, rescuer.Account, corpse, "item"); !errors.Is(e, ErrRevival) {
|
||||
t.Fatal("replacement death re-enabled old revival", e)
|
||||
}
|
||||
if c.View.Entity.State != "dead" || rescuer.View.Inventory["revival_stone"] != 2 || w.Corpses[corpse] == nil {
|
||||
t.Fatal("rejected old revival spent or moved items")
|
||||
}
|
||||
if e = l.Release(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
restored := game.New(w.ID, 1, now, b)
|
||||
var raw []byte
|
||||
l, raw, e = db.Acquire(ctx, restored)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = json.Unmarshal(raw, restored); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = restored.Restore(now.Add(3 * time.Second)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_ = restored.Connect(rescuer.View.Entity.ID)
|
||||
if e = l.Revive(ctx, restored, rescuer.Account, corpse, "item"); !errors.Is(e, ErrRevival) {
|
||||
t.Fatal("restart lost finality", e)
|
||||
}
|
||||
testRevivalRace(t, db)
|
||||
}
|
||||
|
||||
func testRevivalRace(t *testing.T, db *DB) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
b, _ := content.Load()
|
||||
now := time.Now().UTC()
|
||||
w := game.New("race-source-"+game.ID(), 1, now, b)
|
||||
l, _, e := db.Acquire(ctx, w)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
victim, _ := w.Join("race-victim-"+game.ID(), "Victim")
|
||||
rescuer, _ := w.Join("race-rescuer-"+game.ID(), "Rescuer")
|
||||
_ = w.Connect(rescuer.View.Entity.ID)
|
||||
rescuer.View.Entity.Position = victim.View.Entity.Position
|
||||
rescuer.View.Inventory["revival_stone"] = 1
|
||||
if e = l.Save(ctx, w, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
victim.View.Entity.HP = 0
|
||||
w.Advance(now.Add(time.Second), 1)
|
||||
if e = l.Save(ctx, w, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = l.RevivalConsent(ctx, w, victim.Account, victim.View.Entity.ID, true); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
next := game.New("race-next-"+game.ID(), 2, now, b)
|
||||
nl, _, e := db.Acquire(ctx, next)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
replacement, e := next.Join(victim.Account, "Replacement")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
type outcome struct {
|
||||
revive bool
|
||||
err error
|
||||
}
|
||||
done := make(chan outcome, 2)
|
||||
start := make(chan struct{})
|
||||
go func() {
|
||||
<-start
|
||||
done <- outcome{true, l.Revive(ctx, w, rescuer.Account, victim.RevivalCorpse, "item")}
|
||||
}()
|
||||
go func() { <-start; done <- outcome{false, nl.Save(ctx, next, "")} }()
|
||||
close(start)
|
||||
wins := 0
|
||||
revived := false
|
||||
for i := 0; i < 2; i++ {
|
||||
r := <-done
|
||||
if r.err == nil {
|
||||
wins++
|
||||
revived = r.revive
|
||||
} else if !errors.Is(r.err, ErrRevival) && !errors.Is(r.err, ErrLivingCharacter) {
|
||||
t.Fatal("unexpected race failure", r.err)
|
||||
}
|
||||
}
|
||||
if wins != 1 {
|
||||
t.Fatal("replacement and revival did not produce exactly one winner")
|
||||
}
|
||||
active, e := db.ActiveCharacter(ctx, victim.Account)
|
||||
if e != nil || active == nil {
|
||||
t.Fatal("race lost active life", e)
|
||||
}
|
||||
if revived {
|
||||
if active.ID != victim.View.Entity.ID || rescuer.View.Inventory["revival_stone"] != 0 {
|
||||
t.Fatal("revival winner lost identity or cost")
|
||||
}
|
||||
} else if active.ID != replacement.View.Entity.ID || rescuer.View.Inventory["revival_stone"] != 1 {
|
||||
t.Fatal("replacement winner spent revival cost")
|
||||
}
|
||||
}
|
||||
@@ -139,9 +139,9 @@ 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)
|
||||
return l.save(ctx, w, claimID, command, outcome, nil, nil)
|
||||
}
|
||||
func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt) error {
|
||||
func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt, revival *reviveClaim) error {
|
||||
live := w
|
||||
w = stageTitleWorld(w)
|
||||
data, err := json.Marshal(w)
|
||||
@@ -162,6 +162,11 @@ func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command
|
||||
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
|
||||
|
||||
@@ -23,6 +23,8 @@ func stageTitleWorld(w *game.World) *game.World {
|
||||
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.Equipment = maps.Clone(c.View.Equipment)
|
||||
copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats)
|
||||
|
||||
@@ -106,6 +106,8 @@ func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, re
|
||||
if err = json.Unmarshal(raw, &departing); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
departing.PendingCast = nil
|
||||
departing.View.Casting = nil
|
||||
if route == "escape" {
|
||||
game.TakeStack(&departing, "escape_stone", 1)
|
||||
}
|
||||
|
||||
@@ -71,6 +71,18 @@ func runTravelTests(t *testing.T, dsn string) {
|
||||
if e = source.Connect(id); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c.View.Inventory["book_mend"] = 1
|
||||
if e = source.LearnPower(c, "book_mend"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
spell := c.View.Powers["mend"]
|
||||
spell.XP = 25
|
||||
spell.ReadyAt = float64(now.Unix() + 30)
|
||||
c.View.Powers["mend"] = spell
|
||||
weapon := c.View.Weapons["blades"]
|
||||
weapon.XP = 29
|
||||
c.View.Weapons["blades"] = weapon
|
||||
source.RefreshStats(c)
|
||||
if e = sl.Save(ctx, source, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
@@ -171,7 +183,7 @@ func runTravelTests(t *testing.T, dsn string) {
|
||||
if copies != 1 {
|
||||
t.Fatalf("arrival copies: %d", copies)
|
||||
}
|
||||
if !reflect.DeepEqual(arrived.View.Items, c.View.Items) || !reflect.DeepEqual(arrived.View.Gathering, c.View.Gathering) || !reflect.DeepEqual(arrived.View.AllocatedStats, c.View.AllocatedStats) {
|
||||
if !reflect.DeepEqual(arrived.View.Powers, c.View.Powers) || !reflect.DeepEqual(arrived.View.Weapons, c.View.Weapons) || !reflect.DeepEqual(arrived.View.Items, c.View.Items) || !reflect.DeepEqual(arrived.View.Gathering, c.View.Gathering) || !reflect.DeepEqual(arrived.View.AllocatedStats, c.View.AllocatedStats) {
|
||||
t.Fatal("item identities or character progression changed during travel")
|
||||
}
|
||||
if arrived.View.Inventory["escape_stone"] != 1 || arrived.View.Inventory["wood"] != 31 || arrived.View.Level != 3 || arrived.View.Experience != 7 || arrived.View.StatPoints != 20 || arrived.View.Skills["combat"] != 29 || arrived.DailySeconds != 123 || arrived.WorldsSurvived != 2 || arrived.View.Entity.ID != id || !reflect.DeepEqual(arrived.View.Titles, c.View.Titles) {
|
||||
|
||||
Reference in New Issue
Block a user