server/database_test.go (11910B)
1 package main 2 3 import ( 4 "database/sql" 5 "encoding/json" 6 "fmt" 7 "net/http" 8 "net/url" 9 "os" 10 "testing" 11 "time" 12 ) 13 14 func TestWorldDatabaseInitializationRollsBackAndRetries(t *testing.T) { 15 t.Chdir(t.TempDir()) 16 world := &server{} 17 registerTestDatabaseCleanup(t, world) 18 originalSchema := worldSchema 19 t.Cleanup(func() { worldSchema = originalSchema }) 20 worldSchema += "\nCREATE TRIGGER reject_world BEFORE INSERT ON world BEGIN SELECT RAISE(ABORT, 'reject initialization'); END;" 21 22 // Failure to create the initial world row must also undo the schema. 23 if db, err := world.openDatabase(); err == nil || db != nil || world.db != nil { 24 t.Fatal("failed initialization published a database", db, err) 25 } 26 probe := sql.OpenDB(databaseConnector{&world.databaseQueries}) 27 t.Cleanup(func() { probe.Close() }) 28 var tables int 29 if err := probe.QueryRow("SELECT count(*) FROM sqlite_master WHERE type='table'").Scan(&tables); err != nil || tables != 0 { 30 t.Fatal("failed initialization retained partial schema", tables, err) 31 } 32 33 // Correcting the cause permits a complete initialization in the same file. 34 worldSchema = originalSchema 35 db, err := world.openDatabase() 36 if err != nil { 37 t.Fatal(err) 38 } 39 var rows int 40 if err := db.QueryRow("SELECT count(*) FROM world WHERE id=1").Scan(&rows); err != nil || rows != 1 { 41 t.Fatal("retry did not create the initial world row", rows, err) 42 } 43 } 44 45 func readTestPlayerRecord(id uint32, name string) ([]byte, error) { 46 world := &server{} 47 db, err := world.openDatabase() 48 if err != nil { 49 return nil, err 50 } 51 defer world.closeDatabase() 52 var record characterRecord 53 err = db.QueryRow("SELECT id, "+characterColumns+" FROM characters WHERE id=?", id).Scan(append([]any{&record.Profile.ID}, record.fields()...)...) 54 if err != nil { 55 return nil, err 56 } 57 switch name { 58 case "player": 59 return json.Marshal(record.Profile) 60 case "position": 61 return json.Marshal(record.Position.editor()) 62 default: 63 return nil, fmt.Errorf("unknown test record %q", name) 64 } 65 } 66 67 func readTestItemStore(world *server) ([]byte, error) { 68 store, err := world.readItems() 69 if err != nil { 70 return nil, err 71 } 72 return json.Marshal(store) 73 } 74 75 func readTestChatHistory(world *server, id uint32) ([]byte, error) { 76 entries, err := world.chatHistory(id) 77 if err != nil { 78 return nil, err 79 } 80 var data []byte 81 for _, entry := range entries { 82 line, err := json.Marshal(entry) 83 if err != nil { 84 return nil, err 85 } 86 data = append(data, line...) 87 data = append(data, '\n') 88 } 89 return data, nil 90 } 91 func failDatabaseWrites(t *testing.T, world *server) { 92 t.Helper() 93 db, err := world.openDatabase() 94 if err != nil { 95 t.Fatal(err) 96 } 97 if _, err := db.Exec("PRAGMA query_only=ON"); err != nil { 98 t.Fatal(err) 99 } 100 t.Cleanup(func() { db.Exec("PRAGMA query_only=OFF") }) 101 } 102 103 func TestWorldDatabaseRestoresNPCStateAndPlayerVitals(t *testing.T) { 104 useNPCData(t, testNPCData()) 105 world := newTestServer(t) 106 postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) 107 player := world.characters[1] 108 player.health, player.nano, player.sitting, player.aggDef = 27, 11, true, 33 109 player.inventory.Credits = 913 110 player.nanoRechargeUntil = time.Now().Add(30 * time.Second) 111 if err := world.saveInventory(player, player.inventory); err != nil { 112 t.Fatal(err) 113 } 114 now := time.Now().UTC() 115 npc := world.characters[1000000] 116 npc.health, npc.position = 0, [3]float32{53, 14, 57} 117 npc.motion = &npcMotion{roaming: true, home: [3]float32{52, 14, 56}, destination: [3]float32{54, 14, 58}, nextMove: now.Add(time.Second)} 118 npc.corpse = &npcCorpse{looter: 1, credits: 87, expiresAt: now.Add(180 * time.Second), 119 items: []ownedItem{{ID: 17, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}}} 120 world.corpseExpiry = []*character{npc} 121 world.npcRespawns = []npcRespawn{{npc, now.Add(100 * time.Second)}} 122 // Seed the corpse's items and credits as one durable outcome before startup. 123 if err := world.flushWorld(); err != nil { 124 t.Fatal(err) 125 } 126 shutdown := startTestService(t, world) 127 response := postControlForm(world, "/admin/time", url.Values{"hour": {"9"}, "minute": {"17"}}) 128 129 var clockStarted time.Time 130 callTestZone(t, world, 1, zoneTestCommand(func(state *server) error { 131 clockStarted = state.clockStarted 132 return nil 133 })) 134 if err := shutdown(); err != nil { 135 t.Fatal(err) 136 } 137 restarted := newServerForTest(t) 138 var integrity string 139 if err := restarted.db.QueryRow("PRAGMA integrity_check").Scan(&integrity); err != nil { 140 t.Fatal(err) 141 } 142 var itemCount int 143 if err := restarted.db.QueryRow("SELECT count(*) FROM items").Scan(&itemCount); err != nil { 144 t.Fatal(err) 145 } 146 147 restored := restarted.characters[1] 148 corpse := restarted.characters[1000000] 149 if response.Code != http.StatusSeeOther || integrity != "ok" || itemCount != 1 || len(restarted.characters) != 2 { 150 t.Fatalf("world state: response=%d integrity=%s items=%d characters=%d", response.Code, integrity, itemCount, len(restarted.characters)) 151 } 152 if restored.health != 27 || restored.nano != 11 || !restored.sitting || restored.aggDef != 33 || restored.inventory.Credits != 913 || !restored.nanoRechargeUntil.Equal(player.nanoRechargeUntil) { 153 t.Fatal("player vitals, credits or cooldown were lost") 154 } 155 if corpse.health != 0 || corpse.position != [3]float32{53, 14, 57} || corpse.motion.home != [3]float32{52, 14, 56} || 156 corpse.corpse.credits != 87 || corpse.corpse.looter != 1 || len(corpse.corpse.items) != 1 || corpse.corpse.items[0].ID != 17 || restarted.nextItem != 17 { 157 t.Fatal("NPC pose, corpse ownership, loot or identity counter was lost") 158 } 159 if len(restarted.npcRespawns) != 1 || !restarted.npcRespawns[0].at.Equal(now.Add(100*time.Second)) || 160 len(restarted.corpseExpiry) != 1 || !corpse.corpse.expiresAt.Equal(now.Add(180*time.Second)) { 161 t.Fatal("corpse or respawn deadline was lost") 162 } 163 if restarted.gameSeconds != 33420 || !restarted.clockStarted.Equal(clockStarted) { 164 t.Fatal("world clock reset") 165 } 166 for _, path := range []string{"data/players", "data/items.yaml"} { 167 if _, err := os.Stat(path); !os.IsNotExist(err) { 168 t.Fatalf("mutable YAML state still exists at %s", path) 169 } 170 } 171 } 172 173 func TestWorldDatabaseKeepsRespawnAfterCorpseExpires(t *testing.T) { 174 useNPCData(t, testNPCData()) 175 world := newTestServer(t) 176 now := time.Now().UTC() 177 npc := world.characters[1000000] 178 npc.health = 0 179 npc.motion = &npcMotion{roaming: true, home: [3]float32{52, 14, 56}} 180 npc.corpse = &npcCorpse{expiresAt: now.Add(time.Second), items: []ownedItem{{ID: 17, Type: 51018, Template: 121567, Quality: 1, Slot: 0, Count: 1}}} 181 world.corpseExpiry = []*character{npc} 182 world.npcRespawns = []npcRespawn{{npc, now.Add(3 * time.Second)}} 183 if err := world.flushWorld(); err != nil { 184 t.Fatal(err) 185 } 186 187 world.advanceCorpseExpiry(now.Add(time.Second)) 188 if err := world.flushWorld(); err != nil { 189 t.Fatal(err) 190 } 191 restarted := newServerForTest(t) 192 if restarted.characters[1000000] != nil || len(restarted.npcRespawns) != 1 || len(restarted.items) != 0 { 193 t.Fatal("expired corpse was restored or its respawn source was discarded") 194 } 195 restarted.advanceNPCRespawns(now.Add(3 * time.Second)) 196 if err := restarted.flushWorld(); err != nil { 197 t.Fatal(err) 198 } 199 again := newServerForTest(t) 200 201 if len(again.characters) != 1 || again.characters[1000001] == nil || again.characters[1000001].position != [3]float32{52, 14, 56} || 202 len(again.npcRespawns) != 0 || len(again.corpseExpiry) != 0 || len(again.mobileNPCs[950]) != 1 || again.nextItem != 17 || again.nextNPC != 1000002 { 203 t.Fatal("respawn duplicated the source, lost home or reused an identity") 204 } 205 } 206 207 func TestWorldDatabaseRollsBackCorpseCashWithInventory(t *testing.T) { 208 t.Chdir(t.TempDir()) 209 world, _ := newCorpseCreditWorld(t) 210 defer world.closeDatabase() 211 world.characters[1].inventory.Credits = 10 212 world.characters[1000000].corpse.credits = 32 213 if err := world.saveInventory(world.characters[1], world.characters[1].inventory); err != nil { 214 t.Fatal(err) 215 } 216 if _, err := world.db.Exec("CREATE TRIGGER reject_cash BEFORE UPDATE ON npcs WHEN NEW.id=1000000 AND NEW.credits=0 BEGIN SELECT RAISE(ABORT, 'write failed'); END"); err != nil { 217 t.Fatal(err) 218 } 219 220 saveErr := world.handleLootUse(world.clients[1], lootUseRequest(1)) 221 restarted := newTestInventoryServer(t) 222 if _, err := world.db.Exec("DROP TRIGGER reject_cash"); err != nil { 223 t.Fatal(err) 224 } 225 if err := world.handleLootUse(world.clients[1], lootUseRequest(2)); err != nil { 226 t.Fatal(err) 227 } 228 committed := newTestInventoryServer(t) 229 230 if saveErr == nil || restarted.characters[1].inventory.Credits != 10 || restarted.characters[1000000].corpse.credits != 32 || 231 committed.characters[1].inventory.Credits != 42 || committed.characters[1000000].corpse.credits != 0 { 232 t.Fatalf("corpse cash and player inventory did not commit together: %v", saveErr) 233 } 234 } 235 236 func TestProfileEditorCommitsCurrentResourcesWithProfile(t *testing.T) { 237 useNPCData(t, testNPCData()) 238 world := newTestServer(t) 239 postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) 240 world.characters[1].health, world.characters[1].nano = 30, 12 241 242 response := postControlForm(world, "/admin/players/1", playerFixtureForm("id: 1\nname: Explorer\nappearance: {race: 1, fatness: 1, breed: 1, sex: 2, side: 1, head: 0}\nlevel: 2\n")) 243 restarted := newServerForTest(t) 244 245 if response.Code != http.StatusSeeOther || restarted.characters[1].level != 2 || restarted.characters[1].health != 30 || restarted.characters[1].nano != 12 { 246 t.Fatal("profile edit saved stale health or nano") 247 } 248 } 249 250 func TestWorldDatabasePersistsContributorChangesAfterRestart(t *testing.T) { 251 useNPCData(t, testNPCData()) 252 world := newTestServer(t) 253 world.characters[1000000].damageContributors = map[damageContributor]uint32{{player: 1}: 4} 254 if err := world.flushWorld(); err != nil { 255 t.Fatal(err) 256 } 257 restarted := newServerForTest(t) 258 259 restarted.characters[1000000].damageContributors[damageContributor{player: 1}] = 9 260 if err := restarted.flushWorld(); err != nil { 261 t.Fatal(err) 262 } 263 again := newServerForTest(t) 264 var damage uint32 265 err := again.db.QueryRow("SELECT damage FROM npc_damage_contributors WHERE npc_id=1000000 AND player_id=1").Scan(&damage) 266 267 if err != nil || damage != 9 || again.characters[1000000].damageContributors[damageContributor{player: 1}] != 9 { 268 t.Fatalf("NPC contribution change was not checkpointed: %d, %v", damage, err) 269 } 270 } 271 272 func TestNPCCheckpointsSkipDormantNPCsAndLimitRoutineWrites(t *testing.T) { 273 useNPCData(t, testNPCData()) 274 world := newTestServer(t) 275 postControlForm(world, "/admin/players", url.Values{"name": {"Explorer"}}) 276 now := time.Now() 277 if err := world.checkpointWorld(now); err != nil { 278 t.Fatal(err) 279 } 280 if _, err := world.db.Exec("CREATE TABLE npc_updates (id INTEGER); CREATE TRIGGER npc_update AFTER UPDATE ON characters WHEN NEW.id>=1000000 BEGIN INSERT INTO npc_updates VALUES (NEW.id); END"); err != nil { 281 t.Fatal(err) 282 } 283 284 steps := []struct { 285 seconds int 286 present bool 287 x float32 288 }{{60, false, 53}, {61, true, 53}, {62, true, 54}, {80, true, 54}, {102, true, 54}, {103, true, 55}, {1004, false, 55}, {1065, false, 56}} 289 var counts [8]int 290 var positions [8]float32 291 for index, step := range steps { 292 if step.present { 293 world.clients[1] = &worldClient{id: 1, ready: true} 294 } else { 295 delete(world.clients, 1) 296 } 297 world.characters[1000000].position[0] = step.x 298 if err := world.checkpointWorld(now.Add(time.Duration(step.seconds) * time.Second)); err != nil { 299 t.Fatal(err) 300 } 301 if err := world.db.QueryRow("SELECT count(*) FROM npc_updates").Scan(&counts[index]); err != nil { 302 t.Fatal(err) 303 } 304 if err := world.db.QueryRow("SELECT position_x FROM characters WHERE id=1000000").Scan(&positions[index]); err != nil { 305 t.Fatal(err) 306 } 307 } 308 309 if counts != [8]int{0, 1, 1, 1, 2, 2, 3, 3} || positions != [8]float32{52, 53, 53, 53, 54, 54, 55, 55} { 310 t.Fatalf("dormant NPCs or early checkpoints rewrote NPC state: counts=%v positions=%v", counts, positions) 311 } 312 }