Add reusable content sets publication previews and focused input handling
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Sets are immutable authoring building blocks. Consumers receive expanded
|
||||
// values at publication; earned awards and acquired items never hold live refs.
|
||||
type RequirementSet struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Requirements []TitleRequirement `json:"requirements"`
|
||||
}
|
||||
type EffectSet struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
}
|
||||
|
||||
func ValidRequirement(r TitleRequirement) bool {
|
||||
return (KnownStat(r.Metric) || slices.Contains([]string{"level", "kills", "worldKills", "bossKills", "worldsSurvived", "gathering", "crafting", "combat", "deaths"}, r.Metric)) && r.AtLeast >= 1 && r.AtLeast <= 1000000000
|
||||
}
|
||||
|
||||
func validSetIdentity(id, name, description string) bool {
|
||||
return titleID.MatchString(id) && len(strings.TrimSpace(name)) > 0 && len(name) <= 80 && len(description) <= 500
|
||||
}
|
||||
|
||||
func (c Catalog) validateLibrary() error {
|
||||
if len(c.RequirementSets) > 256 || len(c.EffectSets) > 256 {
|
||||
return fmt.Errorf("too many reusable sets")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, set := range c.RequirementSets {
|
||||
if !validSetIdentity(set.ID, set.Name, set.Description) || seen[set.ID] || len(set.Requirements) < 1 || len(set.Requirements) > 8 {
|
||||
return fmt.Errorf("invalid or duplicate requirement set %q", set.ID)
|
||||
}
|
||||
seen[set.ID] = true
|
||||
metrics := map[string]bool{}
|
||||
for _, r := range set.Requirements {
|
||||
if !ValidRequirement(r) || metrics[r.Metric] {
|
||||
return fmt.Errorf("invalid or repeated metric in requirement set %q", set.ID)
|
||||
}
|
||||
metrics[r.Metric] = true
|
||||
}
|
||||
}
|
||||
seen = map[string]bool{}
|
||||
for _, set := range c.EffectSets {
|
||||
if !validSetIdentity(set.ID, set.Name, set.Description) || seen[set.ID] || len(set.Modifiers) < 1 {
|
||||
return fmt.Errorf("invalid or duplicate effect set %q", set.ID)
|
||||
}
|
||||
seen[set.ID] = true
|
||||
if err := ValidateModifiers(set.Modifiers); err != nil {
|
||||
return fmt.Errorf("effect set %q: %w", set.ID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResolveSets is also used by publication previews. References cannot recurse:
|
||||
// sets contain only concrete predicates/modifiers, never other set references.
|
||||
func (c Catalog) ResolveSets(requirements, effects []string) ([]TitleRequirement, []StatModifier, error) {
|
||||
if len(requirements) > 8 || len(effects) > 8 {
|
||||
return nil, nil, fmt.Errorf("choose at most eight sets of each kind")
|
||||
}
|
||||
var req []TitleRequirement
|
||||
var mods []StatModifier
|
||||
seen := map[string]bool{}
|
||||
for _, id := range requirements {
|
||||
if seen[id] {
|
||||
return nil, nil, fmt.Errorf("repeated requirement set %q", id)
|
||||
}
|
||||
seen[id] = true
|
||||
index := slices.IndexFunc(c.RequirementSets, func(s RequirementSet) bool { return s.ID == id })
|
||||
if index < 0 {
|
||||
return nil, nil, fmt.Errorf("unknown requirement set %q", id)
|
||||
}
|
||||
req = append(req, c.RequirementSets[index].Requirements...)
|
||||
}
|
||||
seen = map[string]bool{}
|
||||
for _, id := range effects {
|
||||
if seen[id] {
|
||||
return nil, nil, fmt.Errorf("repeated effect set %q", id)
|
||||
}
|
||||
seen[id] = true
|
||||
index := slices.IndexFunc(c.EffectSets, func(s EffectSet) bool { return s.ID == id })
|
||||
if index < 0 {
|
||||
return nil, nil, fmt.Errorf("unknown effect set %q", id)
|
||||
}
|
||||
mods = append(mods, c.EffectSets[index].Modifiers...)
|
||||
}
|
||||
return req, mods, nil
|
||||
}
|
||||
@@ -52,7 +52,6 @@ func (b Balance) validateProgression() error {
|
||||
return fmt.Errorf("too many title definitions")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
metrics := map[string]bool{"level": true, "kills": true, "worldKills": true, "bossKills": true, "worldsSurvived": true, "gathering": true, "crafting": true, "combat": true, "deaths": true}
|
||||
for _, title := range b.Titles {
|
||||
if !titleID.MatchString(title.ID) || seen[title.ID] || len(title.Name) < 1 || len(title.Name) > 80 || len(title.Description) > 500 {
|
||||
return fmt.Errorf("invalid or duplicate title %q", title.ID)
|
||||
@@ -65,7 +64,7 @@ func (b Balance) validateProgression() error {
|
||||
return fmt.Errorf("title %q needs bounded requirements", title.ID)
|
||||
}
|
||||
for _, r := range title.Requirements {
|
||||
if (!metrics[r.Metric] && !KnownStat(r.Metric)) || r.AtLeast < 1 || r.AtLeast > 1000000000 {
|
||||
if !ValidRequirement(r) {
|
||||
return fmt.Errorf("invalid title requirement for %q", title.ID)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,10 +44,12 @@ type ItemDefinition struct {
|
||||
Modifiers []StatModifier `json:"modifiers" yaml:"modifiers"`
|
||||
}
|
||||
type Catalog struct {
|
||||
Version int64 `json:"version"`
|
||||
Titles []Title `json:"titles"`
|
||||
Items []ItemDefinition `json:"items"`
|
||||
Stats StatsRules `json:"stats"`
|
||||
Version int64 `json:"version"`
|
||||
Titles []Title `json:"titles"`
|
||||
Items []ItemDefinition `json:"items"`
|
||||
Stats StatsRules `json:"stats"`
|
||||
RequirementSets []RequirementSet `json:"requirementSets,omitempty"`
|
||||
EffectSets []EffectSet `json:"effectSets,omitempty"`
|
||||
}
|
||||
|
||||
func KnownStat(stat string) bool {
|
||||
@@ -120,6 +122,9 @@ func (item ItemDefinition) Validate() error {
|
||||
return ValidateModifiers(item.Modifiers)
|
||||
}
|
||||
func (c Catalog) Validate() error {
|
||||
if err := c.validateLibrary(); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Version < 1 || len(c.Items) > 512 {
|
||||
return fmt.Errorf("invalid catalog version or item count")
|
||||
}
|
||||
|
||||
@@ -2,8 +2,103 @@
|
||||
package protocol
|
||||
|
||||
type Protocol struct {
|
||||
Intent Intent `json:"intent"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
Catalog *ContentCatalog `json:"catalog,omitempty"`
|
||||
CatalogChange *ContentChange `json:"catalogChange,omitempty"`
|
||||
CatalogPreview *ContentPreview `json:"catalogPreview,omitempty"`
|
||||
Intent Intent `json:"intent"`
|
||||
Snapshot Snapshot `json:"snapshot"`
|
||||
}
|
||||
|
||||
type ContentCatalog struct {
|
||||
EffectSets []EffectSet `json:"effectSets,omitempty"`
|
||||
Items []ItemDefinition `json:"items"`
|
||||
RequirementSets []RequirementSet `json:"requirementSets,omitempty"`
|
||||
Stats ContentStatsRules `json:"stats"`
|
||||
Titles []TitleDefinition `json:"titles"`
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
|
||||
type EffectSet struct {
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type StatModifier struct {
|
||||
Flat float64 `json:"flat"`
|
||||
Percent float64 `json:"percent"`
|
||||
Stat string `json:"stat"`
|
||||
}
|
||||
|
||||
type ItemDefinition struct {
|
||||
Description string `json:"description"`
|
||||
DropChance float64 `json:"dropChance"`
|
||||
ID string `json:"id"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
Name string `json:"name"`
|
||||
Requirements ItemRequirements `json:"requirements"`
|
||||
Slot string `json:"slot"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type ItemRequirements struct {
|
||||
Level int64 `json:"level"`
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Titles []string `json:"titles"`
|
||||
}
|
||||
|
||||
type RequirementSet struct {
|
||||
Description string `json:"description"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Requirements []ContentRequirement `json:"requirements"`
|
||||
}
|
||||
|
||||
type ContentRequirement struct {
|
||||
AtLeast int64 `json:"atLeast"`
|
||||
Metric string `json:"metric"`
|
||||
}
|
||||
|
||||
type ContentStatsRules struct {
|
||||
Base map[string]float64 `json:"base"`
|
||||
Coefficients map[string]map[string]float64 `json:"coefficients"`
|
||||
Version int64 `json:"version"`
|
||||
}
|
||||
|
||||
type TitleDefinition struct {
|
||||
Description string `json:"description"`
|
||||
Effects TitleEffects `json:"effects"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Requirements []ContentRequirement `json:"requirements"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
type TitleEffects struct {
|
||||
Damage float64 `json:"damage"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
MoveSpeed float64 `json:"moveSpeed"`
|
||||
}
|
||||
|
||||
type ContentChange struct {
|
||||
EffectSet *EffectSet `json:"effectSet,omitempty"`
|
||||
EffectSetIDS []string `json:"effectSetIds,omitempty"`
|
||||
ExpectedVersion int64 `json:"expectedVersion"`
|
||||
ID string `json:"id"`
|
||||
Item *ItemDefinition `json:"item,omitempty"`
|
||||
Op string `json:"op"`
|
||||
Reason string `json:"reason"`
|
||||
RequirementSet *RequirementSet `json:"requirementSet,omitempty"`
|
||||
RequirementSetIDS []string `json:"requirementSetIds,omitempty"`
|
||||
Stats *ContentStatsRules `json:"stats,omitempty"`
|
||||
Title *TitleDefinition `json:"title,omitempty"`
|
||||
}
|
||||
|
||||
type ContentPreview struct {
|
||||
BasedOnVersion int64 `json:"basedOnVersion"`
|
||||
ProposedVersion int64 `json:"proposedVersion"`
|
||||
Resolved ContentChange `json:"resolved"`
|
||||
}
|
||||
|
||||
type Intent struct {
|
||||
@@ -94,18 +189,6 @@ type ItemInstance struct {
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type StatModifier struct {
|
||||
Flat float64 `json:"flat"`
|
||||
Percent float64 `json:"percent"`
|
||||
Stat string `json:"stat"`
|
||||
}
|
||||
|
||||
type ItemRequirements struct {
|
||||
Level int64 `json:"level"`
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Titles []string `json:"titles"`
|
||||
}
|
||||
|
||||
type StatValue struct {
|
||||
Base float64 `json:"base"`
|
||||
Final float64 `json:"final"`
|
||||
@@ -123,12 +206,6 @@ type TitleAward struct {
|
||||
WorldID string `json:"worldId"`
|
||||
}
|
||||
|
||||
type TitleEffects struct {
|
||||
Damage float64 `json:"damage"`
|
||||
Modifiers []StatModifier `json:"modifiers"`
|
||||
MoveSpeed float64 `json:"moveSpeed"`
|
||||
}
|
||||
|
||||
type WorldInfo struct {
|
||||
AgeSeconds float64 `json:"ageSeconds"`
|
||||
BossHP float64 `json:"bossHp"`
|
||||
|
||||
@@ -17,13 +17,17 @@ 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"`
|
||||
RequirementSet *content.RequirementSet `json:"requirementSet,omitempty"`
|
||||
EffectSet *content.EffectSet `json:"effectSet,omitempty"`
|
||||
RequirementSetIDs []string `json:"requirementSetIds,omitempty"`
|
||||
EffectSetIDs []string `json:"effectSetIds,omitempty"`
|
||||
}
|
||||
type CatalogResult struct {
|
||||
Version int64 `json:"version"`
|
||||
@@ -110,6 +114,12 @@ func (c CatalogChange) validate() error {
|
||||
return fmt.Errorf("%w: request ID, current version and 5-240 character reason required", ErrCatalogInvalid)
|
||||
}
|
||||
valid := false
|
||||
count := 0
|
||||
for _, present := range []bool{c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} {
|
||||
if present {
|
||||
count++
|
||||
}
|
||||
}
|
||||
switch c.Op {
|
||||
case "create-title":
|
||||
valid = c.Title != nil && c.Item == nil && c.Stats == nil
|
||||
@@ -117,8 +127,12 @@ func (c CatalogChange) validate() error {
|
||||
valid = c.Item != nil && c.Title == nil && c.Stats == nil
|
||||
case "update-stats":
|
||||
valid = c.Stats != nil && c.Title == nil && c.Item == nil
|
||||
case "create-requirement-set":
|
||||
valid = c.RequirementSet != nil
|
||||
case "create-effect-set":
|
||||
valid = c.EffectSet != nil
|
||||
}
|
||||
if !valid {
|
||||
if !valid || count != 1 || ((c.Op != "create-title" && c.Op != "create-item") && (len(c.RequirementSetIDs) != 0 || len(c.EffectSetIDs) != 0)) {
|
||||
return fmt.Errorf("%w: operation must have exactly its matching payload", ErrCatalogInvalid)
|
||||
}
|
||||
return nil
|
||||
@@ -176,20 +190,9 @@ func (d *DB) PublishCatalog(ctx context.Context, actor string, change CatalogCha
|
||||
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)
|
||||
catalog, target, _, err := buildCatalog(catalog, change)
|
||||
if err != nil {
|
||||
return CatalogResult{}, err
|
||||
}
|
||||
encoded, err := json.Marshal(catalog)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLibraryPreviewPublicationAndRestart(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dsn := "file:" + filepath.ToSlash(filepath.Join(t.TempDir(), "library.db"))
|
||||
db, err := Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { db.Close() }()
|
||||
catalog, err := db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publish := func(c CatalogChange) CatalogResult {
|
||||
t.Helper()
|
||||
c.ID = game.ID()
|
||||
c.ExpectedVersion = catalog.Version
|
||||
c.Reason = "Library test publication"
|
||||
r, e := db.PublishCatalog(ctx, "operator", c)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
catalog, e = db.Catalog(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return r
|
||||
}
|
||||
publish(CatalogChange{Op: "create-requirement-set", RequirementSet: &content.RequirementSet{ID: "strong", Name: "Strong", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 3}, {Metric: "strength", AtLeast: 4}}}})
|
||||
publish(CatalogChange{Op: "create-effect-set", EffectSet: &content.EffectSet{ID: "sturdy", Name: "Sturdy", Modifiers: []content.StatModifier{{Stat: "strength", Flat: 2, Percent: 10}, {Stat: "moveSpeed", Percent: -5}}}})
|
||||
item := content.ItemDefinition{ID: "library_ring", Name: "Library ring", Slot: "ring", Weight: 1, Requirements: content.ItemRequirements{Level: 1, Stats: map[string]float64{"strength": 5}}, Modifiers: []content.StatModifier{{Stat: "strength", Flat: 1}}}
|
||||
change := CatalogChange{ID: game.ID(), ExpectedVersion: catalog.Version, Op: "create-item", Reason: "Publish composed item", Item: &item, RequirementSetIDs: []string{"strong"}, EffectSetIDs: []string{"sturdy"}}
|
||||
before, _ := json.Marshal(change)
|
||||
audits, err := db.CatalogChanges(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
preview, err := db.PreviewCatalog(ctx, change)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, _ := json.Marshal(change)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("preview mutated caller input")
|
||||
}
|
||||
unchanged, err := db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newAudits, err := db.CatalogChanges(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(catalog, unchanged) || len(audits) != len(newAudits) {
|
||||
t.Fatal("preview wrote catalog/audit")
|
||||
}
|
||||
resolved := preview.Resolved.Item
|
||||
if len(preview.Resolved.RequirementSetIDs) != 0 || len(preview.Resolved.EffectSetIDs) != 0 {
|
||||
t.Fatal("resolved preview would expand sets twice")
|
||||
}
|
||||
if resolved.Requirements.Level != 3 || resolved.Requirements.Stats["strength"] != 5 || len(resolved.Modifiers) != 3 {
|
||||
t.Fatalf("unexpected resolution: %+v", resolved)
|
||||
}
|
||||
result, err := db.PublishCatalog(ctx, "operator", change)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replay, err := db.PublishCatalog(ctx, "operator", change)
|
||||
if err != nil || replay != result {
|
||||
t.Fatal("replay failed", err)
|
||||
}
|
||||
if _, err = db.PreviewCatalog(ctx, change); !errors.Is(err, ErrCatalogConflict) {
|
||||
t.Fatal("stale preview accepted", err)
|
||||
}
|
||||
changed := change
|
||||
changed.EffectSetIDs = nil
|
||||
if _, err = db.PublishCatalog(ctx, "operator", changed); !errors.Is(err, ErrCatalogRequest) {
|
||||
t.Fatal("changed reference replay accepted", err)
|
||||
}
|
||||
catalog, err = db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(catalog.Items[len(catalog.Items)-1], *resolved) {
|
||||
t.Fatal("publication differs from preview")
|
||||
}
|
||||
// A set used without inline requirements also composes a real title.
|
||||
publish(CatalogChange{Op: "create-title", Title: &content.Title{ID: "library_title", Name: "Library title", Scope: "personal"}, RequirementSetIDs: []string{"strong"}, EffectSetIDs: []string{"sturdy"}})
|
||||
if len(catalog.Titles[len(catalog.Titles)-1].Requirements) != 2 {
|
||||
t.Fatal("title did not expand sets")
|
||||
}
|
||||
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 || !reflect.DeepEqual(catalog, restored) {
|
||||
t.Fatal("restart lost library or expanded definitions", err)
|
||||
}
|
||||
// Immutable set IDs cannot alter already published consumers.
|
||||
duplicate := CatalogChange{ID: game.ID(), ExpectedVersion: catalog.Version, Op: "create-effect-set", Reason: "Duplicate set test", EffectSet: &content.EffectSet{ID: "sturdy", Name: "Changed", Modifiers: []content.StatModifier{{Stat: "strength", Flat: 99}}}}
|
||||
if _, err = db.PublishCatalog(ctx, "operator", duplicate); !errors.Is(err, ErrCatalogInvalid) {
|
||||
t.Fatal("set overwrite accepted", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryRejectsInvalidCompositionWithoutWrites(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "invalid.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
initial, err := db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.PublishCatalog(ctx, "operator", CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Op: "create-requirement-set", Reason: "Title-only requirements", RequirementSet: &content.RequirementSet{ID: "slayer", Name: "Slayer", Requirements: []content.TitleRequirement{{Metric: "kills", AtLeast: 3}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
initial, err = db.Catalog(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, mutate := range map[string]func(*CatalogChange){
|
||||
"unknown reference": func(c *CatalogChange) { c.RequirementSetIDs = []string{"missing"} },
|
||||
"duplicate reference": func(c *CatalogChange) { c.RequirementSetIDs = []string{"slayer", "slayer"} },
|
||||
"title metric on equipment": func(c *CatalogChange) { c.RequirementSetIDs = []string{"slayer"} },
|
||||
"unknown effect": func(c *CatalogChange) { c.EffectSetIDs = []string{"missing"} },
|
||||
"mixed payload": func(c *CatalogChange) { c.EffectSet = &content.EffectSet{ID: "bad", Name: "Bad"} },
|
||||
"protected field": func(c *CatalogChange) {
|
||||
c.Op = "create-effect-set"
|
||||
c.Item = nil
|
||||
c.EffectSet = &content.EffectSet{ID: "bad", Name: "Bad", Modifiers: []content.StatModifier{{Stat: "dailySeconds", Flat: 100}}}
|
||||
},
|
||||
"empty set": func(c *CatalogChange) {
|
||||
c.Op = "create-effect-set"
|
||||
c.Item = nil
|
||||
c.EffectSet = &content.EffectSet{ID: "empty", Name: "Empty"}
|
||||
},
|
||||
"set recursion": func(c *CatalogChange) {
|
||||
c.Op = "create-requirement-set"
|
||||
c.Item = nil
|
||||
c.RequirementSetIDs = []string{"slayer"}
|
||||
c.RequirementSet = &content.RequirementSet{ID: "nested", Name: "Nested", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 1}}}
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c := CatalogChange{ID: game.ID(), ExpectedVersion: initial.Version, Op: "create-item", Reason: "Invalid composition test", Item: &content.ItemDefinition{ID: "invalid_ring", Name: "Ring", Slot: "ring", Requirements: content.ItemRequirements{Level: 1}}}
|
||||
mutate(&c)
|
||||
if _, err := db.PreviewCatalog(ctx, c); !errors.Is(err, ErrCatalogInvalid) {
|
||||
t.Fatal("invalid preview accepted", err)
|
||||
}
|
||||
if _, err := db.PublishCatalog(ctx, "operator", c); !errors.Is(err, ErrCatalogInvalid) {
|
||||
t.Fatal("invalid publication accepted", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
final, err := db.Catalog(ctx)
|
||||
if err != nil || !reflect.DeepEqual(initial, final) {
|
||||
t.Fatal("rejected changes wrote catalog", err)
|
||||
}
|
||||
audits, err := db.CatalogChanges(ctx)
|
||||
if err != nil || len(audits) != 1 {
|
||||
t.Fatal("rejected changes wrote audit", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CatalogPreview struct {
|
||||
BasedOnVersion int64 `json:"basedOnVersion"`
|
||||
ProposedVersion int64 `json:"proposedVersion"`
|
||||
Resolved CatalogChange `json:"resolved"`
|
||||
}
|
||||
|
||||
// Read-only. Publication repeats this exact validation under the catalog lock.
|
||||
func (d *DB) PreviewCatalog(ctx context.Context, change CatalogChange) (CatalogPreview, error) {
|
||||
change.Reason = strings.TrimSpace(change.Reason)
|
||||
if err := change.validate(); err != nil {
|
||||
return CatalogPreview{}, err
|
||||
}
|
||||
c, err := d.Catalog(ctx)
|
||||
if err != nil {
|
||||
return CatalogPreview{}, err
|
||||
}
|
||||
if c.Version != change.ExpectedVersion {
|
||||
return CatalogPreview{}, ErrCatalogConflict
|
||||
}
|
||||
next, _, resolved, err := buildCatalog(c, change)
|
||||
if err != nil {
|
||||
return CatalogPreview{}, err
|
||||
}
|
||||
return CatalogPreview{BasedOnVersion: c.Version, ProposedVersion: next.Version, Resolved: resolved}, nil
|
||||
}
|
||||
|
||||
func buildCatalog(c content.Catalog, change CatalogChange) (content.Catalog, string, CatalogChange, error) {
|
||||
invalid := func(err error) (content.Catalog, string, CatalogChange, error) {
|
||||
return content.Catalog{}, "", CatalogChange{}, fmt.Errorf("%w: %v", ErrCatalogInvalid, err)
|
||||
}
|
||||
req, mods, err := c.ResolveSets(change.RequirementSetIDs, change.EffectSetIDs)
|
||||
if err != nil {
|
||||
return invalid(err)
|
||||
}
|
||||
resolved := change
|
||||
// The preview is a concrete definition, not another request to expand its sets.
|
||||
resolved.RequirementSetIDs = nil
|
||||
resolved.EffectSetIDs = nil
|
||||
target := "stats"
|
||||
switch change.Op {
|
||||
case "create-title":
|
||||
title := *change.Title
|
||||
if len(title.Requirements) > 8 {
|
||||
return invalid(fmt.Errorf("at most eight inline requirements are allowed"))
|
||||
}
|
||||
// All thresholds are ANDed, so repeated metrics resolve to their maximum.
|
||||
title.Requirements = nil
|
||||
for _, r := range append(slices.Clone(change.Title.Requirements), req...) {
|
||||
if !content.ValidRequirement(r) {
|
||||
return invalid(fmt.Errorf("invalid requirement for %q", title.ID))
|
||||
}
|
||||
i := slices.IndexFunc(title.Requirements, func(v content.TitleRequirement) bool { return v.Metric == r.Metric })
|
||||
if i < 0 {
|
||||
title.Requirements = append(title.Requirements, r)
|
||||
} else if r.AtLeast > title.Requirements[i].AtLeast {
|
||||
title.Requirements[i] = r
|
||||
}
|
||||
}
|
||||
title.Effects.Modifiers = append(slices.Clone(title.Effects.Modifiers), mods...)
|
||||
resolved.Title = &title
|
||||
c.Titles = append(slices.Clone(c.Titles), title)
|
||||
target = title.ID
|
||||
case "create-item":
|
||||
item := *change.Item
|
||||
// Validate inline values before merging, so sets cannot mask invalid input.
|
||||
if err := item.Validate(); err != nil {
|
||||
return invalid(err)
|
||||
}
|
||||
item.Requirements.Stats = maps.Clone(item.Requirements.Stats)
|
||||
if item.Requirements.Stats == nil {
|
||||
item.Requirements.Stats = map[string]float64{}
|
||||
}
|
||||
for _, r := range req {
|
||||
if r.Metric == "level" {
|
||||
item.Requirements.Level = max(item.Requirements.Level, r.AtLeast)
|
||||
} else if content.KnownStat(r.Metric) {
|
||||
item.Requirements.Stats[r.Metric] = max(item.Requirements.Stats[r.Metric], float64(r.AtLeast))
|
||||
} else {
|
||||
return invalid(fmt.Errorf("equipment cannot use metric %q; use level/stat requirement sets", r.Metric))
|
||||
}
|
||||
}
|
||||
item.Modifiers = append(slices.Clone(item.Modifiers), mods...)
|
||||
resolved.Item = &item
|
||||
c.Items = append(slices.Clone(c.Items), item)
|
||||
target = item.ID
|
||||
case "update-stats":
|
||||
c.Stats = *change.Stats
|
||||
case "create-requirement-set":
|
||||
c.RequirementSets = append(slices.Clone(c.RequirementSets), *change.RequirementSet)
|
||||
target = change.RequirementSet.ID
|
||||
case "create-effect-set":
|
||||
c.EffectSets = append(slices.Clone(c.EffectSets), *change.EffectSet)
|
||||
target = change.EffectSet.ID
|
||||
}
|
||||
c.Version++
|
||||
if err := c.Validate(); err != nil {
|
||||
return invalid(err)
|
||||
}
|
||||
return c, target, resolved, nil
|
||||
}
|
||||
@@ -29,38 +29,46 @@ func (h *HTTP) catalogRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
for _, path := range []string{"/api/control/catalog", "/api/control/catalog/preview"} {
|
||||
mux.HandleFunc("POST "+path, 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()
|
||||
var result any
|
||||
var err error
|
||||
if r.URL.Path == "/api/control/catalog/preview" {
|
||||
result, err = h.auth.db.PreviewCatalog(ctx, change)
|
||||
} else {
|
||||
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.
|
||||
|
||||
@@ -65,15 +65,38 @@ func TestControlAuthorizationAndExecution(t *testing.T) {
|
||||
if request("GET", "/api/control", "", "", "") != 401 {
|
||||
t.Fatal("anonymous admin access")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", "{}", "", server.URL) != 401 {
|
||||
t.Fatal("anonymous preview access")
|
||||
}
|
||||
token := game.ID() + game.ID()
|
||||
_ = db.CreateSession(ctx, hash(token), "operator")
|
||||
if request("GET", "/api/control", "", token, "") != 403 {
|
||||
t.Fatal("player has admin access")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", "{}", token, server.URL) != 403 {
|
||||
t.Fatal("player preview access")
|
||||
}
|
||||
_ = db.GrantAdmin(ctx, hash(token), 600)
|
||||
if request("GET", "/api/control", "", token, "") != 200 {
|
||||
t.Fatal("admin denied")
|
||||
}
|
||||
previewBody := `{"id":"` + game.ID() + `","expectedVersion":1,"op":"create-effect-set","reason":"Preview effects","effectSet":{"id":"test_effect","name":"Test effect","description":"","modifiers":[{"stat":"strength","flat":2,"percent":0}]}}`
|
||||
if request("POST", "/api/control/catalog/preview", previewBody, token, "https://evil.example") != 403 {
|
||||
t.Fatal("cross-origin preview")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", previewBody, token, server.URL) != 200 {
|
||||
t.Fatal("valid preview rejected")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", strings.Replace(previewBody, `"flat":2`, `"flat":2,"script":"bad"`, 1), token, server.URL) != 400 {
|
||||
t.Fatal("unknown nested field accepted")
|
||||
}
|
||||
if request("POST", "/api/control/catalog/preview", previewBody+` {}`, token, server.URL) != 400 {
|
||||
t.Fatal("trailing JSON accepted")
|
||||
}
|
||||
previewCatalog, err := db.Catalog(ctx)
|
||||
if err != nil || previewCatalog.Version != 1 || len(previewCatalog.EffectSets) != 0 {
|
||||
t.Fatal("preview changed catalog", err)
|
||||
}
|
||||
body := `{"id":"` + game.ID() + `","worldId":"control-test","op":"close-admissions","reason":"maintenance window"}`
|
||||
if request("POST", "/api/control/commands", body, token, "https://evil.example") != 403 {
|
||||
t.Fatal("cross-origin admin command")
|
||||
|
||||
Reference in New Issue
Block a user