Complete player stats inventory and Control content editors

This commit is contained in:
dingo
2026-09-08 06:02:13 -04:00
parent 2df1f6ab38
commit b6ce3bc292
27 changed files with 960 additions and 267 deletions
+3 -1
View File
@@ -107,7 +107,9 @@ func (b Balance) Validate() error {
if b.TickHz > 60 || b.SnapshotHz > b.TickHz || b.TickHz%b.SnapshotHz != 0 || b.TerrainResolution > 64 || b.ResourcesPerChunk > 128 || b.MaxPlayers > 2000 || b.WorldRadius < b.ChunkSize*2 {
return fmt.Errorf("invalid capacity, terrain, or tick configuration")
}
if b.MaxYieldPerAction > 1000 || b.CriticalMultiplier > 100 { return fmt.Errorf("invalid yield or critical damage tuning") }
if b.MaxYieldPerAction > 1000 || b.CriticalMultiplier > 100 {
return fmt.Errorf("invalid yield or critical damage tuning")
}
known := map[string]bool{"knife": true, "axe": true, "flint_and_steel": true, "fishing_pole": true, "wood": true, "ore": true, "herb": true, "spear": true, "bandage": true}
check := func(items map[string]int64) error {
if len(items) == 0 {
+185 -68
View File
@@ -1,76 +1,193 @@
package game
import (
"encoding/json"
"math"
"testing"
"time"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
"encoding/json"
"math"
"testing"
"time"
)
func gearCount(items []p.ItemInstance,definition string)int{n:=0;for _,item:=range items{if item.DefinitionID==definition{n++}};return n}
func testGear(id,slot string,modifiers ...p.StatModifier)p.ItemInstance{return p.ItemInstance{ID:id,DefinitionID:"test_"+id,Name:"Test "+id,Slot:slot,Weight:2,Requirements:p.ItemRequirements{Level:1,Stats:map[string]float64{},Titles:[]string{}},Modifiers:append([]p.StatModifier{},modifiers...)}}
func TestEquipmentSlotsAndRequirements(t *testing.T){
w,c:=fixture(t);w.grantXP(c,100)
for n:=0;n<5;n++{if err:=w.allocateStat(c,"strength");err!=nil{t.Fatal(err)}}
for _,slot:=range equipmentSlots{
category:=slot;if len(slot)==5&&slot[:4]=="ring"{category="ring"}
item:=testGear("slot_"+slot,category,p.StatModifier{Stat:"strength",Flat:1,Percent:10});c.View.Items=append(c.View.Items,item)
if err:=w.equip(c,item.ID,slot);err!=nil{t.Fatal(slot,err)}
}
if len(c.View.Equipment)!=21{t.Fatal("missing equipment slots")}
if w.equip(c,"missing","weapon")==nil||w.equip(c,"slot_ring1","ring9")==nil{t.Fatal("invalid ownership/slot accepted")}
if w.equip(c,"slot_ring1","ring2")==nil{t.Fatal("same instance equipped twice")}
if err:=w.unequip(c,"helmet");err!=nil{t.Fatal(err)}
gated:=testGear("gated","helmet",p.StatModifier{Stat:"strength",Flat:100});gated.Requirements.Stats["strength"]=6;c.View.Items=append(c.View.Items,gated)
if w.equip(c,gated.ID,"helmet")==nil{t.Fatal("equipment satisfied its own prerequisite")}
item:=ownedItem(c,gated.ID);item.Requirements.Stats["strength"]=5;item.Requirements.Level=3;item.Requirements.Titles=[]string{"trial"}
if w.equip(c,item.ID,"helmet")==nil{t.Fatal("missing level accepted")};item.Requirements.Level=2
if w.equip(c,item.ID,"helmet")==nil{t.Fatal("missing title accepted")}
c.View.Titles=append(c.View.Titles,p.TitleAward{ID:"trial"})
if err:=w.equip(c,item.ID,"helmet");err!=nil{t.Fatal(err)}
c.View.Titles=append(c.View.Titles,p.TitleAward{ID:"curse",Effects:p.TitleEffects{Modifiers:[]p.StatModifier{{Stat:"strength",Flat:-1}}}});w.RefreshStats(c)
if c.View.Equipment["helmet"]!=""||ownedItem(c,gated.ID)==nil{t.Fatal("invalidated gear stayed active or was lost")}
func gearCount(items []p.ItemInstance, definition string) int {
n := 0
for _, item := range items {
if item.DefinitionID == definition {
n++
}
}
return n
}
func TestEquipmentDeathDropLootAndRestart(t *testing.T){
w,c:=fixture(t);ring:=testGear("unique_ring","ring",p.StatModifier{Stat:"luck",Flat:2});c.View.Items=append(c.View.Items,ring)
if err:=w.equip(c,ring.ID,"ring8");err!=nil{t.Fatal(err)}
if err:=w.dropItem(c,ring.ID);err!=nil{t.Fatal(err)}
if ownedItem(c,ring.ID)!=nil||c.View.Equipment["ring8"]!=""{t.Fatal("drop retained ownership")}
var pile string;for id:=range w.Corpses{pile=id}
if err:=w.lootCorpse(c,pile);err!=nil{t.Fatal(err)};if w.lootCorpse(c,pile)==nil{t.Fatal("looted twice")}
if err:=w.equip(c,ring.ID,"ring8");err!=nil{t.Fatal(err)}
c.DailySeconds=123;raw,_:=json.Marshal(w);var restored World
if err:=json.Unmarshal(raw,&restored);err!=nil{t.Fatal(err)};if err:=restored.Restore(w.now);err!=nil{t.Fatal(err)}
survivor:=restored.Characters[c.View.Entity.ID];survivor.View.Entity.State="eligible"
next:=New("gear-next",345,w.now,w.Balance);if err:=next.Import(survivor);err!=nil{t.Fatal(err)}
if survivor.DailySeconds!=123||survivor.View.Equipment["ring8"]!=ring.ID||ownedItem(survivor,ring.ID)==nil{t.Fatal("passage changed item or daily usage")}
count:=len(survivor.View.Items);next.kill(survivor,"test death")
corpse:=next.Corpses["corpse:"+survivor.View.Entity.ID]
if len(corpse.Items)!=count||len(survivor.View.Items)!=0||len(survivor.View.Equipment)!=0{t.Fatal("death duplicated/lost items")}
replacement,err:=next.Join(c.Account,"Replacement");if err!=nil{t.Fatal(err)};replacement.View.Entity.Position=corpse.Entity.Position
if err=next.lootCorpse(replacement,corpse.Entity.ID);err!=nil{t.Fatal(err)}
if ownedItem(replacement,ring.ID)==nil||next.Connect(survivor.View.Entity.ID)==nil{t.Fatal("loot changed identity or resurrected life")}
func testGear(id, slot string, modifiers ...p.StatModifier) p.ItemInstance {
return p.ItemInstance{ID: id, DefinitionID: "test_" + id, Name: "Test " + id, Slot: slot, Weight: 2, Requirements: p.ItemRequirements{Level: 1, Stats: map[string]float64{}, Titles: []string{}}, Modifiers: append([]p.StatModifier{}, modifiers...)}
}
func TestLegacyEquipmentMigrationAndAtomicFailures(t *testing.T){
w,c:=fixture(t);original:=len(c.View.Items);c.View.Inventory["spear"]=2
w.Corpses["legacy"]=&Corpse{Entity:p.Entity{ID:"legacy",Position:c.View.Entity.Position},Inventory:map[string]int64{"spear":1,"ore":3}}
for n:=0;n<2;n++{if err:=w.Restore(w.now);err!=nil{t.Fatal(err)};if len(c.View.Items)!=original+2||len(w.Corpses["legacy"].Items)!=1||c.View.Inventory["spear"]!=0{t.Fatal("migration duplicated/lost gear")}}
corpse:=w.Corpses["legacy"];corpse.Items=append(corpse.Items,c.View.Items[0]);before:=c.View.Inventory["ore"]
if w.lootCorpse(c,"legacy")==nil||c.View.Inventory["ore"]!=before||w.Corpses["legacy"]==nil{t.Fatal("failed loot changed inventory")}
if w.Restore(w.now)==nil{t.Fatal("duplicate ID restored")}
delete(w.Corpses,"legacy")
c.View.Inventory["wood"]=3;c.View.Inventory["ore"]=2
w.Balance.Recipes["spear"]=content.Recipe{Inputs:map[string]int64{"wood":3,"ore":2},Outputs:map[string]int64{"spear":100001}}
if w.craft(c,"spear")==nil||c.View.Inventory["wood"]!=3||c.View.Inventory["ore"]!=2{t.Fatal("failed craft consumed materials")}
c.View.Inventory["wood"]=math.MaxInt64
w.Corpses["overflow"]=&Corpse{Entity:p.Entity{ID:"overflow",Position:c.View.Entity.Position},Inventory:map[string]int64{"wood":1}}
if w.lootCorpse(c,"overflow")==nil||c.View.Inventory["wood"]!=math.MaxInt64{t.Fatal("overflow loot changed inventory")}
func TestEquipmentSlotsAndRequirements(t *testing.T) {
w, c := fixture(t)
w.grantXP(c, 100)
for n := 0; n < 5; n++ {
if err := w.allocateStat(c, "strength"); err != nil {
t.Fatal(err)
}
}
for _, slot := range equipmentSlots {
category := slot
if len(slot) == 5 && slot[:4] == "ring" {
category = "ring"
}
item := testGear("slot_"+slot, category, p.StatModifier{Stat: "strength", Flat: 1, Percent: 10})
c.View.Items = append(c.View.Items, item)
if err := w.equip(c, item.ID, slot); err != nil {
t.Fatal(slot, err)
}
}
if len(c.View.Equipment) != 21 {
t.Fatal("missing equipment slots")
}
if w.equip(c, "missing", "weapon") == nil || w.equip(c, "slot_ring1", "ring9") == nil {
t.Fatal("invalid ownership/slot accepted")
}
if w.equip(c, "slot_ring1", "ring2") == nil {
t.Fatal("same instance equipped twice")
}
if err := w.unequip(c, "helmet"); err != nil {
t.Fatal(err)
}
gated := testGear("gated", "helmet", p.StatModifier{Stat: "strength", Flat: 100})
gated.Requirements.Stats["strength"] = 6
c.View.Items = append(c.View.Items, gated)
if w.equip(c, gated.ID, "helmet") == nil {
t.Fatal("equipment satisfied its own prerequisite")
}
item := ownedItem(c, gated.ID)
item.Requirements.Stats["strength"] = 5
item.Requirements.Level = 3
item.Requirements.Titles = []string{"trial"}
if w.equip(c, item.ID, "helmet") == nil {
t.Fatal("missing level accepted")
}
item.Requirements.Level = 2
if w.equip(c, item.ID, "helmet") == nil {
t.Fatal("missing title accepted")
}
c.View.Titles = append(c.View.Titles, p.TitleAward{ID: "trial"})
if err := w.equip(c, item.ID, "helmet"); err != nil {
t.Fatal(err)
}
c.View.Titles = append(c.View.Titles, p.TitleAward{ID: "curse", Effects: p.TitleEffects{Modifiers: []p.StatModifier{{Stat: "strength", Flat: -1}}}})
w.RefreshStats(c)
if c.View.Equipment["helmet"] != "" || ownedItem(c, gated.ID) == nil {
t.Fatal("invalidated gear stayed active or was lost")
}
}
func TestCatalogEquipmentCanDropFromSentinels(t *testing.T){
w,c:=fixture(t);w.Balance.Items=append(w.Balance.Items,content.ItemDefinition{ID:"drop_ring",Name:"Dropped Ring",Slot:"ring",Weight:1,DropChance:100,Requirements:content.ItemRequirements{Level:1}})
w.now=w.now.Add(time.Second);w.Mobs["test"]=&Mob{Entity:p.Entity{ID:"test",HP:1,Position:c.View.Entity.Position}}
if err:=w.attack(c,"test");err!=nil{t.Fatal(err)}
if gearCount(c.View.Items,"drop_ring")!=1{t.Fatal("authored gear never dropped")}
if w.attack(c,"test")==nil||gearCount(c.View.Items,"drop_ring")!=1{t.Fatal("repeated kill duplicated gear")}
func TestEquipmentDeathDropLootAndRestart(t *testing.T) {
w, c := fixture(t)
ring := testGear("unique_ring", "ring", p.StatModifier{Stat: "luck", Flat: 2})
c.View.Items = append(c.View.Items, ring)
if err := w.equip(c, ring.ID, "ring8"); err != nil {
t.Fatal(err)
}
if err := w.dropItem(c, ring.ID); err != nil {
t.Fatal(err)
}
if ownedItem(c, ring.ID) != nil || c.View.Equipment["ring8"] != "" {
t.Fatal("drop retained ownership")
}
var pile string
for id := range w.Corpses {
pile = id
}
if err := w.lootCorpse(c, pile); err != nil {
t.Fatal(err)
}
if w.lootCorpse(c, pile) == nil {
t.Fatal("looted twice")
}
if err := w.equip(c, ring.ID, "ring8"); err != nil {
t.Fatal(err)
}
c.DailySeconds = 123
raw, _ := json.Marshal(w)
var restored World
if err := json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
if err := restored.Restore(w.now); err != nil {
t.Fatal(err)
}
survivor := restored.Characters[c.View.Entity.ID]
survivor.View.Entity.State = "eligible"
next := New("gear-next", 345, w.now, w.Balance)
if err := next.Import(survivor); err != nil {
t.Fatal(err)
}
if survivor.DailySeconds != 123 || survivor.View.Equipment["ring8"] != ring.ID || ownedItem(survivor, ring.ID) == nil {
t.Fatal("passage changed item or daily usage")
}
count := len(survivor.View.Items)
next.kill(survivor, "test death")
corpse := next.Corpses["corpse:"+survivor.View.Entity.ID]
if len(corpse.Items) != count || len(survivor.View.Items) != 0 || len(survivor.View.Equipment) != 0 {
t.Fatal("death duplicated/lost items")
}
replacement, err := next.Join(c.Account, "Replacement")
if err != nil {
t.Fatal(err)
}
replacement.View.Entity.Position = corpse.Entity.Position
if err = next.lootCorpse(replacement, corpse.Entity.ID); err != nil {
t.Fatal(err)
}
if ownedItem(replacement, ring.ID) == nil || next.Connect(survivor.View.Entity.ID) == nil {
t.Fatal("loot changed identity or resurrected life")
}
}
func TestLegacyEquipmentMigrationAndAtomicFailures(t *testing.T) {
w, c := fixture(t)
original := len(c.View.Items)
c.View.Inventory["spear"] = 2
w.Corpses["legacy"] = &Corpse{Entity: p.Entity{ID: "legacy", Position: c.View.Entity.Position}, Inventory: map[string]int64{"spear": 1, "ore": 3}}
for n := 0; n < 2; n++ {
if err := w.Restore(w.now); err != nil {
t.Fatal(err)
}
if len(c.View.Items) != original+2 || len(w.Corpses["legacy"].Items) != 1 || c.View.Inventory["spear"] != 0 {
t.Fatal("migration duplicated/lost gear")
}
}
corpse := w.Corpses["legacy"]
corpse.Items = append(corpse.Items, c.View.Items[0])
before := c.View.Inventory["ore"]
if w.lootCorpse(c, "legacy") == nil || c.View.Inventory["ore"] != before || w.Corpses["legacy"] == nil {
t.Fatal("failed loot changed inventory")
}
if w.Restore(w.now) == nil {
t.Fatal("duplicate ID restored")
}
delete(w.Corpses, "legacy")
c.View.Inventory["wood"] = 3
c.View.Inventory["ore"] = 2
w.Balance.Recipes["spear"] = content.Recipe{Inputs: map[string]int64{"wood": 3, "ore": 2}, Outputs: map[string]int64{"spear": 100001}}
if w.craft(c, "spear") == nil || c.View.Inventory["wood"] != 3 || c.View.Inventory["ore"] != 2 {
t.Fatal("failed craft consumed materials")
}
c.View.Inventory["wood"] = math.MaxInt64
w.Corpses["overflow"] = &Corpse{Entity: p.Entity{ID: "overflow", Position: c.View.Entity.Position}, Inventory: map[string]int64{"wood": 1}}
if w.lootCorpse(c, "overflow") == nil || c.View.Inventory["wood"] != math.MaxInt64 {
t.Fatal("overflow loot changed inventory")
}
}
func TestCatalogEquipmentCanDropFromSentinels(t *testing.T) {
w, c := fixture(t)
w.Balance.Items = append(w.Balance.Items, content.ItemDefinition{ID: "drop_ring", Name: "Dropped Ring", Slot: "ring", Weight: 1, DropChance: 100, Requirements: content.ItemRequirements{Level: 1}})
w.now = w.now.Add(time.Second)
w.Mobs["test"] = &Mob{Entity: p.Entity{ID: "test", HP: 1, Position: c.View.Entity.Position}}
if err := w.attack(c, "test"); err != nil {
t.Fatal(err)
}
if gearCount(c.View.Items, "drop_ring") != 1 {
t.Fatal("authored gear never dropped")
}
if w.attack(c, "test") == nil || gearCount(c.View.Items, "drop_ring") != 1 {
t.Fatal("repeated kill duplicated gear")
}
}
+11 -2
View File
@@ -31,7 +31,9 @@ func (w *World) orderedCharacters() []*Character {
}
func (w *World) restoreProgression(c *Character) error {
if c.StatsVersion < 0 || c.StatsVersion > 1 { return errors.New("unsupported character stats version") }
if c.StatsVersion < 0 || c.StatsVersion > 1 {
return errors.New("unsupported character stats version")
}
if c.View.Level == 0 {
c.View.Level = 1
}
@@ -45,7 +47,9 @@ func (w *World) restoreProgression(c *Character) error {
c.View.StatPoints += (c.View.Level - 1) * (w.Balance.Progression.StatPointsPerLevel - rules.StatPointsPerLevel)
}
// Preserve any older, more generous grant curve rather than deleting points.
if rules.StatPointsPerLevel < w.Balance.Progression.StatPointsPerLevel { rules.StatPointsPerLevel = w.Balance.Progression.StatPointsPerLevel }
if rules.StatPointsPerLevel < w.Balance.Progression.StatPointsPerLevel {
rules.StatPointsPerLevel = w.Balance.Progression.StatPointsPerLevel
}
rules.StaminaPerLevel = w.Balance.Progression.StaminaPerLevel
rules.VitalPointsPerChoice = w.Balance.Progression.VitalPointsPerChoice
c.Progression = &rules
@@ -69,6 +73,11 @@ func (w *World) restoreProgression(c *Character) error {
if c.View.Titles == nil {
c.View.Titles = []p.TitleAward{}
}
for i := range c.View.Titles {
if c.View.Titles[i].Effects.Modifiers == nil {
c.View.Titles[i].Effects.Modifiers = []p.StatModifier{}
}
}
return nil
}
+1 -1
View File
@@ -95,7 +95,7 @@ func TestOnlySuccessfulActionsGrantXP(t *testing.T) {
func TestProgressionSurvivesRestartDeathAndTransfer(t *testing.T) {
w, c := fixture(t)
w.grantXP(c, 275)
c.View.Titles = []p.TitleAward{{ID: "bound", Name: "Bound", Scope: "personal", Effects: p.TitleEffects{Damage: 2}}}
c.View.Titles = []p.TitleAward{{ID: "bound", Name: "Bound", Scope: "personal", Effects: p.TitleEffects{Damage: 2, Modifiers: []p.StatModifier{}}}}
c.DailySeconds = 123
c.WorldKills = 7
raw, err := json.Marshal(w)
+8 -2
View File
@@ -126,8 +126,12 @@ func (w *World) Restore(now time.Time) error {
w.dirty = true
}
if w.Balance.MaxYieldPerAction == 0 {
defaults, err := content.Load(); if err != nil { return err }
w.Balance.MaxYieldPerAction = defaults.MaxYieldPerAction; w.dirty = true
defaults, err := content.Load()
if err != nil {
return err
}
w.Balance.MaxYieldPerAction = defaults.MaxYieldPerAction
w.dirty = true
}
if err := w.Balance.Validate(); err != nil {
return err
@@ -441,6 +445,7 @@ func (w *World) gather(c *Character, target string) error {
w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds
w.dirty = true
c.Message = "Gathered " + item
w.RefreshStats(c)
w.grantXP(c, w.Balance.Progression.GatherXP)
w.evaluateTitles(c)
return nil
@@ -531,6 +536,7 @@ func (w *World) attack(c *Character, target string) error {
}
}
}
w.RefreshStats(c)
w.grantXP(c, w.Balance.Progression.MobKillXP)
}
}
+3 -3
View File
@@ -122,7 +122,7 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) {
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 5, Target: "spear"}); err != nil {
t.Fatal(err)
}
if gearCount(c.View.Items,"spear") != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 {
if gearCount(c.View.Items, "spear") != 1 || c.View.Inventory["wood"] != 0 || c.View.Inventory["ore"] != 0 {
t.Fatal("recipe not atomic")
}
w.kill(c, "test death")
@@ -143,7 +143,7 @@ func TestGatherCraftAndPermanentDeath(t *testing.T) {
if c.DiedAt == nil || c.DeathReason != "test death" {
t.Fatal("missing durable death record")
}
if len(c.View.Inventory) != 0 || gearCount(w.Corpses["corpse:"+id].Items,"spear") != 1 {
if len(c.View.Inventory) != 0 || gearCount(w.Corpses["corpse:"+id].Items, "spear") != 1 {
t.Fatal("corpse inventory")
}
raw, _ := json.Marshal(w)
@@ -283,7 +283,7 @@ func TestSpawnAndTransferPreserveBudget(t *testing.T) {
if err := next.Import(c); err != nil {
t.Fatal(err)
}
if c.DailySeconds != 123 || c.View.PlayedSeconds != 456 || c.View.Skills["combat"] != 9 || gearCount(c.View.Items,"spear") != 1 {
if c.DailySeconds != 123 || c.View.PlayedSeconds != 456 || c.View.Skills["combat"] != 9 || gearCount(c.View.Items, "spear") != 1 {
t.Fatal("transfer changed progress or budget")
}
if err := next.Import(c); err == nil {
+203 -92
View File
@@ -1,113 +1,224 @@
package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"aeternalis/server/content"
"aeternalis/server/content"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
)
var ErrCatalogConflict = errors.New("catalog changed; refresh before publishing")
var ErrCatalogRequest = errors.New("request ID already used for a different catalog change")
var ErrCatalogInvalid = errors.New("invalid catalog change")
var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
type CatalogChange struct {
ID string `json:"id"`
ExpectedVersion int64 `json:"expectedVersion"`
Op string `json:"op"`
Reason string `json:"reason"`
Title *content.Title `json:"title,omitempty"`
Item *content.ItemDefinition `json:"item,omitempty"`
Stats *content.StatsRules `json:"stats,omitempty"`
ID string `json:"id"`
ExpectedVersion int64 `json:"expectedVersion"`
Op string `json:"op"`
Reason string `json:"reason"`
Title *content.Title `json:"title,omitempty"`
Item *content.ItemDefinition `json:"item,omitempty"`
Stats *content.StatsRules `json:"stats,omitempty"`
}
type CatalogResult struct {
Version int64 `json:"version"`
}
type CatalogResult struct { Version int64 `json:"version"` }
type CatalogAudit struct {
ID string `json:"id"`
Actor string `json:"actor"`
Op string `json:"op"`
Target string `json:"target"`
Reason string `json:"reason"`
Version int64 `json:"version"`
CreatedAt int64 `json:"createdAt"`
ID string `json:"id"`
Actor string `json:"actor"`
Op string `json:"op"`
Target string `json:"target"`
Reason string `json:"reason"`
Version int64 `json:"version"`
CreatedAt int64 `json:"createdAt"`
}
func (d *DB) ensureCatalog(ctx context.Context) error {
defaults,err:=content.DefaultCatalog();if err!=nil{return err}
if err=defaults.Validate();err!=nil{return err}
raw,err:=json.Marshal(defaults);if err!=nil{return err}
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 control_catalog(id INTEGER PRIMARY KEY CHECK(id=1),version BIGINT NOT NULL,document TEXT NOT NULL)`,
`CREATE TABLE IF NOT EXISTS catalog_changes(id TEXT PRIMARY KEY,actor TEXT NOT NULL,op TEXT NOT NULL,target TEXT NOT NULL,reason TEXT NOT NULL,expected_version BIGINT NOT NULL,result_version BIGINT NOT NULL,request_json TEXT NOT NULL,created_at BIGINT NOT NULL)`,
`CREATE INDEX IF NOT EXISTS catalog_changes_version ON catalog_changes(result_version)`,
}{if _,err=tx.ExecContext(ctx,stmt);err!=nil{return err}}
if _,err=tx.ExecContext(ctx,d.q(`INSERT INTO control_catalog(id,version,document) VALUES(1,1,?) ON CONFLICT(id) DO NOTHING`),string(raw));err!=nil{return err}
return tx.Commit()
defaults, err := content.DefaultCatalog()
if err != nil {
return err
}
if err = defaults.Validate(); err != nil {
return err
}
raw, err := json.Marshal(defaults)
if err != nil {
return err
}
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 control_catalog(id INTEGER PRIMARY KEY CHECK(id=1),version BIGINT NOT NULL,document TEXT NOT NULL)`,
`CREATE TABLE IF NOT EXISTS catalog_changes(id TEXT PRIMARY KEY,actor TEXT NOT NULL,op TEXT NOT NULL,target TEXT NOT NULL,reason TEXT NOT NULL,expected_version BIGINT NOT NULL,result_version BIGINT NOT NULL,request_json TEXT NOT NULL,created_at BIGINT NOT NULL)`,
`CREATE INDEX IF NOT EXISTS catalog_changes_version ON catalog_changes(result_version)`,
} {
if _, err = tx.ExecContext(ctx, stmt); err != nil {
return err
}
}
if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO control_catalog(id,version,document) VALUES(1,1,?) ON CONFLICT(id) DO NOTHING`), string(raw)); err != nil {
return err
}
return tx.Commit()
}
func decodeCatalog(version int64,raw string)(content.Catalog,error){
var catalog content.Catalog
if err:=json.Unmarshal([]byte(raw),&catalog);err!=nil{return catalog,err}
if catalog.Version!=version{return catalog,errors.New("catalog version mismatch")}
return catalog,catalog.Validate()
func decodeCatalog(version int64, raw string) (content.Catalog, error) {
var catalog content.Catalog
if err := json.Unmarshal([]byte(raw), &catalog); err != nil {
return catalog, err
}
if catalog.Version != version {
return catalog, errors.New("catalog version mismatch")
}
return catalog, catalog.Validate()
}
func(d *DB) Catalog(ctx context.Context)(content.Catalog,error){
var version int64;var raw string
if err:=d.sql.QueryRowContext(ctx,`SELECT version,document FROM control_catalog WHERE id=1`).Scan(&version,&raw);err!=nil{return content.Catalog{},err}
return decodeCatalog(version,raw)
func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) {
var version int64
var raw string
if err := d.sql.QueryRowContext(ctx, `SELECT version,document FROM control_catalog WHERE id=1`).Scan(&version, &raw); err != nil {
return content.Catalog{}, err
}
return decodeCatalog(version, raw)
}
func(d *DB) CatalogAfter(ctx context.Context,after int64)(*content.Catalog,error){
var version int64;var raw string
err:=d.sql.QueryRowContext(ctx,d.q(`SELECT version,document FROM control_catalog WHERE id=1 AND version>?`),after).Scan(&version,&raw)
if errors.Is(err,sql.ErrNoRows){return nil,nil};if err!=nil{return nil,err}
catalog,err:=decodeCatalog(version,raw);return &catalog,err
func (d *DB) CatalogAfter(ctx context.Context, after int64) (*content.Catalog, error) {
var version int64
var raw string
err := d.sql.QueryRowContext(ctx, d.q(`SELECT version,document FROM control_catalog WHERE id=1 AND version>?`), after).Scan(&version, &raw)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
catalog, err := decodeCatalog(version, raw)
return &catalog, err
}
func(c CatalogChange) validate()error{
if !catalogRequestID.MatchString(c.ID)||c.ExpectedVersion<1||len(c.Reason)<5||len(c.Reason)>240{return fmt.Errorf("%w: request ID, current version and 5-240 character reason required",ErrCatalogInvalid)}
valid:=false
switch c.Op{
case "create-title":valid=c.Title!=nil&&c.Item==nil&&c.Stats==nil
case "create-item":valid=c.Item!=nil&&c.Title==nil&&c.Stats==nil
case "update-stats":valid=c.Stats!=nil&&c.Title==nil&&c.Item==nil
}
if !valid{return fmt.Errorf("%w: operation must have exactly its matching payload",ErrCatalogInvalid)};return nil
func (c CatalogChange) validate() error {
if !catalogRequestID.MatchString(c.ID) || c.ExpectedVersion < 1 || len(c.Reason) < 5 || len(c.Reason) > 240 {
return fmt.Errorf("%w: request ID, current version and 5-240 character reason required", ErrCatalogInvalid)
}
valid := false
switch c.Op {
case "create-title":
valid = c.Title != nil && c.Item == nil && c.Stats == nil
case "create-item":
valid = c.Item != nil && c.Title == nil && c.Stats == nil
case "update-stats":
valid = c.Stats != nil && c.Title == nil && c.Item == nil
}
if !valid {
return fmt.Errorf("%w: operation must have exactly its matching payload", ErrCatalogInvalid)
}
return nil
}
func(d *DB) PublishCatalog(ctx context.Context,actor string,change CatalogChange)(CatalogResult,error){
change.Reason=strings.TrimSpace(change.Reason)
if actor==""{return CatalogResult{},fmt.Errorf("%w: actor required",ErrCatalogInvalid)}
if err:=change.validate();err!=nil{return CatalogResult{},err}
request,err:=json.Marshal(change);if err!=nil{return CatalogResult{},fmt.Errorf("%w: %v",ErrCatalogInvalid,err)}
tx,err:=d.sql.BeginTx(ctx,nil);if err!=nil{return CatalogResult{},err};defer tx.Rollback()
// Serialize editors without locking world/character/passage/award rows.
locked,err:=tx.ExecContext(ctx,`UPDATE control_catalog SET version=version WHERE id=1`);if err!=nil{return CatalogResult{},err}
n,err:=locked.RowsAffected();if err!=nil{return CatalogResult{},err};if n!=1{return CatalogResult{},errors.New("catalog unavailable")}
var previousActor,previousRequest string;var result CatalogResult
err=tx.QueryRowContext(ctx,d.q(`SELECT actor,request_json,result_version FROM catalog_changes WHERE id=?`),change.ID).Scan(&previousActor,&previousRequest,&result.Version)
if err==nil{if previousActor!=actor||previousRequest!=string(request){return CatalogResult{},ErrCatalogRequest};return result,tx.Commit()}
if !errors.Is(err,sql.ErrNoRows){return CatalogResult{},err}
var version int64;var raw string
if err=tx.QueryRowContext(ctx,`SELECT version,document FROM control_catalog WHERE id=1`).Scan(&version,&raw);err!=nil{return CatalogResult{},err}
if version!=change.ExpectedVersion{return CatalogResult{},ErrCatalogConflict}
catalog,err:=decodeCatalog(version,raw);if err!=nil{return CatalogResult{},err}
target:="stats"
switch change.Op{
case "create-title":catalog.Titles=append(catalog.Titles,*change.Title);target=change.Title.ID
case "create-item":catalog.Items=append(catalog.Items,*change.Item);target=change.Item.ID
case "update-stats":catalog.Stats=*change.Stats
}
catalog.Version=version+1
if err=catalog.Validate();err!=nil{return CatalogResult{},fmt.Errorf("%w: %v",ErrCatalogInvalid,err)}
encoded,err:=json.Marshal(catalog);if err!=nil{return CatalogResult{},err}
if _,err=tx.ExecContext(ctx,d.q(`UPDATE control_catalog SET version=?,document=? WHERE id=1`),catalog.Version,string(encoded));err!=nil{return CatalogResult{},err}
if _,err=tx.ExecContext(ctx,d.q(`INSERT INTO catalog_changes(id,actor,op,target,reason,expected_version,result_version,request_json,created_at) VALUES(?,?,?,?,?,?,?,?,`+d.now()+`)`),change.ID,actor,change.Op,target,change.Reason,change.ExpectedVersion,catalog.Version,string(request));err!=nil{return CatalogResult{},err}
if err=tx.Commit();err!=nil{return CatalogResult{},err};return CatalogResult{Version:catalog.Version},nil
func (d *DB) PublishCatalog(ctx context.Context, actor string, change CatalogChange) (CatalogResult, error) {
change.Reason = strings.TrimSpace(change.Reason)
if actor == "" {
return CatalogResult{}, fmt.Errorf("%w: actor required", ErrCatalogInvalid)
}
if err := change.validate(); err != nil {
return CatalogResult{}, err
}
request, err := json.Marshal(change)
if err != nil {
return CatalogResult{}, fmt.Errorf("%w: %v", ErrCatalogInvalid, err)
}
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return CatalogResult{}, err
}
defer tx.Rollback()
// Serialize editors without locking world/character/passage/award rows.
locked, err := tx.ExecContext(ctx, `UPDATE control_catalog SET version=version WHERE id=1`)
if err != nil {
return CatalogResult{}, err
}
n, err := locked.RowsAffected()
if err != nil {
return CatalogResult{}, err
}
if n != 1 {
return CatalogResult{}, errors.New("catalog unavailable")
}
var previousActor, previousRequest string
var result CatalogResult
err = tx.QueryRowContext(ctx, d.q(`SELECT actor,request_json,result_version FROM catalog_changes WHERE id=?`), change.ID).Scan(&previousActor, &previousRequest, &result.Version)
if err == nil {
if previousActor != actor || previousRequest != string(request) {
return CatalogResult{}, ErrCatalogRequest
}
return result, tx.Commit()
}
if !errors.Is(err, sql.ErrNoRows) {
return CatalogResult{}, err
}
var version int64
var raw string
if err = tx.QueryRowContext(ctx, `SELECT version,document FROM control_catalog WHERE id=1`).Scan(&version, &raw); err != nil {
return CatalogResult{}, err
}
if version != change.ExpectedVersion {
return CatalogResult{}, ErrCatalogConflict
}
catalog, err := decodeCatalog(version, raw)
if err != nil {
return CatalogResult{}, err
}
target := "stats"
switch change.Op {
case "create-title":
catalog.Titles = append(catalog.Titles, *change.Title)
target = change.Title.ID
case "create-item":
catalog.Items = append(catalog.Items, *change.Item)
target = change.Item.ID
case "update-stats":
catalog.Stats = *change.Stats
}
catalog.Version = version + 1
if err = catalog.Validate(); err != nil {
return CatalogResult{}, fmt.Errorf("%w: %v", ErrCatalogInvalid, err)
}
encoded, err := json.Marshal(catalog)
if err != nil {
return CatalogResult{}, err
}
if _, err = tx.ExecContext(ctx, d.q(`UPDATE control_catalog SET version=?,document=? WHERE id=1`), catalog.Version, string(encoded)); err != nil {
return CatalogResult{}, err
}
if _, err = tx.ExecContext(ctx, d.q(`INSERT INTO catalog_changes(id,actor,op,target,reason,expected_version,result_version,request_json,created_at) VALUES(?,?,?,?,?,?,?,?,`+d.now()+`)`), change.ID, actor, change.Op, target, change.Reason, change.ExpectedVersion, catalog.Version, string(request)); err != nil {
return CatalogResult{}, err
}
if err = tx.Commit(); err != nil {
return CatalogResult{}, err
}
return CatalogResult{Version: catalog.Version}, nil
}
func(d *DB) CatalogChanges(ctx context.Context)([]CatalogAudit,error){
rows,err:=d.sql.QueryContext(ctx,`SELECT id,actor,op,target,reason,result_version,created_at FROM catalog_changes ORDER BY result_version DESC LIMIT 100`);if err!=nil{return nil,err};defer rows.Close()
changes:=[]CatalogAudit{}
for rows.Next(){var c CatalogAudit;if err=rows.Scan(&c.ID,&c.Actor,&c.Op,&c.Target,&c.Reason,&c.Version,&c.CreatedAt);err!=nil{return nil,err};changes=append(changes,c)}
return changes,rows.Err()
func (d *DB) CatalogChanges(ctx context.Context) ([]CatalogAudit, error) {
rows, err := d.sql.QueryContext(ctx, `SELECT id,actor,op,target,reason,result_version,created_at FROM catalog_changes ORDER BY result_version DESC LIMIT 100`)
if err != nil {
return nil, err
}
defer rows.Close()
changes := []CatalogAudit{}
for rows.Next() {
var c CatalogAudit
if err = rows.Scan(&c.ID, &c.Actor, &c.Op, &c.Target, &c.Reason, &c.Version, &c.CreatedAt); err != nil {
return nil, err
}
changes = append(changes, c)
}
return changes, rows.Err()
}
+95
View File
@@ -0,0 +1,95 @@
package store
import (
"aeternalis/server/content"
"aeternalis/server/internal/game"
"context"
"errors"
"os"
"path/filepath"
"sync"
"testing"
)
func TestCatalogEditorsAndDurability(t *testing.T) {
testCatalogEditors(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "catalog.db")))
}
func TestPostgresCatalogEditors(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not configured")
}
testCatalogEditors(t, dsn)
}
func testCatalogEditors(t *testing.T, dsn string) {
ctx := context.Background()
db, err := Open(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer func() {
if db != nil {
db.Close()
}
}()
initial, err := db.Catalog(ctx)
if err != nil {
t.Fatal(err)
}
requests := make([]CatalogChange, 2)
for i := range requests {
title := content.Title{ID: "editor_" + game.ID(), Name: "Editor trial", Scope: "personal", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 2}}}
requests[i] = CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Op: "create-title", Reason: "Concurrent editors", Title: &title}
}
var wg sync.WaitGroup
start := make(chan struct{})
results := make([]error, 2)
for i := range requests {
wg.Add(1)
go func(i int) { defer wg.Done(); <-start; _, results[i] = db.PublishCatalog(ctx, "operator", requests[i]) }(i)
}
close(start)
wg.Wait()
winner := -1
for i, err := range results {
if err == nil {
if winner >= 0 {
t.Fatal("both stale edits committed")
}
winner = i
} else if !errors.Is(err, ErrCatalogConflict) {
t.Fatal(err)
}
}
if winner < 0 {
t.Fatal("no editor committed")
}
request := requests[winner]
result, err := db.PublishCatalog(ctx, "operator", request)
if err != nil || result.Version != initial.Version+1 {
t.Fatal("replay failed", err)
}
if _, err = db.PublishCatalog(ctx, "other", request); !errors.Is(err, ErrCatalogRequest) {
t.Fatal("actor collision accepted", err)
}
request.ID = game.ID()
request.ExpectedVersion = result.Version
if _, err = db.PublishCatalog(ctx, "operator", request); !errors.Is(err, ErrCatalogInvalid) {
t.Fatal("overwrote published ID", err)
}
audits, err := db.CatalogChanges(ctx)
if err != nil || len(audits) < 1 || audits[0].ID != requests[winner].ID {
t.Fatal("audit missing", err)
}
if err = db.Close(); err != nil {
t.Fatal(err)
}
db, err = Open(ctx, dsn)
if err != nil {
t.Fatal(err)
}
restored, err := db.Catalog(ctx)
if err != nil || restored.Version != result.Version || len(restored.Titles) != len(initial.Titles)+1 {
t.Fatal("bootstrap overwrote catalog", err)
}
}
+1 -1
View File
@@ -175,7 +175,7 @@ func runStoreTests(t *testing.T, dsn string) {
t.Fatal(err)
}
loaded := restored.Characters[c.View.Entity.ID]
if loaded == nil || loaded.DailySeconds != 123 || !slices.ContainsFunc(loaded.View.Items,func(item p.ItemInstance)bool{return item.DefinitionID=="spear"}) {
if loaded == nil || loaded.DailySeconds != 123 || !slices.ContainsFunc(loaded.View.Items, func(item p.ItemInstance) bool { return item.DefinitionID == "spear" }) {
t.Fatal("transfer not durable")
}
if err = targetLease.Save(ctx, target, ""); err == nil {
+3
View File
@@ -139,6 +139,9 @@ func (d *DB) accountTitles(ctx context.Context, tx *sql.Tx, account string) ([]p
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()
+74 -35
View File
@@ -1,42 +1,81 @@
package transport
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"time"
"aeternalis/server/internal/store"
"aeternalis/server/internal/store"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"time"
)
func(h *HTTP) catalogRoutes(mux *http.ServeMux){
mux.HandleFunc("GET /api/control/catalog",func(w http.ResponseWriter,r *http.Request){
if _,ok:=h.admin(w,r);!ok{return}
ctx,cancel:=context.WithTimeout(r.Context(),5*time.Second);defer cancel()
catalog,err:=h.auth.db.Catalog(ctx);if err!=nil{fail(w,503,"catalog unavailable");return}
changes,err:=h.auth.db.CatalogChanges(ctx);if err!=nil{fail(w,503,"catalog audit unavailable");return}
respond(w,200,map[string]any{"catalog":catalog,"changes":changes})
})
mux.HandleFunc("POST /api/control/catalog",func(w http.ResponseWriter,r *http.Request){
actor,ok:=h.admin(w,r);if !ok{return}
var change store.CatalogChange
r.Body=http.MaxBytesReader(w,r.Body,32768)
decoder:=json.NewDecoder(r.Body);decoder.DisallowUnknownFields()
if err:=decoder.Decode(&change);err!=nil{fail(w,400,"invalid catalog change");return}
var extra any;if err:=decoder.Decode(&extra);err!=io.EOF{fail(w,400,"invalid catalog change");return}
ctx,cancel:=context.WithTimeout(r.Context(),5*time.Second);defer cancel()
result,err:=h.auth.db.PublishCatalog(ctx,actor,change)
switch{
case errors.Is(err,store.ErrCatalogConflict),errors.Is(err,store.ErrCatalogRequest):fail(w,409,err.Error())
case errors.Is(err,store.ErrCatalogInvalid):fail(w,400,err.Error())
case err!=nil:fail(w,503,"catalog publication unavailable")
default:respond(w,200,result)
}
})
func (h *HTTP) catalogRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/control/catalog", func(w http.ResponseWriter, r *http.Request) {
if _, ok := h.admin(w, r); !ok {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
catalog, err := h.auth.db.Catalog(ctx)
if err != nil {
fail(w, 503, "catalog unavailable")
return
}
changes, err := h.auth.db.CatalogChanges(ctx)
if err != nil {
fail(w, 503, "catalog audit unavailable")
return
}
respond(w, 200, map[string]any{"catalog": catalog, "changes": changes})
})
mux.HandleFunc("POST /api/control/catalog", func(w http.ResponseWriter, r *http.Request) {
actor, ok := h.admin(w, r)
if !ok {
return
}
var change store.CatalogChange
r.Body = http.MaxBytesReader(w, r.Body, 32768)
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&change); err != nil {
fail(w, 400, "invalid catalog change")
return
}
var extra any
if err := decoder.Decode(&extra); err != io.EOF {
fail(w, 400, "invalid catalog change")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
result, err := h.auth.db.PublishCatalog(ctx, actor, change)
switch {
case errors.Is(err, store.ErrCatalogConflict), errors.Is(err, store.ErrCatalogRequest):
fail(w, 409, err.Error())
case errors.Is(err, store.ErrCatalogInvalid):
fail(w, 400, err.Error())
case err != nil:
fail(w, 503, "catalog publication unavailable")
default:
respond(w, 200, result)
}
})
}
// Caller holds s.mu. Checkpoint a catalog before it can reach a snapshot.
func(s *Service) refreshCatalog(ctx context.Context)error{
ctx,cancel:=context.WithTimeout(ctx,5*time.Second);defer cancel()
catalog,err:=s.lease.DB.CatalogAfter(ctx,s.world.CatalogVersion);if err!=nil{return err};if catalog==nil{return nil}
if err=s.world.ApplyCatalog(*catalog);err!=nil{return err};return s.persist(ctx,"")
func (s *Service) refreshCatalog(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
catalog, err := s.lease.DB.CatalogAfter(ctx, s.world.CatalogVersion)
if err != nil {
return err
}
if catalog == nil {
return nil
}
if err = s.world.ApplyCatalog(*catalog); err != nil {
return err
}
return s.persist(ctx, "")
}
@@ -1,44 +1,103 @@
package transport
import (
"context"
"encoding/json"
"path/filepath"
"testing"
"time"
"aeternalis/server/content"
"aeternalis/server/internal/game"
"aeternalis/server/internal/store"
"aeternalis/server/content"
"aeternalis/server/internal/game"
"aeternalis/server/internal/store"
"context"
"encoding/json"
"path/filepath"
"testing"
"time"
)
func TestPublishedTitlesAndStatsReachDurableCharacterViews(t *testing.T) {
ctx:=context.Background()
db,err:=store.Open(ctx,"file:"+filepath.ToSlash(filepath.Join(t.TempDir(),"catalog-owner.db")));if err!=nil{t.Fatal(err)};defer db.Close()
b,err:=content.Load();if err!=nil{t.Fatal(err)}
w:=game.New("catalog-owner",23,time.Now(),b)
lease,_,err:=db.Acquire(ctx,w);if err!=nil{t.Fatal(err)}
svc:=NewService(w,lease)
initial,err:=db.Catalog(ctx);if err!=nil{t.Fatal(err)}
title:=content.Title{ID:"published_strength",Name:"Published Strength",Scope:"personal",Requirements:[]content.TitleRequirement{{Metric:"level",AtLeast:1}},Effects:content.TitleEffects{Modifiers:[]content.StatModifier{{Stat:"strength",Flat:4,Percent:50}}}}
result,err:=db.PublishCatalog(ctx,"operator",store.CatalogChange{ID:game.ID(),ExpectedVersion:initial.Version,Op:"create-title",Reason:"Integration title",Title:&title});if err!=nil{t.Fatal(err)}
view,err:=svc.join(ctx,"catalog-player","Catalog Player","");if err!=nil{t.Fatal(err)}
if len(view.Titles)!=1||view.Titles[0].ID!=title.ID||view.Stats["strength"].Final!=6||view.Stats["meleeDamage"].Final!=24{t.Fatal("published title missing from committed join",view)}
c:=w.Characters[view.Entity.ID];c.View.Entity.HP=20;c.DailySeconds=321
rules:=initial.Stats;rules.Base["healthPoints"]=150
result,err=db.PublishCatalog(ctx,"operator",store.CatalogChange{ID:game.ID(),ExpectedVersion:result.Version,Op:"update-stats",Reason:"Integration formula",Stats:&rules});if err!=nil{t.Fatal(err)}
if err=svc.controls(ctx);err!=nil{t.Fatal(err)}
record,err:=db.ActiveCharacter(ctx,c.Account);if err!=nil{t.Fatal(err)}
if record.Character.View.Entity.MaxHP!=150||record.Character.View.Entity.HP!=20||record.Character.DailySeconds!=321||record.Character.View.Titles[0].Effects.Modifiers[0].Flat!=4{t.Fatal("catalog changed health, budget or earned title")}
worlds,err:=db.Worlds(ctx);if err!=nil||worlds[0].CatalogVersion!=result.Version{t.Fatal("applied version not checkpointed",err)}
if err=lease.Release(ctx);err!=nil{t.Fatal(err)}
nextLease,raw,err:=db.Acquire(ctx,game.New(w.ID,23,time.Now(),b));if err!=nil{t.Fatal(err)};defer nextLease.Release(ctx)
var restored game.World;if err=json.Unmarshal(raw,&restored);err!=nil{t.Fatal(err)}
if err=restored.Restore(time.Now());err!=nil{t.Fatal(err)}
if restored.CatalogVersion!=result.Version||restored.Characters[c.View.Entity.ID].View.Stats["healthPoints"].Final!=150{t.Fatal("restart lost published stats")}
// Old ownership may no longer expose a speculative formula revision.
rules.Base["healthPoints"]=200
if _,err=db.PublishCatalog(ctx,"operator",store.CatalogChange{ID:game.ID(),ExpectedVersion:result.Version,Op:"update-stats",Reason:"Stale owner test",Stats:&rules});err!=nil{t.Fatal(err)}
if err=svc.refreshCatalog(ctx);err==nil||svc.ready.Load(){t.Fatal("stale owner continued after failed catalog checkpoint")}
record,err=db.ActiveCharacter(ctx,c.Account);if err!=nil{t.Fatal(err)}
if record.Character.View.Entity.MaxHP!=150{t.Fatal("failed checkpoint published speculative stats")}
ctx := context.Background()
db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "catalog-owner.db")))
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, err := content.Load()
if err != nil {
t.Fatal(err)
}
w := game.New("catalog-owner", 23, time.Now(), b)
lease, _, err := db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
svc := NewService(w, lease)
initial, err := db.Catalog(ctx)
if err != nil {
t.Fatal(err)
}
title := content.Title{ID: "published_strength", Name: "Published Strength", Scope: "personal", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 1}}, Effects: content.TitleEffects{Modifiers: []content.StatModifier{{Stat: "strength", Flat: 4, Percent: 50}}}}
result, err := db.PublishCatalog(ctx, "operator", store.CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Op: "create-title", Reason: "Integration title", Title: &title})
if err != nil {
t.Fatal(err)
}
view, err := svc.join(ctx, "catalog-player", "Catalog Player", "")
if err != nil {
t.Fatal(err)
}
if len(view.Titles) != 1 || view.Titles[0].ID != title.ID || view.Stats["strength"].Final != 6 || view.Stats["meleeDamage"].Final != 24 {
t.Fatal("published title missing from committed join", view)
}
c := w.Characters[view.Entity.ID]
c.View.Entity.HP = 20
c.DailySeconds = 321
rules := initial.Stats
rules.Base["healthPoints"] = 150
result, err = db.PublishCatalog(ctx, "operator", store.CatalogChange{ID: game.ID(), ExpectedVersion: result.Version, Op: "update-stats", Reason: "Integration formula", Stats: &rules})
if err != nil {
t.Fatal(err)
}
if err = svc.controls(ctx); err != nil {
t.Fatal(err)
}
record, err := db.ActiveCharacter(ctx, c.Account)
if err != nil {
t.Fatal(err)
}
if record.Character.View.Entity.MaxHP != 150 || record.Character.View.Entity.HP != 20 || record.Character.DailySeconds != 321 || record.Character.View.Titles[0].Effects.Modifiers[0].Flat != 4 {
t.Fatal("catalog changed health, budget or earned title")
}
worlds, err := db.Worlds(ctx)
if err != nil || worlds[0].CatalogVersion != result.Version {
t.Fatal("applied version not checkpointed", err)
}
if err = lease.Release(ctx); err != nil {
t.Fatal(err)
}
nextLease, raw, err := db.Acquire(ctx, game.New(w.ID, 23, time.Now(), b))
if err != nil {
t.Fatal(err)
}
defer nextLease.Release(ctx)
var restored game.World
if err = json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
if err = restored.Restore(time.Now()); err != nil {
t.Fatal(err)
}
if restored.CatalogVersion != result.Version || restored.Characters[c.View.Entity.ID].View.Stats["healthPoints"].Final != 150 {
t.Fatal("restart lost published stats")
}
// Old ownership may no longer expose a speculative formula revision.
rules.Base["healthPoints"] = 200
if _, err = db.PublishCatalog(ctx, "operator", store.CatalogChange{ID: game.ID(), ExpectedVersion: result.Version, Op: "update-stats", Reason: "Stale owner test", Stats: &rules}); err != nil {
t.Fatal(err)
}
if err = svc.refreshCatalog(ctx); err == nil || svc.ready.Load() {
t.Fatal("stale owner continued after failed catalog checkpoint")
}
record, err = db.ActiveCharacter(ctx, c.Account)
if err != nil {
t.Fatal(err)
}
if record.Character.View.Entity.MaxHP != 150 {
t.Fatal("failed checkpoint published speculative stats")
}
}
+4 -1
View File
@@ -176,7 +176,10 @@ func (h *HTTP) Handler() http.Handler {
h.s.mu.Lock()
defer h.s.mu.Unlock()
if c := h.s.world.ForAccount(account); c != nil && active != nil && active.WorldID == h.s.world.ID && active.ID == c.View.Entity.ID {
if !h.s.ready.Load() { fail(w, 503, "world unavailable"); return }
if !h.s.ready.Load() {
fail(w, 503, "world unavailable")
return
}
respond(w, 200, map[string]any{"character": c.View, "world": h.s.world.Info()})
return
}