aorecomp

Anarchy Online classic in the browser

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


server/fling_crash_test.go (9393B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"bytes"
      6 	"context"
      7 	"encoding/binary"
      8 	"encoding/json"
      9 	"os"
     10 	"os/exec"
     11 	"reflect"
     12 	"strings"
     13 	"testing"
     14 	"time"
     15 )
     16 
     17 type flingCrashCheckpoint struct {
     18 	Directory string
     19 	Packet    []byte
     20 	Published int
     21 }
     22 
     23 type flingCrashConn struct {
     24 	combatTestConn
     25 	checkpoint func([]byte)
     26 }
     27 
     28 func (conn *flingCrashConn) Write(packet []byte) (int, error) {
     29 	conn.checkpoint(packet)
     30 	return conn.combatTestConn.Write(packet)
     31 }
     32 
     33 func runFlingCrashChild(t *testing.T, mode string) {
     34 	t.Helper()
     35 	var world *server
     36 	var output *combatTestConn
     37 	request := flingShotRequest(1, 1000000)
     38 	if strings.Contains(mode, "/fast/") {
     39 		world, output = newFastAttackWorld(t)
     40 		request = fastAttackRequest(1, 1000000)
     41 	} else {
     42 		world, output = newRangedWorld(t)
     43 	}
     44 	world.combatRoll = func(uint32) uint32 { return 0 }
     45 	world.characters[1].experience = 1400
     46 	if err := world.saveUser(world.characters[1]); err != nil {
     47 		t.Fatal(err)
     48 	}
     49 	target := world.characters[1000000]
     50 	target.health, target.monsterData, target.level = 100, 17655, 1
     51 	target.npcDefinitionID = "950/district/2/group/0/authored_point"
     52 	target.combatProfile = gamedata.NPCCombatProfiles[17655][1]
     53 	if strings.HasSuffix(mode, "/kill") {
     54 		target.health = 1
     55 	}
     56 	if _, err := world.saveDamageOutcome(target, time.Now()); err != nil {
     57 		t.Fatal(err)
     58 	}
     59 	if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
     60 		t.Fatal(err)
     61 	}
     62 	output.packets = nil
     63 
     64 	// Notify the parent at the transaction boundary, then await its forced kill.
     65 	directory, err := os.Getwd()
     66 	if err != nil {
     67 		t.Fatal(err)
     68 	}
     69 	pipe := os.NewFile(3, "crash-checkpoint")
     70 	defer pipe.Close()
     71 	checkpoint := func(packet []byte) {
     72 		if err := json.NewEncoder(pipe).Encode(flingCrashCheckpoint{directory, packet, len(output.packets)}); err != nil {
     73 			panic(err)
     74 		}
     75 		time.Sleep(time.Minute)
     76 		panic("parent did not terminate the crash fixture")
     77 	}
     78 	if strings.HasPrefix(mode, "before/") {
     79 		connection, err := world.db.Conn(context.Background())
     80 		if err != nil {
     81 			t.Fatal(err)
     82 		}
     83 		err = connection.Raw(func(driver any) error {
     84 			driver.(*databaseConnection).RegisterCommitHook(func() int32 { checkpoint(nil); return 0 })
     85 			return nil
     86 		})
     87 		connection.Close()
     88 		if err != nil {
     89 			t.Fatal(err)
     90 		}
     91 	} else {
     92 		world.clients[1].conn = &flingCrashConn{checkpoint: checkpoint}
     93 	}
     94 	if err := world.handleWeaponSpecial(world.clients[1], request[20:]); err != nil {
     95 		t.Fatal(err)
     96 	}
     97 	t.Fatal("shot completed without reaching its crash boundary")
     98 }
     99 
    100 func TestFlingShotProcessCrashRecovery(t *testing.T) {
    101 	if mode := os.Getenv("AO_TEST_FLING_CRASH"); mode != "" {
    102 		runFlingCrashChild(t, mode)
    103 		return
    104 	}
    105 	for _, mode := range []string{"before/living", "after/living", "before/kill", "after/kill", "before/fast/living", "after/fast/living", "before/fast/kill", "after/fast/kill"} {
    106 		t.Run(mode, func(t *testing.T) {
    107 			skill := uint32(150)
    108 			request := flingShotRequest(1, 1000000)
    109 			inventory := []ownedItem{
    110 				{ID: 1, Type: 51018, Template: 123742, Quality: 1, Slot: 6, Count: 1, Ammo: 3},
    111 				{ID: 2, Type: 51005, Template: 21605, Quality: 1, Slot: 64, Count: 100},
    112 			}
    113 			if strings.Contains(mode, "/fast/") {
    114 				skill = 147
    115 				request = fastAttackRequest(1, 1000000)
    116 				inventory = []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}}
    117 			}
    118 			executable, err := os.Executable()
    119 			if err != nil {
    120 				t.Fatal(err)
    121 			}
    122 			reader, writer, err := os.Pipe()
    123 			if err != nil {
    124 				t.Fatal(err)
    125 			}
    126 			defer reader.Close()
    127 			defer writer.Close()
    128 			// Instrumented children initialize the full item and monster catalogs.
    129 			ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
    130 			defer cancel()
    131 			command := exec.CommandContext(ctx, executable, "-test.run=^TestFlingShotProcessCrashRecovery$")
    132 			command.Dir = testLaunchDirectory
    133 			command.Env = append(os.Environ(), "AO_TEST_FLING_CRASH="+mode, "TMPDIR="+t.TempDir())
    134 			command.ExtraFiles = []*os.File{writer}
    135 			var processOutput bytes.Buffer
    136 			command.Stdout, command.Stderr = &processOutput, &processOutput
    137 			if err := command.Start(); err != nil {
    138 				t.Fatal(err)
    139 			}
    140 			t.Cleanup(func() {
    141 				if command.ProcessState == nil {
    142 					command.Process.Kill()
    143 					command.Wait()
    144 				}
    145 			})
    146 			writer.Close()
    147 			var checkpoint flingCrashCheckpoint
    148 			ready := make(chan error, 1)
    149 			go func() { ready <- json.NewDecoder(reader).Decode(&checkpoint) }()
    150 
    151 			select {
    152 			case err := <-ready:
    153 				if err != nil {
    154 					command.Wait()
    155 					t.Fatalf("crash checkpoint: %v\n%s", err, processOutput.String())
    156 				}
    157 			case <-ctx.Done():
    158 				t.Fatal("child did not reach the crash checkpoint")
    159 			}
    160 			if err := command.Process.Kill(); err != nil {
    161 				t.Fatal(err)
    162 			}
    163 			if _, killed := command.Wait().(*exec.ExitError); !killed {
    164 				t.Fatalf("child was not forcibly terminated: %s", processOutput.String())
    165 			}
    166 			if bytes.Contains(processOutput.Bytes(), []byte("WARNING: DATA RACE")) {
    167 				t.Fatalf("child reported a race before termination: %s", processOutput.String())
    168 			}
    169 			t.Chdir(checkpoint.Directory)
    170 			restored := newTestInventoryServer(t)
    171 			player, target := restored.characters[1], restored.characters[1000000]
    172 			initialHealth := uint32(100)
    173 			if strings.HasSuffix(mode, "/kill") {
    174 				initialHealth = 1
    175 			}
    176 
    177 			if checkpoint.Published != 0 {
    178 				t.Fatal("shot published feedback before its commit boundary")
    179 			}
    180 			if !reflect.DeepEqual(player.inventory.Items, inventory) {
    181 				t.Fatal("crash changed pre-15.5 ammunition")
    182 			}
    183 			level, experience, points := uint16(1), uint32(1400), uint32(1500)
    184 			if strings.HasPrefix(mode, "after/") && initialHealth == 1 {
    185 				level, experience, points = 2, 50, 5500
    186 			}
    187 			if player.level != level || player.experience != experience || player.stats.ImprovementPoints != points {
    188 				t.Fatal("crash separated XP, level or IP from the killing special")
    189 			}
    190 			if strings.HasPrefix(mode, "before/") {
    191 				if target.health != initialHealth || len(player.skillLocks) != 0 || len(target.damageContributors) != 0 ||
    192 					target.corpse != nil || len(restored.npcRespawns) != 0 {
    193 					t.Fatalf("uncommitted shot survived the process kill: %+v", target)
    194 				}
    195 			} else {
    196 				if len(checkpoint.Packet) != 44 || !bytes.Equal(checkpoint.Packet[16:], targetPacket(append([]byte(nil), request...))[16:]) {
    197 					t.Fatalf("first post-commit output was not the native special action: %x", checkpoint.Packet)
    198 				}
    199 				damage := initialHealth - target.health
    200 				expected := uint32(24)
    201 				if skill == 147 {
    202 					expected = 25
    203 				}
    204 				if damage != min(expected, initialHealth) {
    205 					t.Fatal("crash fixture did not resolve the controlled critical", damage)
    206 				}
    207 				if damage == 0 || damage > initialHealth || target.health != initialHealth-damage || !player.skillLocks[skill].After(time.Now()) ||
    208 					binary.BigEndian.Uint32(checkpoint.Packet[37:41]) != skill ||
    209 					initialHealth != 1 && target.damageContributors[damageContributor{player: 1}] != damage {
    210 					t.Fatalf("committed shot was lost or partially recovered: HP=%d damage=%d lock=%v", target.health, damage, player.skillLocks)
    211 				}
    212 				if initialHealth == 1 && (target.corpse == nil || target.corpse.looter != 1 || target.corpse.expiresAt.IsZero() || len(restored.npcRespawns) != 1) {
    213 					t.Fatal("committed death lost corpse rights, expiry or pending respawn")
    214 				}
    215 				if initialHealth != 1 && (target.corpse != nil || len(restored.npcRespawns) != 0) {
    216 					t.Fatal("living shot created death state")
    217 				}
    218 			}
    219 
    220 			// Retry the original request twice through a newly authenticated session.
    221 			output := &combatTestConn{}
    222 			restored.clients[1] = &worldClient{id: 1, ready: true, target: true, conn: output, npcs: map[uint32]bool{1000000: true}}
    223 			for range 2 {
    224 				if err := restored.handleWeaponSpecial(restored.clients[1], request[20:]); err != nil {
    225 					t.Fatal(err)
    226 				}
    227 			}
    228 			results := 0
    229 			for _, packet := range output.packets {
    230 				if binary.BigEndian.Uint32(packet[16:20]) == 0x754f1115 {
    231 					results++
    232 				}
    233 			}
    234 			if strings.HasPrefix(mode, "before/") && results != 1 || strings.HasPrefix(mode, "after/") && results != 0 {
    235 				t.Fatalf("retry published %d special results", results)
    236 			}
    237 			again := newTestInventoryServer(t)
    238 			if target.health >= initialHealth || initialHealth != 1 && target.damageContributors[damageContributor{player: 1}] != initialHealth-target.health ||
    239 				again.characters[1000000].health != target.health || !again.characters[1].skillLocks[skill].Equal(player.skillLocks[skill]) ||
    240 				!reflect.DeepEqual(again.characters[1].inventory.Items, inventory) {
    241 				t.Fatal("retry lost or duplicated a durable damage, cooldown or ammunition outcome")
    242 			}
    243 			if initialHealth == 1 && (again.characters[1000000].corpse == nil || again.characters[1000000].corpse.looter != 1 || len(again.npcRespawns) != 1 ||
    244 				len(again.characters[1000000].damageContributors) != 0 || again.characters[1000000].leadingContributor != (damageContributor{player: 1})) {
    245 				t.Fatal("retried kill lost its single corpse or pending respawn")
    246 			}
    247 			if initialHealth == 1 {
    248 				level, experience, points = 2, 50, 5500
    249 			}
    250 			if again.characters[1].level != level || again.characters[1].experience != experience || again.characters[1].stats.ImprovementPoints != points {
    251 				t.Fatal("retry lost or duplicated a durable XP, level or IP outcome")
    252 			}
    253 		})
    254 	}
    255 }