Add durable recipe discovery and profession crafting

This commit is contained in:
dingo
2026-09-09 13:28:07 -04:00
parent 940a345613
commit b65f3e8562
42 changed files with 2183 additions and 136 deletions
+33 -14
View File
@@ -17,15 +17,19 @@ var ErrCatalogInvalid = errors.New("invalid catalog change")
var catalogRequestID = regexp.MustCompile(`^[a-f0-9-]{32,36}$`)
type CatalogChange struct {
TargetID string `json:"targetId,omitempty"`
Attack *content.CombatAttack `json:"attack,omitempty"`
Mob *content.MobDefinition `json:"mob,omitempty"`
Loot *content.LootTable `json:"loot,omitempty"`
Spawn *content.MobSpawn `json:"spawn,omitempty"`
GatheringSkill *content.GatheringSkill `json:"gatheringSkill,omitempty"`
Resource *content.ResourceDefinition `json:"resource,omitempty"`
Biome *content.BiomeDefinition `json:"biome,omitempty"`
Consumable *content.GatheringConsumable `json:"consumable,omitempty"`
CraftRecipe *content.CraftRecipe `json:"craftRecipe,omitempty"`
CraftProfession *content.GatheringSkill `json:"craftProfession,omitempty"`
CraftMaterial *content.CraftMaterial `json:"craftMaterial,omitempty"`
CraftRules *content.CraftRules `json:"craftRules,omitempty"`
TargetID string `json:"targetId,omitempty"`
Attack *content.CombatAttack `json:"attack,omitempty"`
Mob *content.MobDefinition `json:"mob,omitempty"`
Loot *content.LootTable `json:"loot,omitempty"`
Spawn *content.MobSpawn `json:"spawn,omitempty"`
GatheringSkill *content.GatheringSkill `json:"gatheringSkill,omitempty"`
Resource *content.ResourceDefinition `json:"resource,omitempty"`
Biome *content.BiomeDefinition `json:"biome,omitempty"`
Consumable *content.GatheringConsumable `json:"consumable,omitempty"`
ID string `json:"id"`
ExpectedVersion int64 `json:"expectedVersion"`
@@ -47,7 +51,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.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.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 {
@@ -118,6 +122,13 @@ func decodeCatalog(version int64, raw string) (content.Catalog, error) {
}
catalog.Combat = b.Combat
}
if catalog.Crafting == nil {
defaults, e := content.Load()
if e != nil {
return catalog, e
}
catalog.RestoreCrafting(defaults)
}
return catalog, catalog.Validate()
}
func (d *DB) Catalog(ctx context.Context) (content.Catalog, error) {
@@ -142,10 +153,10 @@ func (d *DB) CatalogAfter(ctx context.Context, after int64) (*content.Catalog, e
return &catalog, err
}
func (c CatalogChange) validate() error {
if (c.Op == "update-biome") != (c.TargetID != "") {
return fmt.Errorf("%w: only biome edits require an existing target", ErrCatalogInvalid)
if (c.Op == "update-biome" || c.Op == "update-craft-recipe") != (c.TargetID != "") {
return fmt.Errorf("%w: only biome and recipe edits require an existing target", ErrCatalogInvalid)
}
if c.Biome != nil && c.Biome.Revision != 0 {
if (c.Biome != nil && c.Biome.Revision != 0) || (c.CraftRecipe != nil && c.CraftRecipe.Revision != 0) {
return fmt.Errorf("%w: revisions are assigned by the server", ErrCatalogInvalid)
}
if !catalogRequestID.MatchString(c.ID) || c.ExpectedVersion < 1 || len(c.Reason) < 5 || len(c.Reason) > 240 {
@@ -153,12 +164,20 @@ func (c CatalogChange) validate() error {
}
valid := false
count := 0
for _, present := range []bool{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.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-craft-recipe", "update-craft-recipe":
valid = c.CraftRecipe != nil
case "create-craft-profession":
valid = c.CraftProfession != nil
case "create-craft-material":
valid = c.CraftMaterial != nil
case "update-craft-rules":
valid = c.CraftRules != nil
case "create-attack":
valid = c.Attack != nil
case "create-mob":
+57
View File
@@ -35,6 +35,15 @@ 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.CraftRecipe != nil && change.Op != "update-craft-recipe" {
resolved.CraftRecipe.ID = ""
}
if resolved.CraftProfession != nil {
resolved.CraftProfession.ID = ""
}
if resolved.CraftMaterial != nil {
resolved.CraftMaterial.ID = ""
}
if resolved.Attack != nil {
resolved.Attack.ID = ""
}
@@ -106,7 +115,55 @@ func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, str
}
combat := *c.Combat
c.Combat = &combat
if c.Crafting == nil {
b, e := content.Load()
if e != nil {
return invalid(e)
}
c.RestoreCrafting(b)
}
crafting := *c.Crafting
c.Crafting = &crafting
switch change.Op {
case "create-craft-recipe", "update-craft-recipe":
v := *change.CraftRecipe
v.Revision = 1
if change.Op == "update-craft-recipe" {
i := slices.IndexFunc(c.Crafting.Recipes, func(r content.CraftRecipe) bool { return r.ID == change.TargetID })
if i < 0 {
return invalid(fmt.Errorf("recipe not found"))
}
v.ID = c.Crafting.Recipes[i].ID
v.Revision = c.Crafting.Recipes[i].Revision + 1
c.Crafting.Recipes = slices.Clone(c.Crafting.Recipes)
c.Crafting.Recipes[i] = v
} else {
if v.ID == "" {
v.ID = "recipe_" + game.ID()
}
c.Crafting.Recipes = append(slices.Clone(c.Crafting.Recipes), v)
}
resolved.CraftRecipe = &v
target = v.ID
case "create-craft-profession":
v := *change.CraftProfession
if v.ID == "" {
v.ID = "profession_" + game.ID()
}
c.Crafting.Professions = append(slices.Clone(c.Crafting.Professions), v)
resolved.CraftProfession = &v
target = v.ID
case "create-craft-material":
v := *change.CraftMaterial
if v.ID == "" {
v.ID = "material_" + game.ID()
}
c.Crafting.Materials = append(slices.Clone(c.Crafting.Materials), v)
resolved.CraftMaterial = &v
target = v.ID
case "update-craft-rules":
c.Crafting.Rules = *change.CraftRules
target = "crafting-rules"
case "create-attack":
v := *change.Attack
if v.ID == "" {
+87
View File
@@ -0,0 +1,87 @@
package store
import (
"aeternalis/server/internal/game"
p "aeternalis/server/internal/protocol"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
)
var ErrCraft = errors.New("craft rejected")
type craftReceipt struct{ ID, Account, CharacterID, Request, Result string }
func (d *DB) CraftReceipt(ctx context.Context, account string, req p.CraftRequest) (*p.CraftResult, error) {
var request, result string
e := d.sql.QueryRowContext(ctx, d.q(`SELECT request_json,result_json FROM craft_receipts WHERE account_id=? AND id=?`), account, req.ID).Scan(&request, &result)
if errors.Is(e, sql.ErrNoRows) {
return nil, nil
}
if e != nil {
return nil, e
}
raw, _ := json.Marshal(req)
if string(raw) != request {
return nil, fmt.Errorf("%w: attempt ID already used with different ingredients", ErrCraft)
}
var out p.CraftResult
e = json.Unmarshal([]byte(result), &out)
return &out, e
}
// Called under the world service mutex. Consumption, rolls, discovery, XP and
// the replay receipt share the same fenced snapshot transaction.
func (l *Lease) Craft(ctx context.Context, live *game.World, account string, req p.CraftRequest) (p.CraftResult, error) {
fail := func(msg string) (p.CraftResult, error) { return p.CraftResult{}, fmt.Errorf("%w: %s", ErrCraft, msg) }
if !game.ValidCraftRequest(req) {
return fail("invalid crafting request")
}
if old, e := l.DB.CraftReceipt(ctx, account, req); e != nil {
return p.CraftResult{}, e
} else if old != nil {
return *old, nil
}
active, e := l.DB.ActiveCharacter(ctx, account)
if e != nil {
return p.CraftResult{}, e
}
if active == nil || active.ID != req.CharacterID || active.WorldID != live.ID || active.State != "alive" {
return fail("character is not active in this world")
}
original := live.Characters[req.CharacterID]
if original == nil || original.Account != account {
return fail("character unavailable")
}
staged := stageTitleWorld(live)
// Deep-copy only the acting view; leave all other players' live inputs intact.
raw, e := json.Marshal(original.View)
if e != nil {
return p.CraftResult{}, e
}
var view p.Character
if e = json.Unmarshal(raw, &view); e != nil {
return p.CraftResult{}, e
}
staged.Characters[req.CharacterID].View = view
result, e := staged.AttemptCraft(staged.Characters[req.CharacterID], req)
if e != nil {
return fail(e.Error())
}
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 {
return p.CraftResult{}, e
}
// Retain character pointers captured by existing WebSocket handlers.
for id, c := range staged.Characters {
*live.Characters[id] = *c
}
live.RandomCounter = staged.RandomCounter
live.PendingTitles = nil
live.Saved()
return result, nil
}
+218
View File
@@ -0,0 +1,218 @@
package store
import (
"aeternalis/server/content"
"aeternalis/server/internal/game"
p "aeternalis/server/internal/protocol"
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"reflect"
"testing"
"time"
)
func TestCraftDurability(t *testing.T) {
testCraftDurability(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "craft.db")))
}
func TestPostgresCraftDurability(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not configured")
}
testCraftDurability(t, dsn)
}
func testCraftDurability(t *testing.T, dsn string) {
ctx := context.Background()
db, e := Open(ctx, dsn)
if e != nil {
t.Fatal(e)
}
defer db.Close()
b, e := content.Load()
if e != nil {
t.Fatal(e)
}
b.Crafting.Rules.BaseFailure = 0
b.Crafting.Rules.MinFailure = 0
b.Crafting.Rules.MaxFailure = 0
now := time.Now().UTC()
w := game.New("craft-"+game.ID(), 1, now, b)
l, _, e := db.Acquire(ctx, w)
if e != nil {
t.Fatal(e)
}
c, e := w.Join("crafter-"+game.ID(), "Maker")
if e != nil {
t.Fatal(e)
}
if e = w.Connect(c.View.Entity.ID); e != nil {
t.Fatal(e)
}
c.View.Inventory["wood"] = 20
c.View.Inventory["ore"] = 20
c.View.Inventory["escape_stone"] = 1
if e = l.Save(ctx, w, ""); e != nil {
t.Fatal(e)
}
req := p.CraftRequest{ID: game.ID(), CharacterID: c.View.Entity.ID, Profession: "weapon_smithing", Ingredients: map[string]int64{"wood": 3, "ore": 2}}
before, _ := json.Marshal(c)
random := w.RandomCounter
for _, state := range []string{"offline", "sheltered", "dead", "capped"} {
switch state {
case "offline":
c.Online = false
case "sheltered":
c.Sheltered = true
case "dead":
c.View.Entity.State = "dead"
case "capped":
c.View.RemainingSeconds = 0
}
if _, e = l.Craft(ctx, w, c.Account, req); !errors.Is(e, ErrCraft) {
t.Fatalf("accepted %s: %v", state, e)
}
var restored game.Character
if e = json.Unmarshal(before, &restored); e != nil {
t.Fatal(e)
}
*c = restored
c.Online = true
}
stale := *l
stale.Revision--
if _, e = stale.Craft(ctx, w, c.Account, req); !errors.Is(e, ErrOwnership) {
t.Fatal("stale craft was not fenced", e)
}
after, _ := json.Marshal(c)
if string(after) != string(before) || w.RandomCounter != random {
t.Fatal("failed save changed live crafting state")
}
if receipt, e := db.CraftReceipt(ctx, c.Account, req); e != nil || receipt != nil {
t.Fatal("failed save left receipt", e)
}
result, e := l.Craft(ctx, w, c.Account, req)
if e != nil || !result.Success {
t.Fatal(result, e)
}
if w.Characters[c.View.Entity.ID] != c || c.View.Inventory["wood"] != 17 || c.View.Crafting["weapon_smithing"].XP != 20 {
t.Fatal("craft did not publish onto live character")
}
committed, _ := json.Marshal(c)
random = w.RandomCounter
replay, e := l.Craft(ctx, w, c.Account, req)
if e != nil || !reflect.DeepEqual(result, replay) {
t.Fatal("retry changed result", e)
}
after, _ = json.Marshal(c)
if string(after) != string(committed) || w.RandomCounter != random {
t.Fatal("retry spent resources or rerolled")
}
changed := req
changed.Ingredients = map[string]int64{"wood": 4, "ore": 2}
if _, e = l.Craft(ctx, w, c.Account, changed); !errors.Is(e, ErrCraft) {
t.Fatal("reused nonce accepted changed ingredients", e)
}
if _, e = l.Craft(ctx, w, "intruder", req); !errors.Is(e, ErrCraft) {
t.Fatal("other account recovered receipt", e)
}
// Reload from the durable world snapshot, not the live result.
if e = l.Release(ctx); e != nil {
t.Fatal(e)
}
restored := game.New(w.ID, 1, now, b)
var snapshot []byte
l, snapshot, e = db.Acquire(ctx, restored)
if e != nil {
t.Fatal(e)
}
if e = json.Unmarshal(snapshot, restored); e != nil {
t.Fatal(e)
}
if e = restored.Restore(now); e != nil {
t.Fatal(e)
}
w = restored
c = w.ForAccount(c.Account)
if c == nil || len(c.View.DiscoveredRecipes) != 1 || c.View.Crafting["weapon_smithing"].XP != 20 {
t.Fatal("restart lost progression")
}
if e = w.Connect(c.View.Entity.ID); e != nil {
t.Fatal(e)
}
hub := game.New("hub-"+game.ID(), 2, now, b)
hub.Kind = "hub"
hub.Phase = "hub"
hl, _, e := db.Acquire(ctx, hub)
if e != nil {
t.Fatal(e)
}
progression, _ := json.Marshal([]any{c.View.Crafting, c.View.DiscoveredRecipes, c.View.Items, c.View.Experience, c.CraftReadyAt})
transfer, e := l.PrepareTravel(ctx, w, c.Account, game.ID(), hub.ID, "escape")
if e != nil {
t.Fatal(e)
}
if _, e = hl.AcceptTravel(ctx, hub, c.Account, transfer.ID); e != nil {
t.Fatal(e)
}
arrived := hub.ForAccount(c.Account)
after, _ = json.Marshal([]any{arrived.View.Crafting, arrived.View.DiscoveredRecipes, arrived.View.Items, arrived.View.Experience, arrived.CraftReadyAt})
if string(progression) != string(after) {
t.Fatal("travel changed crafting progression or provenance")
}
replay, e = hl.Craft(ctx, hub, c.Account, req)
if e != nil || !reflect.DeepEqual(result, replay) {
t.Fatal("travel lost original receipt", e)
}
}
func TestCraftRecipeRevision(t *testing.T) {
ctx := context.Background()
db, e := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "recipes.db")))
if e != nil {
t.Fatal(e)
}
defer db.Close()
initial, e := db.Catalog(ctx)
if e != nil {
t.Fatal(e)
}
recipe := content.CraftRecipe{Name: "Trial spear", Profession: "weapon_smithing", Level: 2, XP: 25, Inputs: map[string]int64{"wood": 5, "ore": 3}, Outputs: map[string]int64{"spear": 1}}
change := CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Op: "create-craft-recipe", Reason: "Create a test recipe", CraftRecipe: &recipe}
first, e := db.PublishCatalog(ctx, "operator", change)
if e != nil {
t.Fatal(e)
}
firstCatalog, e := db.Catalog(ctx)
if e != nil {
t.Fatal(e)
}
made := firstCatalog.Crafting.Recipes[len(firstCatalog.Crafting.Recipes)-1]
if made.ID == "" || made.Revision != 1 {
t.Fatal("server did not assign recipe identity")
}
replay, e := db.PublishCatalog(ctx, "operator", change)
if e != nil || replay.Version != first.Version {
t.Fatal("recipe create retry failed", e)
}
recipe.Inputs = map[string]int64{"wood": 6, "ore": 3}
update := CatalogChange{ID: game.ID(), ExpectedVersion: first.Version, Op: "update-craft-recipe", TargetID: made.ID, Reason: "Revise test ingredients", CraftRecipe: &recipe}
_, e = db.PublishCatalog(ctx, "operator", update)
if e != nil {
t.Fatal(e)
}
revised, e := db.Catalog(ctx)
if e != nil {
t.Fatal(e)
}
got := revised.Crafting.Recipes[len(revised.Crafting.Recipes)-1]
if got.ID != made.ID || got.Revision != 2 || len(revised.Crafting.Recipes) != len(firstCatalog.Crafting.Recipes) || made.Inputs["wood"] != 5 {
t.Fatal("revision duplicated identity or mutated prior version")
}
update.ID = game.ID()
if _, e = db.PublishCatalog(ctx, "operator", update); !errors.Is(e, ErrCatalogConflict) {
t.Fatal("stale edit accepted", e)
}
}
+1
View File
@@ -65,6 +65,7 @@ func (d *DB) migrate(ctx context.Context) error {
}
}
for _, stmt := range []string{
`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))`,
`CREATE TABLE IF NOT EXISTS title_revocations(account_id TEXT NOT NULL,title_id TEXT NOT NULL,command_id TEXT NOT NULL,PRIMARY KEY(account_id,title_id))`,
+8
View File
@@ -139,6 +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)
}
func (l *Lease) save(ctx context.Context, w *game.World, claimID string, command *Command, outcome string, receipt *craftReceipt) error {
live := w
w = stageTitleWorld(w)
data, err := json.Marshal(w)
@@ -159,6 +162,11 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string,
if n != 1 {
return ErrOwnership
}
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 {
+2
View File
@@ -21,6 +21,8 @@ func stageTitleWorld(w *game.World) *game.World {
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.Inventory = maps.Clone(c.View.Inventory)
copy.View.Equipment = maps.Clone(c.View.Equipment)
copy.View.AllocatedStats = maps.Clone(c.View.AllocatedStats)
+1 -4
View File
@@ -107,10 +107,7 @@ func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, re
return nil, err
}
if route == "escape" {
departing.View.Inventory["escape_stone"]--
if departing.View.Inventory["escape_stone"] == 0 {
delete(departing.View.Inventory, "escape_stone")
}
game.TakeStack(&departing, "escape_stone", 1)
}
raw, err = json.Marshal(&departing)
if err != nil {