aorecomp

Anarchy Online classic in the browser

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


server/npc_checkpoint_batch_test.go (5380B)


      1 package main
      2 
      3 import (
      4 	"maps"
      5 	"reflect"
      6 	"testing"
      7 	"time"
      8 )
      9 
     10 func newNPCCheckpointPopulation(t *testing.T, count int) (*server, time.Time) {
     11 	t.Helper()
     12 	data := testNPCData()
     13 	group := &data.Playfields[0].Districts[0].Groups[0]
     14 	group.PlacementStatus = "authored_point"
     15 	group.Positions = make([][3]float32, count)
     16 	for index := range group.Positions {
     17 		group.Positions[index] = [3]float32{52, 14, 56}
     18 	}
     19 	useNPCData(t, data)
     20 	world := newTestServer(t)
     21 	player := world.newCharacter()
     22 	player.position = [3]float32{52, 14, 56}
     23 	world.clients[player.id] = &worldClient{id: player.id, ready: true}
     24 	start := time.Now()
     25 	if err := world.checkpointWorld(start); err != nil {
     26 		t.Fatal(err)
     27 	}
     28 	return world, start
     29 }
     30 
     31 func TestNPCCheckpointBatchesOnlyChangedTables(t *testing.T) {
     32 	for _, change := range []string{"health", "roaming", "both"} {
     33 		t.Run(change, func(t *testing.T) {
     34 			world, start := newNPCCheckpointPopulation(t, 1000)
     35 			for _, npc := range world.characters {
     36 				if !npc.npc {
     37 					continue
     38 				}
     39 				if change != "roaming" {
     40 					npc.health = 53
     41 				}
     42 				if change != "health" {
     43 					npc.motion.roaming = false
     44 				}
     45 			}
     46 			queries := world.databaseQueries.Load()
     47 			now := start.Add(41 * time.Second)
     48 
     49 			if err := world.checkpointWorld(now); err != nil {
     50 				t.Fatal(err)
     51 			}
     52 
     53 			want := uint64(10)
     54 			if change == "both" {
     55 				want = 20
     56 			}
     57 			if got := world.databaseQueries.Load() - queries; got != want {
     58 				t.Fatalf("1000 NPC checkpoints: got %d queries, want %d", got, want)
     59 			}
     60 			var positions, routes int
     61 			if err := world.db.QueryRow(`SELECT sum(health=53), sum(idle_roaming=0)
     62 				FROM characters JOIN npcs USING(id)`).Scan(&positions, &routes); err != nil {
     63 				t.Fatal(err)
     64 			}
     65 			if change != "roaming" && positions != 1000 || change != "health" && routes != 1000 {
     66 				t.Fatal("batch lost NPC state", positions, routes)
     67 			}
     68 			deadlines := make(map[time.Time]bool)
     69 			for _, saved := range world.savedNPCs {
     70 				if saved.NextSave.Before(now.Add(20*time.Second)) || !saved.NextSave.Before(now.Add(30*time.Second)) {
     71 					t.Fatal("checkpoint did not schedule 20-30 second jitter", saved.NextSave.Sub(now))
     72 				}
     73 				deadlines[saved.NextSave] = true
     74 			}
     75 			if len(deadlines) < 2 {
     76 				t.Fatal("checkpoint deadlines were synchronized")
     77 			}
     78 
     79 			// Further movement remains in memory until the next checkpoint is due.
     80 			world.characters[1000000].position[0] = 54
     81 			queries = world.databaseQueries.Load()
     82 			if err := world.checkpointWorld(now.Add(19 * time.Second)); err != nil {
     83 				t.Fatal(err)
     84 			}
     85 			if world.databaseQueries.Load()-queries != 0 || world.savedNPCs[1000000].State.Character.Position.Position[0] == 54 {
     86 				t.Fatal("routine movement persisted before 20 seconds")
     87 			}
     88 		})
     89 	}
     90 }
     91 
     92 func TestNPCCheckpointBatchFailureRollsBackAndRetries(t *testing.T) {
     93 	for _, table := range []string{"characters", "npcs"} {
     94 		for _, failure := range []string{"IGNORE", "ABORT, 'checkpoint failure'"} {
     95 			t.Run(table+"/"+failure, func(t *testing.T) {
     96 				world, start := newNPCCheckpointPopulation(t, 250)
     97 				before := maps.Clone(world.savedNPCs)
     98 				for _, npc := range world.characters {
     99 					if npc.npc {
    100 						npc.health, npc.motion.home[0] = 53, 53
    101 					}
    102 				}
    103 				column := "health"
    104 				if table == "npcs" {
    105 					column = "home_x"
    106 				}
    107 				// Fail after two full batches have already written inside the transaction.
    108 				if _, err := world.db.Exec("CREATE TRIGGER reject_checkpoint BEFORE UPDATE ON " + table +
    109 					" WHEN (SELECT count(*) FROM " + table + " WHERE id>=1000000 AND " + column + "=53)>=200" +
    110 					" BEGIN SELECT RAISE(" + failure + "); END"); err != nil {
    111 					t.Fatal(err)
    112 				}
    113 				now := start.Add(41 * time.Second)
    114 
    115 				if err := world.checkpointWorld(now); err == nil {
    116 					t.Fatal("incomplete batch succeeded")
    117 				}
    118 
    119 				var changed int
    120 				if err := world.db.QueryRow(`SELECT count(*) FROM characters JOIN npcs USING(id)
    121 					WHERE health=53 OR home_x=53`).Scan(&changed); err != nil {
    122 					t.Fatal(err)
    123 				}
    124 				if changed != 0 || !reflect.DeepEqual(before, world.savedNPCs) {
    125 					t.Fatal("failed checkpoint published partial database or cache state", changed)
    126 				}
    127 				if _, err := world.db.Exec("DROP TRIGGER reject_checkpoint"); err != nil {
    128 					t.Fatal(err)
    129 				}
    130 				if err := world.checkpointWorld(now); err != nil {
    131 					t.Fatal(err)
    132 				}
    133 				if err := world.db.QueryRow(`SELECT count(*) FROM characters JOIN npcs USING(id)
    134 					WHERE health=53 AND home_x=53`).Scan(&changed); err != nil || changed != 250 {
    135 					t.Fatal("checkpoint retry lost rows", changed, err)
    136 				}
    137 			})
    138 		}
    139 	}
    140 }
    141 
    142 func TestLivingNPCRoamingDoesNotWriteCheckpoints(t *testing.T) {
    143 	world, start := newNPCCheckpointPopulation(t, 1)
    144 	npc := world.characters[1000000]
    145 	npc.position[0] = 53
    146 	npc.rotation = [4]float32{0, 1, 0, 0}
    147 	npc.motion.destination[0] = 55
    148 	npc.motion.moving = true
    149 	npc.motion.nextMove = start.Add(time.Second)
    150 	queries := world.databaseQueries.Load()
    151 
    152 	if err := world.checkpointWorld(start.Add(time.Minute)); err != nil {
    153 		t.Fatal(err)
    154 	}
    155 	if world.databaseQueries.Load() != queries {
    156 		t.Fatal("roaming generated database work")
    157 	}
    158 	restored := newTestInventoryServer(t).characters[1000000]
    159 	if restored.position != [3]float32{52, 14, 56} || restored.motion.moving || restored.motion.destination != restored.motion.home {
    160 		t.Fatal("living NPC did not restart at home with a fresh route")
    161 	}
    162 }