aorecomp

Anarchy Online classic in the browser

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


server/corpse_expiry_outcome_test.go (8317B)


      1 package main
      2 
      3 import (
      4 	"context"
      5 	"database/sql"
      6 	"encoding/binary"
      7 	"fmt"
      8 	"testing"
      9 	"time"
     10 )
     11 
     12 type corpseExpiryCommitConn struct {
     13 	combatTestConn
     14 	db       *sql.DB
     15 	observed bool
     16 	visible  int
     17 	items    int
     18 	location int
     19 	err      error
     20 }
     21 
     22 func (conn *corpseExpiryCommitConn) Write(packet []byte) (int, error) {
     23 	if !conn.observed && binary.BigEndian.Uint32(packet[16:20]) == 0x2049527c {
     24 		conn.observed = true
     25 		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
     26 		defer cancel()
     27 		conn.err = conn.db.QueryRowContext(ctx, `SELECT
     28 			EXISTS(SELECT 1 FROM npcs WHERE id=1000000 AND present=1),
     29 			EXISTS(SELECT 1 FROM items WHERE id=3),
     30 			EXISTS(SELECT 1 FROM item_locations WHERE item_id=3)`).Scan(&conn.visible, &conn.items, &conn.location)
     31 	}
     32 	return conn.combatTestConn.Write(packet)
     33 }
     34 
     35 func newCorpseExpiryOutcomeWorld(t *testing.T, pending bool) (*server, *corpseExpiryCommitConn, time.Time) {
     36 	t.Helper()
     37 	world, _ := newKillExperienceWorld(t, "unarmed")
     38 	world.combatRoll = func(uint32) uint32 { return 0 }
     39 	if pending {
     40 		profile := *world.characters[1000000].combatProfile
     41 		profile.CorpseSeconds = 1
     42 		world.characters[1000000].combatProfile = &profile
     43 	}
     44 	attackForExperience(t, world, "unarmed")
     45 	if granted, err := world.grantItem(world.characters[1], 99719); err != nil || !granted {
     46 		t.Fatal(granted, err)
     47 	}
     48 	if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil {
     49 		t.Fatal(err)
     50 	}
     51 	if !pending {
     52 		world.advanceNPCRespawns(world.npcRespawns[0].at)
     53 	}
     54 	output := &corpseExpiryCommitConn{db: world.db}
     55 	world.clients[1].conn = output
     56 	return world, output, world.characters[1000000].corpse.expiresAt
     57 }
     58 
     59 func TestCorpseExpiryCommitsBeforeClosingTheNativeContainer(t *testing.T) {
     60 	for _, pending := range []bool{false, true} {
     61 		t.Run(fmt.Sprintf("pending=%t", pending), func(t *testing.T) {
     62 			world, output, deadline := newCorpseExpiryOutcomeWorld(t, pending)
     63 
     64 			world.advanceCorpseExpiry(deadline)
     65 			cold := newTestInventoryServer(t)
     66 			cold.advanceNPCRespawns(deadline.Add(100 * time.Second))
     67 
     68 			if !output.observed || output.err != nil || output.visible != 0 || output.items != 0 || output.location != 0 {
     69 				t.Fatal("native expiry preceded durable corpse/item retirement", output.observed, output.err, output.visible, output.items, output.location)
     70 			}
     71 			if world.characters[1000000] != nil || cold.characters[1000000] != nil || cold.characters[1000001] == nil ||
     72 				cold.characters[1000001].health != 20 || world.items[3].Template != 0 || cold.items[3].Template != 0 ||
     73 				world.items[4].Template != 99719 || cold.items[4].Template != 99719 || cold.nextItem != 4 || cold.nextNPC != 1000002 {
     74 				t.Fatal("expiry restored the corpse, reused an identity or lost the unrelated owned item")
     75 			}
     76 			if len(output.packets) != 3 || world.clients[1].lootCorpse != 0 || world.clients[1].npcs[1000000] {
     77 				t.Fatal("committed expiry did not close and delete exactly once")
     78 			}
     79 		})
     80 	}
     81 }
     82 
     83 func TestCorpseExpiryWriteFailuresRetainStateAndRetry(t *testing.T) {
     84 	for _, pending := range []bool{false, true} {
     85 		for _, failure := range []string{"placement failure", "ignored placement", "item failure", "ignored item", "retirement failure", "ignored retirement", "commit"} {
     86 			t.Run(fmt.Sprintf("pending=%t/%s", pending, failure), func(t *testing.T) {
     87 				world, output, deadline := newCorpseExpiryOutcomeWorld(t, pending)
     88 				corpse := world.characters[1000000]
     89 				statement := "CREATE TRIGGER fail_expiry BEFORE DELETE ON item_locations WHEN OLD.item_id=3 BEGIN SELECT RAISE(FAIL,'expiry'); END"
     90 				switch failure {
     91 				case "ignored placement":
     92 					statement = "CREATE TRIGGER fail_expiry BEFORE DELETE ON item_locations WHEN OLD.item_id=3 BEGIN SELECT RAISE(IGNORE); END"
     93 				case "item failure":
     94 					statement = "CREATE TRIGGER fail_expiry BEFORE DELETE ON items WHEN OLD.id=3 BEGIN SELECT RAISE(FAIL,'expiry'); END"
     95 				case "ignored item":
     96 					statement = "CREATE TRIGGER fail_expiry BEFORE DELETE ON items WHEN OLD.id=3 BEGIN SELECT RAISE(IGNORE); END"
     97 				case "retirement failure", "ignored retirement":
     98 					operation, table := "DELETE", "characters"
     99 					if pending {
    100 						operation, table = "UPDATE OF present", "npcs"
    101 					}
    102 					result := "FAIL,'expiry'"
    103 					if failure == "ignored retirement" {
    104 						result = "IGNORE"
    105 					}
    106 					statement = fmt.Sprintf("CREATE TRIGGER fail_expiry BEFORE %s ON %s WHEN OLD.id=1000000 BEGIN SELECT RAISE(%s); END", operation, table, result)
    107 				case "commit":
    108 					statement = "CREATE TABLE expiry_commit_failure (id INTEGER REFERENCES items(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_expiry AFTER DELETE ON items WHEN OLD.id=3 BEGIN INSERT INTO expiry_commit_failure VALUES(9999); END"
    109 				}
    110 				if _, err := world.db.Exec(statement); err != nil {
    111 					t.Fatal(err)
    112 				}
    113 
    114 				world.advanceCorpseExpiry(deadline)
    115 
    116 				var items, locations, visible int
    117 				if err := world.db.QueryRow(`SELECT
    118 					(SELECT count(*) FROM items WHERE id=3),
    119 					(SELECT count(*) FROM item_locations WHERE item_id=3),
    120 					(SELECT present FROM npcs WHERE id=1000000)`).Scan(&items, &locations, &visible); err != nil {
    121 					t.Fatal(err)
    122 				}
    123 				if world.characters[1000000] != corpse || corpse.corpse == nil || len(corpse.corpse.items) != 1 ||
    124 					len(world.corpseExpiry) != 1 || world.clients[1].lootCorpse != 1000000 || !world.clients[1].npcs[1000000] ||
    125 					len(output.packets) != 0 || output.observed || items != 1 || locations != 1 || visible != 1 || world.items[3].Template != 42640 {
    126 					t.Fatal("failed expiry changed cached state, durable ownership or native handles")
    127 				}
    128 
    129 				// Retry the same deadline after removing the fault.
    130 				if _, err := world.db.Exec("DROP TRIGGER fail_expiry"); err != nil {
    131 					t.Fatal(err)
    132 				}
    133 				world.advanceCorpseExpiry(deadline.Add(time.Second))
    134 				world.advanceCorpseExpiry(deadline.Add(2 * time.Second))
    135 				cold := newTestInventoryServer(t)
    136 				if world.characters[1000000] != nil || cold.characters[1000000] != nil || len(world.corpseExpiry) != 0 ||
    137 					!output.observed || output.err != nil || output.visible != 0 || output.items != 0 || output.location != 0 ||
    138 					len(output.packets) != 3 || world.items[4].Template != 99719 || cold.items[4].Template != 99719 {
    139 					t.Fatal("expiry retry did not retire exactly once or preserve the unrelated item")
    140 				}
    141 			})
    142 		}
    143 	}
    144 }
    145 
    146 func TestCorpseExpiryContainedItemFailureRollsBackTheWholeBag(t *testing.T) {
    147 	for _, failure := range []struct{ name, sql string }{
    148 		{"ignored placement", "CREATE TRIGGER fail_bag_expiry BEFORE DELETE ON item_locations WHEN OLD.item_id=18 BEGIN SELECT RAISE(IGNORE); END"},
    149 		{"ignored item", "CREATE TRIGGER fail_bag_expiry BEFORE DELETE ON items WHEN OLD.id=18 BEGIN SELECT RAISE(IGNORE); END"},
    150 		{"commit", "CREATE TABLE bag_expiry_commit (id INTEGER REFERENCES items(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_bag_expiry AFTER DELETE ON items WHEN OLD.id=18 BEGIN INSERT INTO bag_expiry_commit VALUES(9999); END"},
    151 	} {
    152 		t.Run(failure.name, func(t *testing.T) {
    153 			world := newFilledLootContainerWorld(t, 143832)
    154 			corpse := world.characters[1000000]
    155 			world.corpseExpiry = []*character{corpse}
    156 			if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil {
    157 				t.Fatal(err)
    158 			}
    159 			output := &combatTestConn{}
    160 			world.clients[1].conn = output
    161 			if _, err := world.db.Exec(failure.sql); err != nil {
    162 				t.Fatal(err)
    163 			}
    164 
    165 			world.advanceCorpseExpiry(time.Now())
    166 			cold := newTestInventoryServer(t)
    167 
    168 			if world.characters[1000000] != corpse || corpse.corpse == nil || len(output.packets) != 0 ||
    169 				len(world.items) != 2 || len(cold.items) != 2 || len(world.corpseExpiry) != 1 ||
    170 				world.clients[1].lootCorpse != 1000000 || cold.items[18].Count != 3 ||
    171 				world.items[17].Slots["slot_1"] == nil || *world.items[17].Slots["slot_1"] != 18 {
    172 				t.Fatal("contained-item failure retired the bag, contents or open container")
    173 			}
    174 			if _, err := world.db.Exec("DROP TRIGGER fail_bag_expiry"); err != nil {
    175 				t.Fatal(err)
    176 			}
    177 			world.advanceCorpseExpiry(time.Now())
    178 			cold = newTestInventoryServer(t)
    179 			if len(world.items) != 0 || len(cold.items) != 0 || cold.nextItem != 18 || len(output.packets) != 3 {
    180 				t.Fatal("bag expiry retry left orphan contents, reused IDs or repeated removal")
    181 			}
    182 		})
    183 	}
    184 }