aorecomp

Anarchy Online classic in the browser

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


server/team_loot_order_test.go (15569B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/binary"
      6 	"fmt"
      7 	"reflect"
      8 	"slices"
      9 	"sync"
     10 	"testing"
     11 )
     12 
     13 func TestTeamLootOrderQueryUsesOriginalDefaultMode(t *testing.T) {
     14 	world, connections := newTeamWorld(t)
     15 	formTestTeam(t, world, 1, 2)
     16 	connections[0].packets, connections[1].packets = nil, nil
     17 
     18 	err := world.handleTeamAction(world.clients[2], characterActionPacket(2, [5]uint32{145})[20:])
     19 
     20 	if err != nil || len(connections[0].packets) != 0 || len(connections[1].packets) != 1 ||
     21 		!bytes.Equal(connections[1].packets[0][16:], targetPacket(characterActionPacket(2, [5]uint32{145, 0, 0, 0, 3}))[16:]) {
     22 		t.Fatalf("native team loot query did not return All to its owner: leader %x, member %x, error %v", connections[0].packets, connections[1].packets, err)
     23 	}
     24 }
     25 
     26 func TestTeamLootOrderModesBroadcastQueryAndColdRestore(t *testing.T) {
     27 	for _, mode := range []uint32{3, 4, 5} {
     28 		t.Run(fmt.Sprint(mode), func(t *testing.T) {
     29 			world, connections := newTeamWorld(t)
     30 			formTestTeam(t, world, 1, 2)
     31 			for _, connection := range connections {
     32 				connection.packets = nil
     33 			}
     34 
     35 			if err := world.handleTeamAction(world.clients[1], characterActionPacket(1, [5]uint32{127, 0, mode})[20:]); err != nil {
     36 				t.Fatal(err)
     37 			}
     38 			if err := world.handleTeamAction(world.clients[2], characterActionPacket(2, [5]uint32{145})[20:]); err != nil {
     39 				t.Fatal(err)
     40 			}
     41 			cold := newTestInventoryServer(t)
     42 
     43 			if len(connections[0].packets) != 1 || len(connections[1].packets) != 2 || len(connections[2].packets) != 0 ||
     44 				world.characters[1].team.lootOrder != mode-3 || cold.characters[1].team.lootOrder != mode-3 ||
     45 				cold.characters[1].team != cold.characters[2].team {
     46 				t.Fatal("mode delivery or durable team state differs")
     47 			}
     48 			for _, connection := range connections[:2] {
     49 				if binary.BigEndian.Uint32(connection.packets[0][29:33]) != 127 || binary.BigEndian.Uint32(connection.packets[0][37:41]) != mode {
     50 					t.Fatal("set feedback uses the wrong original pair")
     51 				}
     52 			}
     53 			if binary.BigEndian.Uint32(connections[1].packets[1][29:33]) != 145 || binary.BigEndian.Uint32(connections[1].packets[1][45:49]) != mode {
     54 				t.Fatal("query feedback uses the wrong original pair")
     55 			}
     56 		})
     57 	}
     58 }
     59 
     60 func TestTeamLootOrderRejectsForgedAndFailedChanges(t *testing.T) {
     61 	for _, scenario := range []string{"zero", "team keyword", "loot keyword", "outside", "nonleader", "foreign owner", "not teamed", "first type", "second pair", "query arguments", "loading", "stale", "failed write", "ignored write"} {
     62 		t.Run(scenario, func(t *testing.T) {
     63 			world, connections := newTeamWorld(t)
     64 			formTestTeam(t, world, 1, 2)
     65 			client := world.clients[1]
     66 			request := characterActionPacket(1, [5]uint32{127, 0, 4})[20:]
     67 			switch scenario {
     68 			case "zero", "team keyword", "loot keyword", "outside":
     69 				mode := map[string]uint32{"zero": 0, "team keyword": 1, "loot keyword": 2, "outside": 6}[scenario]
     70 				binary.BigEndian.PutUint32(request[24:28], mode)
     71 			case "nonleader", "not teamed":
     72 				owner := uint32(2)
     73 				if scenario == "not teamed" {
     74 					owner = 3
     75 				}
     76 				client = world.clients[owner]
     77 				request = characterActionPacket(owner, [5]uint32{127, 0, 4})[20:]
     78 			case "foreign owner":
     79 				binary.BigEndian.PutUint32(request[8:12], 2)
     80 			case "first type":
     81 				binary.BigEndian.PutUint32(request[20:24], 50000)
     82 			case "second pair":
     83 				binary.BigEndian.PutUint32(request[32:36], 1)
     84 			case "query arguments":
     85 				request = characterActionPacket(1, [5]uint32{145, 0, 4})[20:]
     86 			case "loading":
     87 				client.loading = true
     88 			case "stale":
     89 				world.clients[1] = &worldClient{id: 1}
     90 			case "failed write", "ignored write":
     91 				raise := "RAISE(FAIL, 'mode failure')"
     92 				if scenario == "ignored write" {
     93 					raise = "RAISE(IGNORE)"
     94 				}
     95 				if _, err := world.db.Exec("CREATE TRIGGER refuse_mode BEFORE UPDATE ON teams BEGIN SELECT " + raise + "; END"); err != nil {
     96 					t.Fatal(err)
     97 				}
     98 			}
     99 			before := world.characters[1].team
    100 			for _, connection := range connections {
    101 				connection.packets = nil
    102 			}
    103 
    104 			err := world.handleTeamAction(client, request)
    105 			cold := newTestInventoryServer(t)
    106 
    107 			if (err != nil) != (scenario == "failed write" || scenario == "ignored write") ||
    108 				world.characters[1].team != before || !reflect.DeepEqual(cold.characters[1].team, before) {
    109 				t.Fatal("refused mode changed the team", err)
    110 			}
    111 			for _, connection := range connections {
    112 				if len(connection.packets) != 0 {
    113 					t.Fatal("refused mode sent success")
    114 				}
    115 			}
    116 		})
    117 	}
    118 }
    119 
    120 func newTeamLootOrderWorld(t *testing.T, mode uint32) *server {
    121 	t.Helper()
    122 	t.Chdir(t.TempDir())
    123 	world := newLootRightsWorld(t)
    124 	for index, name := range []string{"Zulu", "Alpha", "Beta"} {
    125 		player := world.characters[uint32(index+1)]
    126 		player.name = name
    127 		if err := world.saveUser(player); err != nil {
    128 			t.Fatal(err)
    129 		}
    130 	}
    131 	formTestTeam(t, world, 1, 2)
    132 	if err := world.handleTeamAction(world.clients[1], characterActionPacket(1, [5]uint32{127, 0, mode})[20:]); err != nil {
    133 		t.Fatal(err)
    134 	}
    135 	world.characters[1000000].health = 1
    136 	world.characters[1000000].inventory.Items = nil
    137 	if err := world.flushWorld(); err != nil {
    138 		t.Fatal(err)
    139 	}
    140 	return world
    141 }
    142 
    143 func TestTeamLootOrderCapturedRightsAndNativeCorpseMetadata(t *testing.T) {
    144 	for _, scenario := range []struct {
    145 		mode   uint32
    146 		looter uint32
    147 		access []uint32
    148 	}{{3, 0, []uint32{1, 2}}, {4, 1, []uint32{1}}, {5, 2, []uint32{2}}} {
    149 		t.Run(fmt.Sprint(scenario.mode), func(t *testing.T) {
    150 			world := newTeamLootOrderWorld(t, scenario.mode)
    151 			npc := world.characters[1000000]
    152 
    153 			if err := world.handleCombat(world.clients[2], attackPacket(2, npc.id)[20:]); err != nil {
    154 				t.Fatal(err)
    155 			}
    156 			world.advanceCombat(world.characters[2].nextAttack)
    157 			for id := uint32(1); id <= 3; id++ {
    158 				if err := world.handleLootUse(world.clients[id], teamLootUse(id, 1)); err != nil {
    159 					t.Fatal(err)
    160 				}
    161 			}
    162 			cold := newTestInventoryServer(t)
    163 
    164 			if npc.health != 0 || npc.corpse == nil || npc.corpse.looter != scenario.looter || npc.corpse.lootOrder+3 != scenario.mode ||
    165 				cold.characters[npc.id].corpse.looter != scenario.looter || cold.characters[npc.id].corpse.lootOrder != npc.corpse.lootOrder {
    166 				t.Fatal("death did not capture and retain its loot mode")
    167 			}
    168 			for id := uint32(1); id <= 3; id++ {
    169 				allowed := false
    170 				for _, member := range scenario.access {
    171 					allowed = allowed || member == id
    172 				}
    173 				if (world.clients[id].lootCorpse == npc.id) != allowed {
    174 					t.Fatalf("mode %d grants the wrong access to player %d", scenario.mode, id)
    175 				}
    176 			}
    177 			packet := corpsePacket(npc)
    178 			length := int(binary.BigEndian.Uint16(packet[6:8]))
    179 			if binary.BigEndian.Uint32(packet[length-16:]) != scenario.mode || binary.BigEndian.Uint32(packet[length-8:]) != scenario.looter {
    180 				t.Fatal("native corpse mode or designated owner differs")
    181 			}
    182 		})
    183 	}
    184 }
    185 
    186 func TestTeamLootOrderFailedDeathRetainsCursorAndRetriesAtomically(t *testing.T) {
    187 	for _, attack := range []string{"unarmed", "pistol", "fling", "nano"} {
    188 		for _, failure := range []struct{ name, sql string }{
    189 			{"cursor", "CREATE TRIGGER refuse_loot BEFORE UPDATE OF alpha_cursor ON teams BEGIN SELECT RAISE(FAIL,'cursor'); END"},
    190 			{"ignored cursor", "CREATE TRIGGER refuse_loot BEFORE UPDATE OF alpha_cursor ON teams BEGIN SELECT RAISE(IGNORE); END"},
    191 			{"corpse", "CREATE TRIGGER refuse_loot BEFORE UPDATE ON npcs WHEN NEW.has_corpse=1 BEGIN SELECT RAISE(FAIL,'corpse'); END"},
    192 			{"commit", "CREATE TABLE pending_team_loot (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER refuse_loot AFTER UPDATE OF alpha_cursor ON teams BEGIN INSERT INTO pending_team_loot VALUES(999999); END"},
    193 		} {
    194 			t.Run(attack+"/"+failure.name, func(t *testing.T) {
    195 				world, output := newKillExperienceWorld(t, attack)
    196 				world.combatRoll = func(uint32) uint32 { return 0 }
    197 				player := world.characters[1]
    198 				player.name = "Zulu"
    199 				if err := world.saveUser(player); err != nil {
    200 					t.Fatal(err)
    201 				}
    202 				member := world.newCharacter()
    203 				member.name = "Alpha"
    204 				if err := world.saveUser(member); err != nil {
    205 					t.Fatal(err)
    206 				}
    207 				world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}, npcs: map[uint32]bool{1000000: true}}
    208 				formTestTeam(t, world, 1, 2)
    209 				if err := world.handleTeamAction(world.clients[1], characterActionPacket(1, [5]uint32{127, 0, 5})[20:]); err != nil {
    210 					t.Fatal(err)
    211 				}
    212 				identity := world.nextItem
    213 				output.packets = nil
    214 				if _, err := world.db.Exec(failure.sql); err != nil {
    215 					t.Fatal(err)
    216 				}
    217 
    218 				if attack == "fling" {
    219 					if err := world.handleWeaponSpecial(world.clients[1], flingShotRequest(1, 1000000)[20:]); err == nil {
    220 						t.Fatal("failed Fling assignment returned success")
    221 					}
    222 				} else {
    223 					attackForExperience(t, world, attack)
    224 				}
    225 				cold := newTestInventoryServer(t)
    226 				var cursor uint32
    227 				err := world.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor)
    228 
    229 				if err != nil || cursor != 0 || !player.skillLocks[150].IsZero() {
    230 					t.Fatal("failed death advanced Alpha or consumed Fling's lock", err)
    231 				}
    232 				for _, current := range []*server{world, cold} {
    233 					if current.characters[1000000].health != 1 || current.characters[1000000].corpse != nil || current.nextItem != identity {
    234 						t.Fatal("failed assignment committed death or item allocation")
    235 					}
    236 				}
    237 				for _, packet := range output.packets {
    238 					switch binary.BigEndian.Uint32(packet[16:20]) {
    239 					case 0x46002f16, 0x754f1115, 0x4727213e, 0x4f474e05:
    240 						t.Fatal("failed assignment published damage or a corpse")
    241 					}
    242 				}
    243 				if _, err := world.db.Exec("DROP TRIGGER refuse_loot"); err != nil {
    244 					t.Fatal(err)
    245 				}
    246 				attackForExperience(t, world, attack)
    247 				retried := newTestInventoryServer(t)
    248 				if err := world.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor); err != nil {
    249 					t.Fatal(err)
    250 				}
    251 				if cursor != 2 || retried.characters[1000000].corpse == nil || retried.characters[1000000].corpse.looter != 2 ||
    252 					retried.characters[1000000].corpse.lootOrder != 2 || len(retried.characters[1000000].corpse.items) != 1 || retried.characters[1000000].corpse.items[0].ID <= identity || retried.nextItem != retried.characters[1000000].corpse.items[0].ID {
    253 					t.Fatal("retried death failed to commit exactly one Alpha assignment and item")
    254 				}
    255 			})
    256 		}
    257 	}
    258 }
    259 
    260 func TestTeamLootOrderCapturedLeaderSurvivesModeAndLeadershipChanges(t *testing.T) {
    261 	world := newTeamLootOrderWorld(t, 4)
    262 	formTestTeam(t, world, 1, 3)
    263 	if err := world.handleCombat(world.clients[2], attackPacket(2, 1000000)[20:]); err != nil {
    264 		t.Fatal(err)
    265 	}
    266 	world.advanceCombat(world.characters[2].nextAttack)
    267 
    268 	if err := world.handleTeamAction(world.clients[1], characterActionPacket(1, [5]uint32{127, 0, 3})[20:]); err != nil {
    269 		t.Fatal(err)
    270 	}
    271 	if err := world.handleTeamAction(world.clients[1], teamRequest(1, 25, 2, 0)); err != nil {
    272 		t.Fatal(err)
    273 	}
    274 	for id := uint32(1); id <= 2; id++ {
    275 		if err := world.handleLootUse(world.clients[id], teamLootUse(id, 1)); err != nil {
    276 			t.Fatal(err)
    277 		}
    278 	}
    279 
    280 	corpse := world.characters[1000000].corpse
    281 	if corpse.lootOrder != 1 || corpse.looter != 1 || world.clients[1].lootCorpse != 1000000 || world.clients[2].lootCorpse != 0 ||
    282 		world.characters[2].team.leader != 2 || world.characters[2].team.lootOrder != 0 {
    283 		t.Fatal("new live team settings reassigned an existing corpse")
    284 	}
    285 	if err := world.handleTeamAction(world.clients[1], teamRequest(1, 24, 0, 0)); err != nil {
    286 		t.Fatal(err)
    287 	}
    288 	if err := world.handleLootUse(world.clients[1], teamLootUse(1, 2)); err != nil {
    289 		t.Fatal(err)
    290 	}
    291 	if world.clients[1].lootCorpse != 0 || world.characters[2].team.id != corpse.team {
    292 		t.Fatal("departed designated owner retained a usable team handle")
    293 	}
    294 	cold := newTestInventoryServer(t)
    295 	if cold.characters[1000000].corpse.looter != 1 || cold.characters[1000000].corpse.lootOrder != 1 || cold.characters[2].team.leader != 2 {
    296 		t.Fatal("cold replay changed the captured owner or current team leader")
    297 	}
    298 }
    299 
    300 func TestTeamLootOrderAlphaIncludesAbsentMembersAndRechecksRoster(t *testing.T) {
    301 	world := newTeamLootOrderWorld(t, 5)
    302 	base := *world.characters[1000000]
    303 	delete(world.clients, 2)
    304 	world.characters[2].playfield = 705
    305 	var owners []uint32
    306 
    307 	for index := uint32(0); index < 3; index++ {
    308 		if index == 1 {
    309 			formTestTeam(t, world, 1, 3)
    310 		} else if index == 2 {
    311 			if err := world.handleTeamAction(world.clients[1], teamRequest(1, 22, 3, 0)); err != nil {
    312 				t.Fatal(err)
    313 			}
    314 		}
    315 		npc := base
    316 		npc.id = 1000000 + index
    317 		world.characters[npc.id] = &npc
    318 		world.clients[1].npcs[npc.id] = true
    319 		if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil {
    320 			t.Fatal(err)
    321 		}
    322 		world.advanceCombat(world.characters[1].nextAttack)
    323 		owners = append(owners, npc.corpse.looter)
    324 	}
    325 
    326 	if !reflect.DeepEqual(owners, []uint32{2, 3, 2}) {
    327 		t.Fatal("Alpha skipped an absent member or used a stale roster", owners)
    328 	}
    329 }
    330 
    331 func TestTeamLootOrderAlphaRotatesEmptyCorpsesAndSurvivesColdLoad(t *testing.T) {
    332 	world := newTeamLootOrderWorld(t, 5)
    333 	base := *world.characters[1000000]
    334 	var owners []uint32
    335 
    336 	for index := uint32(0); index < 3; index++ {
    337 		npc := base
    338 		npc.id = 1000000 + index
    339 		world.characters[npc.id] = &npc
    340 		world.clients[1].npcs[npc.id] = true
    341 		if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil {
    342 			t.Fatal(err)
    343 		}
    344 		world.advanceCombat(world.characters[1].nextAttack)
    345 		if npc.corpse == nil || len(npc.corpse.items) != 0 {
    346 			t.Fatal("fixture did not produce an empty awarded corpse")
    347 		}
    348 		owners = append(owners, npc.corpse.looter)
    349 	}
    350 	cold := newTestInventoryServer(t)
    351 	var cursor uint32
    352 	err := world.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor)
    353 
    354 	if err != nil || cursor != 2 || !reflect.DeepEqual(owners, []uint32{2, 1, 2}) || cold.characters[1].team.lootOrder != 2 {
    355 		t.Fatal("Alpha did not repeat alphabetical allocation durably", owners, cursor, err)
    356 	}
    357 	for index, owner := range owners {
    358 		if cold.characters[1000000+uint32(index)].corpse.looter != owner {
    359 			t.Fatal("cold loading changed an existing Alpha assignment")
    360 		}
    361 	}
    362 }
    363 
    364 func TestTeamLootOrderConcurrentDeathsAdvanceAlphaOnceEach(t *testing.T) {
    365 	world := newTeamLootOrderWorld(t, 5)
    366 	second := *world.characters[1000000]
    367 	second.id = 1000001
    368 	world.characters[second.id] = &second
    369 	world.clients[2].npcs[second.id] = true
    370 
    371 	if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
    372 		t.Fatal(err)
    373 	}
    374 	if err := world.handleCombat(world.clients[2], attackPacket(2, second.id)[20:]); err != nil {
    375 		t.Fatal(err)
    376 	}
    377 	deadline := world.characters[1].nextAttack
    378 	if world.characters[2].nextAttack.After(deadline) {
    379 		deadline = world.characters[2].nextAttack
    380 	}
    381 	zone, stop := startTestZone(t, world)
    382 	var pending sync.WaitGroup
    383 	for range 2 {
    384 		pending.Go(func() {
    385 			if err := zone.call(zoneTestCommand(func(state *server) error { state.advanceCombat(deadline); return nil })); err != nil {
    386 				t.Error(err)
    387 			}
    388 		})
    389 	}
    390 	pending.Wait()
    391 	if err := stop(); err != nil {
    392 		t.Fatal(err)
    393 	}
    394 	cold := newTestInventoryServer(t)
    395 	var cursor uint32
    396 	err := world.db.QueryRow("SELECT alpha_cursor FROM teams WHERE id=1").Scan(&cursor)
    397 
    398 	owners := []uint32{cold.characters[1000000].corpse.looter, cold.characters[1000001].corpse.looter}
    399 	slices.Sort(owners)
    400 	if err != nil || cursor != 1 || !slices.Equal(owners, []uint32{1, 2}) {
    401 		t.Fatal("concurrent deaths repeated or skipped an Alpha turn", owners, cursor, err)
    402 	}
    403 }