aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/respawn_durability_test.go (9499B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"database/sql"
      6 	"encoding/binary"
      7 	"reflect"
      8 	"testing"
      9 	"time"
     10 )
     11 
     12 type respawnCommitConn struct {
     13 	combatTestConn
     14 	db       *sql.DB
     15 	health   uint32
     16 	deadline time.Time
     17 	nextID   uint32
     18 	err      error
     19 }
     20 
     21 func (conn *respawnCommitConn) Write(packet []byte) (int, error) {
     22 	if binary.BigEndian.Uint32(packet[16:20]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[24:28]) == 1000001 {
     23 		conn.err = conn.db.QueryRow("SELECT replacement.health, source.respawn_at, world.last_npc_id FROM characters replacement JOIN npcs source ON source.id=1000000 JOIN world ON world.id=1 WHERE replacement.id=1000001").Scan(&conn.health, &conn.deadline, &conn.nextID)
     24 	}
     25 	return conn.combatTestConn.Write(packet)
     26 }
     27 
     28 func TestNPCRespawnBirthIsDurableBeforePublication(t *testing.T) {
     29 	world, _ := newRangedWorld(t)
     30 	target := world.characters[1000000]
     31 	target.health, target.monsterData, target.level = 1, 17655, 1
     32 	target.combatProfile = gamedata.NPCCombatProfiles[17655][1]
     33 	if err := world.flushWorld(); err != nil {
     34 		t.Fatal(err)
     35 	}
     36 	world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:])
     37 	world.advanceCombat(world.characters[1].nextAttack)
     38 	conn := &respawnCommitConn{db: world.db}
     39 	world.clients[1].conn = conn
     40 
     41 	world.advanceNPCRespawns(world.npcRespawns[0].at)
     42 	restored := newTestInventoryServer(t)
     43 	published := false
     44 	for _, packet := range conn.packets {
     45 		if binary.BigEndian.Uint32(packet[16:20]) == 0x271b3a6b && binary.BigEndian.Uint32(packet[24:28]) == 1000001 {
     46 			published = true
     47 		}
     48 	}
     49 
     50 	if !published {
     51 		t.Fatal("fixture did not publish its new actor")
     52 	}
     53 	if conn.err != nil || conn.health != 100 || !conn.deadline.IsZero() || conn.nextID != 1000002 {
     54 		t.Fatalf("first native actor packet preceded the committed lifecycle: health=%d deadline=%v nextID=%d, %v", conn.health, conn.deadline, conn.nextID, conn.err)
     55 	}
     56 	if restored.characters[1000001] == nil || len(restored.npcRespawns) != 0 {
     57 		t.Fatalf("published respawn not committed: new NPC exists=%t; old pending respawns=%d", restored.characters[1000001] != nil, len(restored.npcRespawns))
     58 	}
     59 }
     60 
     61 func TestNPCRespawnFailureKeepsPendingLifeAndRetriesOnce(t *testing.T) {
     62 	for _, failure := range []struct{ name, statement string }{
     63 		{"source", "CREATE TRIGGER fail_respawn BEFORE UPDATE ON npcs WHEN NEW.id=1000000 BEGIN SELECT RAISE(FAIL, 'test source failure'); END"},
     64 		{"new character", "CREATE TRIGGER fail_respawn BEFORE INSERT ON characters WHEN NEW.id>=1000001 BEGIN SELECT RAISE(FAIL, 'test actor failure'); END"},
     65 		{"new NPC", "CREATE TRIGGER fail_respawn BEFORE INSERT ON npcs WHEN NEW.id>=1000001 BEGIN SELECT RAISE(FAIL, 'test NPC failure'); END"},
     66 		{"identity", "CREATE TRIGGER fail_respawn BEFORE UPDATE ON world WHEN NEW.last_npc_id>=1000002 BEGIN SELECT RAISE(FAIL, 'test identity failure'); END"},
     67 		{"commit", "CREATE TABLE pending_spawn (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_respawn AFTER INSERT ON npcs WHEN NEW.id>=1000001 BEGIN INSERT INTO pending_spawn VALUES (999999); END"},
     68 	} {
     69 		t.Run(failure.name, func(t *testing.T) {
     70 			world, conn := newRespawnWorld(t)
     71 			world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:])
     72 			world.advanceCombat(world.characters[1].nextAttack)
     73 			due := world.npcRespawns[0].at
     74 			before := world.savedNPCs[1000000]
     75 			source := world.characters[1000000]
     76 			if _, err := world.db.Exec(failure.statement); err != nil {
     77 				t.Fatal(err)
     78 			}
     79 			conn.packets = nil
     80 
     81 			world.advanceNPCRespawns(due)
     82 			world.advanceNPCRespawns(due.Add(time.Second))
     83 			restored := newTestInventoryServer(t)
     84 			if world.characters[1000001] != nil || world.nextNPC != 1000001 || len(world.npcRespawns) != 1 ||
     85 				!world.npcRespawns[0].at.Equal(due) || !reflect.DeepEqual(world.savedNPCs[1000000], before) ||
     86 				len(world.mobileNPCs[950]) != 1 || world.mobileNPCs[950][0] != source || len(conn.packets) != 0 ||
     87 				restored.characters[1000001] != nil || restored.nextNPC != 1000001 || len(restored.npcRespawns) != 1 ||
     88 				!restored.npcRespawns[0].at.Equal(due) {
     89 				t.Fatal("failed transaction changed live or durable respawn state, or published an actor")
     90 			}
     91 			if _, err := world.db.Exec("DROP TRIGGER fail_respawn"); err != nil {
     92 				t.Fatal(err)
     93 			}
     94 			world.advanceNPCRespawns(due.Add(2 * time.Second))
     95 			world.advanceNPCRespawns(due.Add(3 * time.Second))
     96 			afterRetry := newTestInventoryServer(t)
     97 
     98 			if world.characters[1000003] == nil || world.characters[1000003].health != 20 || len(world.npcRespawns) != 0 ||
     99 				world.nextNPC != 1000004 || world.mobileNPCs[950][0].id != 1000003 || len(conn.packets) != 2 ||
    100 				afterRetry.characters[1000003] == nil || len(afterRetry.npcRespawns) != 0 || afterRetry.nextNPC != 1000004 {
    101 				t.Fatal("retry did not create and commit exactly one fresh life")
    102 			}
    103 		})
    104 	}
    105 }
    106 
    107 func newRespawnWithFilledCorpse(t *testing.T) (*server, time.Time) {
    108 	t.Helper()
    109 	useNPCData(t, testNPCData())
    110 	world := newFilledLootContainerWorld(t, 143832)
    111 	source := world.characters[1000000]
    112 	source.level = 1
    113 	source.combatProfile = gamedata.NPCCombatProfiles[17655][1]
    114 	now := time.Now().UTC()
    115 	source.corpse.expiresAt = now.Add(time.Second)
    116 	world.corpseExpiry = []*character{source}
    117 	world.npcRespawns = []npcRespawn{{source, now.Add(3 * time.Second)}}
    118 	if granted, err := world.grantItem(world.characters[1], 121567); !granted || err != nil {
    119 		t.Fatalf("fixture inventory item: %t %v", granted, err)
    120 	}
    121 	if err := world.flushWorld(); err != nil {
    122 		t.Fatal(err)
    123 	}
    124 	return world, now
    125 }
    126 
    127 func TestNPCRespawnAfterExpiryCleansOnlyUnlootedContents(t *testing.T) {
    128 	for _, checkpoint := range []bool{false, true} {
    129 		t.Run(map[bool]string{false: "before checkpoint", true: "after checkpoint"}[checkpoint], func(t *testing.T) {
    130 			world, now := newRespawnWithFilledCorpse(t)
    131 			world.advanceCorpseExpiry(now.Add(time.Second))
    132 			if checkpoint {
    133 				if err := world.flushWorld(); err != nil {
    134 					t.Fatal(err)
    135 				}
    136 			}
    137 
    138 			world.advanceNPCRespawns(now.Add(3 * time.Second))
    139 			restored := newTestInventoryServer(t)
    140 
    141 			if world.characters[1000000] != nil || restored.characters[1000000] != nil || restored.characters[1000001] == nil ||
    142 				len(world.items) != 1 || len(restored.items) != 1 || len(restored.npcRespawns) != 0 || len(restored.corpseExpiry) != 0 ||
    143 				restored.nextNPC != 1000002 || restored.nextItem != 19 || len(restored.characters[1].inventory.Items) != 1 ||
    144 				restored.characters[1].inventory.Items[0].ID != 19 || restored.items[19].Template != 121567 ||
    145 				len(world.itemPlacements) != 1 || world.itemPlacements[19].Player != 1 {
    146 				t.Fatal("expired filled corpse cleanup lost unrelated inventory, retained orphan items or replayed its respawn")
    147 			}
    148 		})
    149 	}
    150 }
    151 
    152 func TestNPCRespawnAfterExpiryPreservesTransferredBackpack(t *testing.T) {
    153 	world, now := newRespawnWithFilledCorpse(t)
    154 	if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil {
    155 		t.Fatal(err)
    156 	}
    157 	if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil {
    158 		t.Fatal(err)
    159 	}
    160 	world.advanceCorpseExpiry(now.Add(time.Second))
    161 
    162 	world.advanceNPCRespawns(now.Add(3 * time.Second))
    163 	restored := newTestInventoryServer(t)
    164 
    165 	if restored.characters[1000000] != nil || restored.characters[1000001] == nil || len(restored.items) != 3 || restored.nextItem != 19 ||
    166 		len(restored.characters[1].inventory.Items) != 2 || len(restored.characters[1].inventory.Containers[17]) != 1 ||
    167 		restored.characters[1].inventory.Containers[17][0] != (ownedItem{ID: 18, Type: 51005, Template: 152030, Quality: 42, Count: 3}) ||
    168 		world.itemPlacements[17].Player != 1 || world.itemPlacements[18].Backpack != 17 {
    169 		t.Fatal("retiring an expired source removed or changed a backpack already transferred to a player")
    170 	}
    171 }
    172 
    173 func TestNPCRespawnExpiredSourceRemovalFailureKeepsPendingReplacement(t *testing.T) {
    174 	for _, statement := range []string{
    175 		"CREATE TRIGGER fail_cleanup BEFORE DELETE ON characters WHEN OLD.id=1000000 BEGIN SELECT RAISE(FAIL, 'test source removal failure'); END",
    176 		"CREATE TRIGGER fail_cleanup BEFORE DELETE ON characters WHEN OLD.id=1000000 BEGIN SELECT RAISE(IGNORE); END",
    177 	} {
    178 		t.Run(statement, func(t *testing.T) {
    179 			world, now := newRespawnWithFilledCorpse(t)
    180 			world.advanceCorpseExpiry(now.Add(time.Second))
    181 			if _, err := world.db.Exec(statement); err != nil {
    182 				t.Fatal(err)
    183 			}
    184 			conn := world.clients[1].conn.(*combatTestConn)
    185 			conn.packets = nil
    186 
    187 			world.advanceNPCRespawns(now.Add(3 * time.Second))
    188 			var locations uint32
    189 			if err := world.db.QueryRow("SELECT count(*) FROM item_locations WHERE item_id IN (17,18)").Scan(&locations); err != nil {
    190 				t.Fatal(err)
    191 			}
    192 			if locations != 0 || len(world.items) != 1 || len(world.itemPlacements) != 1 || len(world.npcRespawns) != 1 ||
    193 				world.characters[1000001] != nil || world.nextNPC != 1000001 || len(conn.packets) != 0 {
    194 				t.Fatal("failed source removal restored expired loot, lost the pending life or published a replacement")
    195 			}
    196 			if _, err := world.db.Exec("DROP TRIGGER fail_cleanup"); err != nil {
    197 				t.Fatal(err)
    198 			}
    199 			world.advanceNPCRespawns(now.Add(4 * time.Second))
    200 			restored := newTestInventoryServer(t)
    201 
    202 			if restored.characters[1000002] == nil || restored.characters[1000000] != nil || len(restored.items) != 1 ||
    203 				restored.items[19].Template != 121567 || len(restored.npcRespawns) != 0 || restored.nextNPC != 1000003 {
    204 				t.Fatal("retry failed to commit cleanup and one replacement")
    205 			}
    206 		})
    207 	}
    208 }