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.View.Entity.Appearance = content.DefaultCharacterAppearance() 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) } c.View.Inventory["book_mend"] = 1 if e = source.LearnPower(c, "book_mend"); e != nil { t.Fatal(e) } spell := c.View.Powers["mend"] spell.XP = 25 spell.ReadyAt = float64(now.Unix() + 30) c.View.Powers["mend"] = spell weapon := c.View.Weapons["blades"] weapon.XP = 29 c.View.Weapons["blades"] = weapon source.RefreshStats(c) 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.Entity.Appearance, c.View.Entity.Appearance) || !reflect.DeepEqual(arrived.View.Powers, c.View.Powers) || !reflect.DeepEqual(arrived.View.Weapons, c.View.Weapons) || !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 } traveler := current.ForAccount(c.Account) traveler.View.Entity.Position.X += 100 beforePortal, _ := json.Marshal(current) requestAtPortal := game.ID() if _, e = lease.PrepareTravel(ctx, current, c.Account, requestAtPortal, switchTo.ID, "hub"); !errors.Is(e, ErrTravel) { t.Fatal("remote hub travel accepted", e) } afterPortal, _ := json.Marshal(current) if string(beforePortal) != string(afterPortal) { t.Fatal("remote portal rejection mutated source") } if pending, e := db.PendingTransfer(ctx, c.Account); e != nil || pending != nil { t.Fatal("remote portal rejection created transit escrow", e) } traveler.View.Entity.Position = current.PortalPosition() switched, e := lease.PrepareTravel(ctx, current, c.Account, requestAtPortal, 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") } }