commit 12780bfc715560c65c06749cecf82ede86b77537 parent cc9c0fa40554717c796dbe15c904e095809a34a4 Author: anon <anon@example.com> Date: Sat, 7 Nov 2026 16:09:27 +0000 Separate world coordination and reduce profiled delivery costs Diffstat:
56 files changed, 773 insertions(+), 516 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -70,7 +70,7 @@ replacement. | --- | --- | | Protocol and sessions | `main.go` decodes native messages and owns socket deadlines; `world_dispatch.go` dispatches game commands; `browser_socket.go` and `browser_account.go` authorize browser streams and credentials. Connection state belongs to `worldClient`, `chatClient` and their output/stream adapters. Decode and authorize before invoking a game action. | | World simulation | Each `zone_runtime.go` goroutine exclusively owns its zone's characters, sessions, inventories, spatial indexes and lifecycle queues. It processes commands and simulation ticks. `simulation.go` starts and drains these owners. Browser scenarios must not supply their own tick loops. | -| Cross-zone coordination | `world_runtime.go` owns routing and detached metadata; `world_operations.go` coordinates operations involving multiple owners. Team and chat owners exchange detached messages with zones. Never read another zone's entity pointers. | +| Cross-zone coordination | `world_directory.go` owns routing and detached metadata through the `world_runtime.go` channel API; `world_operations.go` coordinates operations involving multiple owners. Team and chat owners exchange detached messages with zones. Never read another zone's entity pointers. | | Shared geometry | Asset decoders publish immutable results once per resource through `sync.Map` and `sync.OnceValue`. A short mutex protects mission registrations; decoding and geometry queries execute outside it. Navigation jobs pin their mission scene until completion. | | Rules and content | Action implementations such as `inventory.go`, combat and nano handlers decide admission and outcomes using `gamedata`. UI and transport code report those outcomes rather than reproducing the rules. | | Durable transactions | `database.go`, `item_store.go` and `world_store.go` own database records, item ownership and checkpoints. Significant actions commit their related changes before updating shared ownership or publishing success. Keep frequent movement in memory until its checkpoint. | @@ -136,8 +136,13 @@ ticks running; a full writer queue defers the checkpoint to the next visit. Production startup uses these same owners. A startup regression blocks SQLite in one zone while another zone accepts movement and advances its position; shutdown persists both zones' final changes. -`world_runtime.go` owns the zone directory on a separate goroutine. Committed -teleports transfer a player's entity and item records to the destination through +`worldDirectory` owns routing, environment defaults and the mission catalog on +a separate goroutine. `worldServices` supplies shared service handles and content; +new zones receive distinct mutable maps and cloned door defaults. Lifecycle +workers receive a `worldCoordinator` containing services and account drafts, +without access to zone entities. + +Committed teleports transfer a player's entity and item records to the destination through its command channel. Reconnects wait for arrival; old connections remain bound to their source zone. A departure never waits for the destination to execute, so simultaneous opposite transfers cannot deadlock. Shutdown quiesces ticks, @@ -384,12 +389,15 @@ that happened while they were absent or outside vicinity range. World and chat sessions each have a dedicated FIFO output writer. Shared broadcast paths only enqueue owned packet bytes; they never wait for a -recipient's socket. Pending output is capped at 8 MiB per connection, plus -one packet being written. Queue overflow or a failed, short or timed-out write -disconnects that connection. Writes have a five-second deadline and run outside +recipient's socket. Writers combine already queued packets without a batching +delay and send chunks of at most 32 KiB. Pending output is capped at 8 MiB per +connection, including detached unsent bytes. Queue overflow or a failed, short +or timed-out write disconnects that connection. Writes have a five-second deadline and run outside the zone and chat owners, so a slow recipient cannot stall other players' updates. -Forced disconnects discard queued output and wake the connection's writer; -socket shutdown also runs there, so a transport close handshake cannot delay +Forced disconnects discard queued output and the rest of the detached batch +after the current write. Orderly shutdown drains accepted output. Failed world +recipients are excluded from subsequent broadcasts while departure completes. +Socket shutdown runs on the writer, so a transport close handshake cannot delay shared work or a replacement session. `chat_runtime.go` owns social state on one goroutine. World owners publish diff --git a/server/admin_pages.go b/server/admin_pages.go @@ -37,7 +37,7 @@ func (server *server) controlPage(w http.ResponseWriter, r *http.Request) { var seconds, weather, items int counts := &zoneAdminCounts{} if server.world == nil { - seconds, weather, items = int(server.currentGameSeconds()), server.weather, len(server.items) + seconds, weather, items = int(currentGameSeconds(server.gameSeconds, server.clockStarted)), server.weather, len(server.items) counts.execute(server) } else { snapshot, err := server.world.snapshot() diff --git a/server/admin_test.go b/server/admin_test.go @@ -16,7 +16,8 @@ import ( func newAdminTestServer(t *testing.T) *server { t.Helper() t.Chdir(t.TempDir()) - world := &server{baseURL: "/", characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), clockStarted: time.Now()} + world := &server{ + worldServices: worldServices{baseURL: "/"}, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), clockStarted: time.Now()} openTestDatabase(t, world) return world } diff --git a/server/admin_weather.go b/server/admin_weather.go @@ -38,7 +38,7 @@ func (state *server) setWeather(w http.ResponseWriter, r *http.Request) { http.Error(w, "Invalid weather", 400) return } - err = state.world.operate(func(configuration *server) error { + err = state.world.operate(func(coordinator *worldCoordinator) error { return state.world.publishEnvironment(zoneWeather{weather, time.Now().Add(5 * time.Minute)}) }) if err != nil { diff --git a/server/admin_weather_test.go b/server/admin_weather_test.go @@ -75,7 +75,7 @@ func TestAdminWeatherReturnsToAutomatic(t *testing.T) { } // The directory also presents an expired event as automatic weather. - if err := world.world.operate(func(*server) error { + if err := world.world.operate(func(*worldCoordinator) error { return world.world.publishEnvironment(zoneWeather{2, time.Now().Add(-time.Second)}) }); err != nil { t.Fatal(err) diff --git a/server/arrival_hall_test.go b/server/arrival_hall_test.go @@ -52,7 +52,7 @@ func arrivalHallTestWorld(t *testing.T, group string) (*server, uint32) { player.appearance = 277 player.playfield, player.position = 4604, representative.position player.position[2] += 3 - if err := world.browserStartingItems(player); err != nil { + if err := browserStartingItems(world.identityAllocator(), player); err != nil { t.Fatal(err) } player.inventory.Items = slices.DeleteFunc(player.inventory.Items, func(item ownedItem) bool { return item.Template == 116697 }) diff --git a/server/browser_account_change.go b/server/browser_account_change.go @@ -139,13 +139,13 @@ func (state *server) applyAccountIdentities(updates []accountIdentity) { } } -func (change *browserAccountChange) persist(configuration *server) error { +func (change *browserAccountChange) persist(coordinator *worldCoordinator) error { write := &browserAccountWrite{action: change.action, current: change.current, target: change.target, previous: change.previous, credential: change.credential, abandoned: change.abandoned, name: change.name, salt: change.salt, hash: change.hash} if change.created != nil { change.created.name, change.created.browserTokenHash = change.name, change.credential - if err := configuration.browserStartingItems(change.created); err != nil { + if err := browserStartingItems(coordinator.identities, change.created); err != nil { return err } if change.action == "native" { @@ -158,7 +158,7 @@ func (change *browserAccountChange) persist(configuration *server) error { created := prepareBrowserPlayerWrite(change.created, change.salt, change.hash) write.created = &created } - if err := configuration.commitWrite(write); err != nil { + if err := coordinator.commitWrite(write); err != nil { return err } change.target = write.target @@ -169,14 +169,14 @@ func (change *browserAccountChange) persist(configuration *server) error { } func (state *server) changeBrowserAccount(change *browserAccountChange) error { - return state.accountOperation(func(configuration *server) error { - return state.applyBrowserAccountChange(configuration, change) + return state.accountOperation(func(coordinator *worldCoordinator) error { + return state.applyBrowserAccountChange(coordinator, change) }) } -func (state *server) applyBrowserAccountChange(configuration *server, change *browserAccountChange) error { +func (state *server) applyBrowserAccountChange(coordinator *worldCoordinator, change *browserAccountChange) error { if state.world != nil { - if err := state.world.changeAccount(configuration, change); err != nil { + if err := state.world.changeAccount(coordinator, change); err != nil { return err } // Release the owners before replacement, but finish replacement before @@ -192,7 +192,7 @@ func (state *server) applyBrowserAccountChange(configuration *server, change *br if change.created == nil && state.characters[change.target] == nil { return errBrowserLogin } - if err := change.persist(state); err != nil { + if err := change.persist(coordinator); err != nil { return err } state.applyAccountIdentities(change.identities()) @@ -246,7 +246,7 @@ func (part *accountParticipant) execute(state *server) error { return decision.err } -func (world *worldRuntime) changeAccount(configuration *server, change *browserAccountChange) error { +func (world *worldRuntime) changeAccount(coordinator *worldCoordinator, change *browserAccountChange) error { players := []uint32{change.current} if change.created == nil && change.current != change.target { players = append(players, change.target) @@ -292,7 +292,7 @@ func (world *worldRuntime) changeAccount(configuration *server, change *browserA return err } } - err := change.persist(configuration) + err := change.persist(coordinator) decision := accountDecision{err: err} if err == nil { decision.updates = change.identities() diff --git a/server/browser_account_owner_test.go b/server/browser_account_owner_test.go @@ -220,11 +220,11 @@ func TestWorldPlayerAdmissionWaitsForCommittedCreationPublication(t *testing.T) }() finished := make(chan error, 1) go func() { - finished <- fixture.world.operate(func(configuration *server) error { + finished <- fixture.world.operate(func(coordinator *worldCoordinator) error { change := &browserAccountChange{action: "create", current: 1, previous: previous, credential: "created", abandoned: "abandoned", name: "Alice", created: created, salt: []byte{}, hash: []byte{}} - if err := change.persist(configuration); err != nil { + if err := change.persist(coordinator); err != nil { return err } close(committed) @@ -322,7 +322,7 @@ func TestBrowserAccountReplacementFinishesBeforeNextWorldOperation(t *testing.T) started := make(chan struct{}) nextDone := make(chan error, 1) fixture.world.operations <- worldOperation{ - run: func(*server) error { close(started); return nil }, + run: func(*worldCoordinator) error { close(started); return nil }, finish: func(err error) { nextDone <- err }, } owner, err := fixture.world.owner(1) diff --git a/server/browser_account_session_test.go b/server/browser_account_session_test.go @@ -42,11 +42,22 @@ func TestBrowserAccountRejectsRevokedConnectionBeforeWorldOrChatInitialization(t if err == nil || len(conn.packets) != 0 || connected { t.Fatal("revoked credential initialized a world session", err) } - conn = &combatInterestConn{input: bytes.NewReader(chatTestAuth(1))} - - err = world.serveChatClient(&chatClient{id: 1, conn: conn, browserTokenHash: credential}) - - if err == nil || readChatState(t, world).clients[1] != nil || len(conn.packets) != 1 { + chatHost, chatPeer := net.Pipe() + defer chatPeer.Close() + chatPeer.SetDeadline(time.Now().Add(3 * time.Second)) + finished := make(chan error, 1) + go func() { + finished <- world.serveChatClient(&chatClient{id: 1, conn: chatHost, browserTokenHash: credential}) + }() + if kind, _, err := readChatPacket(chatPeer); err != nil || kind != 0 { + t.Fatal("missing chat seed", kind, err) + } + if _, err := chatPeer.Write(chatTestAuth(1)); err != nil { + t.Fatal(err) + } + err = <-finished + _, _, received := readChatPacket(chatPeer) + if err == nil || readChatState(t, world).clients[1] != nil || received == nil { t.Fatal("revoked credential initialized chat after its seed", err) } } diff --git a/server/browser_client_test.go b/server/browser_client_test.go @@ -24,7 +24,8 @@ func TestBrowserClientServesPublishedWasm(t *testing.T) { request.Header.Set("Accept-Encoding", "br") response := httptest.NewRecorder() - (&server{baseURL: "/"}).browserClient(response, request) + (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient(response, request) if response.Code != http.StatusOK || response.Header().Get("Content-Type") != "application/wasm" || response.Header().Get("Content-Encoding") != "br" { t.Fatalf("WASM response: %d %v", response.Code, response.Header()) @@ -55,12 +56,14 @@ func TestBrowserClientRevalidatesUnchangedFiles(t *testing.T) { path = "/wasm/game.wasm" } first := httptest.NewRecorder() - (&server{baseURL: "/"}).browserClient(first, httptest.NewRequest("GET", path, nil)) + (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient(first, httptest.NewRequest("GET", path, nil)) request := httptest.NewRequest("GET", path, nil) request.Header.Set("If-None-Match", first.Header().Get("ETag")) response := httptest.NewRecorder() - (&server{baseURL: "/"}).browserClient(response, request) + (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient(response, request) if first.Header().Get("ETag") == "" || response.Code != http.StatusNotModified || response.Body.Len() != 0 { t.Fatalf("cache revalidation: %d %v %q", response.Code, response.Header(), response.Body.String()) @@ -83,7 +86,8 @@ func TestBrowserClientDetectsSameSecondReplacement(t *testing.T) { t.Fatal(err) } first := httptest.NewRecorder() - (&server{baseURL: "/"}).browserClient(first, httptest.NewRequest("GET", "/wasm/game.js", nil)) + (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient(first, httptest.NewRequest("GET", "/wasm/game.js", nil)) if err := os.WriteFile("client/game.js", []byte("new"), 0644); err != nil { t.Fatal(err) } @@ -95,7 +99,8 @@ func TestBrowserClientDetectsSameSecondReplacement(t *testing.T) { request.Header.Set("If-None-Match", first.Header().Get("ETag")) response := httptest.NewRecorder() - (&server{baseURL: "/"}).browserClient(response, request) + (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient(response, request) if response.Code != http.StatusOK || response.Body.String() != "new" || response.Header().Get("ETag") == first.Header().Get("ETag") { t.Fatalf("replacement response: %d %v %q", response.Code, response.Header(), response.Body.String()) @@ -114,7 +119,8 @@ func TestBrowserClientServesPublishedPageWithoutBuildDirectory(t *testing.T) { for _, path := range []string{"/", "/wasm/"} { response := httptest.NewRecorder() - (&server{baseURL: "/"}).browserClient(response, httptest.NewRequest("GET", path, nil)) + (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient(response, httptest.NewRequest("GET", path, nil)) if response.Code != http.StatusOK || response.Body.String() != "Loading client" || response.Header().Get("Cross-Origin-Opener-Policy") != "same-origin" || response.Header().Get("Cross-Origin-Embedder-Policy") != "require-corp" { t.Fatalf("client page %s: %d %q", path, response.Code, response.Body.String()) diff --git a/server/browser_creation.go b/server/browser_creation.go @@ -115,9 +115,9 @@ func startingItemTemplates(profession uint16, side uint16) []uint32 { return templates } -func (server *server) browserStartingItems(player *character) error { +func browserStartingItems(identities *worldIdentities, player *character) error { templates := startingItemTemplates(player.profession, uint16(unpackAppearance(player.appearance).Side)) - first, err := server.reserveItems(uint32(len(templates))) + first, err := reserveIdentities(&identities.items, 0, uint32(len(templates)), ^uint32(0)) if err != nil { return err } diff --git a/server/browser_launch.go b/server/browser_launch.go @@ -35,7 +35,7 @@ func (server *server) browserPlayerID(credential string) (uint32, error) { func (state *server) browserLaunch(w http.ResponseWriter, r *http.Request) { var id uint32 var token string - err := state.accountOperation(func(configuration *server) error { + err := state.accountOperation(func(coordinator *worldCoordinator) error { credential := browserCredential(r) var err error id, err = state.browserPlayerID(credential) @@ -46,13 +46,13 @@ func (state *server) browserLaunch(w http.ResponseWriter, r *http.Request) { if id == 0 { return errBrowserSessionChanged } - if configuration.browserCreations == nil { - configuration.browserCreations = make(map[string]*browserCreationCredentials) + if coordinator.browserCreations == nil { + coordinator.browserCreations = make(map[string]*browserCreationCredentials) } - configuration.browserCreations[credential] = &browserCreationCredentials{} + coordinator.browserCreations[credential] = &browserCreationCredentials{} } else if id != 0 { // Returning to the game cancels an unfinished native creator. - delete(configuration.browserCreations, credential) + delete(coordinator.browserCreations, credential) } if id != 0 { return nil @@ -76,7 +76,7 @@ func (state *server) browserLaunch(w http.ResponseWriter, r *http.Request) { player.appearance = appearance.packed() player.stats = defaultCharacterStats(appearance.Breed) player.health = player.maximumHealth() - if err := configuration.saveVisitor(player); err != nil { + if err := coordinator.saveVisitor(player); err != nil { return err } id = player.id diff --git a/server/browser_launch_test.go b/server/browser_launch_test.go @@ -37,7 +37,8 @@ func TestBrowserLaunchCreatesPersistentVisitor(t *testing.T) { if err := os.Mkdir("data", 0755); err != nil { t.Fatal(err) } - world := &server{baseURL: "/", worldPort: 7501, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement)} + world := &server{ + worldServices: worldServices{baseURL: "/", worldPort: 7501}, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement)} openTestDatabase(t, world) response := httptest.NewRecorder() @@ -101,11 +102,13 @@ func TestBrowserLaunchResumesOwnedCharacterAfterRestart(t *testing.T) { if err := os.Mkdir("data", 0755); err != nil { t.Fatal(err) } - world := &server{worldPort: 7501, characters: make(map[uint32]*character), items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement)} + world := &server{ + worldServices: worldServices{worldPort: 7501}, characters: make(map[uint32]*character), items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement)} openTestDatabase(t, world) first := httptest.NewRecorder() world.browserLaunch(first, httptest.NewRequest("POST", "/browser-launch", nil)) - loaded := &server{worldPort: 7501, characters: make(map[uint32]*character), clients: map[uint32]*worldClient{1: {}}} + loaded := &server{ + worldServices: worldServices{worldPort: 7501}, characters: make(map[uint32]*character), clients: map[uint32]*worldClient{1: {}}} openTestDatabase(t, loaded) if err := loaded.loadUsers(); err != nil { t.Fatal(err) @@ -129,7 +132,8 @@ func TestBrowserLaunchSeparatesVisitorsAndReplacesUnknownCookie(t *testing.T) { if err := os.Mkdir("data", 0755); err != nil { t.Fatal(err) } - world := &server{worldPort: 7501, characters: make(map[uint32]*character), items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement)} + world := &server{ + worldServices: worldServices{worldPort: 7501}, characters: make(map[uint32]*character), items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement)} openTestDatabase(t, world) first := httptest.NewRecorder() world.browserLaunch(first, httptest.NewRequest("POST", "/browser-launch", nil)) diff --git a/server/browser_mission_waypoint_expiry_test.go b/server/browser_mission_waypoint_expiry_test.go @@ -81,8 +81,8 @@ func TestBrowserMissionWaypointExpiry(t *testing.T) { })) for index, name := range []string{"a", "b"} { mux.HandleFunc("POST /test-expire/"+name, func(w http.ResponseWriter, r *http.Request) { - if err := world.world.operate(func(configuration *server) error { - return world.world.retireMission(configuration, missionOperation{expired: &accepted[index]}) + if err := world.world.operate(func(coordinator *worldCoordinator) error { + return world.world.retireMission(coordinator, missionOperation{expired: &accepted[index]}) }); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/server/chat.go b/server/chat.go @@ -61,7 +61,7 @@ func (client *chatClient) send(packet []byte) error { } func (client *chatClient) send_locked(packet []byte) error { - return client.enqueue_locked(client.conn, append([]byte(nil), packet...)) + return client.enqueue_locked(client.conn, packet) } func chatNamePacket(id uint32, name string) []byte { diff --git a/server/city_doors_test.go b/server/city_doors_test.go @@ -9,8 +9,8 @@ import ( func cityDoorWorld() (*server, []*combatTestConn) { world := &server{ - zoneLinks: map[string]map[uint32]zoneLinks{"target": {705: {Doors: []zoneDoor{{ID: 0xc01102c1, Position: [3]float32{10, 2, 20}}}}}}, - cityDoors: map[doorOrigin]bool{{705, 0xc01102c1}: false}, + worldServices: worldServices{zoneLinks: map[string]map[uint32]zoneLinks{"target": {705: {Doors: []zoneDoor{{ID: 0xc01102c1, Position: [3]float32{10, 2, 20}}}}}}, cityDoors: map[doorOrigin]bool{{705, 0xc01102c1}: false}}, + characters: map[uint32]*character{}, clients: map[uint32]*worldClient{}, } var outputs []*combatTestConn diff --git a/server/client_output.go b/server/client_output.go @@ -10,12 +10,13 @@ import ( ) type clientOutput struct { - mutex sync.Mutex - outgoing [][]byte - outgoingBytes int - writeWake chan struct{} - writeDone chan struct{} - writeClosed bool + mutex sync.Mutex + outgoing []byte + pendingBytes int + writeWake chan struct{} + writeDone chan struct{} + writeClosed bool + writeDiscarded bool } func (client *clientOutput) startWriter(conn net.Conn) { @@ -50,8 +51,9 @@ func (client *clientOutput) disconnect(conn net.Conn) { func (client *clientOutput) discard_locked() { // The writer owns socket shutdown, including any transport close handshake. client.writeClosed = true + client.writeDiscarded = true client.outgoing = nil - client.outgoingBytes = 0 + client.pendingBytes = 0 select { case client.writeWake <- struct{}{}: default: @@ -70,7 +72,7 @@ func writeClientPacket(conn net.Conn, packet []byte) error { } func (client *clientOutput) enqueue_locked(conn net.Conn, packet []byte) error { - // The caller holds mutex and transfers ownership of the packet bytes. + // The caller holds mutex; the queue copies the packet before returning. // Standalone protocol fixtures have no writer; live sessions start one first. if client.writeWake == nil { return writeClientPacket(conn, packet) @@ -78,13 +80,13 @@ func (client *clientOutput) enqueue_locked(conn net.Conn, packet []byte) error { if client.writeClosed { return net.ErrClosed } - // Bound queued bytes just as the browser transport bounds retained output. - if client.outgoingBytes+len(packet) > 8*1024*1024 { + // Include the detached batch so a slow transport cannot double the limit. + if client.pendingBytes+len(packet) > 8*1024*1024 { client.discard_locked() return fmt.Errorf("client output queue full") } - client.outgoing = append(client.outgoing, packet) - client.outgoingBytes += len(packet) + client.outgoing = append(client.outgoing, packet...) + client.pendingBytes += len(packet) select { case client.writeWake <- struct{}{}: default: @@ -97,13 +99,15 @@ func (client *clientOutput) writePackets(conn net.Conn) { client.mutex.Lock() client.writeClosed = true client.outgoing = nil - client.outgoingBytes = 0 + client.pendingBytes = 0 client.mutex.Unlock() conn.Close() close(client.writeDone) }() - // One writer preserves packet order without holding shared server locks on I/O. + // Swap buffers so producers can enqueue while the writer sends a batch. Reuse + // small buffers, but release large admission snapshots after they are sent. + var buffer []byte for range client.writeWake { for { client.mutex.Lock() @@ -115,14 +119,28 @@ func (client *clientOutput) writePackets(conn net.Conn) { } break } - packet := client.outgoing[0] - client.outgoing[0] = nil - client.outgoing = client.outgoing[1:] - client.outgoingBytes -= len(packet) + buffer, client.outgoing = client.outgoing, buffer[:0] client.mutex.Unlock() - if err := writeClientPacket(conn, packet); err != nil { - log.Printf("Client output: %v", err) - return + for offset := 0; offset < len(buffer); offset += 32768 { + client.mutex.Lock() + discarded := client.writeDiscarded + client.mutex.Unlock() + if discarded { + return + } + end := min(offset+32768, len(buffer)) + if err := writeClientPacket(conn, buffer[offset:end]); err != nil { + log.Printf("Client output: %v", err) + return + } + client.mutex.Lock() + if !client.writeDiscarded { + client.pendingBytes -= end - offset + } + client.mutex.Unlock() + } + if cap(buffer) > 8192 { + buffer = nil } } } diff --git a/server/combat.go b/server/combat.go @@ -660,7 +660,10 @@ func (server *server) sendCombatUpdates(updates map[*worldClient][][]byte) { for client, packets := range updates { for _, packet := range packets { if err := client.send(packet); err != nil { - log.Printf("Combat: %v", err) + if client.ready { + log.Printf("Combat: %v", err) + } + client.ready = false client.disconnect(client.conn) break } diff --git a/server/combat_interest_test.go b/server/combat_interest_test.go @@ -18,10 +18,14 @@ func (conn *combatInterestConn) Read(buffer []byte) (int, error) { } func (conn *combatInterestConn) Write(packet []byte) (int, error) { + previous := len(conn.packets) + count, err := conn.combatTestConn.Write(packet) if conn.onWrite != nil { - conn.onWrite(packet) + for _, complete := range conn.packets[previous:] { + conn.onWrite(complete) + } } - return conn.combatTestConn.Write(packet) + return count, err } func (conn *combatInterestConn) Close() error { diff --git a/server/combat_test.go b/server/combat_test.go @@ -13,6 +13,7 @@ import ( type combatTestConn struct { net.Conn packets [][]byte + pending []byte } func (conn *combatTestConn) RemoteAddr() net.Addr { @@ -22,7 +23,19 @@ func (conn *combatTestConn) RemoteAddr() net.Addr { func (conn *combatTestConn) SetWriteDeadline(time.Time) error { return nil } func (conn *combatTestConn) Write(packet []byte) (int, error) { - conn.packets = append(conn.packets, append([]byte(nil), packet...)) + // TCP writes may contain multiple packets or part of one packet. + conn.pending = append(conn.pending, packet...) + for len(conn.pending) >= 16 { + length := (int(binary.BigEndian.Uint16(conn.pending[6:8])) + 3) &^ 3 + if length < 20 { + return 0, fmt.Errorf("invalid test world packet length %d", length) + } + if len(conn.pending) < length { + break + } + conn.packets = append(conn.packets, append([]byte(nil), conn.pending[:length]...)) + conn.pending = conn.pending[length:] + } return len(packet), nil } @@ -38,6 +51,7 @@ func newCombatWorld(t *testing.T) (*server, *combatTestConn) { t.Chdir(t.TempDir()) conn := &combatTestConn{} world := &server{ + worldServices: worldServices{combatRoll: landedCombatRoll}, characters: map[uint32]*character{ 1: {id: 1, playfield: 950, health: 100, stats: testCharacterStats()}, 1000000: {id: 1000000, playfield: 950, position: [3]float32{1, 0, 0}, appearance: 229, npc: true, health: 100, stats: testCharacterStats()}, @@ -45,8 +59,7 @@ func newCombatWorld(t *testing.T) (*server, *combatTestConn) { clients: map[uint32]*worldClient{ 1: {id: 1, conn: conn, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}, }, - fighting: make(map[uint32]*character), - combatRoll: landedCombatRoll, + fighting: make(map[uint32]*character), } openTestDatabase(t, world) diff --git a/server/control.go b/server/control.go @@ -166,10 +166,10 @@ func (state *server) setGameTime(w http.ResponseWriter, r *http.Request) { return } - err := state.world.operate(func(configuration *server) error { + err := state.world.operate(func(coordinator *worldCoordinator) error { change := zoneGameTime{float64(hour*3600 + minute*60), time.Now()} write := recordUpdate{"world", "game_seconds, clock_started", 1, []any{change.seconds, change.started.UTC().Format(time.RFC3339Nano)}} - if err := configuration.commitWrite(write); err != nil { + if err := coordinator.commitWrite(write); err != nil { return err } return state.world.publishEnvironment(change) diff --git a/server/control_data_test.go b/server/control_data_test.go @@ -15,7 +15,8 @@ import ( ) func TestControlItemCatalogPaginatesAndFilters(t *testing.T) { - world := &server{baseURL: "/share/test/"} + world := &server{ + worldServices: worldServices{baseURL: "/share/test/"}} handler := adminTestHandler(world) first, second, filtered := httptest.NewRecorder(), httptest.NewRecorder(), httptest.NewRecorder() @@ -46,7 +47,8 @@ func TestControlItemCatalogPaginatesAndFilters(t *testing.T) { } func TestControlInstancesPaginateFilteredResults(t *testing.T) { - world := &server{baseURL: "/", items: make(map[uint32]itemRecord)} + world := &server{ + worldServices: worldServices{baseURL: "/"}, items: make(map[uint32]itemRecord)} for id := uint32(1); id <= 1001; id++ { world.items[id] = itemRecord{Type: 51018, Template: 121567, Quality: 1, Count: 1} } @@ -254,7 +256,8 @@ func TestControlNestedSkillsAndImprovementPointsPersistAndReachClient(t *testing } func TestControlRoutesRequireAdminPrefix(t *testing.T) { - world := &server{baseURL: "/"} + world := &server{ + worldServices: worldServices{baseURL: "/"}} handler := world.httpHandler() for _, path := range []string{"users/1", "users", "items", "items/1", "time", "teleport/1", "map-players", "map-assets/manifest.json", "control-map.js"} { diff --git a/server/corpse_credits_test.go b/server/corpse_credits_test.go @@ -216,7 +216,8 @@ func TestCorpseCreditsRejectOutOfRangePersistentBalance(t *testing.T) { if _, err := saved.db.Exec(`UPDATE players SET credits=1000000001 WHERE id=1`); err != nil { t.Fatal(err) } - world := &server{db: saved.db, characters: make(map[uint32]*character)} + world := &server{ + worldServices: worldServices{db: saved.db}, characters: make(map[uint32]*character)} err := world.loadUsers() diff --git a/server/database_writer.go b/server/database_writer.go @@ -73,11 +73,11 @@ func commitDatabaseWrite(db *sql.DB, write databaseWrite) error { return tx.Commit() } -func (server *server) commitWrite(write databaseWrite) error { - if server.databaseWriter == nil { +func (services *worldServices) commitWrite(write databaseWrite) error { + if services.databaseWriter == nil { return errors.New("database writer is closed") } - return server.databaseWriter.commit(write) + return services.databaseWriter.commit(write) } func (writer *databaseWriter) commit(write databaseWrite) error { diff --git a/server/embedded_resources_test.go b/server/embedded_resources_test.go @@ -44,8 +44,10 @@ func TestEmbeddedResourceProviderMatchesExternal(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("GET /browser-assets/{path...}", browserAsset) mux.HandleFunc("GET /browser-manifest", browserManifest) - mux.HandleFunc("GET /wasm/", (&server{baseURL: "/"}).browserClient) - mux.HandleFunc("GET /{$}", (&server{baseURL: "/"}).browserClient) + mux.HandleFunc("GET /wasm/", (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient) + mux.HandleFunc("GET /{$}", (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient) for _, path := range []string{"/", "/wasm/game.js", "/wasm/game.wasm", "/browser-manifest", "/browser-assets/version.id", "/browser-assets/cd_image/data/db/ResourceDatabase.dat"} { t.Run(path, func(t *testing.T) { var responses []*httptest.ResponseRecorder diff --git a/server/http_test.go b/server/http_test.go @@ -13,7 +13,8 @@ import ( ) func TestHTTPHandlerKeepsRequestTraceOutOfConsole(t *testing.T) { - world := &server{baseURL: "/"} + world := &server{ + worldServices: worldServices{baseURL: "/"}} handler := world.httpHandler() var console, trace bytes.Buffer previousConsole, previousTrace := log.Writer(), traceLog.Writer() @@ -74,7 +75,8 @@ func TestHTTPHandlerServesOriginalFavicon(t *testing.T) { for _, baseURL := range []string{"/", "/share/demo/"} { t.Run(baseURL, func(t *testing.T) { useResources(t, assets.Files) - handler := (&server{baseURL: baseURL}).httpHandler() + handler := (&server{ + worldServices: worldServices{baseURL: baseURL}}).httpHandler() response := httptest.NewRecorder() handler.ServeHTTP(response, httptest.NewRequest("GET", baseURL+"favicon.ico", nil)) @@ -123,7 +125,8 @@ func TestHTTPHandlerScopesVisitorCookieAndRedirects(t *testing.T) { } func TestHTTPHandlerPreservesBaseURLInDirectoryRedirects(t *testing.T) { - world := &server{baseURL: "/share/demo/"} + world := &server{ + worldServices: worldServices{baseURL: "/share/demo/"}} handler := adminTestHandler(world) for _, redirect := range []struct{ from, to string }{ {"/share/demo/wasm?profile=1", "/share/demo/wasm/?profile=1"}, @@ -141,7 +144,8 @@ func TestHTTPHandlerPreservesBaseURLInDirectoryRedirects(t *testing.T) { func TestHTTPHandlerReturnsNotFoundForUnknownPaths(t *testing.T) { for _, baseURL := range []string{"/", "/share/demo/"} { t.Run(baseURL, func(t *testing.T) { - world := &server{baseURL: baseURL} + world := &server{ + worldServices: worldServices{baseURL: baseURL}} handler := world.httpHandler() response := httptest.NewRecorder() diff --git a/server/identities_test.go b/server/identities_test.go @@ -21,10 +21,12 @@ func (grant *zoneItemGrant) execute(state *server) error { func TestZoneItemGrantsAllocateDistinctDurableIdentities(t *testing.T) { world, _ := newInventoryWriteWorld(t) identities := world.identityAllocator() - first := &server{db: world.db, databaseWriter: world.databaseWriter, identities: identities, nextItem: world.nextItem, + first := &server{ + worldServices: worldServices{db: world.db, databaseWriter: world.databaseWriter, identities: identities}, nextItem: world.nextItem, characters: map[uint32]*character{1: world.characters[1]}, items: map[uint32]itemRecord{1: world.items[1]}, itemPlacements: map[uint32]itemPlacement{1: world.itemPlacements[1]}} - second := &server{db: world.db, databaseWriter: world.databaseWriter, identities: identities, nextItem: world.nextItem, + second := &server{ + worldServices: worldServices{db: world.db, databaseWriter: world.databaseWriter, identities: identities}, nextItem: world.nextItem, characters: map[uint32]*character{2: world.characters[2]}} delete(world.characters, 1) delete(world.characters, 2) diff --git a/server/inventory_test.go b/server/inventory_test.go @@ -173,7 +173,8 @@ func TestInventoryNativeMoveDeleteAndRestart(t *testing.T) { func newTestInventoryServer(t *testing.T) *server { t.Helper() - world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), combatRoll: landedCombatRoll} + world := &server{ + worldServices: worldServices{combatRoll: landedCombatRoll}, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character)} openTestDatabase(t, world) var err error world.worldResources, err = readWorldResources() diff --git a/server/item_catalog_test.go b/server/item_catalog_test.go @@ -9,9 +9,10 @@ import ( ) func TestControlItemCatalogDecodesBrontoMeat(t *testing.T) { - world := &server{baseURL: "/", items: map[uint32]itemRecord{ - 1: {Type: 51005, Template: 165275, Quality: 1, Count: 1}, - }} + world := &server{ + worldServices: worldServices{baseURL: "/"}, items: map[uint32]itemRecord{ + 1: {Type: 51005, Template: 165275, Quality: 1, Count: 1}, + }} t.Chdir(t.TempDir()) openTestDatabase(t, world) for id, item := range world.items { @@ -43,9 +44,10 @@ func TestControlItemCatalogDecodesBrontoMeat(t *testing.T) { } func TestControlItemCatalogUsesInstanceQuality(t *testing.T) { - world := &server{baseURL: "/", items: map[uint32]itemRecord{ - 1: {Type: 51022, Template: 85596, Quality: 5, Count: 1}, - }} + world := &server{ + worldServices: worldServices{baseURL: "/"}, items: map[uint32]itemRecord{ + 1: {Type: 51022, Template: 85596, Quality: 5, Count: 1}, + }} t.Chdir(t.TempDir()) openTestDatabase(t, world) for id, item := range world.items { @@ -75,9 +77,10 @@ func TestControlItemCatalogPreservesUnknownFieldsAndEscapesSource(t *testing.T) definition.Stats = append(definition.Stats, [2]uint32{99999, 4294967295}) gamedata.ItemTemplates[definition.ID] = &definition t.Cleanup(func() { delete(gamedata.ItemTemplates, definition.ID) }) - world := &server{baseURL: "/", items: map[uint32]itemRecord{ - 1: {Type: 51005, Template: definition.ID, Quality: 1, Count: 1}, - }} + world := &server{ + worldServices: worldServices{baseURL: "/"}, items: map[uint32]itemRecord{ + 1: {Type: 51005, Template: definition.ID, Quality: 1, Count: 1}, + }} t.Chdir(t.TempDir()) openTestDatabase(t, world) for id, item := range world.items { diff --git a/server/item_owner.go b/server/item_owner.go @@ -75,10 +75,10 @@ func (state *server) serveItemHTTP(w http.ResponseWriter, r *http.Request) { func (state *server) editOwnedItem(owner itemOwner, id uint32, r *http.Request, response *zoneHTTPResponse) error { if owner.entity == 0 && owner.mission == 0 && owner.resource == 0 { - return state.world.operate(func(configuration *server) error { + return state.world.operate(func(coordinator *worldCoordinator) error { // Unassigned bags and their children form one durable ownership unit. // The draft is private to this operation and is discarded afterward. - draft := configuration.emptyZone() + draft := coordinator.newZone(worldEnvironment{}) imported, err := draft.importItems([]uint32{owner.root}) if errors.Is(err, errItemAssigned) { return errZoneOwnerChanged diff --git a/server/main_test.go b/server/main_test.go @@ -25,7 +25,8 @@ func TestTargetDimensionListUsesInstalledVersionWithoutChangingReleaseList(t *te } target := httptest.NewRecorder() release := httptest.NewRecorder() - world := &server{loginPort: 7500, httpPort: 8080} + world := &server{ + worldServices: worldServices{loginPort: 7500, httpPort: 8080}} world.dimensionList(target, httptest.NewRequest("GET", "/target/dimensions.txt", nil)) world.dimensionList(release, httptest.NewRequest("GET", "/dimensions/dimensions.txt", nil)) @@ -36,7 +37,8 @@ func TestTargetDimensionListUsesInstalledVersionWithoutChangingReleaseList(t *te } func TestDimensionListUsesConfiguredPorts(t *testing.T) { - world := &server{loginPort: 7520, httpPort: 8180} + world := &server{ + worldServices: worldServices{loginPort: 7520, httpPort: 8180}} response := httptest.NewRecorder() world.dimensionList(response, httptest.NewRequest("GET", "/dimensions/dimensions.txt", nil)) @@ -48,7 +50,8 @@ func TestDimensionListUsesConfiguredPorts(t *testing.T) { func TestLoginRedirectUsesConfiguredWorldPort(t *testing.T) { t.Chdir(t.TempDir()) - world := &server{worldPort: 7620, characters: map[uint32]*character{1: {id: 1}}} + world := &server{ + worldServices: worldServices{worldPort: 7620}, characters: map[uint32]*character{1: {id: 1}}} openTestDatabase(t, world) if err := world.saveUser(world.characters[1]); err != nil { t.Fatal(err) diff --git a/server/mission_entrance_test.go b/server/mission_entrance_test.go @@ -24,8 +24,9 @@ func newMissionEntranceWorld(t *testing.T) (*server, *combatTestConn) { func reloadMissionEntranceWorld(t *testing.T) *server { t.Helper() - world := &server{characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), - fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), geometry: missionGeometryFixture(t)} + world := &server{ + worldServices: worldServices{geometry: missionGeometryFixture(t)}, characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), + fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character)} openTestDatabase(t, world) if _, err := world.loadNPCs(); err != nil { t.Fatal(err) diff --git a/server/mission_instance_test.go b/server/mission_instance_test.go @@ -233,7 +233,8 @@ func TestMissionLoadRejectsCorruptGeneratorWithoutSubstitutingDefaults(t *testin if _, err := world.db.Exec("UPDATE missions SET layout=x'000300' WHERE id=2"); err != nil { t.Fatal(err) } - cold := &server{db: world.db, characters: map[uint32]*character{1: {id: 1}}} + cold := &server{ + worldServices: worldServices{db: world.db}, characters: map[uint32]*character{1: {id: 1}}} err := cold.loadMissions() diff --git a/server/mission_item_rewards_test.go b/server/mission_item_rewards_test.go @@ -106,7 +106,8 @@ func TestMissionItemRewardColdLoadRejectsUnsupportedSelections(t *testing.T) { if _, err := world.db.Exec("UPDATE missions SET reward_item=?, reward_quality=?", pair[0], pair[1]); err != nil { t.Fatal(err) } - cold := &server{db: world.db} + cold := &server{ + worldServices: worldServices{db: world.db}} failure := cold.loadUsers() diff --git a/server/native_creation.go b/server/native_creation.go @@ -42,7 +42,7 @@ func (state *server) prepareBrowserCreation(w http.ResponseWriter, r *http.Reque credential := browserCredential(r) var currentID uint32 var pending *browserCreationCredentials - err := state.accountOperation(func(configuration *server) error { + err := state.accountOperation(func(coordinator *worldCoordinator) error { var err error currentID, err = state.browserPlayerID(credential) if err != nil { @@ -51,7 +51,7 @@ func (state *server) prepareBrowserCreation(w http.ResponseWriter, r *http.Reque if currentID == 0 { return errBrowserSessionChanged } - pending = configuration.browserCreations[credential] + pending = coordinator.browserCreations[credential] if pending == nil { return errBrowserCreationRequired } @@ -62,7 +62,7 @@ func (state *server) prepareBrowserCreation(w http.ResponseWriter, r *http.Reque salt := make([]byte, 16) rand.Read(salt) hash := state.browserPassword(password, salt) - err = state.accountOperation(func(configuration *server) error { + err = state.accountOperation(func(coordinator *worldCoordinator) error { id, err := state.browserPlayerID(credential) if err != nil { return err @@ -70,11 +70,11 @@ func (state *server) prepareBrowserCreation(w http.ResponseWriter, r *http.Reque if id == 0 || id != currentID { return errBrowserSessionChanged } - if configuration.browserCreations[credential] != pending { + if coordinator.browserCreations[credential] != pending { return errBrowserCreationEnded } var taken bool - if err := configuration.db.QueryRow("SELECT EXISTS(SELECT 1 FROM characters WHERE id<1000000 AND name=? COLLATE NOCASE)", name).Scan(&taken); err != nil { + if err := coordinator.db.QueryRow("SELECT EXISTS(SELECT 1 FROM characters WHERE id<1000000 AND name=? COLLATE NOCASE)", name).Scan(&taken); err != nil { return err } if taken { @@ -103,7 +103,7 @@ func (state *server) browserCreate(w http.ResponseWriter, r *http.Request) { credential := browserCredential(r) var id uint32 var pending *browserCreationCredentials - err := state.accountOperation(func(configuration *server) error { + err := state.accountOperation(func(coordinator *worldCoordinator) error { var err error id, err = state.browserPlayerID(credential) if err != nil { @@ -112,7 +112,7 @@ func (state *server) browserCreate(w http.ResponseWriter, r *http.Request) { if id == 0 { return errBrowserSessionChanged } - pending = configuration.browserCreations[credential] + pending = coordinator.browserCreations[credential] if pending == nil { return errBrowserCreationRequired } @@ -166,7 +166,7 @@ func (state *server) serveNativeCreation(conn net.Conn, currentID uint32, creden response = systemPacket(0x0e, binary.BigEndian.AppendUint32(nil, 0)) case 0x55: var name string - if err := state.accountOperation(func(*server) error { name = pending.name; return nil }); err != nil { + if err := state.accountOperation(func(*worldCoordinator) error { name = pending.name; return nil }); err != nil { return err } if name == "" { @@ -261,8 +261,8 @@ func (state *server) createNativeCharacter(currentID uint32, credential string, // The coordinator owns pending credentials until commit and publication finish. var created, reason uint32 - err = state.accountOperation(func(configuration *server) error { - if configuration.browserCreations[credential] != pending || len(pending.hash) == 0 { + err = state.accountOperation(func(coordinator *worldCoordinator) error { + if coordinator.browserCreations[credential] != pending || len(pending.hash) == 0 { reason = 2 return nil } @@ -273,7 +273,7 @@ func (state *server) createNativeCharacter(currentID uint32, credential string, change := &browserAccountChange{action: "native", current: currentID, previous: credential, credential: credential, abandoned: fmt.Sprintf("%x", sha256.Sum256([]byte(rand.Text()))), name: name, salt: pending.salt, hash: pending.hash, created: player} - err := state.applyBrowserAccountChange(configuration, change) + err := state.applyBrowserAccountChange(coordinator, change) switch { case errors.Is(err, errBrowserSessionChanged): reason = 2 @@ -285,7 +285,7 @@ func (state *server) createNativeCharacter(currentID uint32, credential string, return err default: created = change.target - delete(configuration.browserCreations, credential) + delete(coordinator.browserCreations, credential) } return nil }) diff --git a/server/native_creation_owner_test.go b/server/native_creation_owner_test.go @@ -61,8 +61,8 @@ func TestNativeCreationRoutedCommitRetryAndCookieTransfer(t *testing.T) { if err := owner.call(location); err != nil || location.playfield != 4604 { t.Fatal("native creation did not arrive in Arrival Hall", location, err) } - if err := fixture.accountOperation(func(configuration *server) error { - if len(configuration.browserCreations) != 0 { + if err := fixture.accountOperation(func(coordinator *worldCoordinator) error { + if len(coordinator.browserCreations) != 0 { t.Error("completed native attempt retained credentials") } return nil diff --git a/server/native_creation_test.go b/server/native_creation_test.go @@ -163,8 +163,8 @@ func TestNativeCreationPersistsAndRedirects(t *testing.T) { repeated := nativeCreationExchange(t, connection, nativeCreationAlice(t)) redirect := nativeCreationExchange(t, connection, systemPacket(0x16, []byte{0, 0, 0, 2})) var pending int - if err := world.accountOperation(func(configuration *server) error { - pending = len(configuration.browserCreations) + if err := world.accountOperation(func(coordinator *worldCoordinator) error { + pending = len(coordinator.browserCreations) return nil }); err != nil { t.Fatal(err) diff --git a/server/npc_data_test.go b/server/npc_data_test.go @@ -92,7 +92,7 @@ func TestGuideNameKeepsUnresolvedAppearance(t *testing.T) { } for index := range spawns { if spawns[index].playfield == 1931 && spawns[index].name == "Acolyte Seleen" { - acolyte = &spawns[index] + acolyte = spawns[index] } } diff --git a/server/npc_facing_test.go b/server/npc_facing_test.go @@ -35,7 +35,7 @@ func TestFixedNPCFacingUsesOriginalDegrees(t *testing.T) { t.Fatal("fixed facing changed population count", len(spawns)) } for index := range spawns { - packet := characterPacket(&spawns[index]) + packet := characterPacket(spawns[index]) for component, value := range want[index] { wire := math.Float32frombits(binary.BigEndian.Uint32(packet[51+component*4:])) if math.Abs(float64(spawns[index].rotation[component]-value)) > 1e-6 || wire != spawns[index].rotation[component] { diff --git a/server/npc_placement.go b/server/npc_placement.go @@ -2,11 +2,10 @@ package main import "ao/server/gamedata" -func (server *server) placeFallbackNPCs(spawns []character) { +func (server *server) placeFallbackNPCs(spawns []*character) { // Collect admitted combatants without changing the catalog's source placements. byGroup := make(map[string][]*character) - for index := range spawns { - spawn := &spawns[index] + for _, spawn := range spawns { if spawn.combatProfile != nil && gamedata.NPCGroups[spawn.npcDefinitionID].PlacementStatus == "district_center_fallback" { byGroup[spawn.npcDefinitionID] = append(byGroup[spawn.npcDefinitionID], spawn) } diff --git a/server/npcs.go b/server/npcs.go @@ -66,11 +66,11 @@ func (npc *character) equipNPCOutfit() { } } -func readNPCSpawns() ([]character, error) { +func readNPCSpawns() ([]*character, error) { data := gamedata.NPCs // Expand shared batch fields into the same live character representation. - var spawns []character + var spawns []*character identity := uint32(1000000) for _, playfield := range data.Playfields { if _, exists := gamedata.Playfields[playfield.ID]; !exists { @@ -98,7 +98,7 @@ func readNPCSpawns() ([]character, error) { spawn := makeNPCSpawn(&group, level, position) spawn.id, spawn.playfield = identity, playfield.ID identity++ - spawns = append(spawns, spawn) + spawns = append(spawns, &spawn) } } } diff --git a/server/packaged_resources_test.go b/server/packaged_resources_test.go @@ -22,8 +22,10 @@ func TestPackagedResourcesServeAfterWorkingDirectoryChanges(t *testing.T) { mux.HandleFunc("GET /browser-assets/{path...}", browserAsset) mux.HandleFunc("GET /browser-manifest", browserManifest) mux.HandleFunc("GET /browser-resource-index", browserResourceIndex) - mux.HandleFunc("GET /wasm/", (&server{baseURL: "/"}).browserClient) - mux.HandleFunc("GET /{$}", (&server{baseURL: "/"}).browserClient) + mux.HandleFunc("GET /wasm/", (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient) + mux.HandleFunc("GET /{$}", (&server{ + worldServices: worldServices{baseURL: "/"}}).browserClient) mux.Handle("GET /admin/map-assets/", http.StripPrefix("/admin/map-assets/", http.FileServerFS(maps))) for _, path := range []string{"/", "/wasm/game.js", "/wasm/build.json", "/browser-manifest", "/browser-resource-index", "/admin/map-assets/manifest.json", "/browser-assets/version.id", "/browser-assets/cd_image/text/help/What%20%27s-This%20General%20Help.txt"} { diff --git a/server/state.go b/server/state.go @@ -2,11 +2,9 @@ package main import ( "ao/server/gamedata" - "database/sql" "encoding/binary" "fmt" "log" - "math" "net" "sync" "sync/atomic" @@ -112,12 +110,20 @@ func (client *worldClient) send(packet []byte) error { // Broadcasts and connection replies must not interleave on the TCP stream. client.mutex.Lock() defer client.mutex.Unlock() - packet = append([]byte(nil), packet...) if client.target && binary.BigEndian.Uint16(packet[2:4]) == 10 { - packet = targetPacket(packet) + packet = targetPacket(append([]byte(nil), packet...)) } - binary.BigEndian.PutUint32(packet[12:16], client.id) - return client.enqueue_locked(client.conn, packet) + if client.writeWake == nil { + packet = append([]byte(nil), packet...) + binary.BigEndian.PutUint32(packet[12:16], client.id) + return writeClientPacket(client.conn, packet) + } + start := len(client.outgoing) + if err := client.enqueue_locked(client.conn, packet); err != nil { + return err + } + binary.BigEndian.PutUint32(client.outgoing[start+12:start+16], client.id) + return nil } // Startup constructs the world before admitting requests. Partitioning transfers @@ -125,6 +131,7 @@ func (client *worldClient) send(packet []byte) error { // Game operations run on their owning zone; cross-zone work exchanges commands // and detached values through the directory and lifecycle coordinator. type server struct { + worldServices browserStreamsOnce sync.Once browserStreamService *browserStreamRegistry @@ -134,26 +141,15 @@ type server struct { playfield uint32 retiredMission *acceptedMission databaseQueries atomic.Uint64 - passwordHasher *passwordHasher profileWriter *profileWriter - db *sql.DB - databaseWriter *databaseWriter - teamService *teamDirectory - chatService *chatRuntime savedNPCs map[uint32]savedNPC activeNPCs map[uint32]bool itemPlacements map[uint32]itemPlacement - loginPort int - worldPort int - httpPort int - baseURL string - identities *worldIdentities nextCharacter uint32 nextNPC uint32 nextItem uint32 items map[uint32]itemRecord worldItems map[uint32]worldItem - worldResources map[uint32]worldResource depletedResources map[uint32]bool characters map[uint32]*character mobileNPCs map[uint32][]*character @@ -169,7 +165,6 @@ type server struct { missionExpiry []acceptedMission clients map[uint32]*worldClient fighting map[uint32]*character - combatRoll func(uint32) uint32 browserCreations map[string]*browserCreationCredentials weather int weatherUntil time.Time @@ -177,17 +172,12 @@ type server struct { gameSeconds float64 clockStarted time.Time lastNPCUpdate time.Time - terrain map[uint32]*terrain - geometry *sceneGeometry - zoneLinks map[string]map[uint32]zoneLinks - cityDoors map[doorOrigin]bool } func newServer() *server { server := &server{ - loginPort: 7500, worldPort: 7501, httpPort: 8080, - baseURL: "/", - gameSeconds: 48600, clockStarted: time.Now(), + worldServices: worldServices{loginPort: 7500, worldPort: 7501, httpPort: 8080, baseURL: "/"}, + gameSeconds: 48600, clockStarted: time.Now(), characters: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), clients: make(map[uint32]*worldClient), @@ -236,10 +226,10 @@ func newServer() *server { } server.placeFallbackNPCs(spawns) for _, spawn := range spawns { - server.addNPC(&spawn) + server.addNPC(spawn) server.nextNPC = max(server.nextNPC, spawn.id+1) if spawn.motion != nil { - server.mobileNPCs[spawn.playfield] = append(server.mobileNPCs[spawn.playfield], &spawn) + server.mobileNPCs[spawn.playfield] = append(server.mobileNPCs[spawn.playfield], spawn) } } } @@ -252,11 +242,6 @@ func newServer() *server { return server } -func (server *server) currentGameSeconds() float64 { - // Rubi-Ka has 27-hour days and advances 15 game seconds per real second. - return math.Mod(server.gameSeconds+time.Since(server.clockStarted).Seconds()*15, 97200) -} - func (server *server) newCharacter() *character { server.nextCharacter++ player := newPlayerCharacter(server.nextCharacter) @@ -277,8 +262,7 @@ func newPlayerCharacter(id uint32) *character { } func (server *server) broadcast(playfield, exclude uint32, packet []byte) { - // Copy the connection list before performing any network writes. - var clients []*worldClient + // The zone owns the recipients; sending only enqueues bytes for their writers. key := binary.BigEndian.Uint32(packet[20:24]) for id, client := range server.clients { if id != exclude && client.ready && server.characters[id].playfield == playfield { @@ -286,14 +270,11 @@ func (server *server) broadcast(playfield, exclude uint32, packet []byte) { if (key == 0x271b3a6b || key == 0x36510078) && binary.BigEndian.Uint32(packet[24:28]) == 50000 { delete(client.absorbedBonuses, binary.BigEndian.Uint32(packet[28:32])) } - clients = append(clients, client) - } - } - - for _, client := range clients { - if err := client.send(packet); err != nil { - log.Printf("World broadcast: %v", err) - client.disconnect(client.conn) + if err := client.send(packet); err != nil { + log.Printf("World broadcast: %v", err) + client.ready = false + client.disconnect(client.conn) + } } } } diff --git a/server/synthetic_player.go b/server/synthetic_player.go @@ -15,9 +15,9 @@ func (write *syntheticPlayerWrite) persist(tx *sql.Tx) error { func (state *server) createSyntheticPlayer() (userData, error) { var user userData - err := state.accountOperation(func(configuration *server) error { + err := state.accountOperation(func(coordinator *worldCoordinator) error { write := &syntheticPlayerWrite{} - if err := configuration.commitWrite(write); err != nil { + if err := coordinator.commitWrite(write); err != nil { return err } user = write.player.userData() diff --git a/server/visitor_names.go b/server/visitor_names.go @@ -72,14 +72,14 @@ func randomVisitorName() string { } } -func (server *server) saveVisitor(player *character) error { - if err := server.browserStartingItems(player); err != nil { +func (coordinator *worldCoordinator) saveVisitor(player *character) error { + if err := browserStartingItems(coordinator.identities, player); err != nil { return err } for { player.name = randomVisitorName() var exists bool - if err := server.db.QueryRow("SELECT EXISTS(SELECT 1 FROM characters WHERE id<1000000 AND name=? COLLATE NOCASE)", player.name).Scan(&exists); err != nil { + if err := coordinator.db.QueryRow("SELECT EXISTS(SELECT 1 FROM characters WHERE id<1000000 AND name=? COLLATE NOCASE)", player.name).Scan(&exists); err != nil { return err } if exists { @@ -87,7 +87,7 @@ func (server *server) saveVisitor(player *character) error { } // The index also protects against a competing database writer after the check. write := &allocatedPlayerWrite{player: prepareBrowserPlayerWrite(player, []byte{}, []byte{})} - err := server.commitWrite(write) + err := coordinator.commitWrite(write) var constraint sqlite3.Error if errors.As(err, &constraint) && constraint.ExtendedCode == sqlite3.ErrConstraintUnique { continue diff --git a/server/world_directory.go b/server/world_directory.go @@ -0,0 +1,252 @@ +package main + +import ( + "errors" + "fmt" + "log" + "maps" + "slices" + "time" +) + +// Only this goroutine reads or changes routing, environment defaults and the +// mission catalog. Lifecycle workers receive services and detached inputs. +type worldDirectory struct { + world *worldRuntime + services worldServices + environment worldEnvironment + coordinator *worldCoordinator + zones map[uint32]*zoneRuntime + routes map[uint32]*worldRoute + presence map[uint32]playerPresence + missions *missionCatalog + stopping chan struct{} + arrivals, quiescing int + arrived, quiesced chan struct{} + lifecycle []worldOperation + completed chan error + admissions map[uint32][]worldLookup + expiring map[uint32]bool +} + +func (directory *worldDirectory) run() { + world := directory.world + zones, routes, presence, missions := directory.zones, directory.routes, directory.presence, directory.missions + defer close(world.done) + messages := 0 + delivered := make(chan worldDelivery) + pending := make(map[uint32][]worldMessage) + directory.completed = make(chan error) + directory.admissions = make(map[uint32][]worldLookup) + expiry := time.NewTicker(time.Second) + defer expiry.Stop() + expiryTicks := expiry.C + directory.expiring = make(map[uint32]bool) + for { + if directory.stopping == nil && directory.arrivals == 0 && directory.quiescing == 0 && messages == 0 && len(directory.lifecycle) == 0 { + for _, zone := range zones { + if err := zone.stop(); err != nil { + world.stopError = errors.Join(world.stopError, err) + } + } + return + } + select { + case reply := <-world.snapshots: + weather := directory.environment.weather + if !time.Now().Before(directory.environment.weatherUntil) { + weather = 0 + } + reply <- worldSnapshot{maps.Clone(zones), currentGameSeconds(directory.environment.gameSeconds, directory.environment.clockStarted), weather} + case update := <-world.environment: + update.change.apply(&directory.environment) + update.reply <- slices.Collect(maps.Values(zones)) + case operation := <-world.operations: + directory.enqueue(operation) + case operation := <-world.missionOperations: + directory.retire(operation) + case err := <-directory.completed: + directory.finishOperation(err) + case now := <-expiryTicks: + for id, mission := range missions.byID { + if now.Before(mission.expiresAt) || directory.expiring[id] { + continue + } + route := routes[mission.owner] + if route == nil { + continue + } + operation := missionOperation{zone: route.zone, expired: cloneStoredMission(&mission)} + directory.expiring[id] = true + directory.retire(operation) + } + case query := <-world.missionParticipants: + selected := make(map[*zoneRuntime]bool) + if zone := zones[query.world]; zone != nil { + selected[zone] = true + } + for _, id := range query.entities { + if route := routes[id]; route != nil { + selected[route.zone] = true + } + } + var result []*zoneRuntime + for zone := range selected { + result = append(result, zone) + } + query.reply <- result + case query := <-world.missionLookups: + query.reply <- missions.lookup(query) + case change := <-world.missionChanges: + if change.removed { + delete(missions.byID, change.mission.id) + delete(missions.byWorld, change.mission.world) + delete(missions.byExterior[change.mission.offer.definition.Playfield], change.mission.id) + } else if _, exists := missions.byID[change.mission.id]; exists { + missions.publish(change.mission) + } + close(change.done) + case creation := <-world.missionCreations: + directory.createMission(creation) + case creation := <-world.playerCreations: + player := creation.player + route := &worldRoute{ready: make(chan struct{})} + if routes[player.id] != nil { + route.err = fmt.Errorf("player %d already has a zone owner", player.id) + close(route.ready) + creation.reply <- route + continue + } + route = directory.arrive(player, zoneNewPlayer{player}) + for _, query := range directory.admissions[player.id] { + query.reply <- route + } + delete(directory.admissions, player.id) + creation.reply <- route + case query := <-world.admissions: + if route := routes[query.player]; route != nil || len(directory.lifecycle) == 0 { + query.reply <- route + } else { + directory.admissions[query.player] = append(directory.admissions[query.player], query) + } + case lookup := <-world.lookups: + lookup.reply <- routes[lookup.player] + case query := <-world.people: + query.reply <- presence[query.id] + case update := <-world.presence: + for _, person := range update.players { + if route := routes[person.id]; route != nil && route.zone == update.zone { + presence[person.id] = person + } + } + close(update.done) + case ownership := <-world.ownership: + if ownership.zone == nil { + delete(routes, ownership.id) + delete(presence, ownership.id) + } else { + ready := make(chan struct{}) + close(ready) + routes[ownership.id] = &worldRoute{zone: ownership.zone, ready: ready} + } + close(ownership.done) + case message := <-world.messages: + messages++ + pending[message.entity] = append(pending[message.entity], message) + if len(pending[message.entity]) == 1 { + go func() { delivered <- worldDelivery{message.entity, world.deliver(message)} }() + } + close(message.accepted) + case result := <-delivered: + messages-- + if result.err != nil { + log.Printf("Cross-zone message for %d: %v", result.entity, result.err) + } + pending[result.entity][0] = worldMessage{} + pending[result.entity] = pending[result.entity][1:] + if len(pending[result.entity]) == 0 { + delete(pending, result.entity) + } else { + message := pending[result.entity][0] + go func() { delivered <- worldDelivery{message.entity, world.deliver(message)} }() + } + case transfer := <-world.transfers: + player := transfer.arrival.player + previous := routes[player.id] + if previous == nil || previous.zone != transfer.source { + transfer.reply <- fmt.Errorf("character %d transfer has a stale source owner", player.id) + continue + } + person := presence[player.id] + person.combat = false + presence[player.id] = person + directory.arrive(player, transfer.arrival) + transfer.reply <- nil + case <-directory.stopping: + directory.stopping = nil + expiry.Stop() + expiryTicks = nil + // Finish active departures while all destinations can still receive. + for _, zone := range zones { + directory.quiescing++ + go func() { zone.quiesce(); directory.quiesced <- struct{}{} }() + } + case <-directory.quiesced: + directory.quiescing-- + case <-directory.arrived: + directory.arrivals-- + } + } +} + +func (directory *worldDirectory) arrive(player *character, command zoneCommand) *worldRoute { + zone := directory.zones[player.playfield] + if zone == nil { + state := directory.services.newZone(directory.environment) + state.world, state.playfield = directory.world, player.playfield + zone = newZoneRuntime(state) + directory.zones[player.playfield] = zone + if directory.stopping == nil { + directory.quiescing++ + go func() { zone.quiesce(); directory.quiesced <- struct{}{} }() + } + } + route := &worldRoute{zone: zone, ready: make(chan struct{})} + directory.routes[player.id] = route + // A destination may be busy. Never wait for it on the routing goroutine. + directory.arrivals++ + go func() { + route.err = zone.call(command) + close(route.ready) + directory.arrived <- struct{}{} + }() + return route +} + +func (directory *worldDirectory) createMission(creation missionCreation) { + if directory.zones[creation.mission.world] != nil { + creation.reply <- fmt.Errorf("mission %d already has a zone owner", creation.mission.id) + return + } + state := creation.state + state.gameSeconds, state.clockStarted = directory.environment.gameSeconds, directory.environment.clockStarted + state.weather, state.weatherUntil = directory.environment.weather, directory.environment.weatherUntil + state.world = directory.world + var identities []uint32 + for id := range state.characters { + identities = append(identities, id) + } + zone := newZoneRuntime(state) + directory.zones[creation.mission.world] = zone + directory.missions.publish(creation.mission) + ready := make(chan struct{}) + close(ready) + for _, id := range identities { + directory.routes[id] = &worldRoute{zone: zone, ready: ready} + } + if directory.stopping == nil { + directory.quiescing++ + go func() { zone.quiesce(); directory.quiesced <- struct{}{} }() + } + creation.reply <- nil +} diff --git a/server/world_environment.go b/server/world_environment.go @@ -1,10 +1,25 @@ package main -import "time" +import ( + "math" + "time" +) + +type worldEnvironment struct { + gameSeconds float64 + clockStarted time.Time + weather int + weatherUntil time.Time +} + +func currentGameSeconds(seconds float64, started time.Time) float64 { + // Rubi-Ka has 27-hour days and advances 15 game seconds per real second. + return math.Mod(seconds+time.Since(started).Seconds()*15, 97200) +} type environmentChange interface { zoneCommand - apply(*server) + apply(*worldEnvironment) } type worldEnvironmentUpdate struct { @@ -31,12 +46,12 @@ type zoneGameTime struct { started time.Time } -func (change zoneGameTime) apply(state *server) { +func (change zoneGameTime) apply(state *worldEnvironment) { state.gameSeconds, state.clockStarted = change.seconds, change.started } func (change zoneGameTime) execute(state *server) error { - change.apply(state) + state.gameSeconds, state.clockStarted = change.seconds, change.started updates := make(map[*worldClient][][]byte) for _, client := range state.clients { if client.ready { @@ -52,12 +67,12 @@ type zoneWeather struct { until time.Time } -func (change zoneWeather) apply(state *server) { - state.weather, state.weatherUntil, state.nextWeather = change.weather, change.until, time.Time{} +func (change zoneWeather) apply(state *worldEnvironment) { + state.weather, state.weatherUntil = change.weather, change.until } func (change zoneWeather) execute(state *server) error { - change.apply(state) + state.weather, state.weatherUntil, state.nextWeather = change.weather, change.until, time.Time{} updates := make(map[*worldClient][][]byte) state.weatherUpdates(time.Now(), updates) state.sendCombatUpdates(updates) diff --git a/server/world_mission_retirement.go b/server/world_mission_retirement.go @@ -152,7 +152,7 @@ func missionCredentialOwners(db *sql.DB, mission uint32) ([]uint32, error) { return owners, rows.Err() } -func (world *worldRuntime) retireMission(configuration *server, operation missionOperation) error { +func (world *worldRuntime) retireMission(coordinator *worldCoordinator, operation missionOperation) error { if operation.expired != nil { missions := world.queryMissions(missionLookup{id: operation.expired.id}) if len(missions) == 0 { @@ -182,7 +182,7 @@ func (world *worldRuntime) retireMission(configuration *server, operation missio var err error for { var owners []uint32 - owners, err = missionCredentialOwners(configuration.db, input.mission.id) + owners, err = missionCredentialOwners(coordinator.db, input.mission.id) if err != nil { break } @@ -213,7 +213,7 @@ func (world *worldRuntime) retireMission(configuration *server, operation missio } var removed map[uint32]bool if err == nil { - removed, err = missionCredentials(configuration.db, input.mission) + removed, err = missionCredentials(coordinator.db, input.mission) } if err != nil { for _, part := range participants { @@ -239,7 +239,7 @@ func (world *worldRuntime) retireMission(configuration *server, operation missio batch = append(batch, write) } batch = append(batch, writes[0]) - err = configuration.databaseWriter.commit(batch) + err = coordinator.databaseWriter.commit(batch) } for _, part := range participants { part.decision <- err diff --git a/server/world_operations.go b/server/world_operations.go @@ -2,14 +2,20 @@ package main import "net" +// Lifecycle operations own account drafts, but never borrow a zone's entities. +type worldCoordinator struct { + worldServices + browserCreations map[string]*browserCreationCredentials +} + // Operations that hold multiple zone owners share one coordinator queue. The // directory continues routing while the active operation waits for zones or SQL. type worldOperation struct { - run func(*server) error + run func(*worldCoordinator) error finish func(error) } -func (world *worldRuntime) operate(run func(*server) error) error { +func (world *worldRuntime) operate(run func(*worldCoordinator) error) error { done := make(chan error, 1) operation := worldOperation{run: run, finish: func(err error) { done <- err }} select { @@ -22,11 +28,14 @@ func (world *worldRuntime) operate(run func(*server) error) error { // The coordinator owns account drafts and pending native creation credentials. // Its callbacks finish before the next account or mission lifecycle operation. -func (state *server) accountOperation(run func(*server) error) error { +func (state *server) accountOperation(run func(*worldCoordinator) error) error { if state.world != nil { return state.world.operate(run) } - return run(state) + coordinator := &worldCoordinator{worldServices: state.services(), browserCreations: state.browserCreations} + err := run(coordinator) + state.browserCreations = coordinator.browserCreations + return err } type playerCreation struct { @@ -53,3 +62,45 @@ func (world *worldRuntime) createPlayer(player *character) error { <-route.ready return route.err } + +// The directory starts one lifecycle worker at a time while continuing to route +// messages. Completion callbacks run here before the next operation can start. +func (directory *worldDirectory) enqueue(operation worldOperation) { + directory.lifecycle = append(directory.lifecycle, operation) + if len(directory.lifecycle) == 1 { + go func() { directory.completed <- operation.run(directory.coordinator) }() + } +} + +func (directory *worldDirectory) retire(operation missionOperation) { + directory.enqueue(worldOperation{ + run: func(coordinator *worldCoordinator) error { + return directory.world.retireMission(coordinator, operation) + }, + finish: func(err error) { + finishMissionOperation(operation, err) + if operation.expired != nil { + delete(directory.expiring, operation.expired.id) + } + }, + }) +} + +func (directory *worldDirectory) finishOperation(err error) { + directory.lifecycle[0].finish(err) + directory.lifecycle[0] = worldOperation{} + directory.lifecycle = directory.lifecycle[1:] + // Authentication can observe a committed account just before its + // new player is published. Admissions join that publication, then + // any remaining unknown identities are rejected at operation end. + for id, waiting := range directory.admissions { + for _, query := range waiting { + query.reply <- directory.routes[id] + } + } + clear(directory.admissions) + if len(directory.lifecycle) != 0 { + operation := directory.lifecycle[0] + go func() { directory.completed <- operation.run(directory.coordinator) }() + } +} diff --git a/server/world_output_test.go b/server/world_output_test.go @@ -4,9 +4,11 @@ import ( "bytes" "encoding/binary" "errors" + "io" "net" "slices" "sync" + "sync/atomic" "testing" "time" ) @@ -22,6 +24,99 @@ type blockingCloseConn struct { release chan struct{} } +type countingWorldConn struct { + stalledCombatConn + writes atomic.Int32 +} + +func (conn *countingWorldConn) Write(packet []byte) (int, error) { + conn.writes.Add(1) + return conn.stalledCombatConn.Write(packet) +} + +func TestWorldOutputBatchesQueuedPacketsWithoutWaiting(t *testing.T) { + host, peer := net.Pipe() + peer.SetReadDeadline(time.Now().Add(time.Second)) + conn := &countingWorldConn{stalledCombatConn: stalledCombatConn{Conn: host, started: make(chan struct{})}} + client := &worldClient{conn: conn, id: 7} + client.startWriter(conn) + t.Cleanup(func() { peer.Close(); client.finishWriter() }) + + if err := client.send(systemPacket(0, []byte{0})); err != nil { + t.Fatal(err) + } + <-conn.started + for _, value := range []byte{1, 2} { + if err := client.send(systemPacket(0, []byte{value})); err != nil { + t.Fatal(err) + } + } + for _, value := range []byte{0, 1, 2} { + packet, err := readPacket(peer) + if err != nil || packet[len(packet)-1] != value { + t.Fatalf("packet %d: %x, %v", value, packet, err) + } + } + client.finishWriter() + if conn.writes.Load() != 2 { + t.Fatalf("queued packets used %d transport writes, want 2", conn.writes.Load()) + } +} + +func TestWorldBroadcastRetiresFailedRecipientAndPreservesDeparture(t *testing.T) { + world, observer := newCombatWorld(t) + failed := &failingCombatConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + client := &worldClient{id: 2, conn: failed, ready: true} + world.clients[2] = client + packet := stopFightPacket(1) + + world.broadcast(950, 0, packet) + if client.ready || !failed.closed { + t.Fatal("failed recipient remained eligible for broadcasts") + } + // A later broadcast must not attempt another close on the failed connection. + failed.closed = false + world.broadcast(950, 0, packet) + if failed.closed || len(observer.packets) != 2 { + t.Fatal("broadcast retried the failed recipient or skipped the healthy peer") + } + trade := &playerTrade{clients: [2]*worldClient{world.clients[1], client}} + world.clients[1].trade, client.trade = trade, trade + world.leaveWorldClient(client) + if world.clients[1].trade != nil || client.trade != nil { + t.Fatal("failed recipient left its peer in a trade") + } + if world.clients[2] != nil || len(observer.packets) != 4 || binary.BigEndian.Uint32(observer.packets[3][16:20]) != 0x36510078 { + t.Fatal("failed recipient did not complete normal departure") + } +} + +func TestWorldOutputDisconnectDiscardsRemainderOfDetachedBatch(t *testing.T) { + host, peer := net.Pipe() + peer.SetReadDeadline(time.Now().Add(time.Second)) + conn := &countingWorldConn{stalledCombatConn: stalledCombatConn{Conn: host, started: make(chan struct{})}} + client := &worldClient{conn: conn, id: 7} + client.startWriter(conn) + t.Cleanup(func() { peer.Close(); client.finishWriter() }) + + if err := client.send(systemPacket(0, make([]byte, 60000))); err != nil { + t.Fatal(err) + } + <-conn.started + client.disconnect(conn) + if _, err := io.ReadFull(peer, make([]byte, 32768)); err != nil { + t.Fatal(err) + } + if _, err := peer.Read(make([]byte, 1)); err != io.EOF { + t.Fatalf("discarded batch continued after the in-flight write: %v", err) + } + client.finishWriter() + if conn.writes.Load() != 1 { + t.Fatalf("discarded output used %d transport writes, want 1", conn.writes.Load()) + } +} + func (conn *blockingCloseConn) Close() error { close(conn.started) <-conn.release @@ -202,8 +297,8 @@ func TestWorldOutputRejectsQueueOverflowAndReleasesPendingBytes(t *testing.T) { t.Fatal("queue overflow did not close the blocked writer") } - if sendErr == nil || !errors.Is(client.send(packet), net.ErrClosed) || len(client.outgoing) != 0 || client.outgoingBytes != 0 { - t.Fatalf("overflow left an open queue: err=%v bytes=%d", sendErr, client.outgoingBytes) + if sendErr == nil || !errors.Is(client.send(packet), net.ErrClosed) || len(client.outgoing) != 0 { + t.Fatalf("overflow left an open queue: err=%v bytes=%d", sendErr, len(client.outgoing)) } } @@ -242,7 +337,7 @@ func TestWorldOutputUnresponsivePeerIsDisconnected(t *testing.T) { t.Fatal("unresponsive peer outlived its write deadline") } - if !errors.Is(client.send(systemPacket(0, nil)), net.ErrClosed) || client.outgoingBytes != 0 { + if !errors.Is(client.send(systemPacket(0, nil)), net.ErrClosed) || len(client.outgoing) != 0 { t.Fatal("timed out output remained usable") } } diff --git a/server/world_runtime.go b/server/world_runtime.go @@ -1,13 +1,9 @@ package main import ( - "errors" "fmt" - "log" - "maps" "net" "slices" - "time" ) // The directory owns routing and detached metadata. Entity state belongs to a @@ -97,10 +93,10 @@ func newWorldRuntime(configuration *server, states map[uint32]*server) (*worldRu if configuration.teamService == nil { configuration.teamService = newTeamDirectory(configuration.databaseWriter, teams) } - creations := configuration.browserCreations + services := configuration.services() + coordinator := &worldCoordinator{worldServices: services, browserCreations: configuration.browserCreations} configuration.browserCreations = nil - configuration = configuration.emptyZone() - configuration.browserCreations = creations + environment := worldEnvironment{configuration.gameSeconds, configuration.clockStarted, configuration.weather, configuration.weatherUntil} zones := make(map[uint32]*zoneRuntime) for playfield, state := range states { state.world, state.playfield, state.identities = world, playfield, configuration.identities @@ -113,276 +109,13 @@ func newWorldRuntime(configuration *server, states map[uint32]*server) (*worldRu for player, playfield := range owners { routes[player] = &worldRoute{zone: zones[playfield], ready: ready} } - go world.run(configuration, zones, routes, presence, missions) + directory := &worldDirectory{world: world, services: services, environment: environment, coordinator: coordinator, + zones: zones, routes: routes, presence: presence, missions: missions, stopping: world.stopping, + arrived: make(chan struct{}), quiesced: make(chan struct{})} + go directory.run() return world, nil } -func (world *worldRuntime) run(configuration *server, zones map[uint32]*zoneRuntime, routes map[uint32]*worldRoute, presence map[uint32]playerPresence, missions *missionCatalog) { - defer close(world.done) - arrivals, quiescing, messages := 0, 0, 0 - arrived, quiesced := make(chan struct{}), make(chan struct{}) - delivered := make(chan worldDelivery) - pending := make(map[uint32][]worldMessage) - stopping := world.stopping - var lifecycle []worldOperation - completed := make(chan error) - admissions := make(map[uint32][]worldLookup) - expiry := time.NewTicker(time.Second) - defer expiry.Stop() - expiryTicks := expiry.C - expiring := make(map[uint32]bool) - startOperation := func(operation worldOperation) { - go func() { completed <- operation.run(configuration) }() - } - enqueue := func(operation worldOperation) { - lifecycle = append(lifecycle, operation) - if len(lifecycle) == 1 { - startOperation(operation) - } - } - retire := func(operation missionOperation) { - enqueue(worldOperation{ - run: func(configuration *server) error { return world.retireMission(configuration, operation) }, - finish: func(err error) { - finishMissionOperation(operation, err) - if operation.expired != nil { - delete(expiring, operation.expired.id) - } - }, - }) - } - for { - if stopping == nil && arrivals == 0 && quiescing == 0 && messages == 0 && len(lifecycle) == 0 { - for _, zone := range zones { - if err := zone.stop(); err != nil { - world.stopError = errors.Join(world.stopError, err) - } - } - return - } - select { - case reply := <-world.snapshots: - weather := configuration.weather - if !time.Now().Before(configuration.weatherUntil) { - weather = 0 - } - reply <- worldSnapshot{maps.Clone(zones), configuration.currentGameSeconds(), weather} - case update := <-world.environment: - update.change.apply(configuration) - update.reply <- slices.Collect(maps.Values(zones)) - case operation := <-world.operations: - enqueue(operation) - case operation := <-world.missionOperations: - retire(operation) - case err := <-completed: - lifecycle[0].finish(err) - lifecycle[0] = worldOperation{} - lifecycle = lifecycle[1:] - // Authentication can observe a committed account just before its - // new player is published. Admissions join that publication, then - // any remaining unknown identities are rejected at operation end. - for id, waiting := range admissions { - for _, query := range waiting { - query.reply <- routes[id] - } - } - clear(admissions) - if len(lifecycle) != 0 { - startOperation(lifecycle[0]) - } - case now := <-expiryTicks: - for id, mission := range missions.byID { - if now.Before(mission.expiresAt) || expiring[id] { - continue - } - route := routes[mission.owner] - if route == nil { - continue - } - operation := missionOperation{zone: route.zone, expired: cloneStoredMission(&mission)} - expiring[id] = true - retire(operation) - } - case query := <-world.missionParticipants: - selected := make(map[*zoneRuntime]bool) - if zone := zones[query.world]; zone != nil { - selected[zone] = true - } - for _, id := range query.entities { - if route := routes[id]; route != nil { - selected[route.zone] = true - } - } - var result []*zoneRuntime - for zone := range selected { - result = append(result, zone) - } - query.reply <- result - case query := <-world.missionLookups: - query.reply <- missions.lookup(query) - case change := <-world.missionChanges: - if change.removed { - delete(missions.byID, change.mission.id) - delete(missions.byWorld, change.mission.world) - delete(missions.byExterior[change.mission.offer.definition.Playfield], change.mission.id) - } else if _, exists := missions.byID[change.mission.id]; exists { - missions.publish(change.mission) - } - close(change.done) - case creation := <-world.missionCreations: - if zones[creation.mission.world] != nil { - creation.reply <- fmt.Errorf("mission %d already has a zone owner", creation.mission.id) - continue - } - state := creation.state - state.gameSeconds, state.clockStarted = configuration.gameSeconds, configuration.clockStarted - state.weather, state.weatherUntil = configuration.weather, configuration.weatherUntil - state.world = world - var identities []uint32 - for id := range state.characters { - identities = append(identities, id) - } - zone := newZoneRuntime(state) - zones[creation.mission.world] = zone - missions.publish(creation.mission) - ready := make(chan struct{}) - close(ready) - for _, id := range identities { - routes[id] = &worldRoute{zone: zone, ready: ready} - } - if stopping == nil { - quiescing++ - go func() { zone.quiesce(); quiesced <- struct{}{} }() - } - creation.reply <- nil - case creation := <-world.playerCreations: - player := creation.player - route := &worldRoute{ready: make(chan struct{})} - if routes[player.id] != nil { - route.err = fmt.Errorf("player %d already has a zone owner", player.id) - close(route.ready) - creation.reply <- route - continue - } - zone := zones[player.playfield] - if zone == nil { - state := configuration.emptyZone() - state.world, state.playfield = world, player.playfield - zone = newZoneRuntime(state) - zones[player.playfield] = zone - if stopping == nil { - quiescing++ - go func() { zone.quiesce(); quiesced <- struct{}{} }() - } - } - route.zone = zone - routes[player.id] = route - arrivals++ - go func() { - route.err = zone.call(zoneNewPlayer{player}) - close(route.ready) - arrived <- struct{}{} - }() - for _, query := range admissions[player.id] { - query.reply <- route - } - delete(admissions, player.id) - creation.reply <- route - case query := <-world.admissions: - if route := routes[query.player]; route != nil || len(lifecycle) == 0 { - query.reply <- route - } else { - admissions[query.player] = append(admissions[query.player], query) - } - case lookup := <-world.lookups: - lookup.reply <- routes[lookup.player] - case query := <-world.people: - query.reply <- presence[query.id] - case update := <-world.presence: - for _, person := range update.players { - if route := routes[person.id]; route != nil && route.zone == update.zone { - presence[person.id] = person - } - } - close(update.done) - case ownership := <-world.ownership: - if ownership.zone == nil { - delete(routes, ownership.id) - delete(presence, ownership.id) - } else { - ready := make(chan struct{}) - close(ready) - routes[ownership.id] = &worldRoute{zone: ownership.zone, ready: ready} - } - close(ownership.done) - case message := <-world.messages: - messages++ - pending[message.entity] = append(pending[message.entity], message) - if len(pending[message.entity]) == 1 { - go func() { delivered <- worldDelivery{message.entity, world.deliver(message)} }() - } - close(message.accepted) - case result := <-delivered: - messages-- - if result.err != nil { - log.Printf("Cross-zone message for %d: %v", result.entity, result.err) - } - pending[result.entity][0] = worldMessage{} - pending[result.entity] = pending[result.entity][1:] - if len(pending[result.entity]) == 0 { - delete(pending, result.entity) - } else { - message := pending[result.entity][0] - go func() { delivered <- worldDelivery{message.entity, world.deliver(message)} }() - } - case transfer := <-world.transfers: - player := transfer.arrival.player - previous := routes[player.id] - if previous == nil || previous.zone != transfer.source { - transfer.reply <- fmt.Errorf("character %d transfer has a stale source owner", player.id) - continue - } - zone := zones[player.playfield] - if zone == nil { - state := configuration.emptyZone() - state.world, state.playfield = world, player.playfield - zone = newZoneRuntime(state) - zones[player.playfield] = zone - if stopping == nil { - quiescing++ - go func() { zone.quiesce(); quiesced <- struct{}{} }() - } - } - route := &worldRoute{zone: zone, ready: make(chan struct{})} - routes[player.id] = route - person := presence[player.id] - person.combat = false - presence[player.id] = person - // A destination may be busy. Never wait for it on the routing goroutine. - arrivals++ - go func() { - route.err = zone.call(transfer.arrival) - close(route.ready) - arrived <- struct{}{} - }() - transfer.reply <- nil - case <-stopping: - stopping = nil - expiry.Stop() - expiryTicks = nil - // Finish active departures while all destinations can still receive. - for _, zone := range zones { - quiescing++ - go func() { zone.quiesce(); quiesced <- struct{}{} }() - } - case <-quiesced: - quiescing-- - case <-arrived: - arrivals-- - } - } -} - func (world *worldRuntime) lookup(player uint32) (*worldRoute, error) { return world.lookupOn(world.lookups, player) } diff --git a/server/world_services.go b/server/world_services.go @@ -0,0 +1,45 @@ +package main + +import ( + "database/sql" + "maps" +) + +// Shared service handles and immutable content contain no live simulation state. +// The directory uses these dependencies to construct independent zone owners. +type worldServices struct { + db *sql.DB + databaseWriter *databaseWriter + teamService *teamDirectory + chatService *chatRuntime + identities *worldIdentities + passwordHasher *passwordHasher + combatRoll func(uint32) uint32 + loginPort int + worldPort int + httpPort int + baseURL string + terrain map[uint32]*terrain + geometry *sceneGeometry + zoneLinks map[string]map[uint32]zoneLinks + cityDoors map[doorOrigin]bool + worldResources map[uint32]worldResource +} + +func (state *server) services() worldServices { + state.identityAllocator() + return state.worldServices +} + +func (services worldServices) newZone(environment worldEnvironment) *server { + services.cityDoors = maps.Clone(services.cityDoors) + return &server{ + worldServices: services, + gameSeconds: environment.gameSeconds, clockStarted: environment.clockStarted, + weather: environment.weather, weatherUntil: environment.weatherUntil, + characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), + items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement), + worldItems: make(map[uint32]worldItem), depletedResources: make(map[uint32]bool), + fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), + } +} diff --git a/server/world_session.go b/server/world_session.go @@ -130,7 +130,7 @@ func (server *server) joinWorldClient(client *worldClient, id uint32) error { } updates = append(updates, scene...) } - updates = append(updates, gameTimePacket(character.id, server.currentGameSeconds())) + updates = append(updates, gameTimePacket(character.id, currentGameSeconds(server.gameSeconds, server.clockStarted))) spawn := characterPacket(character) title := characterTitlePacket(character) playfield := character.playfield diff --git a/server/world_store.go b/server/world_store.go @@ -103,10 +103,7 @@ func (npc *character) worldState(present bool, respawnAt time.Time) npcState { return state } -func writeNPCBatch(tx *sql.Tx, table, columns string, records [][]any) error { - if len(records) == 0 { - return nil - } +func writeNPCBatch(tx *sql.Tx, table, columns string, count int, fields []any) error { names := strings.Split(columns, ", ") assignments := make([]string, len(names)) for index, name := range names { @@ -114,12 +111,8 @@ func writeNPCBatch(tx *sql.Tx, table, columns string, records [][]any) error { } values := "(?" + strings.Repeat(", ?", len(names)) + ")" query := "INSERT INTO " + table + " (id, " + columns + ") VALUES " + - strings.TrimSuffix(strings.Repeat(values+", ", len(records)), ", ") + + strings.TrimSuffix(strings.Repeat(values+", ", count), ", ") + " ON CONFLICT(id) DO UPDATE SET " + strings.Join(assignments, ", ") - var fields []any - for _, record := range records { - fields = append(fields, record...) - } result, err := tx.Exec(query, fields...) if err != nil { return err @@ -128,15 +121,15 @@ func writeNPCBatch(tx *sql.Tx, table, columns string, records [][]any) error { if err != nil { return err } - if changed != int64(len(records)) { - return fmt.Errorf("checkpoint %s: saved %d of %d rows", table, changed, len(records)) + if changed != int64(count) { + return fmt.Errorf("checkpoint %s: saved %d of %d rows", table, changed, count) } return nil } type npcWrite struct { checkpoint npcCheckpoint - characterRows, npcRows [][]any + characterRows, npcRows []uint32 contributors map[uint32]map[damageContributor]uint32 effects []activeNanosWrite now time.Time @@ -204,12 +197,12 @@ func (server *server) prepareNPCWrite(store itemStore, active map[uint32]bool) n } write.checkpoint.saved[id] = savedNPC{state, maps.Clone(npc.damageContributors), nextSave} if !exists || previous.State.Character != state.Character { - write.characterRows = append(write.characterRows, append([]any{id}, state.Character.fields()...)) + write.characterRows = append(write.characterRows, id) } // Character fields live in their own table; compare only NPC metadata here. previous.State.Character = state.Character if !exists || previous.State != state { - write.npcRows = append(write.npcRows, append([]any{id}, state.fields()...)) + write.npcRows = append(write.npcRows, id) } if !maps.Equal(previous.Contributors, npc.damageContributors) { write.contributors[id] = maps.Clone(npc.damageContributors) @@ -240,10 +233,22 @@ func (write npcWrite) persist(tx *sql.Tx) error { // The transaction consumes detached records; it never reads live actors. for _, batch := range []struct { table, columns string - rows [][]any + rows []uint32 }{{"characters", characterColumns, write.characterRows}, {"npcs", npcColumns, write.npcRows}} { + // Box SQL arguments only for the current batch, not the entire world. for start := 0; start < len(batch.rows); start += 100 { - if err := writeNPCBatch(tx, batch.table, batch.columns, batch.rows[start:min(start+100, len(batch.rows))]); err != nil { + ids := batch.rows[start:min(start+100, len(batch.rows))] + fields := make([]any, 0, len(ids)*(strings.Count(batch.columns, ",")+2)) + for _, id := range ids { + state := write.checkpoint.saved[id].State + fields = append(fields, id) + if batch.table == "characters" { + fields = append(fields, state.Character.fields()...) + } else { + fields = append(fields, state.fields()...) + } + } + if err := writeNPCBatch(tx, batch.table, batch.columns, len(ids), fields); err != nil { return err } } diff --git a/server/zone_runtime_test.go b/server/zone_runtime_test.go @@ -27,10 +27,10 @@ func TestZoneRuntimeMovementContinuesWhileAnotherZoneWaitsForSQLite(t *testing.T move := playerMovementRequest(second, 5) // Transfer distinct maps and entities; only persistence and immutable terrain are shared. states := []*server{ - {db: world.db, databaseWriter: world.databaseWriter, geometry: world.geometry, terrain: world.terrain, + {worldServices: worldServices{db: world.db, databaseWriter: world.databaseWriter, geometry: world.geometry, terrain: world.terrain}, characters: map[uint32]*character{1: first}, clients: map[uint32]*worldClient{1: firstClient}, items: map[uint32]itemRecord{1: world.items[1]}, itemPlacements: map[uint32]itemPlacement{1: world.itemPlacements[1]}}, - {db: world.db, databaseWriter: world.databaseWriter, geometry: world.geometry, terrain: world.terrain, + {worldServices: worldServices{db: world.db, databaseWriter: world.databaseWriter, geometry: world.geometry, terrain: world.terrain}, characters: map[uint32]*character{2: second}, clients: map[uint32]*worldClient{2: secondClient}}, } delete(world.characters, 1) diff --git a/server/zone_transfer.go b/server/zone_transfer.go @@ -2,25 +2,14 @@ package main import ( "fmt" - "maps" ) // Create distinct mutable maps. These references are shared infrastructure or // immutable content; none of the source zone's entities or caches are retained. func (source *server) emptyZone() *server { - return &server{ - db: source.db, databaseWriter: source.databaseWriter, teamService: source.teamService, chatService: source.chatService, identities: source.identityAllocator(), - combatRoll: source.combatRoll, passwordHasher: source.passwordHasher, - loginPort: source.loginPort, worldPort: source.worldPort, httpPort: source.httpPort, baseURL: source.baseURL, - terrain: source.terrain, geometry: source.geometry, zoneLinks: source.zoneLinks, cityDoors: maps.Clone(source.cityDoors), - weather: source.weather, weatherUntil: source.weatherUntil, - worldResources: source.worldResources, gameSeconds: source.gameSeconds, clockStarted: source.clockStarted, - nextCharacter: source.nextCharacter, nextItem: source.nextItem, nextNPC: source.nextNPC, - characters: make(map[uint32]*character), clients: make(map[uint32]*worldClient), - items: make(map[uint32]itemRecord), itemPlacements: make(map[uint32]itemPlacement), - worldItems: make(map[uint32]worldItem), depletedResources: make(map[uint32]bool), - fighting: make(map[uint32]*character), mobileNPCs: make(map[uint32][]*character), - } + state := source.services().newZone(worldEnvironment{source.gameSeconds, source.clockStarted, source.weather, source.weatherUntil}) + state.nextCharacter, state.nextNPC, state.nextItem = source.nextCharacter, source.nextNPC, source.nextItem + return state } type playerTransfer struct {