aorecomp

Anarchy Online classic in the browser

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


server/chat_history_test.go (10468B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/binary"
      6 	"encoding/json"
      7 	"fmt"
      8 	"os"
      9 	"runtime"
     10 	"strings"
     11 	"sync"
     12 	"testing"
     13 	"time"
     14 )
     15 
     16 func TestChatHistoryRecordsChannelsAndLegacyText(t *testing.T) {
     17 	server := chatTestServer(t)
     18 	alice, disconnected := startChatTest(t, server, 0)
     19 	if _, err := alice.Write(chatTestAuth(1)); err != nil {
     20 		t.Fatal(err)
     21 	}
     22 	for range 3 {
     23 		if _, _, err := readChatPacket(alice); err != nil {
     24 			t.Fatal(err)
     25 		}
     26 	}
     27 	message := "h\xe9 \x80 \x93quoted\x94\nnext line"
     28 
     29 	for _, kind := range []uint16{30, 65} {
     30 		body := []byte{0, 0, 0, 1}
     31 		if kind == 65 {
     32 			body = []byte{0x87, 0, 0, 0, 1}
     33 		}
     34 		blob := ""
     35 		if kind == 30 {
     36 			blob = "\x00"
     37 		}
     38 		if _, err := alice.Write(chatPacket(kind, appendChatString(appendChatString(body, message), blob))); err != nil {
     39 			t.Fatal(err)
     40 		}
     41 		for range 2 {
     42 			if _, _, err := readChatPacket(alice); err != nil {
     43 				t.Fatal(err)
     44 			}
     45 		}
     46 	}
     47 	alice.Close()
     48 	if err := <-disconnected; err != nil {
     49 		t.Fatal(err)
     50 	}
     51 	for _, kind := range []uint32{0, 1, 2, 3} {
     52 		server.sendVicinity(server.clients[2], kind, message, nil)
     53 	}
     54 
     55 	data, err := readTestChatHistory(server, 1)
     56 	if err != nil {
     57 		t.Fatal(err)
     58 	}
     59 	bobData, err := readTestChatHistory(server, 2)
     60 	if err != nil {
     61 		t.Fatal(err)
     62 	}
     63 	data = append(data, bobData...)
     64 	lines := bytes.Split(bytes.TrimSpace(data), []byte{'\n'})
     65 	if len(lines) != 6 {
     66 		t.Fatalf("history has %d records: %s", len(lines), data)
     67 	}
     68 	for index, channel := range []string{"tell", "Global", "say", "whisper", "shout", "emote"} {
     69 		var entry chatHistoryEntry
     70 		if err := json.Unmarshal(lines[index], &entry); err != nil {
     71 			t.Fatal(err)
     72 		}
     73 		if entry.Channel != channel || entry.Message != "h\u00e9 \u20ac \u201cquoted\u201d\nnext line" || entry.Time.IsZero() {
     74 			t.Fatalf("history entry: %+v", entry)
     75 		}
     76 		if index < 2 && (entry.SenderID != 1 || entry.Sender != "Alice") || index >= 2 && (entry.SenderID != 2 || entry.Sender != "Bob" || entry.Playfield != 710) {
     77 			t.Fatalf("history sender: %+v", entry)
     78 		}
     79 		if index == 0 && entry.RecipientID != 1 || index != 0 && entry.RecipientID != 0 {
     80 			t.Fatalf("history recipient: %+v", entry)
     81 		}
     82 	}
     83 }
     84 
     85 func TestChatHistoryPersistsAcrossDatabaseConnections(t *testing.T) {
     86 	world := chatTestServer(t)
     87 	world.sendVicinity(world.clients[1], 0, "first", nil)
     88 	restarted := &server{characters: world.characters, clients: world.clients}
     89 	openTestDatabase(t, restarted)
     90 
     91 	restarted.sendVicinity(restarted.clients[1], 0, "second", nil)
     92 	history, err := restarted.chatHistory(1)
     93 	info, statErr := os.Stat("data/world.sqlite")
     94 
     95 	if err != nil || len(history) != 2 || history[0].Message != "first" || history[1].Message != "second" {
     96 		t.Fatalf("history across connections: %+v %v", history, err)
     97 	}
     98 	if statErr != nil || runtime.GOOS != "windows" && info.Mode().Perm()&0077 != 0 {
     99 		t.Fatalf("database permissions: %v %v", info, statErr)
    100 	}
    101 }
    102 
    103 func TestChatHistoryExcludesRejectedMessages(t *testing.T) {
    104 	server := chatTestServer(t)
    105 
    106 	for _, message := range []string{"", "bad\x00message", strings.Repeat("x", 4097)} {
    107 		server.sendVicinity(server.clients[1], 0, message, nil)
    108 	}
    109 	server.sendVicinity(server.clients[1], 4, "invalid kind", nil)
    110 	server.sendVicinity(&worldClient{id: 3, ready: true}, 0, "unknown sender", nil)
    111 
    112 	var count int
    113 	if err := server.db.QueryRow("SELECT COUNT(*) FROM chat_history").Scan(&count); err != nil || count != 0 {
    114 		t.Fatal("rejected messages created history", count, err)
    115 	}
    116 }
    117 
    118 func TestChatHistoryKeepsConcurrentMessagesIntact(t *testing.T) {
    119 	server := chatTestServer(t)
    120 	client := server.clients[1]
    121 	shutdown := startTestService(t, server)
    122 	owner, err := server.world.owner(1)
    123 	if err != nil {
    124 		t.Fatal(err)
    125 	}
    126 	var writers sync.WaitGroup
    127 
    128 	for range 20 {
    129 		writers.Add(1)
    130 		go func() {
    131 			defer writers.Done()
    132 			owner.sendVicinity(client, 0, "concurrent message", nil)
    133 		}()
    134 	}
    135 	writers.Wait()
    136 
    137 	data, err := readTestChatHistory(server, 1)
    138 	if err != nil {
    139 		t.Fatal(err)
    140 	}
    141 	lines := bytes.Split(bytes.TrimSpace(data), []byte{'\n'})
    142 	if len(lines) != 20 {
    143 		t.Fatalf("concurrent history has %d records", len(lines))
    144 	}
    145 	for _, line := range lines {
    146 		var entry chatHistoryEntry
    147 		if err := json.Unmarshal(line, &entry); err != nil || entry.Message != "concurrent message" {
    148 			t.Fatalf("concurrent record: %s %v", line, err)
    149 		}
    150 	}
    151 	if err := shutdown(); err != nil {
    152 		t.Fatal(err)
    153 	}
    154 }
    155 
    156 func TestChatHistoryFailureDoesNotPreventDelivery(t *testing.T) {
    157 	server := chatTestServer(t)
    158 	alice := loginChatTest(t, server, 1)
    159 	failDatabaseWrites(t, server)
    160 	done := make(chan struct{})
    161 
    162 	go func() {
    163 		server.sendVicinity(server.clients[2], 0, "still delivered", nil)
    164 		close(done)
    165 	}()
    166 	_, _, nameErr := readChatPacket(alice)
    167 	kind, body, err := readChatPacket(alice)
    168 	<-done
    169 
    170 	if nameErr != nil || err != nil || kind != 34 || !bytes.Contains(body, []byte("still delivered")) {
    171 		t.Fatalf("delivery after history failure: %d %x %v %v", kind, body, nameErr, err)
    172 	}
    173 }
    174 
    175 func TestChatHistoryRestoresReceivedMessagesAfterMovingAndRestarting(t *testing.T) {
    176 	world := chatTestServer(t)
    177 	alice := loginChatTest(t, world, 1)
    178 	done := make(chan struct{})
    179 	go func() {
    180 		world.sendVicinity(world.clients[2], 0, "h\xe9 from Bob", nil)
    181 		close(done)
    182 	}()
    183 	for range 2 {
    184 		if _, _, err := readChatPacket(alice); err != nil {
    185 			t.Fatal(err)
    186 		}
    187 	}
    188 	<-done
    189 	alice.Close()
    190 	world.characters[2].position[0] = 11
    191 	world.sendVicinity(world.clients[2], 0, "outside Alice's vicinity", nil)
    192 	world.characters[1].position[0] = 100
    193 
    194 	restarted := &server{characters: world.characters, clients: world.clients}
    195 	openTestDatabase(t, restarted)
    196 	alice = loginChatTest(t, restarted, 1)
    197 	kind, body, err := readChatPacket(alice)
    198 	message, valid := readChatString(&body)
    199 	ping := chatPacket(100, nil)
    200 	if _, err := alice.Write(ping); err != nil {
    201 		t.Fatal(err)
    202 	}
    203 	nextKind, _, nextErr := readChatPacket(alice)
    204 
    205 	if err != nil || kind != 36 || !valid || !strings.Contains(message, "[say] Bob: h\xe9 from Bob") {
    206 		t.Fatalf("restored history: %d %q %v", kind, message, err)
    207 	}
    208 	if nextErr != nil || nextKind != 100 {
    209 		t.Fatalf("unexpected history or unavailable live chat: %d %v", nextKind, nextErr)
    210 	}
    211 }
    212 
    213 func TestChatHistoryRestoresTellsOnlyForTheirParticipants(t *testing.T) {
    214 	world := chatTestServer(t)
    215 	alice := loginChatTest(t, world, 1)
    216 	bob := loginChatTest(t, world, 2)
    217 	packet := binary.BigEndian.AppendUint32(nil, 2)
    218 	packet = appendChatString(appendChatString(packet, "private conversation"), "\x00")
    219 	if _, err := alice.Write(chatPacket(30, packet)); err != nil {
    220 		t.Fatal(err)
    221 	}
    222 	for range 2 {
    223 		if _, _, err := readChatPacket(bob); err != nil {
    224 			t.Fatal(err)
    225 		}
    226 	}
    227 	alice.Close()
    228 	bob.Close()
    229 	world.characters[3] = &character{id: 3, name: "Carol", playfield: 710}
    230 	world.clients[3] = &worldClient{id: 3, ready: true}
    231 	world.publishChatPerson(world.characters[3])
    232 
    233 	var messages []string
    234 	for _, id := range []uint32{1, 2} {
    235 		peer := loginChatTest(t, world, id)
    236 		kind, body, err := readChatPacket(peer)
    237 		message, valid := readChatString(&body)
    238 		if err != nil || kind != 36 || !valid {
    239 			t.Fatalf("tell history: %d %q %v", kind, message, err)
    240 		}
    241 		messages = append(messages, message)
    242 		peer.Close()
    243 	}
    244 	carol := loginChatTest(t, world, 3)
    245 	if _, err := carol.Write(chatPacket(100, nil)); err != nil {
    246 		t.Fatal(err)
    247 	}
    248 	kind, _, err := readChatPacket(carol)
    249 
    250 	if !strings.Contains(messages[0], "[tell] Alice -> Bob: private conversation") || messages[0] != messages[1] {
    251 		t.Fatalf("tell participants saw different histories: %q", messages)
    252 	}
    253 	if err != nil || kind != 100 {
    254 		t.Fatalf("private history leaked to Carol: %d %v", kind, err)
    255 	}
    256 	aliceData, err := readTestChatHistory(world, 1)
    257 	if err != nil {
    258 		t.Fatal(err)
    259 	}
    260 	bobData, err := readTestChatHistory(world, 2)
    261 	if err != nil || !bytes.Equal(aliceData, bobData) {
    262 		t.Fatalf("tell history was not duplicated for both participants: %v", err)
    263 	}
    264 }
    265 
    266 func TestChatHistoryRestoresNewestEntriesOnlyForItsOwner(t *testing.T) {
    267 	world := chatTestServer(t)
    268 	entry := chatHistoryEntry{Time: time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC), Channel: "say", SenderID: 1, Sender: "Alice"}
    269 	for index := 0; index < 508; index++ {
    270 		entry.Message = fmt.Sprintf("message %d", index)
    271 		if err := world.appendChatHistory([]uint32{1}, entry); err != nil {
    272 			t.Fatal(err)
    273 		}
    274 	}
    275 	entry.Message = "Bob's private history"
    276 	if err := world.appendChatHistory([]uint32{2}, entry); err != nil {
    277 		t.Fatal(err)
    278 	}
    279 
    280 	alice := loginChatTest(t, world, 1)
    281 	var messages []string
    282 	for range 500 {
    283 		kind, body, err := readChatPacket(alice)
    284 		message, valid := readChatString(&body)
    285 		if err != nil || kind != 36 || !valid {
    286 			t.Fatalf("history: %d %q %v", kind, message, err)
    287 		}
    288 		messages = append(messages, message)
    289 	}
    290 	if _, err := alice.Write(chatPacket(100, nil)); err != nil {
    291 		t.Fatal(err)
    292 	}
    293 	kind, _, err := readChatPacket(alice)
    294 
    295 	if messages[0] != "[History 2026-10-20 12:00:00 UTC] [say] Alice: message 8" || messages[496] != "[History 2026-10-20 12:00:00 UTC] [say] Alice: message 504" || messages[499] != "[History 2026-10-20 12:00:00 UTC] [say] Alice: message 507" {
    296 		t.Fatalf("history order: first=%q boundary=%q last=%q", messages[0], messages[496], messages[499])
    297 	}
    298 	if err != nil || kind != 100 {
    299 		t.Fatalf("history exceeded its bound: %d %v", kind, err)
    300 	}
    301 }
    302 
    303 func TestChatHistoryFinishesBeforeLiveDelivery(t *testing.T) {
    304 	world := chatTestServer(t)
    305 	world.sendVicinity(world.clients[1], 0, "earlier message", nil)
    306 	alice, _ := startChatTest(t, world, 0)
    307 	if _, err := alice.Write(chatTestAuth(1)); err != nil {
    308 		t.Fatal(err)
    309 	}
    310 	if kind, _, err := readChatPacket(alice); err != nil || kind != 5 {
    311 		t.Fatalf("chat initialization: %d %v", kind, err)
    312 	}
    313 	done := make(chan struct{})
    314 
    315 	go func() {
    316 		world.sendVicinity(world.clients[2], 0, "new message", nil)
    317 		close(done)
    318 	}()
    319 	var kinds []uint16
    320 	var messages []string
    321 	for range 5 {
    322 		kind, body, err := readChatPacket(alice)
    323 		if err != nil {
    324 			t.Fatal(err)
    325 		}
    326 		kinds = append(kinds, kind)
    327 		if kind == 36 {
    328 			message, _ := readChatString(&body)
    329 			messages = append(messages, message)
    330 		} else if kind == 34 {
    331 			body = body[4:]
    332 			message, _ := readChatString(&body)
    333 			messages = append(messages, message)
    334 		}
    335 	}
    336 	<-done
    337 
    338 	if fmt.Sprint(kinds) != "[20 60 36 20 34]" || len(messages) != 2 || !strings.Contains(messages[0], "[say] Alice: earlier message") || messages[1] != "new message" {
    339 		t.Fatalf("history and live delivery interleaved: %v %q", kinds, messages)
    340 	}
    341 }