aorecomp

Anarchy Online classic in the browser

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


commit 90b055085282df2c8bcc8de34e5050b0d3fbf413
parent ee9904c70966449034753ffa923db657e598d26c
Author: anon <anon@example.com>
Date:   Sat,  7 Nov 2026 00:16:57 +0000

Use scoped SQLite transactions for inventory moves

Diffstat:
MDEVELOPERS.md | 10++++++++++
MTODO.md | 8++++++--
Mserver/backpacks.go | 19++++++++++++++++++-
Mserver/inventory.go | 7+++++++
Aserver/inventory_move.go | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/inventory_move_test.go | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 322 insertions(+), 3 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -73,6 +73,16 @@ that lock. Operations needing ordered simulation/session changes acquire updates under the world lock and use the existing output queues after releasing it. Do not hold the world lock across a blocking network write. +Unworn item moves between carried slots, backpacks and the bank use +`moveStoredItem`: SQLite checks the expected source and backpack ownership, +enforces destination slot uniqueness and commits the placement atomically. +The transaction takes values and has no access to live server state. Its caller +publishes only the affected inventory, placement and backpack references after +commit; it does not reconstruct world inventory or checkpoint NPCs. The caller +still holds the simulation locks while waiting. Releasing them requires ordered +completion with the remaining snapshot-based inventory writers, not just a +goroutine around the SQL call. + Navigation searches use one goroutine and a bounded channel per playfield. Jobs own actor snapshots and pin immutable scene geometry; they never hold the simulation locks. The simulation accepts a result only while its motion request, diff --git a/TODO.md b/TODO.md @@ -52,8 +52,12 @@ research separately. More screenshots and test cases do not count as new gamepla spatial cells, and periodic checkpoints avoid full inventory reconstruction and dormant snapshot copies. Slow-lock and loop timings distinguish contention, lock hold time and scheduling delay. The original stall is still unattributed, - and ordinary state mutations still share the global lock. Full zone ownership - remains a separate architectural change, including command dispatch, transfers + and ordinary state mutations still share the global lock. Unworn item moves + now use isolated SQLite placement transactions with source/owner checks and + no world inventory reconstruction or NPC checkpoints. Their callers still + hold the lock while waiting; transaction completion must be coordinated with + the remaining snapshot-based writers before releasing it. The remaining + migration includes zone ownership, command dispatch, cross-zone transfers and transaction completion. - [x] **Use the original native character creation flow.** Login credentials are diff --git a/server/backpacks.go b/server/backpacks.go @@ -422,7 +422,24 @@ func (server *server) moveContainerItem_locked(client *worldClient, body []byte) if len(inventory.Containers) == 0 { inventory.Containers = nil } - if err := server.saveInventory_locked(player, inventory); err != nil { + + // Transfer only this instance; the database verifies its expected source. + source, destination := itemPlacement{Slot: sourceSlot}, itemPlacement{Slot: slot} + if sourcePage == 105 { + source.Bank = player.id + } else if sourceBag != 0 { + source.Backpack = sourceBag + } else { + source.Player = player.id + } + if targetType == 57005 { + destination.Bank = player.id + } else if targetBag != 0 { + destination.Backpack = targetBag + } else { + destination.Player = player.id + } + if err := server.moveInventoryItem_locked(player, inventory, item.ID, source, destination); err != nil { return err } reply := append([]byte(nil), body[16:]...) diff --git a/server/inventory.go b/server/inventory.go @@ -444,6 +444,13 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { return nil } inventory.Items[index].Slot = destination + // Reordering carried items has no wear effects or other world changes. + item := inventory.Items[index] + if err := server.moveInventoryItem_locked(character, inventory, item.ID, + itemPlacement{Player: character.id, Slot: sourceSlot}, itemPlacement{Player: character.id, Slot: destination}); err != nil { + return err + } + return client.send(n3Packet(key, 50000, client.id, body[16:])) } else { if binary.BigEndian.Uint32(body[16:20]) != 112 || !inventory.Items[index].acceptsDeleteTemplates(binary.BigEndian.Uint32(body[28:32]), binary.BigEndian.Uint32(body[32:36])) { diff --git a/server/inventory_move.go b/server/inventory_move.go @@ -0,0 +1,76 @@ +package main + +import ( + "database/sql" + "fmt" + "maps" +) + +// An unworn item move changes placement only; the transaction owns no live state. +func moveStoredItem(db *sql.DB, player, item uint32, source, destination itemPlacement) error { + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + // A backpack remains the player's carried container throughout the transfer. + var savedID uint32 + for _, placement := range []itemPlacement{source, destination} { + if placement.Backpack != 0 { + if err := tx.QueryRow(`SELECT item_id FROM item_locations + WHERE item_id=? AND player_id=? AND reclaim_at IS NULL`, placement.Backpack, player).Scan(&savedID); err != nil { + return fmt.Errorf("player %d no longer carries backpack %d: %w", player, placement.Backpack, err) + } + } + } + + // Check the expected owner and source inside the same transaction as the move. + if err := tx.QueryRow(`DELETE FROM item_locations + WHERE item_id=? AND (player_id, bank_player_id, backpack_id, slot) + IS (NULLIF(?,0), NULLIF(?,0), NULLIF(?,0), ?) AND reclaim_at IS NULL + RETURNING item_id`, item, source.Player, source.Bank, source.Backpack, source.Slot).Scan(&savedID); err != nil { + return fmt.Errorf("remove item %d move source: %w", item, err) + } + if err := tx.QueryRow(`INSERT INTO item_locations (item_id, player_id, bank_player_id, backpack_id, slot) + VALUES (?, NULLIF(?,0), NULLIF(?,0), NULLIF(?,0), ?) RETURNING item_id`, + item, destination.Player, destination.Bank, destination.Backpack, destination.Slot).Scan(&savedID); err != nil { + return fmt.Errorf("save item %d move destination: %w", item, err) + } + if err := tx.QueryRow(`SELECT item_id FROM item_locations + WHERE item_id=? AND (player_id, bank_player_id, backpack_id, slot) + IS (NULLIF(?,0), NULLIF(?,0), NULLIF(?,0), ?) AND reclaim_at IS NULL`, + item, destination.Player, destination.Bank, destination.Backpack, destination.Slot).Scan(&savedID); err != nil { + return fmt.Errorf("item %d move was not saved: %w", item, err) + } + return tx.Commit() +} + +func (server *server) moveInventoryItem_locked(player *character, inventory playerInventory, item uint32, source, destination itemPlacement) error { + if err := inventory.validate(); err != nil { + return err + } + db, err := server.database() + if err != nil { + return err + } + if err := moveStoredItem(db, player.id, item, source, destination); err != nil { + return err + } + + // Publish just the committed placement and the affected backpack references. + for _, placement := range []itemPlacement{source, destination} { + if placement.Backpack != 0 { + record := server.items[placement.Backpack] + record.Slots = maps.Clone(record.Slots) + record.Slots[fmt.Sprintf("slot_%d", placement.Slot+1)] = nil + if placement == destination { + record.Slots[fmt.Sprintf("slot_%d", placement.Slot+1)] = &item + } + server.items[placement.Backpack] = record + } + } + server.itemPlacements[item] = destination + player.inventory = inventory + return nil +} diff --git a/server/inventory_move_test.go b/server/inventory_move_test.go @@ -0,0 +1,205 @@ +package main + +import ( + "reflect" + "sync" + "testing" + "time" +) + +func TestInventoryMoveDoesNotCheckpointNPCs(t *testing.T) { + world, _ := newInventoryWriteWorld(t) + for id, npc := range world.characters { + if npc.npc { + npc.position[0]++ + saved := world.savedNPCs[id] + saved.NextSave = time.Time{} + world.savedNPCs[id] = saved + } + } + auditCheckpointWrites(t, world) + + err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 65)[20:]) + + if err != nil { + t.Fatal(err) + } + if writes := checkpointWrites(t, world); !reflect.DeepEqual(writes, map[string]int{"item_locations/DELETE": 1, "item_locations/INSERT": 1}) { + t.Fatalf("item move checkpointed unrelated actors: %v", writes) + } +} + +func TestInventoryMoveRejectsOccupiedDurableDestination(t *testing.T) { + world, conn := newInventoryWriteWorld(t) + if granted, err := world.grantItem_locked(world.characters[1], 121567); err != nil || !granted { + t.Fatal(granted, err) + } + if _, err := world.db.Exec("UPDATE item_locations SET slot=66 WHERE item_id=2"); err != nil { + t.Fatal(err) + } + + err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 66)[20:]) + + var slot uint32 + if queryErr := world.db.QueryRow("SELECT slot FROM item_locations WHERE item_id=1").Scan(&slot); queryErr != nil { + t.Fatal(queryErr) + } + if err == nil || slot != 64 || world.characters[1].inventory.Items[0].Slot != 64 || len(conn.packets) != 0 { + t.Fatal("occupied destination did not roll back source removal", err, slot) + } +} + +func TestInventoryMoveCompetingDatabaseConnections(t *testing.T) { + first, firstConn := newInventoryWriteWorld(t) + second := newTestInventoryServer(t) + secondConn := &combatTestConn{} + second.clients[1] = &worldClient{id: 1, conn: secondConn, target: true, ready: true} + start := make(chan struct{}) + var errors [2]error + var done sync.WaitGroup + + // Separate worlds share SQLite, but have independent simulation locks and caches. + for index, world := range []*server{first, second} { + done.Add(1) + go func() { + defer done.Done() + <-start + errors[index] = world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, uint32(65+index))[20:]) + }() + } + close(start) + done.Wait() + + if (errors[0] == nil) == (errors[1] == nil) || len(firstConn.packets)+len(secondConn.packets) != 1 { + t.Fatal("SQLite did not select exactly one successful move", errors) + } + var slot uint32 + if err := first.db.QueryRow("SELECT slot FROM item_locations WHERE item_id=1").Scan(&slot); err != nil { + t.Fatal(err) + } + if errors[0] == nil && slot != 65 || errors[1] == nil && slot != 66 { + t.Fatal("durable destination differs from the successful move", slot, errors) + } +} + +func TestBackpackMoveChecksDurableContainerOwnership(t *testing.T) { + for _, direction := range []string{"deposit", "withdrawal"} { + t.Run(direction, func(t *testing.T) { + world, conn := newBackpackWorld(t) + client := world.clients[1] + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 66, 1)[20:]); err != nil { + t.Fatal(err) + } + request := backpackMoveRequest(104, 68, 51017, 3, 111) + if direction == "withdrawal" { + if err := world.handleInventory(client, request[20:]); err != nil { + t.Fatal(err) + } + request = backpackMoveRequest(107, 1<<16, 50000, 1, 93) + } + if _, err := world.db.Exec("UPDATE item_locations SET player_id=NULL, bank_player_id=1, slot=0 WHERE item_id=3"); err != nil { + t.Fatal(err) + } + conn.packets = nil + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + inventory := world.characters[1].inventory + + err = world.handleInventory(client, request[20:]) + + if err == nil || len(conn.packets) != 0 || !reflect.DeepEqual(inventory, world.characters[1].inventory) { + t.Fatal("move used a backpack that is no longer carried", err) + } + after, err := readTestItemStore(world) + if err != nil || !reflect.DeepEqual(before, after) { + t.Fatal("refused backpack move changed durable ownership", err) + } + }) + } +} + +func TestInventoryMoveFailedCommitRetainsSource(t *testing.T) { + world, conn := newInventoryWriteWorld(t) + if _, err := world.db.Exec(`CREATE TABLE move_commit_failure ( + player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); + CREATE TRIGGER reject_move_commit AFTER INSERT ON item_locations + BEGIN INSERT INTO move_commit_failure VALUES (99); END;`); err != nil { + t.Fatal(err) + } + + err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 65)[20:]) + + var slot uint32 + if queryErr := world.db.QueryRow("SELECT slot FROM item_locations WHERE item_id=1").Scan(&slot); queryErr != nil { + t.Fatal(queryErr) + } + if err == nil || slot != 64 || world.characters[1].inventory.Items[0].Slot != 64 || len(conn.packets) != 0 { + t.Fatal("failed commit lost the source or published a move", err, slot) + } +} + +func TestInventoryMoveChecksDurableSource(t *testing.T) { + for _, change := range []string{ + "UPDATE item_locations SET slot=66 WHERE item_id=1", + "UPDATE item_locations SET player_id=2 WHERE item_id=1", + } { + t.Run(change, func(t *testing.T) { + world, conn := newInventoryWriteWorld(t) + if _, err := world.db.Exec(change); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + err = world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 65)[20:]) + + if err == nil || world.characters[1].inventory.Items[0].Slot != 64 || len(conn.packets) != 0 { + t.Fatal("stale source was published as a successful move", err) + } + after, err := readTestItemStore(world) + if err != nil || !reflect.DeepEqual(before, after) { + t.Fatal("stale move changed durable ownership", err) + } + }) + } +} + +func TestInventoryMoveRollsBackAndRetries(t *testing.T) { + for _, fault := range []string{ + "BEFORE DELETE ON item_locations BEGIN SELECT RAISE(IGNORE); END", + "BEFORE INSERT ON item_locations BEGIN SELECT RAISE(IGNORE); END", + "BEFORE INSERT ON item_locations BEGIN SELECT RAISE(ABORT, 'move failed'); END", + "AFTER INSERT ON item_locations BEGIN UPDATE item_locations SET slot=66 WHERE item_id=NEW.item_id; END", + } { + t.Run(fault, func(t *testing.T) { + world, conn := newInventoryWriteWorld(t) + if _, err := world.db.Exec("CREATE TRIGGER reject_move " + fault); err != nil { + t.Fatal(err) + } + + err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 65)[20:]) + + var slot uint32 + if queryErr := world.db.QueryRow("SELECT slot FROM item_locations WHERE item_id=1").Scan(&slot); queryErr != nil { + t.Fatal(queryErr) + } + if err == nil || slot != 64 || world.characters[1].inventory.Items[0].Slot != 64 || len(conn.packets) != 0 { + t.Fatal("failed move published or retained a partial change", err, slot) + } + if _, err := world.db.Exec("DROP TRIGGER reject_move"); err != nil { + t.Fatal(err) + } + if err := world.handleInventory(world.clients[1], inventoryMovePacket(1, 64, 65)[20:]); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t) + if restored.characters[1].inventory.Items[0].Slot != 65 || world.characters[1].inventory.Items[0].Slot != 65 || len(conn.packets) != 1 { + t.Fatal("retry did not publish exactly one committed move") + } + }) + } +}