114 lines
6.8 KiB
Go
114 lines
6.8 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"regexp"
|
|
"strings"
|
|
"aeternalis/server/content"
|
|
)
|
|
|
|
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"`
|
|
}
|
|
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"`
|
|
}
|
|
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")}
|
|
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 !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) 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()
|
|
}
|