diff options
Diffstat (limited to 'internal/game')
| -rw-r--r-- | internal/game/act.go | 40 | ||||
| -rw-r--r-- | internal/game/cmd_registry.go | 5 | ||||
| -rw-r--r-- | internal/game/cmd_room_insert.go | 47 | ||||
| -rw-r--r-- | internal/game/cmd_room_remove.go | 33 | ||||
| -rw-r--r-- | internal/game/cmd_room_txn_regression_test.go | 119 | ||||
| -rw-r--r-- | internal/game/cmd_swapid.go | 24 | ||||
| -rw-r--r-- | internal/game/core_production.go | 6 | ||||
| -rw-r--r-- | internal/game/exit_migrate.go | 15 | ||||
| -rw-r--r-- | internal/game/swapid_content_test.go | 64 | ||||
| -rw-r--r-- | internal/game/tick.go | 2 |
10 files changed, 301 insertions, 54 deletions
diff --git a/internal/game/act.go b/internal/game/act.go index 449b2da..7ff805c 100644 --- a/internal/game/act.go +++ b/internal/game/act.go @@ -19,8 +19,8 @@ import ( // cut, talk/speak/ask, steal/thieve, hide) must not be duplicated here: a // registered command is looked up first, so an entry would be dead and its // removal untested. Only shear remains as a pure action alias. -var verbAliases = map[string]string{ - "shear": "gather", +var verbAliases = map[string]behavior.ActionType{ + "shear": behavior.TypeGather, } var verbSkill = map[string]string{ @@ -35,7 +35,7 @@ var verbSkill = map[string]string{ func normalizeVerb(v string) string { if a, ok := verbAliases[v]; ok { - return a + return string(a) } return v } @@ -161,14 +161,14 @@ func (g *Game) startAction(sess *net.Session, verb, target string) { return } - switch bhType { - case "gather": + switch behavior.ActionType(bhType) { + case behavior.TypeGather: if obj == nil || chosen == nil { sess.WriteLine(fmt.Sprintf("You can't %s that.", verb)) return } g.startGather(sess, p, obj, chosen) - case "talk": + case behavior.TypeTalk: if mob != nil { g.startMobTalk(sess, p, mob) } else { @@ -205,27 +205,27 @@ func (g *Game) AdvanceActions() { continue } switch p.Action.Type { - case "gather": + case behavior.TypeGather: g.advanceGather(sess, p) - case "burn": + case behavior.TypeBurn: g.advanceBurn(sess, p) - case "stoke": + case behavior.TypeStoke: g.advanceStoke(sess, p) - case "identify": + case behavior.TypeIdentify: g.advanceIdentify(sess, p) - case "steal": + case behavior.TypeSteal: g.advanceSteal(sess, p) - case "plant": + case behavior.TypePlant: g.advancePlant(sess, p) - case "harvest": + case behavior.TypeHarvest: g.advanceHarvest(sess, p) - case "rake": + case behavior.TypeRake: g.advanceRake(sess, p) - case "water": + case behavior.TypeWater: g.advanceWater(sess, p) - case "cure": + case behavior.TypeCure: g.advanceCure(sess, p) - case "obstacle": + case behavior.TypeObstacle: g.advanceObstacle(sess, p) case behavior.TypeTalk: g.advanceTalk(sess, p) @@ -234,7 +234,7 @@ func (g *Game) AdvanceActions() { case behavior.TypeCombine: g.advanceCombine(sess, p) default: - if productionActionTypes[string(p.Action.Type)] { + if productionActionTypes[p.Action.Type] { g.advanceProduction(sess, p) } } @@ -252,9 +252,9 @@ func (g *Game) AdvanceActions() { continue } switch p.BackgroundAction.Type { - case "fletch": + case behavior.TypeFletch: g.advanceFletch(sess, p) - case "cleaning": + case behavior.TypeClean: g.advanceClean(sess, p) } if p.BackgroundAction == nil { diff --git a/internal/game/cmd_registry.go b/internal/game/cmd_registry.go index fb72c99..ae4c895 100644 --- a/internal/game/cmd_registry.go +++ b/internal/game/cmd_registry.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "thehouseoficarus/internal/behavior" "thehouseoficarus/internal/net" ) @@ -225,7 +226,7 @@ func (g *Game) executeCommand(sess *net.Session, cmd string, args []string, rawI if a, ok := verbAliases[cmd]; ok { g.cancelAction(p) switch a { - case "gather": + case behavior.TypeGather: if len(args) == 0 { target := g.defaultTarget(p.RoomID, cmd) if target == "" { @@ -236,7 +237,7 @@ func (g *Game) executeCommand(sess *net.Session, cmd string, args []string, rawI } else { g.startAction(sess, cmd, strings.Join(args, " ")) } - case "talk": + case behavior.TypeTalk: if len(args) == 0 { sess.WriteLine("Talk to whom?") } else { diff --git a/internal/game/cmd_room_insert.go b/internal/game/cmd_room_insert.go index 2d7ff58..09b2e74 100644 --- a/internal/game/cmd_room_insert.go +++ b/internal/game/cmd_room_insert.go @@ -127,12 +127,6 @@ func (g *Game) roomInsert(sess *net.Session, args []string) { sess.WriteLine("Error creating directory.") return } - if err := writeRoomFile(newPath, data); err != nil { - sess.WriteLine("Error writing room file.") - return - } - - g.World.AddRoomPath(newID, newPath) curRoom.Exits[dir] = world.RewirePreserving(exitDef, newID) curData, err := yaml.Marshal(curRoom) @@ -140,23 +134,42 @@ func (g *Game) roomInsert(sess *net.Session, args []string) { sess.WriteLine("Error updating current room YAML.") return } - if err := writeRoomFile(curPath, curData); err != nil { - sess.WriteLine("Error writing current room file.") + + // Stage all three files (the new room, the current room, and the far + // room's reciprocal exit when it points back) into ONE journal + // transaction. The previous sequential writes could stop after the new + // room existed but before the current room's exit was rewritten, leaving + // a dangling exit with no recovery record; the transaction rolls the + // whole insert back on any failure or crash. + txn := g.newTxn() + if err := txn.Replace(newPath, data, 0644); err != nil { + sess.WriteLine(fmt.Sprintf("Error writing room file: %v", err)) + return + } + if err := txn.Replace(curPath, curData, 0644); err != nil { + sess.WriteLine(fmt.Sprintf("Error writing current room file: %v", err)) return } - if targetExit, tok := targetRoom.Exits[oppositeDir]; tok && targetExit.Room == p.RoomID { - targetRoom.Exits[oppositeDir] = world.RewirePreserving(targetExit, newID) - } - targetPath, tok2 := g.World.GetRoomPath(targetID) - if tok2 { - targetData, terr := yaml.Marshal(targetRoom) - if terr == nil { - if werr := writeRoomFile(targetPath, targetData); werr != nil { - sess.WriteLine(fmt.Sprintf("Warning: could not link the opposite exit in room %d: %v", targetID, werr)) + if targetPath, tok2 := g.World.GetRoomPath(targetID); tok2 { + targetRoom.Exits[oppositeDir] = world.RewirePreserving(targetExit, newID) + targetData, terr := yaml.Marshal(targetRoom) + if terr != nil { + sess.WriteLine(fmt.Sprintf("Error updating room %d YAML: %v", targetID, terr)) + return + } + if err := txn.Replace(targetPath, targetData, 0644); err != nil { + sess.WriteLine(fmt.Sprintf("Error linking the opposite exit in room %d: %v", targetID, err)) + return } } } + if err := txn.Commit(); err != nil { + sess.WriteLine(fmt.Sprintf("Error committing room insert: %v", err)) + return + } + + g.World.AddRoomPath(newID, newPath) oldRoom := p.RoomID p.ClearMoveState() diff --git a/internal/game/cmd_room_remove.go b/internal/game/cmd_room_remove.go index 361cc74..79b84d8 100644 --- a/internal/game/cmd_room_remove.go +++ b/internal/game/cmd_room_remove.go @@ -166,15 +166,21 @@ func (g *Game) roomRemove(sess *net.Session, args []string) { return } - // Apply: rewire A's dir exit to C, preserving A's current dir-exit props. + // Stage A, C, and B's deletion into ONE journal transaction: the previous + // sequential writes could delete B after rewriting A but before C, leaving + // the map half-pulled with no recovery record. The transaction restores + // every before-image on any failure or crash. + txn := g.newTxn() + + // Rewire A's dir exit to C, preserving A's current dir-exit props. aRoom.Exits[dir] = world.RewirePreserving(aExit, cID) aData, err := yaml.Marshal(aRoom) if err != nil { sess.WriteLine("Error updating current room YAML.") return } - if err := writeRoomFile(aPath, aData); err != nil { - sess.WriteLine("Error writing current room file.") + if err := txn.Replace(aPath, aData, 0644); err != nil { + sess.WriteLine(fmt.Sprintf("Error writing current room file: %v", err)) return } @@ -183,21 +189,28 @@ func (g *Game) roomRemove(sess *net.Session, args []string) { cPath, cPathOK := g.World.GetRoomPath(cID) if cPathOK { cData, cerr := yaml.Marshal(cRoom) - if cerr == nil { - if werr := writeRoomFile(cPath, cData); werr != nil { - sess.WriteLine(fmt.Sprintf("Warning: could not link the opposite exit in room %d: %v", cID, werr)) - } + if cerr != nil { + sess.WriteLine(fmt.Sprintf("Error updating room %d YAML: %v", cID, cerr)) + return + } + if err := txn.Replace(cPath, cData, 0644); err != nil { + sess.WriteLine(fmt.Sprintf("Error linking the opposite exit in room %d: %v", cID, err)) + return } } - // Delete B's file. + // Delete B's file in the same transaction. bPath, bPathOK := g.World.GetRoomPath(bID) if !bPathOK { sess.WriteLine(fmt.Sprintf("Room file for %d not found.", bID)) return } - if rerr := os.Remove(bPath); rerr != nil { - sess.WriteLine(fmt.Sprintf("Error deleting room file: %v", rerr)) + if err := txn.Delete(bPath); err != nil { + sess.WriteLine(fmt.Sprintf("Error deleting room file: %v", err)) + return + } + if err := txn.Commit(); err != nil { + sess.WriteLine(fmt.Sprintf("Error committing room remove: %v", err)) return } diff --git a/internal/game/cmd_room_txn_regression_test.go b/internal/game/cmd_room_txn_regression_test.go new file mode 100644 index 0000000..3b5e864 --- /dev/null +++ b/internal/game/cmd_room_txn_regression_test.go @@ -0,0 +1,119 @@ +package game + +// Regression: the in-game `room insert`/`room remove` commands must commit all +// their file changes as one journaled transaction. A failure partway through +// (or a crash) must leave the world exactly as before, with no dangling exit +// and no half-deleted room. + +import ( + "os" + "path/filepath" + "testing" + + "thehouseoficarus/internal/player" + "thehouseoficarus/internal/world" +) + +func TestRoomInsertCommitsTransactionally(t *testing.T) { + dir := t.TempDir() + writeRemoveRoomFile(t, dir, 1, "name: A\nexits:\n east: {room: 2}\n") + writeRemoveRoomFile(t, dir, 2, "name: B\nexits:\n west: {room: 1}\n") + g := newRemoveGame(t, dir) + sess := newRemoveSession(&player.Player{Name: "tester", RoomID: 1}) + + g.roomInsert(sess, []string{"east", "New Room"}) + + // A now leads east to the new room, which leads east to B and west to A; + // B's reciprocal west exit points at the new room. + a := reloadRoom(t, g, 1) + newID := a.Exits[world.East].Room + if newID == 2 { + t.Fatalf("insert did not create a new room: A.east=%d", newID) + } + newRoom := reloadRoom(t, g, newID) + if newRoom.Exits[world.East].Room != 2 || newRoom.Exits[world.West].Room != 1 { + t.Fatalf("new room exits wrong: %+v", newRoom.Exits) + } + b := reloadRoom(t, g, 2) + if b.Exits[world.West].Room != newID { + t.Fatalf("B.west = %d, want %d", b.Exits[world.West].Room, newID) + } + + // A committed transaction leaves no journal behind. + if entries, err := os.ReadDir(filepath.Join(dir, ".journal")); err == nil { + for _, e := range entries { + t.Fatalf("leftover journal after insert: %s", e.Name()) + } + } +} + +// A failure committing the current-room rewrite must roll back the already +// staged new room, leaving no dangling exit and no orphan file. +func TestRoomInsertRollsBackOnCommitFailure(t *testing.T) { + dir := t.TempDir() + writeRemoveRoomFile(t, dir, 1, "name: A\nexits:\n east: {room: 2}\n") + writeRemoveRoomFile(t, dir, 2, "name: B\nexits:\n west: {room: 1}\n") + g := newRemoveGame(t, dir) + sess := newRemoveSession(&player.Player{Name: "tester", RoomID: 1}) + + // Make the current room file unwritable by replacing it with a directory: + // the transaction's replace of curPath fails during apply and rolls back. + curPath := filepath.Join(dir, "rooms", "1.yaml") + if err := os.Remove(curPath); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(curPath, 0o755); err != nil { + t.Fatal(err) + } + + g.roomInsert(sess, []string{"east", "New Room"}) + + // The insert picks the first unused ID (3). The rolled-back insert must + // not leave that file behind. + if _, err := os.Stat(filepath.Join(dir, "rooms", "3.yaml")); !os.IsNotExist(err) { + t.Fatalf("rolled-back insert left the new room file (err=%v)", err) + } + // B's reciprocal exit must be unchanged (no dangling reference to a + // room that was rolled back). + b := reloadRoom(t, g, 2) + if b.Exits[world.West].Room != 1 { + t.Fatalf("B.west = %d, want 1 after rollback", b.Exits[world.West].Room) + } +} + +func TestRoomRemoveRollsBackOnCommitFailure(t *testing.T) { + dir := t.TempDir() + writeRemoveRoomFile(t, dir, 1, "name: A\nexits:\n east: {room: 2}\n") + writeRemoveRoomFile(t, dir, 2, "name: B\nexits:\n east: {room: 3}\n west: {room: 1}\n") + writeRemoveRoomFile(t, dir, 3, "name: C\nexits:\n west: {room: 2}\n") + g := newRemoveGame(t, dir) + sess := newRemoveSession(&player.Player{Name: "tester", RoomID: 1}) + + // Replace C's file with a directory so the transaction's replace of C fails + // AFTER A has been staged. The old sequential code wrote A, only warned on + // the C failure, and still deleted B — leaving A pointing at C while C did + // not point back. The transaction must roll A back and keep B. + cPath := filepath.Join(dir, "rooms", "3.yaml") + if err := os.Remove(cPath); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(cPath, 0o755); err != nil { + t.Fatal(err) + } + + g.roomRemove(sess, []string{"east"}) + + // B must still exist: the remove must not have half-applied. + if _, err := os.Stat(filepath.Join(dir, "rooms", "2.yaml")); err != nil { + t.Fatalf("rolled-back remove deleted B: %v", err) + } + // A must still point at B, not at the C rewrite that was rolled back. + a := reloadRoom(t, g, 1) + if a.Exits[world.East].Room != 2 { + t.Fatalf("A.east = %d, want 2 after rollback", a.Exits[world.East].Room) + } + b := reloadRoom(t, g, 2) + if b.Exits[world.West].Room != 1 || b.Exits[world.East].Room != 3 { + t.Fatalf("B exits changed after rollback: %+v", b.Exits) + } +} diff --git a/internal/game/cmd_swapid.go b/internal/game/cmd_swapid.go index d1dbd68..b0863d4 100644 --- a/internal/game/cmd_swapid.go +++ b/internal/game/cmd_swapid.go @@ -3,10 +3,12 @@ package game import ( "fmt" "os" + "path/filepath" "strconv" "gopkg.in/yaml.v3" + "thehouseoficarus/internal/behavior" "thehouseoficarus/internal/net" ) @@ -149,6 +151,26 @@ func (g *Game) executeSwapID(sess *net.Session, args []string, rawInput string) } updated++ } + // Non-room content (courses, modules, triggers, items, objects, mobs) + // carries structural room references too. Stage it into the SAME journal + // transaction as the room files, so a swap never leaves a course obstacle, + // transport destination, or trigger teleport pointing at the wrong room + // even if one side's write fails. + contentUpdated := 0 + for _, sub := range behavior.RoomRefContentDirs { + changes, cerr := behavior.RewriteRoomRefsInDir(filepath.Join(g.DataDir, sub), idMap) + if cerr != nil { + sess.WriteLine(fmt.Sprintf("Error scanning %s for room references: %v", sub, cerr)) + return + } + for _, ch := range changes { + if werr := rewriteTxn.Replace(ch.Path, ch.Content, 0644); werr != nil { + sess.WriteLine(fmt.Sprintf("Error rewriting %s: %v", ch.Path, werr)) + return + } + contentUpdated++ + } + } if rerr := rewriteTxn.Commit(); rerr != nil { sess.WriteLine(fmt.Sprintf("Error rewriting room references: %v", rerr)) return @@ -162,5 +184,5 @@ func (g *Game) executeSwapID(sess *net.Session, args []string, rawInput string) // from the owner command loop) and must not dispatch again. g.MigrateRoomIDsOnOwner(idMap) - sess.WriteLine(fmt.Sprintf("Swapped room IDs %d and %d (%d files updated).", id1, id2, updated)) + sess.WriteLine(fmt.Sprintf("Swapped room IDs %d and %d (%d room files, %d content files updated).", id1, id2, updated, contentUpdated)) } diff --git a/internal/game/core_production.go b/internal/game/core_production.go index 7a4b6e9..3aaa6b5 100644 --- a/internal/game/core_production.go +++ b/internal/game/core_production.go @@ -109,11 +109,11 @@ var productionTypes = map[string]productionTypeInfo{ }, } -var productionActionTypes map[string]bool +var productionActionTypes map[behavior.ActionType]bool func init() { - productionActionTypes = make(map[string]bool) + productionActionTypes = make(map[behavior.ActionType]bool) for _, pt := range productionTypes { - productionActionTypes[string(pt.ActionType)] = true + productionActionTypes[pt.ActionType] = true } } diff --git a/internal/game/exit_migrate.go b/internal/game/exit_migrate.go index 66fccfe..f6df05d 100644 --- a/internal/game/exit_migrate.go +++ b/internal/game/exit_migrate.go @@ -1,6 +1,7 @@ package game import ( + "log" "strconv" "strings" @@ -190,4 +191,18 @@ func (g *Game) MigrateRoomIDsOnOwner(idMap map[int]int) { // lookups agree with the post-migration layout. g.World.RebuildRoomIndex(g.DataDir) g.RewriteRoomIDs(idMap) + + // Non-room content files (courses, modules, file-backed triggers) were + // rewritten with the same idMap. Reload their in-memory caches so gameplay + // follows the rename immediately instead of at the next restart. In-flight + // sequences hold pointers into the old trigger/step data, so abort them the + // same way a full content reload does. + if g.CourseStore != nil { + g.CourseStore.ReloadAll() + } + if err := g.LoadMods(); err != nil { + log.Printf("room-id migration: reload modules: %v", err) + } + g.abortAllSequences() + g.loadAllFlagTriggers() } diff --git a/internal/game/swapid_content_test.go b/internal/game/swapid_content_test.go new file mode 100644 index 0000000..f1eb978 --- /dev/null +++ b/internal/game/swapid_content_test.go @@ -0,0 +1,64 @@ +package game + +// Regression: `swapid` rewrites structural room references in non-room content +// files (modules, triggers, items, ...) as well as in data/rooms. Before this, +// only room YAML was scanned, so a transport destination or trigger teleport +// silently kept pointing at the pre-swap ID. + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestSwapIDRewritesNonRoomContent(t *testing.T) { + h := newHarness(t) + h.seedAccount("admin") + h.seedCharacter("admin", "admin") + acc, err := h.g.AccountStore.LoadAccount("admin") + if err != nil { + t.Fatal(err) + } + acc.Admin = true + if err := h.g.AccountStore.SaveAccount(acc); err != nil { + t.Fatal(err) + } + sess, _ := h.connect("admin") + + // A transport module destination and an author value that equals a room ID. + modulesDir := filepath.Join(h.dir, "modules") + if err := os.MkdirAll(modulesDir, 0o755); err != nil { + t.Fatal(err) + } + modulePath := filepath.Join(modulesDir, "transport_home.yaml") + if err := os.WriteFile(modulePath, []byte("name: Home\ncategory: transport\ndestination: 1\n"), 0o644); err != nil { + t.Fatal(err) + } + itemsDir := filepath.Join(h.dir, "items") + if err := os.MkdirAll(itemsDir, 0o755); err != nil { + t.Fatal(err) + } + itemPath := filepath.Join(itemsDir, "gem.yaml") + if err := os.WriteFile(itemPath, []byte("name: gem\nvalue: 1\n"), 0o644); err != nil { + t.Fatal(err) + } + + h.g.RunOnOwner(func() { h.g.executeSwapID(sess, []string{"1", "2"}, "swapid 1 2") }) + + module, err := os.ReadFile(modulePath) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(module), "destination: 2") { + t.Errorf("module destination not swapped: %s", module) + } + // value: 1 is an author value, not a structural room reference. + item, err := os.ReadFile(itemPath) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(item), "value: 1") { + t.Errorf("author value equal to a swapped ID was rewritten: %s", item) + } +} diff --git a/internal/game/tick.go b/internal/game/tick.go index a57ea26..6c3eb7d 100644 --- a/internal/game/tick.go +++ b/internal/game/tick.go @@ -208,7 +208,7 @@ func (g *Game) SharedDepletionTick() { activeKeys := make(map[string]bool) for _, sess := range g.Hub.AllSessions() { p := sess.Player - if p == nil || p.Action == nil || p.Action.Type != "gather" { + if p == nil || p.Action == nil || p.Action.Type != behavior.TypeGather { continue } if gd, ok := p.Action.Data.(*behavior.GatherData); ok { |
