96 lines
2.6 KiB
Go
96 lines
2.6 KiB
Go
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)
|
|
}
|
|
}
|