server/world_output_test.go (16003B)
1 package main 2 3 import ( 4 "bytes" 5 "encoding/binary" 6 "errors" 7 "io" 8 "net" 9 "slices" 10 "sync" 11 "sync/atomic" 12 "testing" 13 "time" 14 ) 15 16 type shortWorldConn struct { 17 net.Conn 18 closed bool 19 } 20 21 type blockingCloseConn struct { 22 net.Conn 23 started chan struct{} 24 release chan struct{} 25 } 26 27 type countingWorldConn struct { 28 stalledCombatConn 29 writes atomic.Int32 30 } 31 32 func (conn *countingWorldConn) Write(packet []byte) (int, error) { 33 conn.writes.Add(1) 34 return conn.stalledCombatConn.Write(packet) 35 } 36 37 func TestWorldOutputBatchesQueuedPacketsWithoutWaiting(t *testing.T) { 38 host, peer := net.Pipe() 39 peer.SetReadDeadline(time.Now().Add(time.Second)) 40 conn := &countingWorldConn{stalledCombatConn: stalledCombatConn{Conn: host, started: make(chan struct{})}} 41 client := &worldClient{conn: conn, id: 7} 42 client.startWriter(conn) 43 t.Cleanup(func() { peer.Close(); client.finishWriter() }) 44 45 if err := client.send(systemPacket(0, []byte{0})); err != nil { 46 t.Fatal(err) 47 } 48 <-conn.started 49 for _, value := range []byte{1, 2} { 50 if err := client.send(systemPacket(0, []byte{value})); err != nil { 51 t.Fatal(err) 52 } 53 } 54 for _, value := range []byte{0, 1, 2} { 55 packet, err := readPacket(peer) 56 if err != nil || packet[len(packet)-1] != value { 57 t.Fatalf("packet %d: %x, %v", value, packet, err) 58 } 59 } 60 client.finishWriter() 61 if conn.writes.Load() != 2 { 62 t.Fatalf("queued packets used %d transport writes, want 2", conn.writes.Load()) 63 } 64 } 65 66 func TestWorldBroadcastRetiresFailedRecipientAndPreservesDeparture(t *testing.T) { 67 world, observer := newCombatWorld(t) 68 failed := &failingCombatConn{} 69 world.characters[2] = &character{id: 2, playfield: 950, health: 100} 70 client := &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: failed, ready: true} 71 world.clients[2] = client 72 world.clients[1].players = map[uint32]bool{2: true} 73 packet := stopFightPacket(1) 74 75 world.broadcast(950, 0, packet) 76 if client.ready || !failed.closed { 77 t.Fatal("failed recipient remained eligible for broadcasts") 78 } 79 // A later broadcast must not attempt another close on the failed connection. 80 failed.closed = false 81 world.broadcast(950, 0, packet) 82 if failed.closed || len(observer.packets) != 2 { 83 t.Fatal("broadcast retried the failed recipient or skipped the healthy peer") 84 } 85 trade := &playerTrade{clients: [2]*worldClient{world.clients[1], client}} 86 world.clients[1].trade, client.trade = trade, trade 87 world.leaveWorldClient(client) 88 if world.clients[1].trade != nil || client.trade != nil { 89 t.Fatal("failed recipient left its peer in a trade") 90 } 91 if world.clients[2] != nil || len(observer.packets) != 4 || binary.BigEndian.Uint32(observer.packets[3][16:20]) != 0x36510078 { 92 t.Fatal("failed recipient did not complete normal departure") 93 } 94 } 95 96 func TestWorldOutputDisconnectDiscardsRemainderOfDetachedBatch(t *testing.T) { 97 host, peer := net.Pipe() 98 peer.SetReadDeadline(time.Now().Add(time.Second)) 99 conn := &countingWorldConn{stalledCombatConn: stalledCombatConn{Conn: host, started: make(chan struct{})}} 100 client := &worldClient{conn: conn, id: 7} 101 client.startWriter(conn) 102 t.Cleanup(func() { peer.Close(); client.finishWriter() }) 103 104 if err := client.send(systemPacket(0, make([]byte, 60000))); err != nil { 105 t.Fatal(err) 106 } 107 <-conn.started 108 client.disconnect(conn) 109 if _, err := io.ReadFull(peer, make([]byte, 32768)); err != nil { 110 t.Fatal(err) 111 } 112 if _, err := peer.Read(make([]byte, 1)); err != io.EOF { 113 t.Fatalf("discarded batch continued after the in-flight write: %v", err) 114 } 115 client.finishWriter() 116 if conn.writes.Load() != 1 { 117 t.Fatalf("discarded output used %d transport writes, want 1", conn.writes.Load()) 118 } 119 } 120 121 func (conn *blockingCloseConn) Close() error { 122 close(conn.started) 123 <-conn.release 124 return conn.Conn.Close() 125 } 126 127 func TestWorldReplacementDoesNotWaitForOldTransportClose(t *testing.T) { 128 world, _ := newCombatWorld(t) 129 host, peer := net.Pipe() 130 conn := &blockingCloseConn{Conn: host, started: make(chan struct{}), release: make(chan struct{})} 131 old := world.clients[1] 132 old.conn = conn 133 old.startWriter(conn) 134 replacement := &combatInterestConn{input: bytes.NewReader(systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}))} 135 startTestService(t, world) 136 done := make(chan error, 1) 137 t.Cleanup(func() { close(conn.release); peer.Close(); old.finishWriter(); <-done }) 138 139 go func() { done <- world.serveWorldClient(&worldClient{conn: replacement}); close(done) }() 140 select { 141 case <-conn.started: 142 case <-time.After(time.Second): 143 t.Fatal("replaced transport was not closed") 144 } 145 146 select { 147 case err := <-done: 148 if err != nil { 149 t.Fatal(err) 150 } 151 case <-time.After(250 * time.Millisecond): 152 t.Fatal("replacing a session waited for the old transport's close handshake") 153 } 154 } 155 156 func TestWorldReplacementRemovesRemoteActorBeforeReplayingEquipment(t *testing.T) { 157 for _, scenario := range []string{"visible previous session", "unfinished previous session", "fresh login"} { 158 t.Run(scenario, func(t *testing.T) { 159 world, _ := newRangedWorld(t) 160 player := world.characters[1] 161 player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1}) 162 player.inventory.LastID = 3 163 world.clients[1].conn = &combatInterestConn{} 164 if scenario == "unfinished previous session" { 165 world.clients[1].ready = false 166 } else if scenario == "fresh login" { 167 delete(world.clients, 1) 168 } 169 observer := &combatTestConn{} 170 world.characters[2] = &character{id: 2, playfield: 950, health: 100} 171 world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true} 172 cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}) 173 ready := n3Packet(0x570c2039, 50000, 1, nil) 174 input := append(cookie, ready...) 175 input = append(input, ready...) 176 replacement := &combatInterestConn{input: bytes.NewReader(input)} 177 178 shutdown := startTestService(t, world) 179 err := world.serveWorldClient(&worldClient{conn: replacement, loading: true}) 180 if err := shutdown(); err != nil { 181 t.Fatal(err) 182 } 183 var keys []uint32 184 for _, packet := range observer.packets { 185 keys = append(keys, binary.BigEndian.Uint32(packet[16:20])) 186 } 187 188 expected := []uint32{0x271b3a6b, 0x734e5a7b, 0x570c2039} 189 for range 16 { 190 expected = append(expected, 0x2b333d6e) 191 } 192 expected = append(expected, 0x3b1d2268, 0x35505644, 0x570c2039, 0x36510078) 193 if scenario == "visible previous session" { 194 expected = append([]uint32{0x36510078}, expected...) 195 } 196 if err != nil || !slices.Equal(keys, expected) { 197 t.Fatalf("replacement must discard cached OnWear effects before replay: %x, %v", keys, err) 198 } 199 }) 200 } 201 } 202 203 func TestWorldJoiningObserverWaitsForLoadingPlayersEquipment(t *testing.T) { 204 for _, scenario := range []string{"player loading", "player loaded"} { 205 t.Run(scenario, func(t *testing.T) { 206 world, _ := newRangedWorld(t) 207 world.characters[1].inventory.Items = append(world.characters[1].inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 158790, Quality: 1, Slot: 19, Count: 1}) 208 world.clients[1].loading = scenario == "player loading" 209 world.characters[2] = &character{id: 2, playfield: 950, health: 100} 210 cookie := systemPacket(0x1b, []byte{0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0}) 211 observer := &combatInterestConn{input: bytes.NewReader(cookie)} 212 213 shutdown := startTestService(t, world) 214 err := world.serveWorldClient(&worldClient{conn: observer, loading: true}) 215 if err := shutdown(); err != nil { 216 t.Fatal(err) 217 } 218 var equipment []uint32 219 for _, packet := range observer.packets { 220 key := binary.BigEndian.Uint32(packet[20:24]) 221 if key == 0x35505644 || key == 0x3b1d2268 { 222 equipment = append(equipment, key) 223 } 224 } 225 226 var expected []uint32 227 if scenario == "player loaded" { 228 expected = []uint32{0x3b1d2268, 0x35505644} 229 } 230 if err != nil || !slices.Equal(equipment, expected) { 231 t.Fatalf("initial snapshot must not duplicate equipment still awaiting ready: %x, %v", equipment, err) 232 } 233 }) 234 } 235 } 236 237 func (conn *shortWorldConn) SetWriteDeadline(time.Time) error { return nil } 238 func (conn *shortWorldConn) Write(packet []byte) (int, error) { return len(packet) - 1, nil } 239 func (conn *shortWorldConn) Close() error { 240 conn.closed = true 241 return nil 242 } 243 244 func TestWorldOutputPreservesOrderAndOwnsQueuedPacketBytes(t *testing.T) { 245 host, peer := net.Pipe() 246 peer.SetReadDeadline(time.Now().Add(time.Second)) 247 client := &worldClient{conn: host, id: 7, target: true} 248 client.startWriter(client.conn) 249 t.Cleanup(func() { peer.Close(); client.finishWriter() }) 250 first := attackPacket(1, 1000000) 251 expected := targetPacket(attackPacket(1, 1000000)) 252 binary.BigEndian.PutUint32(expected[12:16], 7) 253 254 if err := client.send(first); err != nil { 255 t.Fatal(err) 256 } 257 first[40] = 99 258 if err := client.send(stopFightPacket(1)); err != nil { 259 t.Fatal(err) 260 } 261 attack, err := readPacket(peer) 262 if err != nil { 263 t.Fatal(err) 264 } 265 stop, err := readPacket(peer) 266 if err != nil { 267 t.Fatal(err) 268 } 269 270 if !bytes.Equal(attack, expected[:binary.BigEndian.Uint16(expected[6:8])]) || binary.BigEndian.Uint32(stop[16:20]) != 0x4a41203e { 271 t.Fatalf("queued bytes changed or reordered: %x %x", attack, stop) 272 } 273 } 274 275 func TestWorldOutputRejectsQueueOverflowAndReleasesPendingBytes(t *testing.T) { 276 host, peer := net.Pipe() 277 conn := &stalledCombatConn{Conn: host, started: make(chan struct{})} 278 client := &worldClient{conn: conn, id: 1} 279 client.startWriter(client.conn) 280 t.Cleanup(func() { peer.Close(); client.finishWriter() }) 281 if err := client.send(systemPacket(0, nil)); err != nil { 282 t.Fatal(err) 283 } 284 <-conn.started 285 packet := systemPacket(0, make([]byte, 60000)) 286 287 var sendErr error 288 for range 150 { 289 if sendErr = client.send(packet); sendErr != nil { 290 break 291 } 292 } 293 // Release the in-flight write after overflow has discarded pending output. 294 peer.Close() 295 select { 296 case <-client.writeDone: 297 case <-time.After(time.Second): 298 t.Fatal("queue overflow did not close the blocked writer") 299 } 300 301 if sendErr == nil || !errors.Is(client.send(packet), net.ErrClosed) || len(client.outgoing) != 0 { 302 t.Fatalf("overflow left an open queue: err=%v bytes=%d", sendErr, len(client.outgoing)) 303 } 304 } 305 306 func TestWorldOutputShortWriteClosesTheConnection(t *testing.T) { 307 conn := &shortWorldConn{} 308 client := &worldClient{conn: conn, id: 1} 309 client.startWriter(client.conn) 310 t.Cleanup(client.finishWriter) 311 312 if err := client.send(systemPacket(0, nil)); err != nil { 313 t.Fatal(err) 314 } 315 select { 316 case <-client.writeDone: 317 case <-time.After(time.Second): 318 t.Fatal("short write left the writer running") 319 } 320 321 if !conn.closed || !errors.Is(client.send(systemPacket(0, nil)), net.ErrClosed) { 322 t.Fatal("short write left the protocol stream usable") 323 } 324 } 325 326 func TestWorldOutputUnresponsivePeerIsDisconnected(t *testing.T) { 327 host, peer := net.Pipe() 328 client := &worldClient{conn: host, id: 1} 329 client.startWriter(client.conn) 330 t.Cleanup(func() { peer.Close(); client.finishWriter() }) 331 332 if err := client.send(systemPacket(0, nil)); err != nil { 333 t.Fatal(err) 334 } 335 select { 336 case <-client.writeDone: 337 case <-time.After(6 * time.Second): 338 t.Fatal("unresponsive peer outlived its write deadline") 339 } 340 341 if !errors.Is(client.send(systemPacket(0, nil)), net.ErrClosed) || len(client.outgoing) != 0 { 342 t.Fatal("timed out output remained usable") 343 } 344 } 345 346 func TestWorldOutputConcurrentProducersPreserveEachPacketSequence(t *testing.T) { 347 host, peer := net.Pipe() 348 peer.SetReadDeadline(time.Now().Add(3 * time.Second)) 349 client := &worldClient{conn: host, id: 1} 350 client.startWriter(client.conn) 351 t.Cleanup(func() { peer.Close(); client.finishWriter() }) 352 var producers sync.WaitGroup 353 sendErrors := make(chan error, 4) 354 355 for producer := range uint32(4) { 356 producers.Add(1) 357 go func() { 358 defer producers.Done() 359 for sequence := range uint32(100) { 360 body := binary.BigEndian.AppendUint32(nil, producer) 361 body = binary.BigEndian.AppendUint32(body, sequence) 362 if err := client.send(systemPacket(0, body)); err != nil { 363 sendErrors <- err 364 return 365 } 366 } 367 }() 368 } 369 producers.Wait() 370 close(sendErrors) 371 for err := range sendErrors { 372 t.Fatal(err) 373 } 374 counts := [4]uint32{} 375 for range 400 { 376 packet, err := readPacket(peer) 377 if err != nil { 378 t.Fatal(err) 379 } 380 producer, sequence := binary.BigEndian.Uint32(packet[20:24]), binary.BigEndian.Uint32(packet[24:28]) 381 if producer >= 4 || sequence != counts[producer] { 382 t.Fatalf("interleaved or reordered stream: %x counts=%v", packet, counts) 383 } 384 counts[producer]++ 385 } 386 387 if counts != [4]uint32{100, 100, 100, 100} { 388 t.Fatalf("lost packets: %v", counts) 389 } 390 } 391 392 func TestWorldOutputDrainsAcceptedPacketsWhenSessionEnds(t *testing.T) { 393 conn := &combatInterestConn{input: bytes.NewReader(nil)} 394 client := &worldClient{conn: conn, id: 1} 395 client.startWriter(client.conn) 396 packet := systemPacket(0, []byte{1, 2, 3, 4}) 397 if err := client.send(packet); err != nil { 398 t.Fatal(err) 399 } 400 401 client.finishWriter() 402 403 if len(conn.packets) != 1 || !bytes.Equal(conn.packets[0][20:24], []byte{1, 2, 3, 4}) { 404 t.Fatalf("session shutdown dropped accepted output: %x", conn.packets) 405 } 406 } 407 408 func TestWorldBroadcastSharesEncodingWithoutSharingRecipientHeaders(t *testing.T) { 409 world, first := newCombatWorld(t) 410 second, legacy := &combatTestConn{}, &combatTestConn{} 411 for id, output := range map[uint32]*combatTestConn{2: second, 3: legacy} { 412 world.characters[id] = &character{id: id, playfield: 950} 413 world.clients[id] = &worldClient{id: id, ready: true, target: id == 2, conn: output, players: map[uint32]bool{1: true}} 414 } 415 packet := npcMovementPacket(world.characters[1], 1) 416 original := append([]byte(nil), packet...) 417 418 world.broadcast(950, 0, packet) 419 420 if !bytes.Equal(packet, original) { 421 t.Fatal("broadcast changed its source packet") 422 } 423 for index, output := range []*combatTestConn{first, second, legacy} { 424 if len(output.packets) != 1 || binary.BigEndian.Uint32(output.packets[0][12:16]) != uint32(index+1) { 425 t.Fatal("shared packet retained another recipient's header", index, output.packets) 426 } 427 length := 48 428 if index == 2 { 429 length = 76 430 } 431 if len(output.packets[0]) != length { 432 t.Fatal("recipient received the wrong protocol layout", index, output.packets[0]) 433 } 434 } 435 } 436 437 func TestCombatBatchPreservesSharedPacketsAndRecipientOrder(t *testing.T) { 438 // Share a packet twice, with a distinct packet between its deliveries. 439 world := &server{} 440 move := npcMovementPacket(&character{id: 17, rotation: [4]float32{0, 0, 0, 1}}, 1) 441 stop := stopFightPacket(17) 442 original := slices.Clone(move) 443 updates := make(map[*worldClient][][]byte) 444 for id := uint32(1); id <= 3; id++ { 445 client := &worldClient{id: id, ready: true, target: id != 3, conn: &combatTestConn{}} 446 updates[client] = [][]byte{move, stop, move} 447 } 448 449 world.sendCombatUpdates(updates) 450 451 if !bytes.Equal(move, original) { 452 t.Fatal("batch conversion mutated its shared source") 453 } 454 for client := range updates { 455 packets := client.conn.(*combatTestConn).packets 456 if len(packets) != 3 || !bytes.Equal(packets[0], packets[2]) { 457 t.Fatal("batch lost or changed a repeated packet", packets) 458 } 459 offset, length := 16, 48 460 if !client.target { 461 offset, length = 20, 76 462 } 463 if len(packets[0]) != length || binary.BigEndian.Uint32(packets[0][offset:]) != 0x54111123 || 464 binary.BigEndian.Uint32(packets[1][offset:]) != 0x4a41203e { 465 t.Fatal("batch changed protocol or packet order", packets) 466 } 467 for _, packet := range packets { 468 if binary.BigEndian.Uint32(packet[12:16]) != client.id { 469 t.Fatal("batch retained another recipient's header", packet) 470 } 471 } 472 } 473 474 // Reusing a source buffer in a later batch must not reuse its old conversion. 475 binary.BigEndian.PutUint32(move[36:40], 2) 476 world.sendCombatUpdates(updates) 477 for client := range updates { 478 packet := client.conn.(*combatTestConn).packets[3] 479 if client.target && packet[29] != 2 || !client.target && binary.BigEndian.Uint32(packet[36:40]) != 2 { 480 t.Fatal("batch retained a stale conversion", packet) 481 } 482 } 483 }