350 lines
13 KiB
Go
350 lines
13 KiB
Go
package store
|
|
|
|
import (
|
|
"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 {
|
|
Visual *content.VisualPreset `json:"visual,omitempty"`
|
|
Building *content.BuildingDefinition `json:"building,omitempty"`
|
|
Power *content.PowerDefinition `json:"power,omitempty"`
|
|
Weapon *content.GatheringSkill `json:"weapon,omitempty"`
|
|
CraftRecipe *content.CraftRecipe `json:"craftRecipe,omitempty"`
|
|
CraftProfession *content.GatheringSkill `json:"craftProfession,omitempty"`
|
|
CraftMaterial *content.CraftMaterial `json:"craftMaterial,omitempty"`
|
|
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"`
|
|
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"`
|
|
ID string `json:"id"`
|
|
}
|
|
|
|
// 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 {
|
|
if c.Visual != nil && c.Visual.ID != "" {
|
|
return true
|
|
}
|
|
return (c.Building != nil && c.Building.ID != "") || (c.Power != nil && c.Power.ID != "") || (c.Weapon != nil && c.Weapon.ID != "") || (c.CraftRecipe != nil && c.CraftRecipe.ID != "") || (c.CraftProfession != nil && c.CraftProfession.ID != "") || (c.CraftMaterial != nil && c.CraftMaterial.ID != "") || (c.Attack != nil && c.Attack.ID != "") || (c.Mob != nil && c.Mob.ID != "") || (c.Loot != nil && c.Loot.ID != "") || (c.Spawn != nil && c.Spawn.ID != "") || (c.GatheringSkill != nil && c.GatheringSkill.ID != "") || (c.Resource != nil && c.Resource.ID != "") || (c.Biome != nil && c.Biome.ID != "") || (c.Consumable != nil && c.Consumable.ID != "") || (c.Title != nil && c.Title.ID != "") || (c.Item != nil && c.Item.ID != "") || (c.RequirementSet != nil && c.RequirementSet.ID != "") || (c.EffectSet != nil && c.EffectSet.ID != "")
|
|
}
|
|
|
|
type CatalogAudit struct {
|
|
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()
|
|
}
|
|
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")
|
|
}
|
|
if catalog.Gathering == nil {
|
|
b, err := content.Load()
|
|
if err != nil {
|
|
return catalog, err
|
|
}
|
|
catalog.Gathering = b.Gathering
|
|
}
|
|
if catalog.Combat == nil {
|
|
b, e := content.Load()
|
|
if e != nil {
|
|
return catalog, e
|
|
}
|
|
catalog.Combat = b.Combat
|
|
}
|
|
if catalog.Crafting == nil {
|
|
defaults, e := content.Load()
|
|
if e != nil {
|
|
return catalog, e
|
|
}
|
|
catalog.RestoreCrafting(defaults)
|
|
}
|
|
if catalog.Powers == nil {
|
|
b, e := content.Load()
|
|
if e != nil {
|
|
return catalog, e
|
|
}
|
|
catalog.RestorePowers(b)
|
|
}
|
|
if catalog.Building == nil {
|
|
b, e := content.Load()
|
|
if e != nil {
|
|
return catalog, e
|
|
}
|
|
catalog.RestoreBuilding(b)
|
|
}
|
|
if catalog.HousingVersion == 0 {
|
|
b, e := content.Load()
|
|
if e != nil {
|
|
return catalog, e
|
|
}
|
|
catalog.RestoreFurniture(b)
|
|
}
|
|
if catalog.Powers != nil {
|
|
for i := range catalog.Powers.Powers {
|
|
d := &catalog.Powers.Powers[i]
|
|
if d.Kind == "ability" && d.MaxLevel == 1 {
|
|
d.MaxLevel = 1000
|
|
}
|
|
}
|
|
}
|
|
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) 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 (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) || (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 {
|
|
return fmt.Errorf("%w: request ID, current version and 5-240 character reason required", ErrCatalogInvalid)
|
|
}
|
|
valid := false
|
|
count := 0
|
|
if c.Visual != nil {
|
|
count++
|
|
}
|
|
for _, present := range []bool{c.Building != nil, c.Power != nil, c.Weapon != nil, c.CraftRecipe != nil, c.CraftProfession != nil, c.CraftMaterial != nil, c.CraftRules != nil, c.Attack != nil, c.Mob != nil, c.Loot != nil, c.Spawn != nil, c.GatheringSkill != nil, c.Resource != nil, c.Biome != nil, c.Consumable != nil, c.Title != nil, c.Item != nil, c.Stats != nil, c.RequirementSet != nil, c.EffectSet != nil} {
|
|
if present {
|
|
count++
|
|
}
|
|
}
|
|
switch c.Op {
|
|
case "create-visual":
|
|
valid = c.Visual != nil
|
|
case "create-building":
|
|
valid = c.Building != nil
|
|
case "create-power":
|
|
valid = c.Power != nil
|
|
case "create-weapon":
|
|
valid = c.Weapon != nil
|
|
case "create-craft-recipe", "update-craft-recipe":
|
|
valid = c.CraftRecipe != nil
|
|
case "create-craft-profession":
|
|
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":
|
|
valid = c.Mob != nil
|
|
case "create-loot":
|
|
valid = c.Loot != nil
|
|
case "create-spawn":
|
|
valid = c.Spawn != nil
|
|
case "create-gathering-skill":
|
|
valid = c.GatheringSkill != nil
|
|
case "create-resource":
|
|
valid = c.Resource != nil
|
|
case "create-biome":
|
|
valid = c.Biome != nil
|
|
case "update-biome":
|
|
valid = c.Biome != nil && c.Biome.ID == ""
|
|
case "create-consumable":
|
|
valid = c.Consumable != nil
|
|
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
|
|
case "create-requirement-set":
|
|
valid = c.RequirementSet != nil
|
|
case "create-effect-set":
|
|
valid = c.EffectSet != nil
|
|
}
|
|
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
|
|
}
|
|
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,target FROM catalog_changes WHERE id=?`), change.ID).Scan(&previousActor, &previousRequest, &result.Version, &result.ID)
|
|
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
|
|
}
|
|
catalog, target, _, err := buildCatalog(catalog, change)
|
|
if err != nil {
|
|
return CatalogResult{}, 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, ID: target}, 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()
|
|
}
|