aorecomp

Anarchy Online classic in the browser

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


commit 021b67796b1f28409acef0ea517c6463eb7fc9fe
parent 1464218e2543fcd707dfb8b5b6f5477301ac5292
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 03:48:51 +0000

Commit completed nano costs and recharge with NPC outcomes

Diffstat:
MTODO.md | 6++++++
Mdocs/nano-damage.md | 37+++++++++++++++++++++++++++++++++++++
Mdocs/world-state.md | 7+++++++
Mserver/control_data_test.go | 2+-
Mserver/nano_casting.go | 9++++++---
Mserver/nano_casting_test.go | 27+++++++++++++++++----------
Aserver/nano_outcome_test.go | 233+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/npc_outcome.go | 36++++++++++++++++++++++++++++++++++++
8 files changed, 343 insertions(+), 14 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -842,6 +842,12 @@ and server restarts. Turn every reproduced bug into a focused regression test. - [ ] Audit nano learning and casting. Cover unmet requirements, duplicates, missing resources, interruption/cancellation, invalid or changing targets, recharge boundaries and interaction with queued weapon results. + Winter's Bite completion now commits caster nano/recharge with NPC health, + contributions and any corpse/respawn state before releasing its native result. + Continue auditing in-progress reservations: a routine vitals checkpoint can + save the temporary debit before completion, while the pending cast itself is + session state. Test crash/restart and cancelled-cast refund persistence across + that boundary, including resource gains while the cast is pending. - [ ] Audit derived stats and equipment bonuses. Cover equip/remove/reconnect, combinations of modifiers, overequipping boundaries, native display versus server arithmetic and removal of exactly the applicable contribution. diff --git a/docs/nano-damage.md b/docs/nano-damage.md @@ -112,6 +112,43 @@ above. Exact evidence, original bytes, arithmetic experiments and bounded unknowns are retained in `local/nano-damage-research/`, `local/nano-casting-research/` and `local/fpu-precision-research/`. +## Completed-cast persistence + +Completion commits the caster's current nano and recharge deadline with the +victim's health, damage contributions and any corpse/respawn transition in one +SQLite transaction. This applies to surviving victims as well as kills. Action +107 and the damage/death packets follow the commit. A missing or ignored caster +update fails the transaction. Detached caster/victim copies and persistence +caches are published only after commit; a failed outcome instead cancels the +pending cast and applies the existing in-memory refund. + +Only nano and nano recharge are written for the caster. Dirty health, posture, +position and other routine simulation values keep their checkpoint cadence. +`server/nano_outcome_test.go` reads SQLite during the first outgoing completion +and reopens it before any checkpoint. It covers lethal/nonlethal results, +cost/recharge/NPC/contribution failures, ignored writes, failed COMMIT, retry, +concurrent completion, output failure and recharge enforcement after restart. +The casting fixture now persists a valid caster row instead of relying on an +unpersisted synthetic actor. + +In-progress reservation recovery remains a separate TODO. Admission debits +available nano in memory, so a periodic vitals checkpoint can save that temporary +debit even though the pending cast belongs to the connection. A crash after that +checkpoint can lose the eventual refund. Completion durability does not resolve +this reservation lifecycle or establish the original server's refund policy. + +A published two-client WASM run used the normal target selection and program +window. At the first received action 107, SQLite already held nano 65 from +the pre-cast 74, a recharge deadline, victim HP 85 and a 15-point contribution. +Both native clients displayed 85 HP. After ordinary recovery and an ungraceful +server stop, the saved rows were unchanged on startup and the owner restored +73 nano. The NPC's saved 88 HP recovered to 100 while the clients loaded; +that later value is not an additional cast result. Both clients had no page or +adapter errors. Test profiles, learned programs, NPC state and contributions +were restored, and all 192 item records and placements remained unchanged. +The full server suite and focused/repeated race checks pass. Captures, first- +packet SQL reads and checked results are in `local/nano-outcome-research/`. + ## Verification `TestWinterBite*` covers learning and persistence, requirement boundaries, diff --git a/docs/world-state.md b/docs/world-state.md @@ -43,6 +43,13 @@ or nano commit before success reaches the client, including when the last charge destroys its item instance. A missing or ignored recipient write fails the transaction. Only the recipient's vital columns are written; positions keep their normal checkpoint cadence. The vital cache changes only after commit. +Completed Winter's Bite casts commit the caster's nano/recharge and the NPC's +health, contributors and death/respawn state together before releasing the +native result. Caster updates touch only nano and nano recharge; routine health +and position remain dirty until their checkpoint. Failed or ignored caster +writes and failed commits publish no damage. In-progress cast reservations +remain session state and still need crash/refund recovery across checkpoints; +see [nano outcome persistence](nano-damage.md#completed-cast-persistence). The world header is updated only when its counters, clock or population-initialization state change. NPC state is checked diff --git a/server/control_data_test.go b/server/control_data_test.go @@ -362,7 +362,7 @@ func TestControlCharacterDocumentPreservesCastRefundAndExplicitNanoEdits(t *test for _, contents := range []string{"name: Edited\n", "name: Edited\nvitals: {nano: 13}\n"} { t.Run(contents, func(t *testing.T) { t.Chdir(t.TempDir()) - world, _ := newNanoCastingWorld() + world, _ := newNanoCastingWorld(t) world.baseURL = "/" player, client := world.characters[1], world.clients[1] if err := world.saveUser_locked(player); err != nil { diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -153,14 +153,17 @@ func (server *server) advanceNanos(now time.Time) { // Only this result changes HP; the native Hit effect is server-owned. damage := min(10+rand.Uint32N(14), target.health) - if err := server.applyDamage_locked(player, target, damage, now); err != nil { + victim := prepareDamage(player, target, damage, now) + caster := *player + recharge := float64(itemStat(gamedata.NanoTemplates[29618], 210)) * float64(float32(0.01)) + caster.nanoRechargeUntil = now.Add(time.Duration(recharge * float64(time.Second))) + if err := server.saveNanoHit_locked(&caster, &victim, now); err != nil { log.Printf("Nano damage: %v", err) server.abortNano_locked(client, now, updates) continue } + *player, *target = caster, victim client.nanoCast = nil - recharge := float64(itemStat(gamedata.NanoTemplates[29618], 210)) * float64(float32(0.01)) - player.nanoRechargeUntil = now.Add(time.Duration(recharge * float64(time.Second))) body := binary.BigEndian.AppendUint32(nil, uint32(-int32(damage))) body = binary.BigEndian.AppendUint32(body, 95) server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, 29618})) diff --git a/server/nano_casting_test.go b/server/nano_casting_test.go @@ -9,9 +9,12 @@ import ( "time" ) -func newNanoCastingWorld() (*server, *combatTestConn) { +func newNanoCastingWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + t.Chdir(t.TempDir()) world, conn := newCombatWorld() player := world.characters[1] + player.name = "Nano Caster" player.profession, player.nano = 8, 30 player.appearance, player.level = 0x315, 1 player.rotation[3] = 1 @@ -19,11 +22,15 @@ func newNanoCastingWorld() (*server, *combatTestConn) { player.stats.NanoAiding.PsychologicalModification, player.stats.NanoAiding.MatterCreation = 7, 6 player.health = player.maximumHealth() player.inventory.LearnedNanos = []uint32{29618} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { world.db.Close() }) return world, conn } func TestWinterBiteTimesOneResultAndRecharge(t *testing.T) { - world, conn := newNanoCastingWorld() + world, conn := newNanoCastingWorld(t) player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] request := characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:] observer := &combatTestConn{} @@ -61,7 +68,7 @@ func TestWinterBiteTimesOneResultAndRecharge(t *testing.T) { func TestWinterBiteRejectsInvalidAdmission(t *testing.T) { for _, scenario := range []string{"unlearned", "profession", "psychology", "creation", "nano", "sitting", "forward", "strafe", "turn", "equipment", "weapon attack", "hidden", "dead target", "player target", "wrong zone", "range", "range vertical", "wrong program", "wrong resource", "foreign owner", "loading", "not ready", "stale", "dead caster"} { t.Run(scenario, func(t *testing.T) { - world, _ := newNanoCastingWorld() + world, _ := newNanoCastingWorld(t) player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] fields := [5]uint32{19, 50000, npc.id, 53019, 29618} owner := uint32(1) @@ -131,7 +138,7 @@ func TestWinterBiteNativeTimingAndRangeBoundary(t *testing.T) { delay time.Duration }{{0, 2575000047}, {100, 1574999928}, {-100, 3575000047}} { t.Run(time.Duration(scenario.agg).String(), func(t *testing.T) { - world, _ := newNanoCastingWorld() + world, _ := newNanoCastingWorld(t) player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] player.aggDef = scenario.agg npc.position = [3]float32{15, 20, 0} @@ -148,7 +155,7 @@ func TestWinterBiteNativeTimingAndRangeBoundary(t *testing.T) { func TestWinterBiteCancellationAndInvalidatedTargetRefundOnce(t *testing.T) { for _, scenario := range []string{"request", "target moved", "target dead", "hidden", "lifecycle"} { t.Run(scenario, func(t *testing.T) { - world, conn := newNanoCastingWorld() + world, conn := newNanoCastingWorld(t) player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, npc.id, 53019, 29618})[20:]) deadline := client.nanoCast.readyAt @@ -181,7 +188,7 @@ func TestWinterBiteCancellationAndInvalidatedTargetRefundOnce(t *testing.T) { func TestWinterBiteDeathUsesSharedLootAndStopsPendingWeapons(t *testing.T) { t.Chdir(t.TempDir()) - world, conn := newNanoCastingWorld() + world, conn := newNanoCastingWorld(t) t.Cleanup(func() { world.db.Close() }) player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] npc.health, npc.monsterData = 1, 17655 @@ -202,7 +209,7 @@ func TestWinterBiteDeathUsesSharedLootAndStopsPendingWeapons(t *testing.T) { } func TestWinterBiteConcurrentRequestsReserveOneCost(t *testing.T) { - world, conn := newNanoCastingWorld() + world, conn := newNanoCastingWorld(t) client := world.clients[1] request := characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:] var workers sync.WaitGroup @@ -239,7 +246,7 @@ func TestWinterBiteMovementCancelsBeforeDelayedResult(t *testing.T) { for _, action := range []uint32{1, 3, 5, 7, 13} { t.Run(time.Duration(action).String(), func(t *testing.T) { t.Chdir(t.TempDir()) - world, _ := newNanoCastingWorld() + world, _ := newNanoCastingWorld(t) player, client := world.characters[1], world.clients[1] world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]) deadline := client.nanoCast.readyAt @@ -254,7 +261,7 @@ func TestWinterBiteMovementCancelsBeforeDelayedResult(t *testing.T) { } func TestWinterBiteWeaponRechargeCannotAccelerateAnAttack(t *testing.T) { - world, _ := newNanoCastingWorld() + world, _ := newNanoCastingWorld(t) player, client, npc := world.characters[1], world.clients[1], world.characters[1000000] world.handleCombat(client, attackPacket(1, npc.id)[20:]) player.rechargeUntil = time.Now().Add(time.Second) @@ -271,7 +278,7 @@ func TestWinterBiteWeaponRechargeCannotAccelerateAnAttack(t *testing.T) { func TestWinterBiteProfileChangeRefundsPendingCast(t *testing.T) { t.Chdir(t.TempDir()) - world, _ := newNanoCastingWorld() + world, _ := newNanoCastingWorld(t) player, client := world.characters[1], world.clients[1] if err := world.saveUser_locked(player); err != nil { t.Fatal(err) diff --git a/server/nano_outcome_test.go b/server/nano_outcome_test.go @@ -0,0 +1,233 @@ +package main + +import ( + "ao/server/gamedata" + "context" + "database/sql" + "encoding/binary" + "reflect" + "sync" + "testing" + "time" +) + +func newNanoOutcomeWorld(t *testing.T, health uint32) (*server, *combatTestConn) { + t.Helper() + world, conn := newRangedWorld(t) + player := world.characters[1] + player.profession, player.nano = 8, 30 + player.stats.NanoAiding.PsychologicalModification, player.stats.NanoAiding.MatterCreation = 7, 6 + player.health = player.maximumHealth() + player.inventory.Items = nil + player.inventory.LearnedNanos = []uint32{29618} + target := world.characters[1000000] + target.health, target.monsterData, target.level = health, 17655, 1 + target.combatProfile = gamedata.NPCCombatProfiles[17655][1] + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + conn.packets = nil + return world, conn +} + +func TestNanoOutcomeFailureRefundsWithoutPublishingDamageAndCanRetry(t *testing.T) { + for _, health := range []uint32{100, 1} { + for _, failure := range []struct{ name, statement string }{ + {"cost", "CREATE TRIGGER fail_nano BEFORE UPDATE OF nano ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'test cost'); END"}, + {"ignored cost", "CREATE TRIGGER fail_nano BEFORE UPDATE OF nano ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(IGNORE); END"}, + {"recharge", "CREATE TRIGGER fail_nano BEFORE UPDATE OF nano_recharge_until ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'test recharge'); END"}, + {"NPC", "CREATE TRIGGER fail_nano BEFORE UPDATE ON npcs WHEN NEW.id=1000000 BEGIN SELECT RAISE(FAIL, 'test target'); END"}, + {"contributions", "CREATE TRIGGER fail_nano BEFORE DELETE ON npc_damage_contributors BEGIN SELECT RAISE(FAIL, 'test contributions'); END"}, + {"commit", "CREATE TABLE pending_nano (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_nano AFTER UPDATE OF nano ON characters WHEN NEW.id=1 BEGIN INSERT INTO pending_nano VALUES (999999); END"}, + } { + t.Run(map[uint32]string{100: "survivor", 1: "kill"}[health]+"/"+failure.name, func(t *testing.T) { + world, conn := newNanoOutcomeWorld(t, health) + target, client := world.characters[1000000], world.clients[1] + target.damageContributors = map[damageContributor]uint32{{player: 1}: 5} + target.leadingContributor = damageContributor{player: 1} + if err := world.flushWorld(); err != nil { + t.Fatal(err) + } + before := world.savedNPCs[1000000] + request := characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 29618})[20:] + if err := world.handleNanoCast(client, request); err != nil { + t.Fatal(err) + } + at := client.nanoCast.readyAt.Add(time.Nanosecond) + if _, err := world.db.Exec(failure.statement); err != nil { + t.Fatal(err) + } + conn.packets = nil + + world.advanceNanos(at) + restored := newTestInventoryServer(t) + + player := world.characters[1] + if player.nano != 30 || !player.nanoRechargeUntil.IsZero() || client.nanoCast != nil || + target.health != health || target.corpse != nil || target.damageContributors[damageContributor{player: 1}] != 5 || + len(world.npcRespawns) != 0 || len(world.corpseExpiry) != 0 || !reflect.DeepEqual(world.savedNPCs[1000000], before) || + restored.characters[1].nano != 30 || !restored.characters[1].nanoRechargeUntil.IsZero() || restored.characters[1000000].health != health || + restored.characters[1000000].damageContributors[damageContributor{player: 1}] != 5 { + t.Fatal("failed nano transaction changed resources, damage, contributions or death state") + } + if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 108 || binary.BigEndian.Uint32(conn.packets[1][33:37]) != 30 { + t.Fatalf("failed nano published a result instead of cancellation/refund: %x", conn.packets) + } + + // Remove the fault and make one fresh cast; a later tick cannot repeat it. + if _, err := world.db.Exec("DROP TRIGGER fail_nano"); err != nil { + t.Fatal(err) + } + if err := world.handleNanoCast(client, request); err != nil { + t.Fatal(err) + } + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + after := target.health + world.advanceNanos(at.Add(time.Hour)) + retried := newTestInventoryServer(t) + if player.nano != 21 || target.health != after || after >= health || retried.characters[1].nano != 21 || + !retried.characters[1].nanoRechargeUntil.Equal(player.nanoRechargeUntil) || retried.characters[1000000].health != after { + t.Fatal("fresh cast after rollback did not commit exactly one outcome") + } + }) + } + } +} + +func TestNanoOutcomeKeepsRoutinePlayerStateOnItsCheckpoint(t *testing.T) { + world, _ := newNanoOutcomeWorld(t, 100) + player := world.characters[1] + before := player.record() + player.position[0], player.health, player.aggDef = 1, 1, 10 + if _, err := world.db.Exec("CREATE TRIGGER fail_unrelated BEFORE UPDATE OF health,position_x,agg_def ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'test routine state'); END"); err != nil { + t.Fatal(err) + } + client := world.clients[1] + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]); err != nil { + t.Fatal(err) + } + + world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) + restored := newTestInventoryServer(t).characters[1] + + if player.nano != 21 || player.health != 1 || player.position[0] != 1 || restored.nano != 21 || + restored.position != before.Position.Position || restored.health != before.Vitals.Health || restored.aggDef != before.Vitals.AggDef || + player.savedVitals.Health != before.Vitals.Health || player.savedVitals.AggDef != before.Vitals.AggDef || player.savedPosition.Position != before.Position.Position { + t.Fatal("nano outcome checkpointed routine player state or marked it clean") + } +} + +func TestNanoOutcomeOutputFailureKeepsCommittedResultAndRechargeAfterRestart(t *testing.T) { + world, conn := newNanoOutcomeWorld(t, 100) + client := world.clients[1] + request := characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:] + if err := world.handleNanoCast(client, request); err != nil { + t.Fatal(err) + } + client.writeWake, client.writeClosed = make(chan struct{}, 1), true + // Simulate a delayed visit so the restored deadline cannot expire during setup. + at := client.nanoCast.readyAt.Add(time.Minute) + + world.advanceNanos(at) + restored := newTestInventoryServer(t) + output := &combatTestConn{} + restored.clients[1] = &worldClient{id: 1, conn: output, target: true, ready: true, npcs: map[uint32]bool{1000000: true}} + if err := restored.handleNanoCast(restored.clients[1], request); err != nil { + t.Fatal(err) + } + + if len(conn.packets) != 2 || len(output.packets) != 0 || restored.clients[1].nanoCast != nil || + restored.characters[1].nano != 21 || !restored.characters[1].nanoRechargeUntil.Equal(world.characters[1].nanoRechargeUntil) || + restored.characters[1000000].health != world.characters[1000000].health || restored.characters[1000000].health >= 100 { + t.Fatal("output failure lost the result or reconnect bypassed its committed recharge") + } +} + +func TestNanoOutcomeConcurrentCompletionCommitsOneHit(t *testing.T) { + world, conn := newNanoOutcomeWorld(t, 100) + client := world.clients[1] + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]); err != nil { + t.Fatal(err) + } + at := client.nanoCast.readyAt.Add(time.Nanosecond) + var workers sync.WaitGroup + + for range 8 { + workers.Add(1) + go func() { + defer workers.Done() + world.advanceNanos(at) + }() + } + workers.Wait() + restored := newTestInventoryServer(t) + + results := 0 + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x4727213e { + results++ + } + } + if results != 1 || restored.characters[1].nano != 21 || restored.characters[1000000].health < 77 || restored.characters[1000000].health > 90 || + restored.characters[1000000].damageContributors[damageContributor{player: 1}] != 100-restored.characters[1000000].health { + t.Fatal("concurrent completion repeated a cost, result or damage contribution") + } +} + +type nanoCommitConn struct { + combatTestConn + db *sql.DB + observed bool + nano uint32 + health uint32 + recharge time.Time + err error +} + +func (conn *nanoCommitConn) Write(packet []byte) (int, error) { + if !conn.observed && binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 107 { + conn.observed = true + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + conn.err = conn.db.QueryRowContext(ctx, "SELECT caster.nano, caster.nano_recharge_until, victim.health FROM characters caster JOIN characters victim ON victim.id=1000000 WHERE caster.id=1").Scan(&conn.nano, &conn.recharge, &conn.health) + } + return conn.combatTestConn.Write(packet) +} + +func TestNanoOutcomeCommitsCostRechargeAndTargetBeforePublication(t *testing.T) { + for _, health := range []uint32{100, 1} { + t.Run(map[uint32]string{100: "survivor", 1: "kill"}[health], func(t *testing.T) { + world, _ := newNanoOutcomeWorld(t, health) + conn := &nanoCommitConn{db: world.db} + client := world.clients[1] + client.conn = conn + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1000000, 53019, 29618})[20:]); err != nil { + t.Fatal(err) + } + at := client.nanoCast.readyAt.Add(time.Nanosecond) + + world.advanceNanos(at) + restored := newTestInventoryServer(t) + + player, target := world.characters[1], world.characters[1000000] + if !conn.observed || conn.err != nil || conn.nano != 21 || conn.health != target.health || !conn.recharge.Equal(player.nanoRechargeUntil) { + t.Fatalf("nano result preceded its committed outcome: observed=%t nano=%d health=%d recharge=%v error=%v", conn.observed, conn.nano, conn.health, conn.recharge, conn.err) + } + if restored.characters[1].nano != 21 || !restored.characters[1].nanoRechargeUntil.Equal(player.nanoRechargeUntil) || + restored.characters[1000000].health != target.health || world.savedNPCs[1000000].State.Character.Vitals.Health != target.health || + player.savedVitals.Nano != 21 || !player.savedVitals.NanoRechargeUntil.Equal(player.nanoRechargeUntil) { + t.Fatal("completed nano cost, recharge or target reverted before a checkpoint") + } + if health == 1 { + if target.health != 0 || restored.characters[1000000].corpse == nil || restored.characters[1000000].corpse.looter != 1 || len(restored.npcRespawns) != 1 { + t.Fatal("killing nano lost its durable corpse or respawn") + } + } else if target.health < 77 || target.health > 90 || restored.characters[1000000].damageContributors[damageContributor{player: 1}] != 100-target.health { + t.Fatal("surviving target lost its damage or contribution") + } + }) + } +} diff --git a/server/npc_outcome.go b/server/npc_outcome.go @@ -115,3 +115,39 @@ func (server *server) saveRangedHit_locked(gun ownedItem, target *character, now } return nil } + +func (server *server) saveNanoHit_locked(player, target *character, now time.Time) error { + db, err := server.database() + if err != nil { + return err + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + // Commit the completed cast's cost and recharge with its damage and death state. + result, err := tx.Exec("UPDATE characters SET nano=?, nano_recharge_until=? WHERE id=?", player.nano, player.nanoRechargeUntil, player.id) + if err != nil { + return err + } + changed, err := result.RowsAffected() + if err != nil { + return err + } + if changed != 1 { + return fmt.Errorf("caster %d nano update affected %d rows", player.id, changed) + } + state, err := writeNPCOutcome_locked(tx, target, now) + if err != nil { + return err + } + if err := tx.Commit(); err != nil { + return err + } + + player.savedVitals.Nano, player.savedVitals.NanoRechargeUntil = player.nano, player.nanoRechargeUntil + server.rememberNPCOutcome_locked(target, state, now) + return nil +}