Add playable hub travel with durable character transfers
This commit is contained in:
@@ -96,7 +96,15 @@ func run() error {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
kind := env("WORLD_KIND", "survival")
|
||||
if kind != "survival" && kind != "hub" {
|
||||
return errors.New("WORLD_KIND must be survival or hub")
|
||||
}
|
||||
w := game.New(id, seed, time.Now().UTC(), b)
|
||||
w.Kind = kind
|
||||
if kind == "hub" {
|
||||
w.Phase = "hub"
|
||||
}
|
||||
lease, raw, err := db.Acquire(ctx, w)
|
||||
if err != nil {
|
||||
return fmt.Errorf("acquire world: %w", err)
|
||||
@@ -109,10 +117,8 @@ func run() error {
|
||||
_ = lease.Release(ctx)
|
||||
}
|
||||
}()
|
||||
if err = json.Unmarshal(raw, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = w.Restore(time.Now().UTC()); err != nil {
|
||||
w, err = restoreInstance(raw, kind, time.Now().UTC())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
auth, err := transport.NewAuth(ctx, db, dev, base, os.Getenv("OIDC_ISSUER"), os.Getenv("OIDC_CLIENT_ID"), os.Getenv("OIDC_CLIENT_SECRET"))
|
||||
@@ -175,3 +181,22 @@ func main() {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func restoreInstance(raw []byte, kind string, now time.Time) (*game.World, error) {
|
||||
var w game.World
|
||||
if err := json.Unmarshal(raw, &w); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// An older image can initialize a new hub ID during image promotion. Only an
|
||||
// untyped, unused legacy instance may adopt its configured hub kind.
|
||||
if w.Kind == "" && kind == "hub" && w.Phase == "gathering" && w.EndedAt == nil && len(w.Characters) == 0 && len(w.Corpses) == 0 {
|
||||
w.Kind = "hub"
|
||||
}
|
||||
if err := w.Restore(now); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if w.Kind != kind {
|
||||
return nil, errors.New("WORLD_KIND does not match saved world; use a new world ID")
|
||||
}
|
||||
return &w, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestInstanceKindRestore(t *testing.T) {
|
||||
b, _ := content.Load()
|
||||
now := time.Now()
|
||||
w := game.New("legacy", 1, now, b)
|
||||
w.Kind = ""
|
||||
raw, _ := json.Marshal(w)
|
||||
if restored, err := restoreInstance(raw, "survival", now); err != nil || restored.Kind != "survival" {
|
||||
t.Fatal("legacy survival restore", err)
|
||||
}
|
||||
if restored, err := restoreInstance(raw, "hub", now); err != nil || restored.Kind != "hub" || restored.Phase != "hub" {
|
||||
t.Fatal("empty hub bootstrap", err)
|
||||
}
|
||||
c, _ := w.Join("account", "Traveler")
|
||||
raw, _ = json.Marshal(w)
|
||||
if _, err := restoreInstance(raw, "hub", now); err == nil {
|
||||
t.Fatal("converted a populated legacy survival world to hub")
|
||||
}
|
||||
c.View.Entity.State = "dead"
|
||||
raw, _ = json.Marshal(w)
|
||||
if _, err := restoreInstance(raw, "hub", now); err == nil {
|
||||
t.Fatal("converted a world with character history")
|
||||
}
|
||||
w = game.New("typed", 2, now, b)
|
||||
raw, _ = json.Marshal(w)
|
||||
if _, err := restoreInstance(raw, "hub", now); err == nil {
|
||||
t.Fatal("changed existing typed instance kind")
|
||||
}
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
raw, _ = json.Marshal(w)
|
||||
if _, err := restoreInstance(raw, "survival", now); err == nil {
|
||||
t.Fatal("changed hub to survival")
|
||||
}
|
||||
}
|
||||
@@ -129,7 +129,7 @@ func (c Catalog) validateCombat() error {
|
||||
attacks[a.ID] = true
|
||||
}
|
||||
items := map[string]bool{}
|
||||
for _, id := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"} {
|
||||
for _, id := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage", "escape_stone"} {
|
||||
items[id] = true
|
||||
}
|
||||
for _, i := range c.Items {
|
||||
|
||||
@@ -42,7 +42,7 @@ func (w *World) AdminItems(c *Character, op, value string) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage"} {
|
||||
for _, key := range []string{"axe", "flint_and_steel", "fishing_pole", "wood", "ore", "herb", "bandage", "escape_stone"} {
|
||||
if key == id {
|
||||
known = true
|
||||
}
|
||||
|
||||
@@ -13,6 +13,11 @@ import (
|
||||
// Read-only arrival preview uses the world's generator and any explored layout.
|
||||
func (w *World) PreviewChunk(x, z int) p.Chunk {
|
||||
c := w.terrain.Chunk(x, z)
|
||||
if w.IsHub() {
|
||||
c.Resources = []p.Entity{}
|
||||
c.Biome = "Survivor haven"
|
||||
return c
|
||||
}
|
||||
if layout, ok := w.ResourceLayouts[c.Key]; ok {
|
||||
c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources
|
||||
}
|
||||
|
||||
@@ -101,6 +101,9 @@ func (w *World) terrainHit(a, b p.Vec3) (p.Vec3, bool) {
|
||||
return b, false
|
||||
}
|
||||
func (w *World) attack(c *Character, target string) error {
|
||||
if !w.AllowsXP() {
|
||||
return errors.New("combat is unavailable here")
|
||||
}
|
||||
a := w.playerAttack(c)
|
||||
if w.Age() < c.AttackReadyAt || w.Age()-c.LastAttack < a.Cooldown {
|
||||
return errors.New("attack cooldown")
|
||||
|
||||
@@ -160,6 +160,9 @@ func (w *World) gatherRisk(c *Character, r content.ResourceDefinition) p.Gatheri
|
||||
return risk
|
||||
}
|
||||
func (w *World) gather(c *Character, target string) error {
|
||||
if w.IsHub() {
|
||||
return errors.New("gathering is unavailable in the hub")
|
||||
}
|
||||
if until := w.Depleted[target]; until > w.Age() {
|
||||
return errors.New("resource depleted")
|
||||
}
|
||||
|
||||
@@ -59,6 +59,9 @@ func (w *World) newMob(id string, d content.MobDefinition, pos p.Vec3, respawn f
|
||||
return m
|
||||
}
|
||||
func (w *World) SpawnMobs(definition, value string) error {
|
||||
if w.IsHub() {
|
||||
return errors.New("combat is unavailable in the hub")
|
||||
}
|
||||
if w.Phase == "won" || w.Phase == "lost" {
|
||||
return errors.New("world has ended")
|
||||
}
|
||||
|
||||
@@ -89,6 +89,9 @@ func (c *Character) nextLevelXP() int64 {
|
||||
}
|
||||
|
||||
func (w *World) grantXP(c *Character, amount int64) {
|
||||
if !w.AllowsXP() {
|
||||
return
|
||||
}
|
||||
if amount <= 0 || c.View.Entity.State != "alive" || c.View.Level >= c.Progression.MaxLevel {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"errors"
|
||||
)
|
||||
|
||||
func (w *World) IsHub() bool { return w.Kind == "hub" }
|
||||
func (w *World) AllowsXP() bool {
|
||||
return w.Kind == "survival" && (w.Phase == "gathering" || w.Phase == "cataclysm")
|
||||
}
|
||||
func (w *World) PortalPosition() p.Vec3 { return w.terrain.Position(0, 0) }
|
||||
|
||||
// Escape is an explicit one-item action. It grants no victory/survival credit.
|
||||
func (w *World) Departure(c *Character, route string) error {
|
||||
if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") {
|
||||
return errors.New("character cannot travel")
|
||||
}
|
||||
if w.IsHub() {
|
||||
if route != "hub" {
|
||||
return errors.New("choose hub travel")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if w.Phase == "won" && c.View.Entity.State == "eligible" {
|
||||
if route != "portal" || distance(c.View.Entity.Position, w.PortalPosition()) > w.Balance.GatherRange {
|
||||
return errors.New("stand next to the victory portal")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if w.Phase != "gathering" && w.Phase != "cataclysm" {
|
||||
return errors.New("world is no longer available")
|
||||
}
|
||||
if route != "escape" || c.View.Inventory["escape_stone"] < 1 {
|
||||
return errors.New("an escape stone is required before victory")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Transfers arrive as the same life. Import retains progression, inventory and
|
||||
// daily usage; its resets apply only to instance-local movement/cooldowns.
|
||||
func (w *World) Arrive(c *Character) error {
|
||||
if c.View.Entity.HP <= 0 || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") {
|
||||
return errors.New("only living characters can arrive")
|
||||
}
|
||||
if old := w.Characters[c.View.Entity.ID]; old != nil {
|
||||
if old.View.Entity.State != "eligible" || old.Online {
|
||||
return errors.New("character already present")
|
||||
}
|
||||
delete(w.Characters, c.View.Entity.ID) // Historical legacy passage copy.
|
||||
}
|
||||
c.View.Entity.State = "eligible"
|
||||
return w.Import(c)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
p "aeternalis/server/internal/protocol"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHubRulesAndDailyLimit(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
w.Kind = "hub"
|
||||
w.Phase = "hub"
|
||||
if _, err := w.Join("new", "New"); err == nil {
|
||||
t.Fatal("new life began in hub")
|
||||
}
|
||||
c.View.Inventory["herb"] = 4
|
||||
xp, craft := c.View.Experience, c.View.Skills["crafting"]
|
||||
if err := w.craft(c, "bandage"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.grantXP(c, 1000)
|
||||
if c.View.Inventory["herb"] != 2 || c.View.Inventory["bandage"] < 1 || c.View.Experience != xp || c.View.Skills["crafting"] != craft {
|
||||
t.Fatal("hub crafting must spend resources without granting XP")
|
||||
}
|
||||
if w.attack(c, "boss") == nil || w.gather(c, "tree") == nil || w.TriggerBoss() == nil || w.Control("end-world", "", "", "test") == nil || w.SpawnMobs("", "") == nil {
|
||||
t.Fatal("hub allowed combat, gathering or destruction")
|
||||
}
|
||||
w.Advance(w.CreatedAt.Add(30*24*time.Hour), .05)
|
||||
if w.Phase != "hub" || len(w.Mobs) != 0 {
|
||||
t.Fatal("hub decayed or spawned mobs")
|
||||
}
|
||||
for _, chunk := range w.Snapshot(c.View.Entity.ID, nil).Chunks {
|
||||
if len(chunk.Resources) != 0 {
|
||||
t.Fatal("hub spawned gathering resources")
|
||||
}
|
||||
}
|
||||
w.Balance.DailyPlaySeconds = 1
|
||||
w.Advance(w.now.Add(2*time.Second), 2)
|
||||
if c.Online || c.View.RemainingSeconds != 0 {
|
||||
t.Fatal("hub bypassed daily time cap")
|
||||
}
|
||||
if w.Departure(c, "hub") == nil {
|
||||
t.Fatal("capped character traveled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVictoryPortalAndTravelEligibility(t *testing.T) {
|
||||
w, c := fixture(t)
|
||||
if w.Departure(c, "escape") == nil {
|
||||
t.Fatal("escaped without item")
|
||||
}
|
||||
c.View.Inventory["escape_stone"] = 1
|
||||
if e := w.Departure(c, "escape"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c.Online = false
|
||||
if w.Departure(c, "escape") == nil {
|
||||
t.Fatal("offline escape")
|
||||
}
|
||||
c.Online = true
|
||||
c.Sheltered = true
|
||||
if w.Departure(c, "escape") == nil {
|
||||
t.Fatal("sheltered escape")
|
||||
}
|
||||
c.Sheltered = false
|
||||
c.View.Entity.State = "dead"
|
||||
if w.Departure(c, "escape") == nil {
|
||||
t.Fatal("dead character escaped")
|
||||
}
|
||||
c.View.Entity.State = "alive"
|
||||
w.Phase = "cataclysm"
|
||||
w.damageBoss(c, w.BossHP)
|
||||
c.View.Entity.Position = w.terrain.Position(100, 100)
|
||||
if w.Departure(c, "portal") == nil {
|
||||
t.Fatal("remote portal use")
|
||||
}
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 1, X: 1}); err != nil {
|
||||
t.Fatal("survivor cannot walk to portal", err)
|
||||
}
|
||||
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 2, Target: "boss"}); err == nil {
|
||||
t.Fatal("combat continued after victory")
|
||||
}
|
||||
c.View.Entity.Position = w.PortalPosition()
|
||||
if e := w.Departure(c, "portal"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
found := false
|
||||
for _, entity := range w.Snapshot(c.View.Entity.ID, nil).Entities {
|
||||
if entity.Kind == "portal" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("victory portal missing from snapshot")
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
var restored World
|
||||
if e := json.Unmarshal(raw, &restored); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := restored.Restore(w.now); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
rc := restored.Characters[c.View.Entity.ID]
|
||||
if e := restored.Connect(rc.View.Entity.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := restored.Departure(rc, "portal"); e != nil {
|
||||
t.Fatal("portal was not preserved across restart", e)
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,7 @@ type ResourceLayout struct {
|
||||
Resources []p.Entity `json:"resources"`
|
||||
}
|
||||
type World struct {
|
||||
Kind string `json:"kind,omitempty"`
|
||||
ProjectileVisuals []p.ProjectileVisual `json:"projectileVisuals,omitempty"`
|
||||
Projectiles map[string]*Projectile `json:"projectiles,omitempty"`
|
||||
Areas map[string]*CombatArea `json:"areas,omitempty"`
|
||||
@@ -114,6 +115,15 @@ func New(id string, seed int64, now time.Time, b content.Balance) *World {
|
||||
return w
|
||||
}
|
||||
func (w *World) Restore(now time.Time) error {
|
||||
if w.Kind == "" {
|
||||
w.Kind = "survival"
|
||||
}
|
||||
if w.Kind != "" && w.Kind != "survival" && w.Kind != "hub" {
|
||||
return errors.New("unknown instance kind")
|
||||
}
|
||||
if w.IsHub() {
|
||||
w.Phase = "hub"
|
||||
}
|
||||
if w.Version != 1 && w.Version != GeneratorVersion {
|
||||
return errors.New("unsupported persisted generator version")
|
||||
}
|
||||
@@ -233,6 +243,9 @@ func (w *World) Age() float64 {
|
||||
func (w *World) Dirty() bool { return w.dirty }
|
||||
func (w *World) Saved() { w.dirty = false }
|
||||
func (w *World) SafeRadius() float64 {
|
||||
if w.IsHub() {
|
||||
return w.Balance.WorldRadius
|
||||
}
|
||||
if w.Phase == "gathering" {
|
||||
return w.Balance.WorldRadius
|
||||
}
|
||||
@@ -248,7 +261,7 @@ func (w *World) Info() p.WorldInfo {
|
||||
online++
|
||||
}
|
||||
}
|
||||
return p.WorldInfo{ID: w.ID, Seed: w.Seed, Phase: w.Phase, AgeSeconds: w.Age(), BossInSeconds: math.Max(0, w.Balance.SeasonSeconds-w.Age()), CollapseInSeconds: math.Max(0, w.Balance.SeasonSeconds+w.Balance.CollapseSeconds-w.Age()), SafeRadius: w.SafeRadius(), Radius: w.Balance.WorldRadius, Online: online, Capacity: int64(w.Balance.MaxPlayers), BossHP: w.BossHP, BossMaxHP: w.Balance.BossHp}
|
||||
return p.WorldInfo{Kind: stringPtr(w.Kind), ID: w.ID, Seed: w.Seed, Phase: w.Phase, AgeSeconds: w.Age(), BossInSeconds: math.Max(0, w.Balance.SeasonSeconds-w.Age()), CollapseInSeconds: math.Max(0, w.Balance.SeasonSeconds+w.Balance.CollapseSeconds-w.Age()), SafeRadius: w.SafeRadius(), Radius: w.Balance.WorldRadius, Online: online, Capacity: int64(w.Balance.MaxPlayers), BossHP: w.BossHP, BossMaxHP: w.Balance.BossHp}
|
||||
}
|
||||
func (w *World) ForAccount(account string) *Character {
|
||||
for _, c := range w.Characters {
|
||||
@@ -289,6 +302,9 @@ func (w *World) spawn(exclude string) (p.Vec3, error) {
|
||||
return p.Vec3{}, errors.New("no separated spawn available")
|
||||
}
|
||||
func (w *World) Join(account, name string) (*Character, error) {
|
||||
if w.IsHub() {
|
||||
return nil, errors.New("new characters must begin in a survival world")
|
||||
}
|
||||
if c := w.ForAccount(account); c != nil {
|
||||
return c, nil
|
||||
}
|
||||
@@ -325,7 +341,7 @@ func (w *World) Join(account, name string) (*Character, error) {
|
||||
return c, nil
|
||||
}
|
||||
func (w *World) Import(c *Character) error {
|
||||
if w.Phase != "gathering" || w.AdmissionsClosed || w.ForAccount(c.Account) != nil || w.Characters[c.View.Entity.ID] != nil || w.LivingCount() >= w.Balance.MaxPlayers {
|
||||
if (w.Phase != "gathering" && w.Phase != "cataclysm" && !w.IsHub()) || w.AdmissionsClosed || w.ForAccount(c.Account) != nil || w.Characters[c.View.Entity.ID] != nil || w.LivingCount() >= w.Balance.MaxPlayers {
|
||||
return errors.New("destination cannot accept character")
|
||||
}
|
||||
if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 {
|
||||
@@ -414,6 +430,12 @@ func (w *World) chunk(x, z int) p.Chunk {
|
||||
return c
|
||||
}
|
||||
c := w.terrain.Chunk(x, z)
|
||||
if w.IsHub() {
|
||||
c.Resources = []p.Entity{}
|
||||
c.Biome = "Survivor haven"
|
||||
w.chunks[key] = c
|
||||
return c
|
||||
}
|
||||
if layout, ok := w.ResourceLayouts[key]; ok {
|
||||
c.Biome, c.Color, c.Resources = layout.Biome, layout.Color, layout.Resources
|
||||
} else {
|
||||
@@ -435,7 +457,7 @@ func (w *World) neighbors(pos p.Vec3) []p.Chunk {
|
||||
}
|
||||
func (w *World) Intent(id string, i p.Intent) error {
|
||||
c := w.Characters[id]
|
||||
if c == nil || !c.Online || c.View.Entity.State != "alive" || w.Phase == "won" || w.Phase == "lost" {
|
||||
if c == nil || !c.Online || (c.View.Entity.State != "alive" && c.View.Entity.State != "eligible") || w.Phase == "lost" {
|
||||
return errors.New("character cannot act")
|
||||
}
|
||||
if i.Seq <= c.View.ACK || i.Seq > c.View.ACK+10000 {
|
||||
@@ -449,6 +471,12 @@ func (w *World) Intent(id string, i p.Intent) error {
|
||||
c.Sheltered = false
|
||||
w.dirty = true
|
||||
}
|
||||
if w.Phase == "won" && i.Op != "move" && i.Op != "jump" && i.Op != "return" {
|
||||
return errors.New("use the victory portal to continue")
|
||||
}
|
||||
if w.IsHub() && (i.Op == "attack" || i.Op == "gather") {
|
||||
return errors.New("combat and gathering are unavailable in the hub")
|
||||
}
|
||||
switch i.Op {
|
||||
case "allocate-stat":
|
||||
return w.allocateStat(c, i.Target)
|
||||
@@ -525,7 +553,9 @@ func (w *World) craft(c *Character, name string) error {
|
||||
}
|
||||
c.View.Inventory, c.View.Items = inventory, items
|
||||
w.RefreshStats(c)
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
if w.AllowsXP() {
|
||||
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
|
||||
}
|
||||
c.Message = "Crafted " + name
|
||||
w.grantXP(c, w.Balance.Progression.CraftXP)
|
||||
w.evaluateTitles(c)
|
||||
@@ -587,6 +617,9 @@ func (w *World) kill(c *Character, reason string) {
|
||||
|
||||
// Operator changes use the same simulation and persistence path as gameplay.
|
||||
func (w *World) Control(op, target, value, reason string) error {
|
||||
if w.IsHub() && (op == "end-world" || op == "awaken-boss" || op == "spawn-mobs") {
|
||||
return errors.New("hubs cannot be destroyed or host combat")
|
||||
}
|
||||
switch op {
|
||||
case "spawn-mobs":
|
||||
return w.SpawnMobs(target, value)
|
||||
@@ -645,9 +678,13 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
}
|
||||
w.ProjectileVisuals = kept
|
||||
dt = math.Max(0, math.Min(dt, 0.25))
|
||||
if w.Phase == "won" || w.Phase == "lost" {
|
||||
if w.Phase == "lost" {
|
||||
return
|
||||
}
|
||||
if w.Phase == "won" || w.IsHub() {
|
||||
clear(w.Projectiles)
|
||||
clear(w.Areas)
|
||||
}
|
||||
if w.Phase == "gathering" && w.Age() >= w.Balance.SeasonSeconds {
|
||||
w.Phase = "cataclysm"
|
||||
w.dirty = true
|
||||
@@ -655,7 +692,7 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
active := map[string]bool{}
|
||||
characters := w.orderedCharacters()
|
||||
for _, c := range characters {
|
||||
if c.View.Entity.State != "alive" {
|
||||
if c.View.Entity.State != "alive" && c.View.Entity.State != "eligible" {
|
||||
continue
|
||||
}
|
||||
w.resetDay(c)
|
||||
@@ -707,7 +744,9 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
w.moveCharacter(c, dt)
|
||||
for _, ch := range w.neighbors(c.View.Entity.Position) {
|
||||
active[ch.Key] = true
|
||||
w.ensureMob(ch)
|
||||
if !w.IsHub() && w.Phase != "won" {
|
||||
w.ensureMob(ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
if w.Phase == "cataclysm" && math.Hypot(c.View.Entity.Position.X, c.View.Entity.Position.Z) > w.SafeRadius() {
|
||||
@@ -718,8 +757,10 @@ func (w *World) Advance(now time.Time, dt float64) {
|
||||
w.kill(c, "The encroaching ruin claimed this character.")
|
||||
}
|
||||
}
|
||||
w.updateMobs(active, dt)
|
||||
w.updateCombat(dt)
|
||||
if !w.IsHub() && w.Phase != "won" {
|
||||
w.updateMobs(active, dt)
|
||||
w.updateCombat(dt)
|
||||
}
|
||||
if w.Phase == "cataclysm" {
|
||||
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
|
||||
for _, c := range characters {
|
||||
@@ -818,7 +859,7 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot {
|
||||
}
|
||||
}
|
||||
for _, m := range w.Mobs {
|
||||
if m.Entity.HP > 0 && visible(m.Entity.Position) {
|
||||
if !w.IsHub() && w.Phase != "won" && m.Entity.HP > 0 && visible(m.Entity.Position) {
|
||||
s.Entities = append(s.Entities, m.Entity)
|
||||
}
|
||||
}
|
||||
@@ -841,10 +882,16 @@ func (w *World) Snapshot(id string, known map[string]bool) p.Snapshot {
|
||||
s.Entities = append(s.Entities, p.Entity{ID: area.ID, Kind: "area", Name: area.Attack.Name, Position: area.Position, State: area.Attack.Effect, Radius: &radius, HP: 1, MaxHP: 1})
|
||||
}
|
||||
}
|
||||
if w.Phase == "won" && visible(w.PortalPosition()) {
|
||||
s.Entities = append(s.Entities, p.Entity{ID: "hub-portal", Kind: "portal", Name: "Portal to the hub", Position: w.PortalPosition(), HP: 1, MaxHP: 1, State: "open"})
|
||||
}
|
||||
sort.Slice(s.Entities, func(i, j int) bool { return s.Entities[i].ID < s.Entities[j].ID })
|
||||
return s
|
||||
}
|
||||
func (w *World) TriggerBoss() error {
|
||||
if w.IsHub() {
|
||||
return errors.New("hubs have no Harbinger")
|
||||
}
|
||||
if w.Phase != "gathering" {
|
||||
return fmt.Errorf("boss event already started")
|
||||
}
|
||||
|
||||
@@ -247,8 +247,11 @@ func TestBossVictoryAndCollapse(t *testing.T) {
|
||||
if c.View.Entity.State != "eligible" {
|
||||
t.Fatal("victory not terminal")
|
||||
}
|
||||
if w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 2, X: 1}) == nil {
|
||||
t.Fatal("survivor mutated frozen world")
|
||||
if w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 2, X: 1}) != nil {
|
||||
t.Fatal("survivor cannot walk to the victory portal")
|
||||
}
|
||||
if w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 3, Target: "boss"}) == nil {
|
||||
t.Fatal("combat continued after victory")
|
||||
}
|
||||
})
|
||||
t.Run("collapse kills offline and capped characters", func(t *testing.T) {
|
||||
|
||||
@@ -107,6 +107,12 @@ func scalar(v string) *yaml.Node { return &yaml.Node{Kind: yaml.ScalarNode, Tag:
|
||||
// Only the worlds sequence is changed; image pins, comments and runtime settings
|
||||
// stay intact. Gitea's content SHA rejects concurrent image-promotion overwrites.
|
||||
func (c *Client) CreateWorld(ctx context.Context, id, seed string) (string, error) {
|
||||
return c.CreateInstance(ctx, id, seed, "survival")
|
||||
}
|
||||
func (c *Client) CreateInstance(ctx context.Context, id, seed, kind string) (string, error) {
|
||||
if kind != "hub" && kind != "survival" {
|
||||
return "", errors.New("invalid world kind")
|
||||
}
|
||||
if !identifier.MatchString(id) || !seedPattern.MatchString(seed) {
|
||||
return "", errors.New("invalid world ID or seed")
|
||||
}
|
||||
@@ -147,16 +153,20 @@ func (c *Client) CreateWorld(ctx context.Context, id, seed string) (string, erro
|
||||
key := mapping(world, "id")
|
||||
if key != nil && key.Value == id {
|
||||
existing := mapping(world, "seed")
|
||||
if existing != nil && existing.Value == seed {
|
||||
existingKind := "survival"
|
||||
if k := mapping(world, "kind"); k != nil {
|
||||
existingKind = k.Value
|
||||
}
|
||||
if existing != nil && existing.Value == seed && existingKind == kind {
|
||||
return "World definition already committed; waiting for ArgoCD readiness.", nil
|
||||
}
|
||||
return "", errors.New("world ID already exists with a different seed")
|
||||
return "", errors.New("world ID already exists with a different seed or kind")
|
||||
}
|
||||
}
|
||||
if len(worlds.Content) >= 50 {
|
||||
return "", errors.New("operator world limit reached (50)")
|
||||
}
|
||||
worlds.Content = append(worlds.Content, &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{scalar("id"), scalar(id), scalar("seed"), scalar(seed), scalar("host"), scalar(public.Host)}})
|
||||
worlds.Content = append(worlds.Content, &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map", Content: []*yaml.Node{scalar("id"), scalar(id), scalar("seed"), scalar(seed), scalar("host"), scalar(public.Host), scalar("kind"), scalar(kind)}})
|
||||
encoded, err := yaml.Marshal(&doc)
|
||||
if err != nil {
|
||||
return "", err
|
||||
|
||||
@@ -74,6 +74,15 @@ func TestCreateWorldPreservesValuesAndRetries(t *testing.T) {
|
||||
if _, err = c.CreateWorld(context.Background(), "../bad", "42"); err == nil {
|
||||
t.Fatal("invalid ID accepted")
|
||||
}
|
||||
if _, err = c.CreateInstance(context.Background(), "hub-001", "50", "hub"); err != nil || !strings.Contains(current, "kind: hub") {
|
||||
t.Fatal("hub definition missing", err, current)
|
||||
}
|
||||
if _, err = c.CreateInstance(context.Background(), "hub-001", "50", "hub"); err != nil || puts != 3 {
|
||||
t.Fatal("hub retry duplicated instance", err)
|
||||
}
|
||||
if _, err = c.CreateWorld(context.Background(), "hub-001", "50"); err == nil {
|
||||
t.Fatal("existing hub changed to survival world")
|
||||
}
|
||||
}
|
||||
func TestGitOpsConfigurationValidation(t *testing.T) {
|
||||
for _, repository := range []string{"http://example.test/o/r", "https://token@example.test/o/r", "https://example.test/only-one", "https://example.test/../repo"} {
|
||||
|
||||
@@ -549,6 +549,7 @@ type WorldInfo struct {
|
||||
Capacity int64 `json:"capacity"`
|
||||
CollapseInSeconds float64 `json:"collapseInSeconds"`
|
||||
ID string `json:"id"`
|
||||
Kind *string `json:"kind,omitempty"`
|
||||
Online int64 `json:"online"`
|
||||
Phase string `json:"phase"`
|
||||
Radius float64 `json:"radius"`
|
||||
|
||||
@@ -24,6 +24,7 @@ type CharacterRecord struct {
|
||||
Character *game.Character `json:"character"`
|
||||
}
|
||||
type WorldRecord struct {
|
||||
Kind string `json:"kind"`
|
||||
ID string `json:"id"`
|
||||
Phase string `json:"phase"`
|
||||
Living int `json:"living"`
|
||||
@@ -69,6 +70,9 @@ func (d *DB) migrate(ctx context.Context) error {
|
||||
`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))`,
|
||||
`CREATE TABLE IF NOT EXISTS character_records(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, world_id TEXT NOT NULL, name TEXT NOT NULL, state TEXT NOT NULL, character TEXT NOT NULL)`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS one_living_character ON character_records(account_id) WHERE state IN ('alive','eligible')`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS one_current_character ON character_records(account_id) WHERE state IN ('alive','eligible','transit')`,
|
||||
`CREATE TABLE IF NOT EXISTS character_transfers(id TEXT PRIMARY KEY,request_id TEXT NOT NULL,account_id TEXT NOT NULL,source_world TEXT NOT NULL,source_kind TEXT NOT NULL,destination TEXT NOT NULL,character_id TEXT NOT NULL,route TEXT NOT NULL,status TEXT NOT NULL,accepted_world TEXT NOT NULL,character TEXT NOT NULL,UNIQUE(account_id,request_id))`,
|
||||
`CREATE UNIQUE INDEX IF NOT EXISTS one_pending_transfer ON character_transfers(account_id) WHERE status='prepared'`,
|
||||
`CREATE INDEX IF NOT EXISTS characters_world ON character_records(world_id)`,
|
||||
`CREATE TABLE IF NOT EXISTS admin_sessions(token_hash TEXT PRIMARY KEY, expires BIGINT NOT NULL)`,
|
||||
`CREATE TABLE IF NOT EXISTS control_commands(id TEXT PRIMARY KEY, world_id TEXT NOT NULL, actor TEXT NOT NULL, op TEXT NOT NULL, target TEXT NOT NULL, value TEXT NOT NULL, reason TEXT NOT NULL, status TEXT NOT NULL, result TEXT NOT NULL, created_at BIGINT NOT NULL, completed_at BIGINT NOT NULL DEFAULT 0)`,
|
||||
@@ -140,7 +144,7 @@ func (d *DB) writeCharacter(ctx context.Context, tx *sql.Tx, world string, c *ga
|
||||
where = "character_records.account_id=excluded.account_id"
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO character_records(character_id,account_id,world_id,name,state,character) VALUES(?,?,?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET world_id=excluded.world_id,name=excluded.name,state=excluded.state,character=excluded.character WHERE `+where), c.View.Entity.ID, c.Account, world, c.View.Entity.Name, c.View.Entity.State, string(raw))
|
||||
if err != nil && (strings.Contains(err.Error(), "one_living_character") || strings.Contains(err.Error(), "character_records.account_id")) {
|
||||
if err != nil && ((strings.Contains(err.Error(), "one_living_character") || strings.Contains(err.Error(), "one_current_character")) || strings.Contains(err.Error(), "character_records.account_id")) {
|
||||
return ErrLivingCharacter
|
||||
}
|
||||
return err
|
||||
@@ -168,7 +172,7 @@ func (d *DB) syncCharacters(ctx context.Context, tx *sql.Tx, w *game.World, clai
|
||||
func (d *DB) ActiveCharacter(ctx context.Context, account string) (*CharacterRecord, error) {
|
||||
var r CharacterRecord
|
||||
var raw string
|
||||
err := d.sql.QueryRowContext(ctx, d.q(`SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE account_id=? AND state IN ('alive','eligible')`), account).Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw)
|
||||
err := d.sql.QueryRowContext(ctx, d.q(`SELECT character_id,account_id,world_id,name,state,character FROM character_records WHERE account_id=? AND state IN ('alive','eligible','transit')`), account).Scan(&r.ID, &r.Account, &r.WorldID, &r.Name, &r.State, &raw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -230,6 +234,10 @@ func (d *DB) Worlds(ctx context.Context) ([]WorldRecord, error) {
|
||||
return nil, err
|
||||
}
|
||||
r.ID = w.ID
|
||||
r.Kind = w.Kind
|
||||
if r.Kind == "" {
|
||||
r.Kind = "survival"
|
||||
}
|
||||
r.CatalogVersion = w.CatalogVersion
|
||||
r.Phase = w.Phase
|
||||
r.Living = w.LivingCount()
|
||||
@@ -299,6 +307,6 @@ func (d *DB) FinishProvision(ctx context.Context, id, result string, success boo
|
||||
if success {
|
||||
status = "completed"
|
||||
}
|
||||
_, err := d.sql.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND status='pending' AND op='create-world'`), status, result, id)
|
||||
_, err := d.sql.ExecContext(ctx, d.q(`UPDATE control_commands SET status=?,result=?,completed_at=`+d.now()+` WHERE id=? AND status='pending' AND op IN ('create-world','create-hub')`), status, result, id)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/game"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
)
|
||||
|
||||
var ErrTravel = errors.New("travel unavailable")
|
||||
|
||||
func travelError(message string) error { return fmt.Errorf("%w: %s", ErrTravel, message) }
|
||||
|
||||
type Transfer struct {
|
||||
ID string `json:"id"`
|
||||
RequestID string `json:"requestId"`
|
||||
Account string `json:"-"`
|
||||
Source string `json:"source"`
|
||||
SourceKind string `json:"sourceKind"`
|
||||
Destination string `json:"destination"`
|
||||
CharacterID string `json:"characterId"`
|
||||
Route string `json:"route"`
|
||||
Status string `json:"status"`
|
||||
AcceptedWorld string `json:"acceptedWorld"`
|
||||
Payload string `json:"-"`
|
||||
}
|
||||
|
||||
const transferColumns = `id,request_id,account_id,source_world,source_kind,destination,character_id,route,status,accepted_world,character`
|
||||
|
||||
func scanTransfer(row interface{ Scan(...any) error }) (*Transfer, error) {
|
||||
t := &Transfer{}
|
||||
err := row.Scan(&t.ID, &t.RequestID, &t.Account, &t.Source, &t.SourceKind, &t.Destination, &t.CharacterID, &t.Route, &t.Status, &t.AcceptedWorld, &t.Payload)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
return t, err
|
||||
}
|
||||
func (d *DB) PendingTransfer(ctx context.Context, account string) (*Transfer, error) {
|
||||
return scanTransfer(d.sql.QueryRowContext(ctx, d.q(`SELECT `+transferColumns+` FROM character_transfers WHERE account_id=? AND status='prepared'`), account))
|
||||
}
|
||||
func (d *DB) Transfer(ctx context.Context, account, id string) (*Transfer, error) {
|
||||
return scanTransfer(d.sql.QueryRowContext(ctx, d.q(`SELECT `+transferColumns+` FROM character_transfers WHERE account_id=? AND id=?`), account, id))
|
||||
}
|
||||
func (d *DB) RequestedTransfer(ctx context.Context, account, request string) (*Transfer, error) {
|
||||
return scanTransfer(d.sql.QueryRowContext(ctx, d.q(`SELECT `+transferColumns+` FROM character_transfers WHERE account_id=? AND request_id=?`), account, request))
|
||||
}
|
||||
func (l *Lease) fenceTravel(ctx context.Context, tx *sql.Tx, w *game.World) error {
|
||||
raw, err := json.Marshal(w)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r, err := tx.ExecContext(ctx, l.DB.q(`UPDATE worlds SET snapshot=?,revision=revision+1,lease_until=`+l.DB.now()+`+30 WHERE id=? AND owner=? AND revision=? AND lease_until>=`+l.DB.now()), string(raw), l.WorldID, l.Owner, l.Revision)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return ErrOwnership
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (l *Lease) PrepareTravel(ctx context.Context, live *game.World, account, request, destination, route string) (*Transfer, error) {
|
||||
d := l.DB
|
||||
previous, err := d.RequestedTransfer(ctx, account, request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if previous != nil {
|
||||
if previous.Source != live.ID || previous.Destination != destination || previous.Route != route {
|
||||
return nil, travelError("request already used")
|
||||
}
|
||||
return previous, nil
|
||||
}
|
||||
c := live.ForAccount(account)
|
||||
if err = live.Departure(c, route); err != nil {
|
||||
return nil, travelError(err.Error())
|
||||
}
|
||||
if destination == live.ID {
|
||||
return nil, travelError("choose another world")
|
||||
}
|
||||
worlds, err := d.Worlds(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
valid := false
|
||||
for _, w := range worlds {
|
||||
if w.ID == destination && w.Available && !w.Closed && w.Living < w.Capacity && (w.Phase == "hub" || w.Phase == "gathering" || w.Phase == "cataclysm") && (live.IsHub() || w.Kind == "hub") {
|
||||
valid = true
|
||||
}
|
||||
}
|
||||
if !valid {
|
||||
return nil, travelError("destination unavailable or full")
|
||||
}
|
||||
// Only the departing copy is changed before commit. Other online players retain
|
||||
// their connections, inputs and acknowledgement counters.
|
||||
staged := *live
|
||||
staged.Characters = maps.Clone(live.Characters)
|
||||
raw, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var departing game.Character
|
||||
if err = json.Unmarshal(raw, &departing); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if route == "escape" {
|
||||
departing.View.Inventory["escape_stone"]--
|
||||
if departing.View.Inventory["escape_stone"] == 0 {
|
||||
delete(departing.View.Inventory, "escape_stone")
|
||||
}
|
||||
}
|
||||
raw, err = json.Marshal(&departing)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t := &Transfer{ID: game.ID(), RequestID: request, Account: account, Source: live.ID, SourceKind: live.Kind, Destination: destination, CharacterID: c.View.Entity.ID, Route: route, Status: "prepared", Payload: string(raw)}
|
||||
delete(staged.Characters, t.CharacterID)
|
||||
tx, err := d.sql.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err = l.fenceTravel(ctx, tx, &staged); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO character_transfers(`+transferColumns+`) VALUES(?,?,?,?,?,?,?,?,?,?,?)`), t.ID, t.RequestID, t.Account, t.Source, t.SourceKind, t.Destination, t.CharacterID, t.Route, t.Status, "", t.Payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
marker := "travel:" + t.ID
|
||||
if _, err = tx.ExecContext(ctx, d.q(`UPDATE passages SET claimed_world=? WHERE character_id=? AND account_id=? AND source_world=? AND claimed_world IS NULL`), marker, t.CharacterID, account, live.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := tx.ExecContext(ctx, d.q(`UPDATE character_records SET world_id=?,state='transit',character=? WHERE character_id=? AND account_id=? AND world_id=? AND state IN ('alive','eligible')`), marker, t.Payload, t.CharacterID, account, live.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return nil, travelError("character no longer belongs to source")
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.Revision++
|
||||
*live = staged
|
||||
live.Saved()
|
||||
return t, nil
|
||||
}
|
||||
func (l *Lease) AcceptTravel(ctx context.Context, live *game.World, account, id string) (*Transfer, error) {
|
||||
d := l.DB
|
||||
t, err := d.Transfer(ctx, account, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if t == nil {
|
||||
return nil, travelError("transfer not found")
|
||||
}
|
||||
if t.Status == "accepted" {
|
||||
return t, nil
|
||||
}
|
||||
if t.SourceKind != "hub" && !live.IsHub() {
|
||||
return nil, travelError("escape and victory lead to a hub")
|
||||
}
|
||||
staged := *live
|
||||
staged.Characters = maps.Clone(live.Characters)
|
||||
var c game.Character
|
||||
if err = json.Unmarshal([]byte(t.Payload), &c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = staged.Arrive(&c); err != nil {
|
||||
return nil, travelError(err.Error())
|
||||
}
|
||||
raw, err := json.Marshal(&c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tx, err := d.sql.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err = l.fenceTravel(ctx, tx, &staged); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := tx.ExecContext(ctx, d.q(`UPDATE character_transfers SET status='accepted',accepted_world=? WHERE id=? AND account_id=? AND status='prepared'`), live.ID, id, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, _ := r.RowsAffected()
|
||||
if n != 1 {
|
||||
return nil, travelError("transfer already accepted; refresh travel status")
|
||||
}
|
||||
marker := "travel:" + id
|
||||
if _, err = tx.ExecContext(ctx, d.q(`UPDATE passages SET claimed_world=? WHERE character_id=? AND account_id=? AND claimed_world=?`), live.ID, t.CharacterID, account, marker); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err = tx.ExecContext(ctx, d.q(`UPDATE character_records SET world_id=?,state='alive',character=? WHERE character_id=? AND account_id=? AND world_id=? AND state='transit'`), live.ID, string(raw), t.CharacterID, account, marker)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, _ = r.RowsAffected()
|
||||
if n != 1 {
|
||||
return nil, travelError("transfer no longer owns character")
|
||||
}
|
||||
if err = tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.Revision++
|
||||
*live = staged
|
||||
live.Saved()
|
||||
t.Status = "accepted"
|
||||
t.AcceptedWorld = live.ID
|
||||
return t, nil
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTravelLifecycle(t *testing.T) {
|
||||
runTravelTests(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "travel.db")))
|
||||
}
|
||||
func TestPostgresTravelLifecycle(t *testing.T) {
|
||||
dsn := os.Getenv("TEST_DATABASE_URL")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_DATABASE_URL not configured")
|
||||
}
|
||||
runTravelTests(t, dsn)
|
||||
}
|
||||
func runTravelTests(t *testing.T, dsn string) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
now := time.Now().UTC()
|
||||
suffix := game.ID()
|
||||
makeWorld := func(id, kind string) (*game.World, *Lease) {
|
||||
t.Helper()
|
||||
w := game.New(id+suffix, 123, now, b)
|
||||
w.Kind = kind
|
||||
if kind == "hub" {
|
||||
w.Phase = "hub"
|
||||
}
|
||||
l, _, e := db.Acquire(ctx, w)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return w, l
|
||||
}
|
||||
source, sl := makeWorld("source", "survival")
|
||||
hub, hl := makeWorld("hub", "hub")
|
||||
other, ol := makeWorld("other", "hub")
|
||||
next, nl := makeWorld("next", "survival")
|
||||
c, e := source.Join("traveler"+suffix, "Traveler")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
id := c.View.Entity.ID
|
||||
c.View.Inventory["escape_stone"] = 2
|
||||
c.View.Inventory["wood"] = 31
|
||||
c.View.Skills["combat"] = 29
|
||||
c.View.Level = 3
|
||||
c.View.PendingVitalChoices = 2
|
||||
c.View.Experience = 7
|
||||
c.View.StatPoints = 20
|
||||
c.DailySeconds = 123
|
||||
c.WorldsSurvived = 2
|
||||
if e = source.AdminItems(c, "grant-item", "spear:1"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = source.Connect(id); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = sl.Save(ctx, source, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = sl.PrepareTravel(ctx, source, c.Account, game.ID(), next.ID, "escape"); !errors.Is(e, ErrTravel) {
|
||||
t.Fatal("escape accepted survival destination", e)
|
||||
}
|
||||
if c.View.Inventory["escape_stone"] != 2 {
|
||||
t.Fatal("rejected escape spent item")
|
||||
}
|
||||
request := game.ID()
|
||||
transfer, e := sl.PrepareTravel(ctx, source, c.Account, request, hub.ID, "escape")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if source.ForAccount(c.Account) != nil {
|
||||
t.Fatal("source retained the live character")
|
||||
}
|
||||
active, e := db.ActiveCharacter(ctx, c.Account)
|
||||
if e != nil || active == nil || active.State != "transit" {
|
||||
t.Fatal("missing travel reservation", e)
|
||||
}
|
||||
// The account cannot create a replacement while in escrow.
|
||||
replacement, _ := next.Join(c.Account, "Replacement")
|
||||
if e = nl.Save(ctx, next, ""); !errors.Is(e, ErrLivingCharacter) {
|
||||
t.Fatal("replacement bypassed in-transit life", e)
|
||||
}
|
||||
delete(next.Characters, replacement.View.Entity.ID)
|
||||
again, e := sl.PrepareTravel(ctx, source, c.Account, request, hub.ID, "escape")
|
||||
if e != nil || again.ID != transfer.ID {
|
||||
t.Fatal("departure retry was not idempotent", e)
|
||||
}
|
||||
if _, e = hl.AcceptTravel(ctx, hub, "intruder", transfer.ID); !errors.Is(e, ErrTravel) {
|
||||
t.Fatal("another account accepted transfer", e)
|
||||
}
|
||||
hub.AdmissionsClosed = true
|
||||
if _, e = hl.AcceptTravel(ctx, hub, c.Account, transfer.ID); !errors.Is(e, ErrTravel) {
|
||||
t.Fatal("closed hub accepted transfer", e)
|
||||
}
|
||||
if hub.ForAccount(c.Account) != nil {
|
||||
t.Fatal("rejected arrival mutated destination")
|
||||
}
|
||||
hub.AdmissionsClosed = false
|
||||
hub.Balance.MaxPlayers = 0
|
||||
if _, e = hl.AcceptTravel(ctx, hub, c.Account, transfer.ID); !errors.Is(e, ErrTravel) {
|
||||
t.Fatal("full hub accepted transfer", e)
|
||||
}
|
||||
hub.Balance.MaxPlayers = b.MaxPlayers
|
||||
// Departure survives source destruction and a process/database restart.
|
||||
source.Phase = "lost"
|
||||
if e = sl.Save(ctx, source, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
reopened, e := Open(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
pending, e := reopened.PendingTransfer(ctx, c.Account)
|
||||
reopened.Close()
|
||||
if e != nil || pending == nil || pending.ID != transfer.ID {
|
||||
t.Fatal("pending transfer was not durable", e)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
results := make(chan error, 2)
|
||||
for i := range 2 {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
w, l := hub, hl
|
||||
if i == 1 {
|
||||
w, l = other, ol
|
||||
}
|
||||
_, err := l.AcceptTravel(ctx, w, c.Account, transfer.ID)
|
||||
results <- err
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
for err := range results {
|
||||
if err != nil && !errors.Is(err, ErrTravel) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
copies := 0
|
||||
var arrived *game.Character
|
||||
var current *game.World
|
||||
var lease *Lease
|
||||
for i, w := range []*game.World{hub, other} {
|
||||
if v := w.ForAccount(c.Account); v != nil {
|
||||
copies++
|
||||
arrived = v
|
||||
current = w
|
||||
lease = hl
|
||||
if i == 1 {
|
||||
lease = ol
|
||||
}
|
||||
}
|
||||
}
|
||||
if copies != 1 {
|
||||
t.Fatalf("arrival copies: %d", copies)
|
||||
}
|
||||
if !reflect.DeepEqual(arrived.View.Items, c.View.Items) || !reflect.DeepEqual(arrived.View.Gathering, c.View.Gathering) || !reflect.DeepEqual(arrived.View.AllocatedStats, c.View.AllocatedStats) {
|
||||
t.Fatal("item identities or character progression changed during travel")
|
||||
}
|
||||
if arrived.View.Inventory["escape_stone"] != 1 || arrived.View.Inventory["wood"] != 31 || arrived.View.Level != 3 || arrived.View.Experience != 7 || arrived.View.StatPoints != 20 || arrived.View.Skills["combat"] != 29 || arrived.DailySeconds != 123 || arrived.WorldsSurvived != 2 || arrived.View.Entity.ID != id || !reflect.DeepEqual(arrived.View.Titles, c.View.Titles) {
|
||||
t.Fatal("travel changed ownership, progression, time, or survival credit")
|
||||
}
|
||||
accepted, e := hl.AcceptTravel(ctx, hub, c.Account, transfer.ID)
|
||||
if e != nil || accepted.AcceptedWorld != current.ID {
|
||||
t.Fatal("arrival retry changed destination", e)
|
||||
}
|
||||
if e = current.Connect(id); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = lease.Save(ctx, current, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
switchTo, switchLease := hub, hl
|
||||
if current == hub {
|
||||
switchTo, switchLease = other, ol
|
||||
}
|
||||
switched, e := lease.PrepareTravel(ctx, current, c.Account, game.ID(), switchTo.ID, "hub")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = switchLease.AcceptTravel(ctx, switchTo, c.Account, switched.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = switchTo.Connect(id); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = switchLease.Save(ctx, switchTo, ""); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
onward, e := switchLease.PrepareTravel(ctx, switchTo, c.Account, game.ID(), next.ID, "hub")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
next.Phase = "lost"
|
||||
if _, e = nl.AcceptTravel(ctx, next, c.Account, onward.ID); !errors.Is(e, ErrTravel) {
|
||||
t.Fatal("destroyed destination accepted traveler", e)
|
||||
}
|
||||
next.Phase = "cataclysm"
|
||||
if _, e = nl.AcceptTravel(ctx, next, c.Account, onward.ID); e != nil {
|
||||
t.Fatal("admission to collapsing world failed", e)
|
||||
}
|
||||
if next.Characters[id].View.Inventory["escape_stone"] != 1 {
|
||||
t.Fatal("hub travel consumed escape item")
|
||||
}
|
||||
// The persisted destination, not just the in-memory world, owns this life.
|
||||
var raw string
|
||||
if e = db.sql.QueryRowContext(ctx, db.q(`SELECT snapshot FROM worlds WHERE id=?`), next.ID).Scan(&raw); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var restored game.World
|
||||
if e = json.Unmarshal([]byte(raw), &restored); e != nil || restored.Characters[id] == nil {
|
||||
t.Fatal("arrival snapshot missing", e)
|
||||
}
|
||||
active, e = db.ActiveCharacter(ctx, c.Account)
|
||||
if e != nil || active.WorldID != next.ID || active.State != "alive" {
|
||||
t.Fatal("arrival registry missing", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTravelLeaseRollback(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, e := Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "fence.db")))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
source := game.New("source", 1, time.Now(), b)
|
||||
hub := game.New("hub", 2, time.Now(), b)
|
||||
hub.Kind = "hub"
|
||||
hub.Phase = "hub"
|
||||
sl, _, _ := db.Acquire(ctx, source)
|
||||
hl, _, _ := db.Acquire(ctx, hub)
|
||||
c, _ := source.Join("account", "Traveler")
|
||||
_ = source.Connect(c.View.Entity.ID)
|
||||
c.View.Inventory["escape_stone"] = 1
|
||||
_ = sl.Save(ctx, source, "")
|
||||
stale := *sl
|
||||
stale.Revision--
|
||||
if _, e = stale.PrepareTravel(ctx, source, c.Account, game.ID(), hub.ID, "escape"); !errors.Is(e, ErrOwnership) {
|
||||
t.Fatal("stale source was not fenced", e)
|
||||
}
|
||||
if source.ForAccount(c.Account) != c || c.View.Inventory["escape_stone"] != 1 {
|
||||
t.Fatal("rollback changed live source")
|
||||
}
|
||||
tr, e := sl.PrepareTravel(ctx, source, c.Account, game.ID(), hub.ID, "escape")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
stale = *hl
|
||||
stale.Revision--
|
||||
if _, e = stale.AcceptTravel(ctx, hub, c.Account, tr.ID); !errors.Is(e, ErrOwnership) {
|
||||
t.Fatal("stale destination was not fenced", e)
|
||||
}
|
||||
if hub.ForAccount(c.Account) != nil {
|
||||
t.Fatal("rollback leaked destination character")
|
||||
}
|
||||
pending, _ := db.PendingTransfer(ctx, c.Account)
|
||||
if pending == nil {
|
||||
t.Fatal("rollback consumed transfer")
|
||||
}
|
||||
}
|
||||
@@ -116,7 +116,7 @@ func (h *HTTP) portalRoutes(mux *http.ServeMux) {
|
||||
fail(w, 400, "choose a title")
|
||||
return
|
||||
}
|
||||
case "create-world":
|
||||
case "create-world", "create-hub":
|
||||
if h.Provisioner == nil {
|
||||
fail(w, 503, "GitOps provisioning is not configured")
|
||||
return
|
||||
@@ -145,7 +145,7 @@ func (h *HTTP) portalRoutes(mux *http.ServeMux) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.Op != "create-world" {
|
||||
if req.Op != "create-world" && req.Op != "create-hub" {
|
||||
worlds, err := h.auth.db.Worlds(r.Context())
|
||||
if err != nil {
|
||||
fail(w, 503, "world directory unavailable")
|
||||
@@ -163,7 +163,7 @@ func (h *HTTP) portalRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
}
|
||||
command := store.Command{ID: req.ID, WorldID: req.WorldID, Actor: actor, Op: req.Op, Target: req.Target, Value: req.Value, Reason: req.Reason}
|
||||
if req.Op == "create-world" {
|
||||
if req.Op == "create-world" || req.Op == "create-hub" {
|
||||
command.Target = req.WorldID
|
||||
command.WorldID = "_provision"
|
||||
}
|
||||
@@ -193,11 +193,15 @@ func (h *HTTP) RunProvisioning(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
for _, c := range commands {
|
||||
if c.Op != "create-world" {
|
||||
if c.Op != "create-world" && c.Op != "create-hub" {
|
||||
continue
|
||||
}
|
||||
request, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
result, err := h.Provisioner.CreateWorld(request, c.Target, c.Value)
|
||||
kind := "survival"
|
||||
if c.Op == "create-hub" {
|
||||
kind = "hub"
|
||||
}
|
||||
result, err := h.Provisioner.CreateInstance(request, c.Target, c.Value, kind)
|
||||
cancel()
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return
|
||||
|
||||
@@ -97,6 +97,7 @@ func (h *HTTP) allow(r *http.Request) bool {
|
||||
func (h *HTTP) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
h.portalRoutes(mux)
|
||||
h.travelRoutes(mux)
|
||||
h.catalogRoutes(mux)
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.s.ready.Load() {
|
||||
@@ -148,7 +149,7 @@ func (h *HTTP) Handler() http.Handler {
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
b := h.s.world.Balance
|
||||
respond(w, 200, map[string]any{"worldId": h.s.world.ID, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "recipes": b.Recipes, "tickHz": b.TickHz})
|
||||
respond(w, 200, map[string]any{"worldId": h.s.world.ID, "kind": h.s.world.Kind, "development": h.auth.dev, "worlds": h.worlds, "chunkSize": b.ChunkSize, "playerSpeed": b.PlayerSpeed, "attackRange": b.AttackRange, "gatherRange": b.GatherRange, "recipes": b.Recipes, "tickHz": b.TickHz})
|
||||
})
|
||||
mux.HandleFunc("GET /api/preview", func(w http.ResponseWriter, r *http.Request) {
|
||||
h.s.mu.Lock()
|
||||
@@ -367,8 +368,10 @@ func (h *HTTP) socket(w http.ResponseWriter, r *http.Request) {
|
||||
cancel()
|
||||
_ = conn.CloseNow()
|
||||
h.s.mu.Lock()
|
||||
delete(h.s.peers, id)
|
||||
h.s.world.Disconnect(id)
|
||||
if h.s.peers[id] == peer {
|
||||
delete(h.s.peers, id)
|
||||
h.s.world.Disconnect(id)
|
||||
}
|
||||
h.s.mu.Unlock()
|
||||
}()
|
||||
go func() {
|
||||
|
||||
@@ -135,6 +135,9 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
|
||||
if err := s.refreshCatalog(ctx); err != nil {
|
||||
return p.Character{}, err
|
||||
}
|
||||
if claim != "" {
|
||||
return p.Character{}, errors.New("use the victory portal and travel menu")
|
||||
}
|
||||
var c *game.Character
|
||||
var err error
|
||||
active, err := s.lease.DB.ActiveCharacter(ctx, account)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"aeternalis/server/internal/store"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (h *HTTP) travelRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/travel", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
var t *store.Transfer
|
||||
if id := r.URL.Query().Get("id"); id != "" {
|
||||
t, err = h.auth.db.Transfer(r.Context(), account, id)
|
||||
} else {
|
||||
t, err = h.auth.db.PendingTransfer(r.Context(), account)
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, 503, "travel status unavailable")
|
||||
return
|
||||
}
|
||||
respond(w, 200, t)
|
||||
})
|
||||
mux.HandleFunc("POST /api/travel/prepare", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
RequestID string `json:"requestId"`
|
||||
Destination string `json:"destination"`
|
||||
Route string `json:"route"`
|
||||
}
|
||||
if decode(w, r, &req) != nil || !requestIDPattern.MatchString(req.RequestID) || !worldIDPattern.MatchString(req.Destination) || (req.Route != "hub" && req.Route != "portal" && req.Route != "escape") {
|
||||
fail(w, 400, "invalid travel request")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
// Flush pending awards and the source's current daily usage before escrow.
|
||||
if err = h.s.persist(r.Context(), ""); err != nil {
|
||||
fail(w, 503, "save unavailable")
|
||||
return
|
||||
}
|
||||
t, err := h.s.lease.PrepareTravel(r.Context(), h.s.world, account, req.RequestID, req.Destination, req.Route)
|
||||
if err != nil {
|
||||
h.travelFailure(w, err)
|
||||
return
|
||||
}
|
||||
if peer := h.s.peers[t.CharacterID]; peer != nil && t.Status == "prepared" && h.s.world.Characters[t.CharacterID] == nil {
|
||||
delete(h.s.peers, t.CharacterID)
|
||||
peer.close()
|
||||
}
|
||||
h.s.lastSave = time.Now()
|
||||
respond(w, 200, t)
|
||||
})
|
||||
mux.HandleFunc("POST /api/travel/accept", func(w http.ResponseWriter, r *http.Request) {
|
||||
account, err := h.auth.account(r)
|
||||
if err != nil {
|
||||
fail(w, 401, "sign in required")
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
TransferID string `json:"transferId"`
|
||||
}
|
||||
if decode(w, r, &req) != nil || !requestIDPattern.MatchString(req.TransferID) {
|
||||
fail(w, 400, "invalid transfer ID")
|
||||
return
|
||||
}
|
||||
h.s.mu.Lock()
|
||||
defer h.s.mu.Unlock()
|
||||
if !h.s.ready.Load() {
|
||||
fail(w, 503, "world unavailable")
|
||||
return
|
||||
}
|
||||
if err = h.s.refreshCatalog(r.Context()); err != nil {
|
||||
h.travelFailure(w, err)
|
||||
return
|
||||
}
|
||||
if err = h.s.persist(r.Context(), ""); err != nil {
|
||||
fail(w, 503, "save unavailable")
|
||||
return
|
||||
}
|
||||
t, err := h.s.lease.AcceptTravel(r.Context(), h.s.world, account, req.TransferID)
|
||||
if err != nil {
|
||||
h.travelFailure(w, err)
|
||||
return
|
||||
}
|
||||
h.s.lastSave = time.Now()
|
||||
respond(w, 200, t)
|
||||
})
|
||||
}
|
||||
func (h *HTTP) travelFailure(w http.ResponseWriter, err error) {
|
||||
if errors.Is(err, store.ErrTravel) {
|
||||
fail(w, 409, err.Error())
|
||||
return
|
||||
}
|
||||
// An uncertain transaction result must never leave a process serving a stale life.
|
||||
h.s.ready.Store(false)
|
||||
for _, p := range h.s.peers {
|
||||
p.close()
|
||||
}
|
||||
fail(w, 503, "travel save unavailable; check travel status before retrying")
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package transport
|
||||
|
||||
import (
|
||||
"aeternalis/server/content"
|
||||
"aeternalis/server/internal/game"
|
||||
"aeternalis/server/internal/store"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTravelHTTPAuthorizationAndResume(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := store.Open(ctx, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "travel.db")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
b, _ := content.Load()
|
||||
source := game.New("source", 1, time.Now(), b)
|
||||
hub := game.New("hub", 2, time.Now(), b)
|
||||
hub.Kind = "hub"
|
||||
hub.Phase = "hub"
|
||||
sl, _, _ := db.Acquire(ctx, source)
|
||||
hl, _, _ := db.Acquire(ctx, hub)
|
||||
c, _ := source.Join("owner", "Traveler")
|
||||
c.View.Inventory["escape_stone"] = 1
|
||||
_ = source.Connect(c.View.Entity.ID)
|
||||
if err = sl.Save(ctx, source, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
auth, _ := NewAuth(ctx, db, true, "http://127.0.0.1", "", "", "")
|
||||
cookie := func(account string) *http.Cookie {
|
||||
t.Helper()
|
||||
out := httptest.NewRecorder()
|
||||
r := httptest.NewRequest("POST", auth.base+"/auth/dev", nil)
|
||||
if e := auth.session(out, r, account); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return out.Result().Cookies()[0]
|
||||
}
|
||||
owner, intruder := cookie("owner"), cookie("intruder")
|
||||
s := NewService(source, sl)
|
||||
h := NewHTTP(s, auth, t.TempDir(), nil).Handler()
|
||||
target := NewHTTP(NewService(hub, hl), auth, t.TempDir(), nil).Handler()
|
||||
request := func(handler http.Handler, path, origin string, body any, cookie *http.Cookie) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
method := "GET"
|
||||
var raw []byte
|
||||
if body != nil {
|
||||
method = "POST"
|
||||
raw, _ = json.Marshal(body)
|
||||
}
|
||||
r := httptest.NewRequest(method, auth.base+path, strings.NewReader(string(raw)))
|
||||
r.RemoteAddr = "127.0.0.1:4321"
|
||||
if origin != "" {
|
||||
r.Header.Set("Origin", origin)
|
||||
}
|
||||
if cookie != nil {
|
||||
r.AddCookie(cookie)
|
||||
}
|
||||
out := httptest.NewRecorder()
|
||||
handler.ServeHTTP(out, r)
|
||||
return out
|
||||
}
|
||||
req := map[string]string{"requestId": game.ID(), "destination": "hub", "route": "escape"}
|
||||
if r := request(h, "/api/travel/prepare", auth.base, req, nil); r.Code != 401 {
|
||||
t.Fatal("anonymous travel", r.Code)
|
||||
}
|
||||
if r := request(h, "/api/travel/prepare", "https://evil.example", req, owner); r.Code != 403 {
|
||||
t.Fatal("cross-origin travel", r.Code)
|
||||
}
|
||||
if r := request(h, "/api/travel/prepare", auth.base, req, intruder); r.Code != 409 {
|
||||
t.Fatal("other account traveled", r.Code)
|
||||
}
|
||||
if !s.ready.Load() {
|
||||
t.Fatal("ordinary rejection froze world")
|
||||
}
|
||||
r := request(h, "/api/travel/prepare", auth.base, req, owner)
|
||||
if r.Code != 200 {
|
||||
t.Fatal(r.Code, r.Body.String())
|
||||
}
|
||||
var tr store.Transfer
|
||||
if err = json.Unmarshal(r.Body.Bytes(), &tr); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(r.Body.String(), "escape_stone") || strings.Contains(r.Body.String(), "account") {
|
||||
t.Fatal("private escrow leaked")
|
||||
}
|
||||
if r = request(h, "/api/travel", auth.base, nil, owner); r.Code != 200 || !strings.Contains(r.Body.String(), tr.ID) {
|
||||
t.Fatal("pending recovery failed", r.Body.String())
|
||||
}
|
||||
if r = request(h, "/api/travel?id="+tr.ID, auth.base, nil, intruder); r.Body.String() != "null\n" {
|
||||
t.Fatal("transfer exposed to another account", r.Body.String())
|
||||
}
|
||||
accept := map[string]string{"transferId": tr.ID}
|
||||
if r = request(target, "/api/travel/accept", auth.base, accept, intruder); r.Code != 409 {
|
||||
t.Fatal("other account claimed transfer", r.Code)
|
||||
}
|
||||
if r = request(target, "/api/travel/accept", auth.base, accept, owner); r.Code != 200 {
|
||||
t.Fatal("arrival failed", r.Body.String())
|
||||
}
|
||||
if r = request(target, "/api/travel/accept", auth.base, accept, owner); r.Code != 200 || hub.LivingCount() != 1 {
|
||||
t.Fatal("arrival retry duplicated character", r.Body.String())
|
||||
}
|
||||
if r = request(h, "/api/join", auth.base, map[string]string{"name": "Replacement", "passage": ""}, owner); r.Code != 409 {
|
||||
t.Fatal("created replacement after travel", r.Code)
|
||||
}
|
||||
if r = request(h, "/api/join", auth.base, map[string]string{"name": "", "passage": c.View.Entity.ID}, owner); r.Code != 409 {
|
||||
t.Fatal("legacy shortcut bypassed travel", r.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user