aorecomp

Anarchy Online classic in the browser

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


commit 9032dbc65c6e8ff59c5129c3977268963ce15f2d
parent f0b7ffe9581f94c7b43ffe0e7b824d88a1cbfde2
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 07:01:26 +0000

Implement owned pet dismissal with committed retirement

Diffstat:
MTODO.md | 13++++++++++++-
Adocs/pet-dismissal.md | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/pet-owner-protocol.md | 2++
Mdocs/pet-summoning.md | 3++-
Aserver/browser_pet_dismiss_test.go | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/browser_pet_follow_test.go | 20+++++++++++++-------
Aserver/pet_dismiss_test.go | 227+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/pet_follow.go | 11+++++++++--
Mserver/pets.go | 58+++++++++++++++++++++++++++++++++++++---------------------
Atools/client/test_pet_dismiss.mjs | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mtools/client/test_pet_owner_protocol.mjs | 11++++++++++-
11 files changed, 568 insertions(+), 33 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -3164,12 +3164,23 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah both native owner/observer reloads pass in the focused wait scenario. - [ ] [P1] Order the pet to attack. Check: it validates the target and begins combat on its own action schedule. + Blocked on the original PT50 combat-profile binding above: retained fist + records120634/120637 establish candidate weapon data, not that this summoned + pet equips them. Keep the attack schedule tied to recovered profile evidence. - [ ] [P1] Stop a pet's attack. Check: the stop command clears combat and queued actions according to the recovered behavior. - [ ] [P1] Handle pet death. Check: death removes the applicable ownership state and stale commands cannot act on a replacement pet. -- [ ] [P1] Dismiss a pet. Check: only its owner can dismiss it and observers lose + Original death/termination animation and corpse presentation still need + evidence; explicit dismissal currently retires the entity without a death clip. +- [x] [P1] Dismiss a pet. Check: only its owner can dismiss it and observers lose the entity exactly once. + Captured command10 now commits character/NPC/ownership deletion before + RemovePet, the packed-limit correction and typed Destroy. Failed/ignored + writes and commit failures retain ownership for retry; loading observers and + owners in another playfield receive retirement. Native follow/terminate, + real replacement casting, both page reloads and cold recovery retain the + other owner's pet and exact costs. See [pet dismissal](docs/pet-dismissal.md). - [ ] [P1] Expire a timed pet. Check: its lifetime ends at the expected point without removing a newer pet or allowing another queued attack. The admitted summon now interprets TimeExist600 as seconds. Ignored retirement diff --git a/docs/pet-dismissal.md b/docs/pet-dismissal.md @@ -0,0 +1,66 @@ +# Owned pet dismissal + +Original `/pet terminate` now retires the authenticated owner's pet. The command +releases the summon limit without charging nano and preserves another owner's +entity. Its retirement shares the same committed path as timed expiry. + +## Original request and scope + +Real keyboard input captures PetCommand `6b333303`, owner envelope50000:id, +with body words `10, 0, 1009, 0, 0`. The empty encoded selector addresses the +owner's set; no explicit pet identity is supplied. The capture is retained in +`local/pet-owner-protocol/20261103-224256/`,15.69 seconds. The shipped +`cd_image/text/help/Pet Commands.txt` describes `/pet terminate` as the pet +killing itself. In the raw fixture the request does not delete the actor locally. + +Only the current ready, living owner can issue this admitted command. Foreign +actors, stale clients, loading owners, arguments and named/explicit selectors +are refused. The server selects its ownership map. An owned entity can be +retired even if it is dead, expired or in another playfield; its owner still +receives the limit correction. Original combat death and termination +animation/corpse presentation remain part of the open pet-death work. + +## Durable retirement + +A SQLite transaction deletes the character and cascades its NPC/ownership rows. +Required deletion uses RETURNING and completes its commit before in-memory +ownership, the world entry, saved NPC cache and active expiry list are removed. +Failed or ignored writes preserve the complete entity and permit retry. + +After commit, original RemovePet updates native membership, stat251 publishes +the remaining packed limit, and a typed Destroy removes the interested actor. +Ready observers whose snapshots are still loading receive the queued removal. +The owner receives membership/limit updates after leaving the pet's playfield. +Duplicate requests with an empty owned set publish no further retirement. +The allocator remains monotonic and the retired entity cannot keep following. + +Timed expiry uses this same path. Its indexed active-list traversal retains +failed retirements and advances to other entries without database writes before +their deadlines. This does not establish the original TimeExist units or +disconnect lifecycle; those TODOs remain open. + +## Focused verification + +The Go baseline leaves the pet owned and moving after the original command. +Public-handler regressions cover one durable retirement, duplicate requests, +foreign actor/ownership and unsupported selectors, ignored deletion, cascade +failure, deferred commit failure, cold retention/retry, loading observers, +another-playfield ownership, simultaneous expiry/dismissal and old deadlines +after replacement. Routine movement after retirement cannot rewrite the entity. + +`TestBrowserPetDismiss` uses two controlled owners, each with one completed +ordinary summon. It is not earned progression. Real chat starts follow, real +movement covers three metres, then `/pet terminate` removes only the first pet. +Both native clients receive one RemovePet and one typed Destroy. The peer's +pose and cost remain unchanged. A real Programs cast creates replacement1000003 +with owner15nano/peer25nano and allocator1000004. Both page reloads and a fresh +server preserve the replacement and peer, with the retired identity absent. + +The passing capture is `local/pet-dismiss/20261103-225205/`: live24.10 seconds, +cold15.05 seconds. No client C/WASM change was required. + +The related Go run passes66 roots/204 results. The focused race run passes18 +results, including concurrent expiry/dismissal and the replacement deadline. +All six native traces have no client errors or dropped events. Vet, driver +syntax and the packet/ownership checks retained in +`local/pet-dismiss/validation.json` pass. diff --git a/docs/pet-owner-protocol.md b/docs/pet-owner-protocol.md @@ -25,6 +25,8 @@ The same native input captures `/pet follow` as `1, 0, 1009, 0, 0`; the owned server implementation is documented in [pet follow](pet-follow.md). It captures `/pet wait` as `4, 0, 1009, 0, 0`, now admitted by the same owned command handler. +Original `/pet terminate` captures `10, 0, 1009, 0, 0`; the owned +[dismissal implementation](pet-dismissal.md) retires only that owner's set. Owner membership replays after CharacterReady and the actor's equipment/nano effects. A two-owned-pet reload regression shows that early bootstrap AddPet diff --git a/docs/pet-summoning.md b/docs/pet-summoning.md @@ -27,7 +27,8 @@ data, not an original14.9.1 server measurement. The later data's four-point skil requirements are not imported: the original requires eight. Weapon selection, raw combat stats, master/type metadata and exact spawn placement remain open. Player-versus-pet combat remains unsupported. The owned pet separately admits -the original all-pets [follow and wait commands](pet-follow.md). +the original all-pets [follow and wait commands](pet-follow.md) and +[dismissal](pet-dismissal.md). TimeExist is interpreted as seconds. A [later compiled nano chart](https://www.slideshare.net/slideshow/nano-formulas/7124531) diff --git a/server/browser_pet_dismiss_test.go b/server/browser_pet_dismiss_test.go @@ -0,0 +1,96 @@ +package main + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserPetDismiss(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for native pet dismissal") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/pet-dismiss", time.Now().Format("20060102-150405")) + world := newBrowserOwnedPetWorld(t) + for _, phase := range []string{"live", "cold"} { + if phase == "cold" { + if err := world.db.Close(); err != nil { + t.Fatal(err) + } + world = newServerForTest(t) + } + if !t.Run(phase, func(t *testing.T) { + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + var owners []map[string]any + for id := uint32(1); id <= 2; id++ { + owner := world.characters[id] + pets := []uint32{} + for pet := range owner.pets { + pets = append(pets, pet) + } + owners = append(owners, map[string]any{"id": id, "pets": pets, "nano": owner.nano}) + } + var rows uint32 + if err := world.db.QueryRow("SELECT count(*) FROM pets").Scan(&rows); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + json.NewEncoder(w).Encode(map[string]any{"owners": owners, "savedPets": rows, "nextNPC": world.nextNPC}) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + stopped := make(chan struct{}) + go func() { + defer close(stopped) + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + select { + case now := <-ticker.C: + world.advancePlayerMovement(now) + world.advanceNPCs(now) + world.advanceNanos(now) + case <-ctx.Done(): + return + } + } + }() + defer func() { cancel(); <-stopped }() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_pet_dismiss.mjs"), host.URL, filepath.Join(output, phase), phase) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + + t.Logf("Browser artifacts: %s", output) + if err != nil { + t.Fatal(err) + } + world.mutex.Lock() + defer world.mutex.Unlock() + if world.characters[1000001] != nil || world.characters[1000002] == nil || world.characters[1000003] == nil || + len(world.characters[1].pets) != 1 || len(world.characters[2].pets) != 1 || len(world.petExpiry) != 2 || + world.characters[1].nano != 15 || world.characters[2].nano != 25 || world.nextNPC != 1000004 { + t.Fatal("dismissal/replacement changed the peer or reused an identity") + } + }) { + return + } + } +} diff --git a/server/browser_pet_follow_test.go b/server/browser_pet_follow_test.go @@ -21,14 +21,8 @@ func TestBrowserPetWait(t *testing.T) { runBrowserPetMotion(t, "wait") } -func runBrowserPetMotion(t *testing.T, scenario string) { +func newBrowserOwnedPetWorld(t *testing.T) *server { t.Helper() - if os.Getenv("AO_GAME_TEST") != "1" { - t.Skip("set AO_GAME_TEST=1 for native pet " + scenario) - } - _, source, _, _ := runtime.Caller(0) - root := filepath.Dir(filepath.Dir(source)) - output := filepath.Join(root, "local/pet-"+scenario, time.Now().Format("20060102-150405")) world := newBrowserPetWorld(t) // Controlled checkpoint: both players have completed the ordinary summon action. for id := uint32(1); id <= 2; id++ { @@ -43,6 +37,18 @@ func runBrowserPetMotion(t *testing.T, scenario string) { world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) } clear(world.clients) + return world +} + +func runBrowserPetMotion(t *testing.T, scenario string) { + t.Helper() + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for native pet " + scenario) + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/pet-"+scenario, time.Now().Format("20060102-150405")) + world := newBrowserOwnedPetWorld(t) mux := http.NewServeMux() mux.Handle("/", world.httpHandler()) mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { diff --git a/server/pet_dismiss_test.go b/server/pet_dismiss_test.go @@ -0,0 +1,227 @@ +package main + +import ( + "encoding/binary" + "sync" + "testing" + "time" +) + +func petDismissRequest(owner uint32) []byte { + packet := petFollowRequest(owner) + binary.BigEndian.PutUint32(packet[36:], 10) + return packet +} + +func TestPetDismissCommitsOneRemovalAndStopsOldMotion(t *testing.T) { + world, output := newPetSummonWorld(t) + player, client := world.characters[1], world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + pet := player.pets[1000001] + world.handlePetCommand(client, petFollowRequest(1)[20:]) + player.position = [3]float32{10, 0, 0} + output.packets = nil + auditCheckpointWrites(t, world) + + err := world.handlePetCommand(client, petDismissRequest(1)[20:]) + world.handlePetCommand(client, petDismissRequest(1)[20:]) + now := time.Now() + for tick := 1; tick <= 60; tick++ { + world.advancePlayerMovement(now.Add(time.Duration(tick) * time.Second / 60)) + } + cold := newServerForTest(t) + + if err != nil || len(player.pets) != 0 || world.characters[pet.id] != nil || len(world.petExpiry) != 0 || + client.npcs[pet.id] || cold.characters[pet.id] != nil || len(cold.characters[1].pets) != 0 || + player.nano != 25 || world.nextNPC != 1000002 || pet.position != [3]float32{2, 0, 0} { + t.Fatal("dismissal did not retire only the owned pet durably", err, len(player.pets), len(world.petExpiry), pet.position) + } + if writes := checkpointWrites(t, world); writes["characters/DELETE"] != 1 || writes["npcs/DELETE"] != 1 { + t.Fatal("dismissal did not delete its entity exactly once", writes) + } + if len(output.packets) != 3 || binary.BigEndian.Uint32(output.packets[0][16:20]) != 0x58742a0f || + binary.BigEndian.Uint32(output.packets[0][24:28]) != 1 || binary.BigEndian.Uint32(output.packets[0][33:37]) != pet.id || + binary.BigEndian.Uint32(output.packets[1][29:33]) != 251 || binary.BigEndian.Uint32(output.packets[1][33:37]) != 0 || + binary.BigEndian.Uint32(output.packets[2][16:20]) != 0x36510078 || binary.BigEndian.Uint32(output.packets[2][24:28]) != pet.id { + t.Fatalf("dismissal did not remove native ownership and the actor exactly once: %x", output.packets) + } +} + +func TestPetDismissFailurePreservesOwnershipAndRetries(t *testing.T) { + for _, scenario := range []string{"ignored deletion", "cascade failure", "commit failure"} { + t.Run(scenario, func(t *testing.T) { + world, output := newPetSummonWorld(t) + player, client := world.characters[1], world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + pet := player.pets[1000001] + query := "CREATE TRIGGER reject_dismiss BEFORE DELETE ON characters WHEN OLD.id=1000001 BEGIN SELECT RAISE(IGNORE); END" + if scenario == "cascade failure" { + query = "CREATE TRIGGER reject_dismiss BEFORE DELETE ON pets WHEN OLD.npc_id=1000001 BEGIN SELECT RAISE(ABORT,'reject ownership deletion'); END" + } + if scenario == "commit failure" { + if _, err := world.db.Exec("CREATE TABLE dismiss_commit_failure (id INTEGER REFERENCES characters(id) DEFERRABLE INITIALLY DEFERRED)"); err != nil { + t.Fatal(err) + } + query = "CREATE TRIGGER reject_dismiss AFTER DELETE ON characters WHEN OLD.id=1000001 BEGIN INSERT INTO dismiss_commit_failure VALUES (999); END" + } + if _, err := world.db.Exec(query); err != nil { + t.Fatal(err) + } + output.packets = nil + + err := world.handlePetCommand(client, petDismissRequest(1)[20:]) + cold := newServerForTest(t) + + if err != nil || world.characters[pet.id] != pet || player.pets[pet.id] != pet || len(world.petExpiry) != 1 || + !client.npcs[pet.id] || len(output.packets) != 0 || player.nano != 25 || len(cold.characters[1].pets) != 1 { + t.Fatal("failed retirement changed ownership or reported success", err, len(output.packets)) + } + if _, err := world.db.Exec("DROP TRIGGER reject_dismiss"); err != nil { + t.Fatal(err) + } + if err := world.handlePetCommand(client, petDismissRequest(1)[20:]); err != nil { + t.Fatal(err) + } + if len(player.pets) != 0 || world.characters[pet.id] != nil || len(output.packets) != 3 || len(world.petExpiry) != 0 { + t.Fatal("dismissal could not retry after persistence recovered") + } + }) + } +} + +func TestPetDismissRejectsForeignOwnerAndSelectors(t *testing.T) { + for _, scenario := range []string{"foreign actor", "other owner", "stale client", "loading", "not ready", "selector"} { + t.Run(scenario, func(t *testing.T) { + world, output := newPetSummonWorld(t) + client := world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + request := petDismissRequest(1)[20:] + switch scenario { + case "foreign actor", "other owner": + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + client = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}} + world.clients[2] = client + if scenario == "other owner" { + binary.BigEndian.PutUint32(request[8:], 2) + } + case "stale client": + world.clients[1] = &worldClient{id: 1} + case "loading": + client.loading = true + case "not ready": + client.ready = false + case "selector": + binary.BigEndian.PutUint32(request[20:], 1000001) + } + output.packets = nil + auditCheckpointWrites(t, world) + + err := world.handlePetCommand(client, request) + + if err != nil || len(world.characters[1].pets) != 1 || world.characters[1000001] == nil || + len(world.petExpiry) != 1 || len(output.packets) != 0 || len(checkpointWrites(t, world)) != 0 { + t.Fatal("untrusted dismissal retired another owner's pet", err) + } + }) + } +} + +func TestPetDismissNotifiesAnObserverStillLoadingItsSnapshot(t *testing.T) { + world, _ := newPetSummonWorld(t) + client := world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + observer := &combatTestConn{} + world.characters[2] = &character{id: 2, playfield: 950, health: 100} + world.clients[2] = &worldClient{id: 2, target: true, ready: true, loading: true, conn: observer, npcs: map[uint32]bool{1000001: true}} + + err := world.handlePetCommand(client, petDismissRequest(1)[20:]) + + if err != nil || len(observer.packets) != 3 || world.clients[2].npcs[1000001] || + binary.BigEndian.Uint32(observer.packets[0][16:20]) != 0x58742a0f || + binary.BigEndian.Uint32(observer.packets[2][16:20]) != 0x36510078 { + t.Fatal("queued pet snapshot did not receive retirement while loading", err, len(observer.packets)) + } +} + +func TestPetDismissInAnotherPlayfieldUpdatesItsOwnersLimit(t *testing.T) { + world, output := newPetSummonWorld(t) + client := world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + world.characters[1].playfield = 951 + clear(client.npcs) + output.packets = nil + + err := world.handlePetCommand(client, petDismissRequest(1)[20:]) + + if err != nil || len(world.characters[1].pets) != 0 || world.characters[1000001] != nil || + len(output.packets) != 2 || binary.BigEndian.Uint32(output.packets[1][29:33]) != 251 || + binary.BigEndian.Uint32(output.packets[1][33:37]) != 0 { + t.Fatal("owner lost its limit correction after leaving the pet's playfield", err, len(output.packets)) + } +} + +func TestPetDismissAndExpiryRetireTheEntityOnce(t *testing.T) { + world, output := newPetSummonWorld(t) + client := world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:]) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + deadline := world.characters[1000001].pet.expiresAt + output.packets = nil + auditCheckpointWrites(t, world) + start := make(chan struct{}) + errors := make(chan error, 1) + var workers sync.WaitGroup + workers.Add(2) + + go func() { + defer workers.Done() + <-start + errors <- world.handlePetCommand(client, petDismissRequest(1)[20:]) + }() + go func() { + defer workers.Done() + <-start + world.advanceNanos(deadline) + }() + close(start) + workers.Wait() + + if err := <-errors; err != nil || world.characters[1000001] != nil || len(world.characters[1].pets) != 0 || + len(world.petExpiry) != 0 || len(output.packets) != 3 || checkpointWrites(t, world)["characters/DELETE"] != 1 { + t.Fatal("concurrent expiry and dismissal did not publish one committed retirement", err, len(output.packets)) + } +} + +func TestPetDismissOldDeadlineCannotRetireReplacement(t *testing.T) { + world, _ := newPetSummonWorld(t) + player, client := world.characters[1], world.clients[1] + cast := characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43324})[20:] + world.handleNanoCast(client, cast) + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + deadline := time.Now().Add(5 * time.Second) + world.characters[1000001].pet.expiresAt = deadline + if _, err := world.db.Exec("UPDATE pets SET expires_at=? WHERE npc_id=1000001", deadline); err != nil { + t.Fatal(err) + } + + err := world.handlePetCommand(client, petDismissRequest(1)[20:]) + player.nanoRechargeUntil = time.Time{} + world.handleNanoCast(client, cast) + if client.nanoCast == nil { + t.Fatal("retired owner limit did not admit its replacement") + } + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + world.advanceNanos(deadline.Add(time.Nanosecond)) + cold := newServerForTest(t) + + if err != nil || world.characters[1000001] != nil || world.characters[1000002] == nil || + len(world.petExpiry) != 1 || player.pets[1000002] == nil || player.nano != 15 || + cold.characters[1000001] != nil || cold.characters[1].pets[1000002] == nil || cold.nextNPC != 1000003 { + t.Fatal("old deadline removed a replacement or reused its identity", err) + } +} diff --git a/server/pet_follow.go b/server/pet_follow.go @@ -3,6 +3,7 @@ package main import ( "encoding/binary" "fmt" + "log" "math" "time" ) @@ -11,10 +12,10 @@ func (server *server) handlePetCommand(client *worldClient, body []byte) error { if len(body) < 36 { return fmt.Errorf("invalid pet command length") } - // Original unfiltered commands: follow=1, wait=4, no argument or named selector. + // Original unfiltered commands: follow=1, wait=4, terminate=10, no named selector. command := binary.BigEndian.Uint32(body[16:20]) if len(body) != 36 || !client.target || binary.BigEndian.Uint32(body[4:8]) != 50000 || - binary.BigEndian.Uint32(body[8:12]) != client.id || command != 1 && command != 4 || + binary.BigEndian.Uint32(body[8:12]) != client.id || command != 1 && command != 4 && command != 10 || binary.BigEndian.Uint32(body[20:24]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 1009 || binary.BigEndian.Uint32(body[28:32]) != 0 || binary.BigEndian.Uint32(body[32:36]) != 0 { return nil @@ -30,6 +31,12 @@ func (server *server) handlePetCommand(client *worldClient, body []byte) error { now := time.Now() updates := make(map[*worldClient][][]byte) for _, pet := range owner.pets { + if command == 10 { + if err := server.retirePet_locked(pet, updates); err != nil { + log.Printf("Pet dismissal: %v", err) + } + continue + } if pet.health == 0 || pet.playfield != owner.playfield || !now.Before(pet.pet.expiresAt) { continue } diff --git a/server/pets.go b/server/pets.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "maps" + "slices" "time" ) @@ -155,33 +156,48 @@ func (server *server) loadPets() error { } func (server *server) expirePets_locked(now time.Time, updates map[*worldClient][][]byte) { - pending := server.petExpiry - server.petExpiry = nil - for _, pet := range pending { + for index := 0; index < len(server.petExpiry); { + pet := server.petExpiry[index] if now.Before(pet.pet.expiresAt) { - server.petExpiry = append(server.petExpiry, pet) + index++ continue } - id := pet.id - var removed uint32 - if err := server.db.QueryRow("DELETE FROM characters WHERE id=? RETURNING id", id).Scan(&removed); err != nil { + if err := server.retirePet_locked(pet, updates); err != nil { log.Printf("Pet expiry: %v", err) - server.petExpiry = append(server.petExpiry, pet) + index++ + } + } +} + +func (server *server) retirePet_locked(pet *character, updates map[*worldClient][][]byte) error { + // Commit entity and cascading ownership deletion before publishing retirement. + tx, err := server.db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + var removed uint32 + if err := tx.QueryRow("DELETE FROM characters WHERE id=? RETURNING id", pet.id).Scan(&removed); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return err + } + + owner := server.characters[pet.pet.owner] + delete(owner.pets, pet.id) + delete(server.characters, pet.id) + delete(server.savedNPCs, pet.id) + server.petExpiry = slices.DeleteFunc(server.petExpiry, func(other *character) bool { return other.id == pet.id }) + for _, client := range server.clients { + if !client.ready || client.id != owner.id && server.characters[client.id].playfield != pet.playfield { continue } - owner := server.characters[pet.pet.owner] - delete(owner.pets, id) - delete(server.characters, id) - delete(server.savedNPCs, id) - for _, client := range server.clients { - if !client.ready || client.loading || server.characters[client.id].playfield != pet.playfield { - continue - } - updates[client] = append(updates[client], petIdentityPacket(0x58742a0f, owner.id, id), petCounterPacket(owner)) - if client.npcs[id] { - delete(client.npcs, id) - updates[client] = append(updates[client], n3Packet(0x36510078, 50000, id, nil)) - } + updates[client] = append(updates[client], petIdentityPacket(0x58742a0f, owner.id, pet.id), petCounterPacket(owner)) + if client.npcs[pet.id] { + delete(client.npcs, pet.id) + updates[client] = append(updates[client], n3Packet(0x36510078, 50000, pet.id, nil)) } } + return nil } diff --git a/tools/client/test_pet_dismiss.mjs b/tools/client/test_pet_dismiss.mjs @@ -0,0 +1,94 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output, phase] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +const games = [], evidence = {commands: []}; +const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id); +try { + for (let index = 0; index < 2; index++) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'pet-cast-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + } + const [owner] = games; + const state = async () => (await owner.page.request.get(url + '/test-state')).json(); + if (phase === 'live') { + await Promise.all(games.map(game => game.wait('two independently owned pets', () => + actor(game, 1000001) && actor(game, 1000002) && actor(game, 1).stats[458] === 1 && actor(game, 2).stats[458] === 1))); + evidence.before = await state(); + evidence.peerBefore = games.map(game => actor(game, 1000002).position); + + async function command(text, code) { + const sequence = owner.sequence; + await owner.key('Enter'); + await owner.page.keyboard.type('/pet ' + text); + await owner.key('Enter'); + await owner.wait('native pet ' + text + ' request', () => owner.events.some(event => + event.sequence > sequence && event.direction === 'framesent' && event.opcode === '6b333303')); + const sent = owner.events.find(event => event.sequence > sequence && event.direction === 'framesent' && event.opcode === '6b333303'); + const packet = Buffer.from(sent.hex, 'hex'); + assert.deepEqual([29, 33, 37, 41, 45].map(offset => packet.readUInt32BE(offset)), [code, 0, 1009, 0, 0]); + evidence.commands.push({text, sent}); + } + + await command('follow', 1); + await owner.wait('owned pet has its native follow controller', () => owner.events.some(event => + event.direction === 'framereceived' && event.opcode === '260f3671' && Buffer.from(event.hex, 'hex').readUInt32BE(24) === 1000001)); + const start = owner.local().position; + await owner.hold('KeyW', 'owner moves three metres with its follower', snapshot => owner.local(snapshot).position[2] > start[2] + 3); + await command('terminate', 10); + await Promise.all(games.map(game => game.wait('owned pet retires while the peer remains', () => + !actor(game, 1000001) && actor(game, 1000002) && actor(game, 1).stats[458] === 0 && actor(game, 1).stats[251] === 0))); + evidence.dismissed = await state(); + assert.deepEqual(evidence.dismissed.owners.map(owner => owner.pets), [[], [1000002]]); + assert.deepEqual(evidence.dismissed.owners.map(owner => owner.nano), [25, 25]); + assert.equal(evidence.dismissed.savedPets, 1); + evidence.removals = games.map(game => game.events.filter(event => { + if (event.direction !== 'framereceived' || !['58742a0f', '36510078'].includes(event.opcode)) return false; + const packet = Buffer.from(event.hex, 'hex'); + return event.opcode === '58742a0f' ? packet.readUInt32BE(33) === 1000001 : packet.readUInt32BE(24) === 1000001; + })); + evidence.removals.forEach(events => assert.deepEqual(events.map(event => event.opcode), ['58742a0f', '36510078'])); + games.forEach((game, index) => assert.deepEqual(actor(game, 1000002).position, evidence.peerBefore[index])); + await Promise.all(games.map((game, index) => game.save(output + '/dismissed-' + index))); + + // A real Programs cast verifies that dismissal released the original packed limit. + await owner.page.keyboard.press('Control+8'); + await owner.click(987, 96); + await owner.wait('original summon program visible', snapshot => snapshot.grids.some(grid => grid.cells.some(cell => + cell.identity[0] === 53019 && cell.identity[1] === 43324 && !cell.dummy))); + const cell = owner.state.grids.flatMap(grid => grid.cells).find(cell => cell.identity[0] === 53019 && cell.identity[1] === 43324); + await owner.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2, 'right'); + await Promise.all(games.map(game => game.wait('replacement uses a new owned identity', () => + actor(game, 1000003) && !actor(game, 1000001) && actor(game, 1).stats[458] === 1))); + evidence.replacement = await state(); + await Promise.all(games.map(async game => { await game.page.reload(); await game.ready(); await game.snapshot(); })); + } + await Promise.all(games.map(game => game.wait('replacement and peer replay once', () => + actor(game, 1000003) && actor(game, 1000002) && !actor(game, 1000001) && + actor(game, 1).stats[458] === 1 && actor(game, 2).stats[458] === 1))); + evidence.final = await state(); + assert.deepEqual(evidence.final.owners.map(owner => owner.pets), [[1000003], [1000002]]); + assert.deepEqual(evidence.final.owners.map(owner => owner.nano), [15, 25]); + assert.equal(evidence.final.savedPets, 2); + assert.equal(evidence.final.nextNPC, 1000004); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS:', phase, 'native owned dismissal, unchanged peer, real replacement cast and page/cold recovery'); +} finally { + try { + await fs.mkdir(output, {recursive: true}); + await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n'); + await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); + } finally { await browser.close(); } +} diff --git a/tools/client/test_pet_owner_protocol.mjs b/tools/client/test_pet_owner_protocol.mjs @@ -66,6 +66,15 @@ try { evidence.wait = owner.events.find(event => event.sequence > wait && event.direction === 'framesent' && event.opcode === '6b333303'); const waitPacket = Buffer.from(evidence.wait.hex, 'hex'); assert.deepEqual([29, 33, 37, 41, 45].map(offset => waitPacket.readUInt32BE(offset)), [4, 0, 1009, 0, 0]); + const terminate = owner.sequence; + await owner.key('Enter'); + await owner.page.keyboard.type('/pet terminate'); + await owner.key('Enter'); + await owner.wait('native terminate request for the owner pet set', () => owner.events.some(event => + event.sequence > terminate && event.direction === 'framesent' && event.opcode === '6b333303')); + evidence.terminate = owner.events.find(event => event.sequence > terminate && event.direction === 'framesent' && event.opcode === '6b333303'); + const terminatePacket = Buffer.from(evidence.terminate.hex, 'hex'); + assert.deepEqual([29, 33, 37, 41, 45].map(offset => terminatePacket.readUInt32BE(offset)), [10, 0, 1009, 0, 0]); assert((await owner.page.request.post(url + '/test-counter')).ok()); await Promise.all(games.map(game => game.wait('packed count is independent from owner list size', () => actor(game, 1).stats[251] === 1))); evidence.counter = counts(); @@ -74,7 +83,7 @@ try { evidence.unlinked = counts(); assert(evidence.unlinked.every(value => value.ownerPacked === 1)); assert(games.every(game => game.errors.length === 0)); - console.log('PASS: original Add/RemovePet owner list, duplicate identity, native report request and independent packed counter'); + console.log('PASS: original owner list, duplicate identity, native report/follow/wait/terminate requests and independent packed counter'); } finally { try { await fs.mkdir(output, {recursive: true});