server/resource_kit_test.go (17862B)
1 package main 2 3 import ( 4 "ao/server/gamedata" 5 "bytes" 6 "encoding/binary" 7 "fmt" 8 "reflect" 9 "slices" 10 "sync" 11 "testing" 12 "time" 13 ) 14 15 func TestResourceKitCatalogAdmission(t *testing.T) { 16 var admitted []uint32 17 18 for _, definition := range gamedata.ItemTemplates { 19 if definition.Quality == nil { 20 continue 21 } 22 item := ownedItem{Type: definition.HeaderWords[0], Template: definition.ID, Quality: *definition.Quality} 23 if _, supported := item.resourceKit(); supported { 24 admitted = append(admitted, definition.ID) 25 } 26 } 27 slices.Sort(admitted) 28 29 if !reflect.DeepEqual(admitted, []uint32{23314, 23316, 25811, 25812, 25820, 25821, 85366, 85367, 116628, 116629, 160276, 160277, 160278, 160295}) { 30 t.Fatal("unexpected medical use contract in the full catalog", admitted) 31 } 32 } 33 34 func newStartupLaboratoryWorld(t *testing.T, other bool) (*server, *character, *combatTestConn) { 35 t.Helper() 36 world, target, conn := newConsumableOutcomeWorld(t, 25812, other) 37 player := world.characters[1] 38 player.inventory.Items[0].Template, player.inventory.Items[0].Count = 116628, 25 39 player.stats.NanoAiding.Treatment = 4 40 target.nano = 1 41 if err := world.saveUser(player); err != nil { 42 t.Fatal(err) 43 } 44 // Persist the fixture's source quantity and both patient resources. 45 if err := world.saveInventory(player, player.inventory); err != nil { 46 t.Fatal(err) 47 } 48 if _, err := world.db.Exec("UPDATE characters SET health=?, nano=? WHERE id=?", target.health, target.nano, target.id); err != nil { 49 t.Fatal(err) 50 } 51 target.savedVitals = target.vitals() 52 return world, target, conn 53 } 54 55 func TestCatalogResourceKitsUseAuthoredQualityAmountsAndLocks(t *testing.T) { 56 for _, scenario := range []struct { 57 template, quality, count uint32 58 health, nanoLow, nanoHigh uint32 59 }{ 60 {25812, 1, 50, 30, 0, 0}, {25811, 200, 50, 1500, 0, 0}, 61 {160277, 400, 50, 5000, 0, 0}, {85366, 1, 25, 0, 10, 12}, 62 {85367, 200, 25, 0, 1000, 1000}, {160295, 400, 25, 0, 1500, 1500}, 63 {116628, 1, 25, 15, 15, 15}, 64 } { 65 t.Run(fmt.Sprint(scenario.template), func(t *testing.T) { 66 world, conn := newEquipmentWorld(t) 67 player, client := world.characters[1], world.clients[1] 68 player.level = 200 69 player.stats.Body.BodyDevelopment, player.stats.Body.NanoPool = 60000, 60000 70 player.stats.NanoAiding.Treatment, player.stats.NanoAiding.FirstAid = 5000, 5000 71 player.health, player.nano, player.sitting = 1, 1, true 72 player.inventory.Items[0] = ownedItem{ID: 1, Type: 51005, Template: scenario.template, Quality: scenario.quality, Slot: 64, Count: uint16(scenario.count)} 73 client.selectedTarget = [2]uint32{50000, 1} 74 if err := world.saveUser(player); err != nil { 75 t.Fatal(err) 76 } 77 if err := world.saveInventory(player, player.inventory); err != nil { 78 t.Fatal(err) 79 } 80 started := time.Now() 81 82 err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) 83 restored := newTestInventoryServer(t).characters[1] 84 85 if err != nil || player.health != 1+scenario.health || player.nano < 1+scenario.nanoLow || player.nano > 1+scenario.nanoHigh || 86 restored.health != player.health || restored.nano != player.nano || player.inventory.Items[0].Count != uint16(scenario.count-1) || 87 !reflect.DeepEqual(restored.inventory.Items, player.inventory.Items) || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 1 || 88 binary.BigEndian.Uint32(conn.packets[1][29:33]) != scenario.template || binary.BigEndian.Uint32(conn.packets[1][37:41]) != scenario.quality { 89 t.Fatal("catalog restoration, quality, charge or persistence mismatch", err) 90 } 91 deadline, seconds := player.skillLocks[124], 15*time.Second 92 if scenario.health == 0 { 93 deadline, seconds = player.skillLocks[123], 40*time.Second 94 } 95 if deadline.Before(started.Add(seconds)) || deadline.After(time.Now().Add(seconds)) { 96 t.Fatal("cooldown differs from the authored SkillTime") 97 } 98 }) 99 } 100 } 101 102 func TestStartupLaboratoryCommitsBothResourcesBeforeSuccess(t *testing.T) { 103 for _, other := range []bool{false, true} { 104 for _, count := range []uint16{1, 25} { 105 t.Run(fmt.Sprintf("other%t/count%d", other, count), func(t *testing.T) { 106 world, target, _ := newStartupLaboratoryWorld(t, other) 107 player := world.characters[1] 108 player.inventory.Items[0].Count = count 109 if err := world.saveInventory(player, player.inventory); err != nil { 110 t.Fatal(err) 111 } 112 conn := &consumableCommitConn{db: world.db, target: target.id} 113 world.clients[1].conn = conn 114 115 err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) 116 restored := newTestInventoryServer(t) 117 118 if err != nil || !conn.observed || conn.err != nil || conn.health != 16 || conn.nano != 16 || conn.count != count-1 || 119 !conn.patient.Valid || conn.patient.Time.IsZero() || conn.firstAid.Valid || 120 target.health != 16 || target.nano != 16 || restored.characters[target.id].health != 16 || restored.characters[target.id].nano != 16 || 121 !restored.characters[target.id].skillLocks[124].Equal(target.skillLocks[124]) { 122 t.Fatal("success preceded an atomic dual-resource/charge/patient-lock commit", err, conn.err) 123 } 124 if count == 1 { 125 if len(player.inventory.Items) != 0 || len(restored.items) != 0 { 126 t.Fatal("exhausted startup laboratory remained in the item store") 127 } 128 removed := slices.ContainsFunc(conn.packets, func(packet []byte) bool { 129 return binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 112 && 130 binary.BigEndian.Uint32(packet[41:45]) == 116628 && binary.BigEndian.Uint32(packet[45:49]) == 116628 131 }) 132 if !removed { 133 t.Fatal("last charge did not remove the native startup row") 134 } 135 } else if len(restored.items) != 1 || restored.characters[1].inventory.Items[0].Count != 24 { 136 t.Fatal("startup quantity or identity changed unexpectedly") 137 } 138 }) 139 } 140 } 141 } 142 143 func TestStartupLaboratoryRollbackPreservesBothResourcesAndRetries(t *testing.T) { 144 for _, phase := range []string{"charge", "lock", "health", "nano"} { 145 t.Run(phase, func(t *testing.T) { 146 world, target, conn := newStartupLaboratoryWorld(t, true) 147 player := world.characters[1] 148 statement := "CREATE TRIGGER reject_startup BEFORE UPDATE ON items BEGIN SELECT RAISE(FAIL, 'charge'); END" 149 switch phase { 150 case "lock": 151 statement = "CREATE TRIGGER reject_startup BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(FAIL, 'lock'); END" 152 case "health": 153 statement = "CREATE TRIGGER reject_startup BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'health'); END" 154 case "nano": 155 statement = "CREATE TRIGGER reject_startup BEFORE UPDATE OF nano ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'nano'); END" 156 } 157 if _, err := world.db.Exec(statement); err != nil { 158 t.Fatal(err) 159 } 160 before, _ := readTestItemStore(world) 161 162 err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) 163 after, _ := readTestItemStore(world) 164 var savedHealth, savedNano uint32 165 if queryErr := world.db.QueryRow("SELECT health,nano FROM characters WHERE id=2").Scan(&savedHealth, &savedNano); queryErr != nil { 166 t.Fatal(queryErr) 167 } 168 if err == nil || !bytes.Equal(before, after) || target.health != 1 || target.nano != 1 || player.inventory.Items[0].Count != 25 || 169 savedHealth != 1 || savedNano != 1 || len(player.skillLocks) != 0 || !target.skillLocks[124].IsZero() || len(conn.packets) != 0 { 170 t.Fatal("failed dual restoration left a partial gain, debit or cooldown", err) 171 } 172 if _, err := world.db.Exec("DROP TRIGGER reject_startup"); err != nil { 173 t.Fatal(err) 174 } 175 err = world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:]) 176 restored := newTestInventoryServer(t) 177 178 if err != nil || target.health != 16 || target.nano != 16 || player.inventory.Items[0].Count != 24 || 179 restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[2].skillLocks[124].IsZero() { 180 t.Fatal("rolled-back startup use could not retry atomically", err) 181 } 182 }) 183 } 184 } 185 186 func TestStartupLaboratoryRejectsInvalidStateAndRetainsBothResources(t *testing.T) { 187 for _, scenario := range []string{"standing patient", "skill equality", "patient lock", "healer attacking", "patient attacking", "incoming healer", "incoming patient", "far", "loading", "dead", "npc", "other zone", "no target", "wrong quality", "wrong type", "unknown predicate", "unknown negated predicate", "unsupported function", "conditional effect", "repeating effect", "wrong effect target"} { 188 t.Run(scenario, func(t *testing.T) { 189 world, target, conn := newStartupLaboratoryWorld(t, true) 190 player, client := world.characters[1], world.clients[1] 191 original := gamedata.ItemTemplates[116628] 192 definition := *original 193 definition.Sections = slices.Clone(original.Sections) 194 switch scenario { 195 case "standing patient": 196 target.sitting = false 197 case "skill equality": 198 player.stats.NanoAiding.Treatment = 3 199 case "patient lock": 200 target.setSkillLock(124, time.Now().Add(time.Minute)) 201 case "healer attacking": 202 player.fighting = 1000000 203 case "patient attacking": 204 target.fighting = 1000000 205 case "incoming healer", "incoming patient": 206 attacker := &character{id: 1000000, npc: true, fighting: 1} 207 if scenario == "incoming patient" { 208 attacker.fighting = 2 209 } 210 world.fighting[attacker.id] = attacker 211 case "far": 212 target.position[0] = player.position[0] + 7.125 213 case "loading": 214 world.clients[2].loading = true 215 case "dead": 216 target.health = 0 217 case "npc": 218 target.npc = true 219 case "other zone": 220 target.playfield = 705 221 case "no target": 222 client.selectedTarget = [2]uint32{} 223 case "wrong quality": 224 player.inventory.Items[0].Quality = 2 225 case "wrong type": 226 player.inventory.Items[0].Type = 51022 227 case "unknown predicate", "unknown negated predicate": 228 requirements := []gamedata.ItemRequirement{{Stat: 9999, Value: 0, Operator: 0}} 229 if scenario == "unknown negated predicate" { 230 requirements = append(requirements, gamedata.ItemRequirement{Operator: 42}) 231 } 232 actions := []gamedata.ItemAction{{Type: 3, Requirements: requirements}} 233 definition.Sections[2].Actions = &actions 234 case "unsupported function", "conditional effect", "repeating effect", "wrong effect target": 235 functions := slices.Clone(*definition.Sections[0].Functions) 236 switch scenario { 237 case "unsupported function": 238 functions[0].ID = 53051 239 case "conditional effect": 240 functions[0].Requirements = []gamedata.ItemRequirement{{Stat: 54, Value: 0, Operator: 2}} 241 case "repeating effect": 242 functions[0].TickCount = 2 243 case "wrong effect target": 244 functions[0].Target = 2 245 } 246 definition.Sections[0].Functions = &functions 247 } 248 gamedata.ItemTemplates[116628] = &definition 249 t.Cleanup(func() { gamedata.ItemTemplates[116628] = original }) 250 before, _ := readTestItemStore(world) 251 health, nano := target.health, target.nano 252 253 err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) 254 after, _ := readTestItemStore(world) 255 256 if err != nil || !bytes.Equal(before, after) || player.inventory.Items[0].Count != 25 || target.health != health || target.nano != nano || 257 len(player.skillLocks) != 0 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { 258 t.Fatal("rejected startup use consumed a charge or partially restored a resource", err) 259 } 260 }) 261 } 262 } 263 264 func TestStartupLaboratoryConcurrentReplayRestoresBothResourcesOnce(t *testing.T) { 265 world, target, _ := newStartupLaboratoryWorld(t, true) 266 var group sync.WaitGroup 267 errors := make(chan error, 16) 268 269 client := world.clients[1] 270 zone, stop := startTestZone(t, world) 271 272 for sequence := uint32(1); sequence <= 16; sequence++ { 273 group.Go(func() { 274 errors <- zone.call(zonePacket{client, backpackUseRequest(1, 64, sequence)[20:]}) 275 }) 276 } 277 group.Wait() 278 if err := stop(); err != nil { 279 t.Fatal(err) 280 } 281 close(errors) 282 restored := newTestInventoryServer(t) 283 284 for err := range errors { 285 if err != nil { 286 t.Fatal(err) 287 } 288 } 289 if target.health != 16 || target.nano != 16 || world.characters[1].inventory.Items[0].Count != 24 || 290 restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[1].inventory.Items[0].Count != 24 { 291 t.Fatal("racing/replayed uses applied a partial or duplicate restoration") 292 } 293 } 294 295 func TestStartupLaboratoryClampsEachResourceIndependently(t *testing.T) { 296 for _, scenario := range []string{"both full", "health full", "nano full", "one missing"} { 297 t.Run(scenario, func(t *testing.T) { 298 world, target, _ := newStartupLaboratoryWorld(t, false) 299 health, nano := uint32(16), uint32(16) 300 switch scenario { 301 case "both full": 302 target.health, target.nano = target.maximumHealth(), target.maximumNano() 303 health, nano = target.maximumHealth(), target.maximumNano() 304 case "health full": 305 target.health, health = target.maximumHealth(), target.maximumHealth() 306 case "nano full": 307 target.nano, nano = target.maximumNano(), target.maximumNano() 308 case "one missing": 309 target.health, target.nano = target.maximumHealth()-1, target.maximumNano()-1 310 health, nano = target.maximumHealth(), target.maximumNano() 311 } 312 313 err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) 314 restored := newTestInventoryServer(t).characters[1] 315 316 if err != nil || target.health != health || target.nano != nano || restored.health != health || restored.nano != nano || 317 target.inventory.Items[0].Count != 24 || restored.inventory.Items[0].Count != 24 { 318 t.Fatal("dual restoration clamped the wrong resource or failed to consume once", err) 319 } 320 }) 321 } 322 } 323 324 func TestStartupLaboratoryPatientCooldownRangeBoundaryAndPrivateNano(t *testing.T) { 325 world, target, _ := newStartupLaboratoryWorld(t, true) 326 player := world.characters[1] 327 player.sitting = false 328 player.setSkillLock(124, time.Now().Add(600*time.Second)) 329 healerLock := player.skillLocks[124] 330 target.position = player.position 331 target.position[0] += 7 332 observer := &combatTestConn{} 333 world.characters[3] = &character{id: 3, playfield: player.playfield, position: player.position, health: 100} 334 world.clients[3] = &worldClient{id: 3, conn: observer, target: true, ready: true, players: map[uint32]bool{1: true, 2: true}} 335 336 err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) 337 deadline := target.skillLocks[124] 338 world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:]) 339 if player.inventory.Items[0].Count != 24 || target.health != 16 || target.nano != 16 { 340 t.Fatal("patient cooldown admitted the immediate repeat") 341 } 342 world.advanceItemEffects(deadline) 343 world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 3)[20:]) 344 345 if err != nil || target.health != 31 || target.nano != 31 || player.inventory.Items[0].Count != 23 || 346 !player.skillLocks[124].Equal(healerLock) || len(observer.packets) != 4 { 347 t.Fatal("standing, locked healer failed at the inclusive range boundary or patient expiry", err) 348 } 349 for _, packet := range observer.packets { 350 key := binary.BigEndian.Uint32(packet[16:20]) 351 if key != 0x35505644 && key != 0x3710256c { 352 t.Fatal("observer received the patient's private nano or cooldown state") 353 } 354 } 355 } 356 357 func TestStartupLaboratoryOutputFailurePreservesBothGainsAndPatientLock(t *testing.T) { 358 world, target, _ := newStartupLaboratoryWorld(t, true) 359 world.clients[1].writeWake, world.clients[1].writeClosed = make(chan struct{}, 1), true 360 361 failedOutput := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) 362 patientPackets := world.clients[2].conn.(*combatTestConn).packets 363 restored := newTestInventoryServer(t) 364 conn := &combatTestConn{} 365 restored.clients[1] = &worldClient{id: 1, conn: conn, target: true, ready: true, selectedTarget: [2]uint32{50000, 2}} 366 restored.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true} 367 replay := restored.handleOwnedItemUse(restored.clients[1], backpackUseRequest(1, 64, 2)[20:]) 368 369 if failedOutput == nil || replay != nil || target.health != 16 || target.nano != 16 || 370 restored.characters[2].health != 16 || restored.characters[2].nano != 16 || restored.characters[2].skillLocks[124].IsZero() || 371 restored.characters[1].inventory.Items[0].Count != 24 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { 372 t.Fatal("output failure lost part of the committed effect or allowed another debit", failedOutput, replay) 373 } 374 if len(patientPackets) != 4 || binary.BigEndian.Uint32(patientPackets[2][41:45]) != 124 || 375 binary.BigEndian.Uint32(patientPackets[3][29:33]) != 214 || binary.BigEndian.Uint32(patientPackets[3][33:37]) != 16 { 376 t.Fatal("failed healer output suppressed the healthy patient's resource/lock replication") 377 } 378 } 379 380 func TestStartupFirstAidSkillEqualityPreservesBothEffects(t *testing.T) { 381 world, target, conn := newStartupLaboratoryWorld(t, true) 382 player := world.characters[1] 383 player.inventory.Items[0].Template, player.inventory.Items[0].Count = 116629, 1 384 player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} 385 player.stats.NanoAiding.FirstAid = 5 386 if err := world.saveInventory(player, player.inventory); err != nil { 387 t.Fatal(err) 388 } 389 before, _ := readTestItemStore(world) 390 391 err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) 392 after, _ := readTestItemStore(world) 393 394 if err != nil || !bytes.Equal(before, after) || target.health != 1 || target.nano != 1 || player.inventory.Items[0].Count != 1 || 395 !player.skillLocks[123].IsZero() || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { 396 t.Fatal("First Aid at strict skill equality changed either resource, its last charge or lock", err) 397 } 398 }