aorecomp

Anarchy Online classic in the browser

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


server/skill_locks_test.go (14975B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"encoding/binary"
      6 	"fmt"
      7 	"net"
      8 	"slices"
      9 	"testing"
     10 	"time"
     11 )
     12 
     13 func setTestSkillLock(t *testing.T, world *server, player *character, skill uint32, deadline time.Time) {
     14 	t.Helper()
     15 	tx, err := world.db.Begin()
     16 	if err != nil {
     17 		t.Fatal(err)
     18 	}
     19 	defer tx.Rollback()
     20 	if err := writeSkillLock(tx, player.id, skill, deadline); err != nil {
     21 		t.Fatal(err)
     22 	}
     23 	if err := tx.Commit(); err != nil {
     24 		t.Fatal(err)
     25 	}
     26 	player.setSkillLock(skill, deadline)
     27 }
     28 
     29 func TestSkillLockMatchesNativeRounding(t *testing.T) {
     30 	for _, scenario := range []struct {
     31 		raw      uint32
     32 		modifier int32
     33 		seconds  int32
     34 	}{
     35 		{15, 5, 15}, {15, 50, 22}, {15, -5, 14}, {15, -50, 7}, {15, -100, 0}, {15, -150, -7},
     36 		{20, 5, 20}, {20, 50, 29}, {20, -5, 19}, {20, -50, 10}, {20, -100, 0}, {20, -150, -9},
     37 		{40, 5, 41}, {40, 50, 59}, {40, -5, 38}, {40, -50, 20}, {40, -100, 0}, {40, -150, -19},
     38 		{600, 5, 629}, {600, 50, 899}, {600, -5, 570}, {600, -50, 300}, {600, -100, 0}, {600, -150, -299},
     39 	} {
     40 		t.Run(fmt.Sprintf("%d/%d", scenario.raw, scenario.modifier), func(t *testing.T) {
     41 			// Values come from the native instruction audit, not another server formula.
     42 
     43 			seconds := scaledSkillLockSeconds(scenario.raw, scenario.modifier)
     44 
     45 			if seconds != scenario.seconds {
     46 				t.Fatalf("native lock rounding: got %d, want %d", seconds, scenario.seconds)
     47 			}
     48 		})
     49 	}
     50 }
     51 
     52 func setTestSkillModifier(t *testing.T, world *server, player *character, modifier int32) {
     53 	t.Helper()
     54 	// Substitute one complete OnWear modifier to isolate equipment/stat accounting.
     55 	original := gamedata.ItemTemplates[101173]
     56 	definition := *original
     57 	definition.Sections = slices.Clone(original.Sections)
     58 	stat := int32(382)
     59 	for index, section := range definition.Sections {
     60 		if section.Type == 2 && section.Subtype == 14 {
     61 			functions := []gamedata.ItemFunction{{ID: 53045, HeaderWords: [2]uint32{0, 4}, ArgumentHeader: 9, Target: 2, TickCount: 1,
     62 				Arguments: []gamedata.ItemArgument{{Integer: &stat}, {Integer: &modifier}}}}
     63 			definition.Sections[index].Functions = &functions
     64 		}
     65 	}
     66 	gamedata.ItemTemplates[101173] = &definition
     67 	t.Cleanup(func() { gamedata.ItemTemplates[101173] = original })
     68 	player.inventory.LastID = world.nextItem + 1
     69 	player.inventory.Items = append(player.inventory.Items, ownedItem{ID: player.inventory.LastID, Type: 51022, Template: 101173, Quality: 1, Slot: 37, Count: 1})
     70 	if err := world.saveInventory(player, player.inventory); err != nil {
     71 		t.Fatal(err)
     72 	}
     73 }
     74 
     75 func nativeSnapshotSkillLocks(t *testing.T, packet []byte) map[uint32]uint32 {
     76 	t.Helper()
     77 	// Skip inventory, its native auxiliary list, learned nanos and three empty lists.
     78 	cursor := 37 + 32*int(binary.BigEndian.Uint32(packet[33:37])/1009-1)
     79 	if binary.BigEndian.Uint32(packet[cursor:]) != 1009 {
     80 		t.Fatal("unexpected inventory auxiliary list")
     81 	}
     82 	cursor += 4
     83 	cursor += 4 + 4*int(binary.BigEndian.Uint32(packet[cursor:])/1009-1)
     84 	for range 3 {
     85 		if binary.BigEndian.Uint32(packet[cursor:]) != 1009 {
     86 			t.Fatal("unexpected list before skill locks")
     87 		}
     88 		cursor += 4
     89 	}
     90 
     91 	// The seventh list contains plain skill/remaining-second pairs.
     92 	count := int(binary.BigEndian.Uint32(packet[cursor:])/1009 - 1)
     93 	cursor += 4
     94 	locks := make(map[uint32]uint32)
     95 	for range count {
     96 		locks[binary.BigEndian.Uint32(packet[cursor:])] = binary.BigEndian.Uint32(packet[cursor+4:])
     97 		cursor += 8
     98 	}
     99 	if len(locks) != count {
    100 		t.Fatal("snapshot repeated a skill lock")
    101 	}
    102 	return locks
    103 }
    104 
    105 func TestSkillLockSnapshotRestoresRemainingSecondsRegardlessOfModifier(t *testing.T) {
    106 	for _, modifier := range []int32{0, -15, -50, 50, 100, -100, -150} {
    107 		t.Run(fmt.Sprint(modifier), func(t *testing.T) {
    108 			world, conn := newNanoKitWorld(t)
    109 			player := world.characters[1]
    110 			setTestSkillModifier(t, world, player, modifier)
    111 			player.inventory.LearnedNanos = []uint32{43324, 29618}
    112 			if err := world.saveInventory(player, player.inventory); err != nil {
    113 				t.Fatal(err)
    114 			}
    115 			now := time.Now()
    116 			deadline := now.Add(600 * time.Second)
    117 			setTestSkillLock(t, world, player, 123, deadline)
    118 			setTestSkillLock(t, world, player, 124, now.Add(-time.Second))
    119 			setTestSkillLock(t, world, player, 131, now.Add(1200*time.Second))
    120 
    121 			restored := newTestInventoryServer(t).characters[1]
    122 			// An expired entry can also remain in memory until the next simulation tick.
    123 			restored.skillLocks[124] = now.Add(-time.Second)
    124 			before := time.Now()
    125 			if err := world.clients[1].send(fullCharacterPacket(restored)); err != nil {
    126 				t.Fatal(err)
    127 			}
    128 			after := time.Now()
    129 			locks := nativeSnapshotSkillLocks(t, conn.packets[0])
    130 
    131 			if len(conn.packets) != 1 || len(locks) != 2 || !restored.skillLocks[123].Equal(deadline) || restored.equipmentBonus(382) != modifier {
    132 				t.Fatalf("snapshot changed lock ownership, deadline or gear: locks=%v deadline=%v modifier=%d", locks, restored.skillLocks[123], restored.equipmentBonus(382))
    133 			}
    134 			for _, skill := range []uint32{123, 131} {
    135 				minimum := uint32((restored.skillLocks[skill].Sub(after) + time.Second - 1) / time.Second)
    136 				maximum := uint32((restored.skillLocks[skill].Sub(before) + time.Second - 1) / time.Second)
    137 				if locks[skill] < minimum || locks[skill] > maximum {
    138 					t.Fatalf("snapshot rescaled skill %d: seconds=%d want=%d..%d", skill, locks[skill], minimum, maximum)
    139 				}
    140 			}
    141 		})
    142 	}
    143 }
    144 
    145 func TestSkillLockExpiryChangesOnlyMemoryAndNotifiesOnce(t *testing.T) {
    146 	world, conn := newNanoKitWorld(t)
    147 	player := world.characters[1]
    148 	deadline := time.Now().Add(time.Minute)
    149 	setTestSkillLock(t, world, player, 123, deadline)
    150 	setTestSkillLock(t, world, player, 124, deadline.Add(time.Second))
    151 	setTestSkillLock(t, world, player, 131, deadline)
    152 	auditCheckpointWrites(t, world)
    153 
    154 	world.advanceItemEffects(deadline.Add(-time.Nanosecond))
    155 	if len(conn.packets) != 0 {
    156 		t.Fatal("lock expired before its authoritative deadline")
    157 	}
    158 	world.advanceItemEffects(deadline)
    159 	world.advanceItemEffects(deadline)
    160 	var persisted int
    161 	if err := world.db.QueryRow("SELECT count(*) FROM skill_locks WHERE player_id=1").Scan(&persisted); err != nil {
    162 		t.Fatal(err)
    163 	}
    164 
    165 	if len(player.skillLocks) != 1 || !player.skillLocks[124].Equal(deadline.Add(time.Second)) || len(conn.packets) != 2 || persisted != 3 || len(checkpointWrites(t, world)) != 0 {
    166 		t.Fatal("expiry removed another skill, repeated notifications or churned the database")
    167 	}
    168 	var cleared []uint32
    169 	for _, packet := range conn.packets {
    170 		if binary.BigEndian.Uint32(packet[29:33]) != 164 {
    171 			t.Fatal("expiry did not use the recovered native removal action")
    172 		}
    173 		cleared = append(cleared, binary.BigEndian.Uint32(packet[45:49]))
    174 	}
    175 	slices.Sort(cleared)
    176 	if !slices.Equal(cleared, []uint32{123, 131}) {
    177 		t.Fatal("expiry notified the wrong skills", cleared)
    178 	}
    179 }
    180 
    181 func TestRechargerSamplesPatientModifierAndKeepsDeadlineAfterGearRemoval(t *testing.T) {
    182 	world, patient, _ := newNanoRechargerWorld(t, true)
    183 	setTestSkillModifier(t, world, patient, -50)
    184 	patient.implantChangesUntil = time.Now().Add(time.Minute)
    185 	started := time.Now()
    186 
    187 	err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
    188 	deadline := patient.skillLocks[131]
    189 	patientPackets := world.clients[2].conn.(*combatTestConn).packets
    190 	if err := world.handleInventory(world.clients[2], itemMovePacket(2, 37, 64)[20:]); err != nil {
    191 		t.Fatal(err)
    192 	}
    193 	if world.clients[2].equipment == nil {
    194 		t.Fatal("modifier implant removal was rejected")
    195 	}
    196 	world.advanceEquipment(world.clients[2].equipment.readyAt)
    197 	restored := newTestInventoryServer(t).characters[2]
    198 
    199 	if err != nil || deadline.Before(started.Add(10*time.Second)) || deadline.After(time.Now().Add(10*time.Second)) ||
    200 		!patient.skillLocks[131].Equal(deadline) || !restored.skillLocks[131].Equal(deadline) || patient.equipmentBonus(382) != 0 ||
    201 		len(patientPackets) != 4 || binary.BigEndian.Uint32(patientPackets[1][41:45]) != 131 || binary.BigEndian.Uint32(patientPackets[1][45:49]) != 20 {
    202 		t.Fatalf("patient lock: elapsed=%v modifier=%d live=%v cold=%v packets=%x err=%v", deadline.Sub(started), patient.equipmentBonus(382), patient.skillLocks[131], restored.skillLocks[131], patientPackets, err)
    203 	}
    204 }
    205 
    206 func TestClinicSharesScaledTreatmentLock(t *testing.T) {
    207 	world, conn := newNanoKitWorld(t)
    208 	player := world.characters[1]
    209 	setTestSkillModifier(t, world, player, 50)
    210 	if granted, err := world.grantItem(player, 43552); !granted || err != nil {
    211 		t.Fatal(granted, err)
    212 	}
    213 	started := time.Now()
    214 
    215 	err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 65, 1)[20:])
    216 	restored := newTestInventoryServer(t).characters[1]
    217 
    218 	if err != nil || player.skillLocks[124].Before(started.Add(899*time.Second)) || player.skillLocks[124].After(time.Now().Add(899*time.Second)) ||
    219 		!restored.skillLocks[124].Equal(player.skillLocks[124]) || restored.implantChangesUntil.Before(started.Add(30*time.Second)) ||
    220 		len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[2][41:45]) != 124 || binary.BigEndian.Uint32(conn.packets[2][45:49]) != 600 {
    221 		t.Fatal("clinic did not share the native-scaled Treatment lock or changed its independent access window", err)
    222 	}
    223 }
    224 
    225 func TestWeaponSpecialSharesScaledSkillLock(t *testing.T) {
    226 	world, conn := newFastAttackWorld(t)
    227 	player := world.characters[1]
    228 	setTestSkillModifier(t, world, player, -50)
    229 	started := time.Now()
    230 
    231 	err := world.handleWeaponSpecial(world.clients[1], fastAttackRequest(1, 1000000)[20:])
    232 	restored := newTestInventoryServer(t).characters[1]
    233 
    234 	if err != nil || len(conn.packets) < 2 {
    235 		t.Fatal("special attack was rejected", err)
    236 	}
    237 	raw := binary.BigEndian.Uint32(conn.packets[1][45:49])
    238 	if raw != 19 || player.skillLocks[147].Before(started.Add(9*time.Second)) || player.skillLocks[147].After(time.Now().Add(9*time.Second)) ||
    239 		!restored.skillLocks[147].Equal(player.skillLocks[147]) {
    240 		t.Fatal("special attack used a separate unscaled cooldown or failed cold recovery")
    241 	}
    242 }
    243 
    244 func TestSkillLockReconnectRestoresOnlyOwnerWithoutStartReplay(t *testing.T) {
    245 	world, patient, _ := newNanoRechargerWorld(t, true)
    246 	deadline := time.Now().Add(10 * time.Minute)
    247 	setTestSkillLock(t, world, world.characters[1], 124, deadline)
    248 	setTestSkillLock(t, world, patient, 131, deadline)
    249 	world = newTestInventoryServer(t)
    250 	shutdown := startTestService(t, world)
    251 	client, connection := net.Pipe()
    252 	defer client.Close()
    253 	client.SetDeadline(time.Now().Add(5 * time.Second))
    254 	done := make(chan error, 1)
    255 	go func() { defer connection.Close(); done <- world.serveWorldConnection(connection) }()
    256 	cookie := systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0})
    257 	binary.BigEndian.PutUint16(cookie, 0xdfdf)
    258 
    259 	client.Write(cookie)
    260 	var locks map[uint32]uint32
    261 	for {
    262 		packet, err := readPacket(client)
    263 		if err != nil {
    264 			t.Fatal(err)
    265 		}
    266 		key := binary.BigEndian.Uint32(packet[16:20])
    267 		if key == 0x29304349 {
    268 			locks = nativeSnapshotSkillLocks(t, packet)
    269 		}
    270 		if key == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 170 {
    271 			t.Fatal("reconnect replayed an already restored skill lock")
    272 		}
    273 		if key == 0x5f52412e {
    274 			break
    275 		}
    276 	}
    277 	client.Close()
    278 	if err := <-done; err != nil {
    279 		t.Fatal(err)
    280 	}
    281 
    282 	if err := shutdown(); err != nil {
    283 		t.Fatal(err)
    284 	}
    285 	restored := newTestInventoryServer(t)
    286 	if len(locks) != 1 || locks[131] < 599 || locks[131] > 600 ||
    287 		len(restored.characters[2].skillLocks) != 1 || !restored.characters[2].skillLocks[131].Equal(deadline) {
    288 		t.Fatal("reconnect lost the patient lock or disclosed another owner's lock", locks)
    289 	}
    290 }
    291 
    292 func TestClinicWindowAndSkillLockRollbackTogether(t *testing.T) {
    293 	for _, phase := range []string{"window", "lock", "ignored lock", "commit"} {
    294 		t.Run(phase, func(t *testing.T) {
    295 			world, conn := newImplantWorld(t)
    296 			player := world.characters[1]
    297 			statement := "CREATE TRIGGER reject_clinic BEFORE UPDATE OF implant_changes_until ON characters BEGIN SELECT RAISE(FAIL, 'window'); END"
    298 			switch phase {
    299 			case "lock":
    300 				statement = "CREATE TRIGGER reject_clinic BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(FAIL, 'lock'); END"
    301 			case "ignored lock":
    302 				statement = "CREATE TRIGGER reject_clinic BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(IGNORE); END"
    303 			case "commit":
    304 				statement = "CREATE TABLE pending_clinic (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_clinic AFTER INSERT ON skill_locks BEGIN INSERT INTO pending_clinic VALUES (999999); END"
    305 			}
    306 			if _, err := world.db.Exec(statement); err != nil {
    307 				t.Fatal(err)
    308 			}
    309 
    310 			failed := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 67, 1)[20:])
    311 			rolledBack := newTestInventoryServer(t).characters[1]
    312 			if failed == nil || len(conn.packets) != 0 || !player.implantChangesUntil.IsZero() || len(player.skillLocks) != 0 ||
    313 				!rolledBack.implantChangesUntil.IsZero() || len(rolledBack.skillLocks) != 0 {
    314 				t.Fatal("failed clinic use published or committed only one part of the effect", failed)
    315 			}
    316 			if _, err := world.db.Exec("DROP TRIGGER reject_clinic"); err != nil {
    317 				t.Fatal(err)
    318 			}
    319 			err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 67, 2)[20:])
    320 			restored := newTestInventoryServer(t).characters[1]
    321 
    322 			if err != nil || player.implantChangesUntil.IsZero() || player.skillLocks[124].IsZero() ||
    323 				!restored.implantChangesUntil.Equal(player.implantChangesUntil) || !restored.skillLocks[124].Equal(player.skillLocks[124]) || len(conn.packets) != 3 {
    324 				t.Fatal("clinic retry did not commit one complete window/cooldown outcome", err)
    325 			}
    326 		})
    327 	}
    328 }
    329 
    330 func TestKitCombinesPatientEquipmentAndNanoLockModifiers(t *testing.T) {
    331 	world, patient, _ := newNanoRechargerWorld(t, true)
    332 	setTestSkillModifier(t, world, patient, -25)
    333 	original := gamedata.NanoTemplates[26360]
    334 	definition := *original
    335 	definition.Sections = slices.Clone(original.Sections)
    336 	stat, modifier := int32(382), int32(-25)
    337 	for index, section := range definition.Sections {
    338 		if section.Type == 2 && section.Subtype == 0 {
    339 			functions := []gamedata.ItemFunction{{ID: 53045, Target: 3, TickCount: 1,
    340 				Arguments: []gamedata.ItemArgument{{Integer: &stat}, {Integer: &modifier}}}}
    341 			definition.Sections[index].Functions = &functions
    342 		}
    343 	}
    344 	gamedata.NanoTemplates[26360] = &definition
    345 	t.Cleanup(func() { gamedata.NanoTemplates[26360] = original })
    346 	patient.activeNanos = []activeNano{{program: 26360, caster: 1, remaining: time.Minute}}
    347 	if err := world.savePosition(patient); err != nil {
    348 		t.Fatal(err)
    349 	}
    350 	started := time.Now()
    351 
    352 	err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:])
    353 	restored := newTestInventoryServer(t).characters[2]
    354 
    355 	if err != nil || patient.skillLocks[131].Before(started.Add(10*time.Second)) || patient.skillLocks[131].After(time.Now().Add(10*time.Second)) ||
    356 		!restored.skillLocks[131].Equal(patient.skillLocks[131]) || restored.nanoBonus(382) != -25 || restored.equipmentBonus(382) != -25 {
    357 		t.Fatal("combined modifiers did not apply once to the patient's persistent lock", err)
    358 	}
    359 }