Files
aeternalis/server/internal/transport/service.go
T
dingoandClaude Sonnet 5 9454b51914 perf: take the admin-command DB poll off the world tick's global lock
Testing one specific, targeted hypothesis rather than another blind
patch: the portal merge added an unconditional per-second DB query
(controls(), checking for pending admin commands) directly inside the
world tick loop's s.mu-locked section -- the same lock every websocket
intent, every HTTP handler, and every snapshot broadcast to every
connected player depends on. That runs forever, for every world,
whether or not the admin feature is ever used.

Verified the actual game logic isn't broken (a live-instrumented run
of the unpatched single-shot gather/attack code landed its first hit
immediately and correctly), so the e2e flakiness has to be about
something making the server slower under load rather than a logic
defect. This is the one change in the merge positioned to tax *every*
player's snapshot/intent latency, every second, permanently -- not
just an occasional per-request cost like the other additions.

controls() now runs on its own ticker, independent of the simulation
tick, and only takes s.mu at all if there's an actual pending command
to apply (the DB read itself needs no lock -- world.ID is immutable
after creation). The idle case, which is the overwhelming majority of
ticks, no longer touches s.mu for this at all.

Verified: go build/vet/test clean, and the full local e2e suite (7/7,
both spec files, including the admin-command test that exercises
controls() directly) passes across two runs.

If this doesn't change CI's result, it should be reverted and ruled
out -- the next candidate would be the new /worlds/<id> routing
rewrite or the added per-request ActiveCharacter DB lookups.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-06 13:55:15 -04:00

251 lines
6.3 KiB
Go

package transport
import (
"context"
"encoding/json"
"errors"
"log/slog"
"maps"
"sync"
"sync/atomic"
"time"
"aeternalis/server/internal/game"
p "aeternalis/server/internal/protocol"
"aeternalis/server/internal/store"
)
type peer struct {
character string
out chan []byte
known map[string]bool
close func()
}
type Service struct {
mu sync.Mutex
world *game.World
lease *store.Lease
peers map[string]*peer
ready atomic.Bool
lastSave time.Time
done chan struct{}
}
func NewService(w *game.World, l *store.Lease) *Service {
s := &Service{world: w, lease: l, peers: map[string]*peer{}, lastSave: time.Now(), done: make(chan struct{})}
s.ready.Store(true)
return s
}
func (s *Service) persist(ctx context.Context, claim string) error {
err := s.lease.Save(ctx, s.world, claim)
if err != nil {
s.ready.Store(false)
slog.Error("world frozen: persistence failed", "error", err)
for _, p := range s.peers {
p.close()
}
return err
}
s.lastSave = time.Now()
return nil
}
func (s *Service) Run(ctx context.Context) {
defer close(s.done)
// Runs on its own cadence rather than inline in the tick below: it does a real DB
// round-trip, and that must never sit behind s.mu while the common case (no pending
// admin commands) still pays for it every second, for every world, forever -- that
// would tax every player's snapshot delivery and intent handling on this single
// global lock for a feature most ticks have nothing to do.
go s.runControls(ctx)
ticker := time.NewTicker(time.Second / time.Duration(s.world.Balance.TickHz))
defer ticker.Stop()
last := time.Now()
for {
select {
case <-ctx.Done():
return
case now := <-ticker.C:
s.mu.Lock()
if !s.ready.Load() {
s.mu.Unlock()
return
}
s.world.Advance(now, now.Sub(last).Seconds())
last = now
if s.world.Dirty() || now.Sub(s.lastSave) >= time.Second {
saveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := s.persist(saveCtx, "")
cancel()
if err != nil {
s.mu.Unlock()
return
}
}
if s.world.Tick%int64(s.world.Balance.TickHz/s.world.Balance.SnapshotHz) == 0 {
for id, p := range s.peers {
snapshot := s.world.Snapshot(id, p.known)
data, err := json.Marshal(snapshot)
if err != nil {
slog.Error("snapshot encoding failed", "error", err)
p.close()
continue
}
select {
case p.out <- data:
for key := range p.known {
delete(p.known, key)
}
for _, key := range snapshot.ChunkKeys {
p.known[key] = true
}
default:
p.close()
}
}
}
s.mu.Unlock()
}
}
}
func (s *Service) Stop(ctx context.Context) error {
s.mu.Lock()
defer s.mu.Unlock()
wasReady := s.ready.Swap(false)
for id, p := range s.peers {
s.world.Disconnect(id)
p.close()
}
if !wasReady {
return errors.New("world already frozen; lease will expire")
}
if err := s.lease.Save(ctx, s.world, ""); err != nil {
return err
}
return s.lease.Release(ctx)
}
func (s *Service) join(ctx context.Context, account, name, claim string) (p.Character, error) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.ready.Load() {
return p.Character{}, errors.New("world unavailable")
}
var c *game.Character
var err error
active, err := s.lease.DB.ActiveCharacter(ctx, account)
if err != nil {
return p.Character{}, errors.New("character registry unavailable")
}
if active != nil {
transfer := claim != "" && active.ID == claim && active.State == "eligible" && active.WorldID != s.world.ID
resume := claim == "" && active.WorldID == s.world.ID
if !transfer && !resume {
return p.Character{}, store.ErrLivingCharacter
}
}
existing := s.world.ForAccount(account)
if claim != "" {
c, err = s.lease.DB.ReadPassage(ctx, claim, account)
if err != nil {
return p.Character{}, errors.New("passage unavailable")
}
if err = s.world.Import(c); err != nil {
return p.Character{}, err
}
} else {
c, err = s.world.Join(account, name)
if err != nil {
return p.Character{}, err
}
}
if err = s.lease.Save(ctx, s.world, claim); err != nil {
if errors.Is(err, store.ErrLivingCharacter) {
if existing == nil {
delete(s.world.Characters, c.View.Entity.ID)
}
return p.Character{}, err
}
s.ready.Store(false)
for _, peer := range s.peers {
peer.close()
}
return p.Character{}, errors.New("world persistence unavailable")
}
s.lastSave = time.Now()
view := c.View
view.Inventory = maps.Clone(view.Inventory)
view.Skills = maps.Clone(view.Skills)
return view, nil
}
// runControls polls for pending admin commands on its own cadence, independent of the
// simulation tick, so an idle world (the overwhelming common case) never holds s.mu for
// a database round-trip it didn't need.
func (s *Service) runControls(ctx context.Context) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if !s.ready.Load() {
return
}
if err := s.controls(ctx); err != nil {
s.mu.Lock()
s.ready.Store(false)
for _, p := range s.peers {
p.close()
}
s.mu.Unlock()
return
}
}
}
}
func (s *Service) controls(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
// Read-only, and s.world.ID never changes after creation: safe to query without s.mu.
commands, err := s.lease.DB.Commands(ctx, s.world.ID, true)
if err != nil || len(commands) == 0 {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if !s.ready.Load() {
return nil
}
for _, command := range commands {
result := ""
if time.Now().Unix()-command.CreatedAt > 900 {
result = "command expired before execution"
} else if command.Op == "revoke-sessions" {
found := false
for id, c := range s.world.Characters {
if c.Account == command.Target {
found = true
s.world.Disconnect(id)
if p := s.peers[id]; p != nil {
p.close()
}
}
}
if !found {
result = "account not found in world"
}
} else if err = s.world.Control(command.Op, command.Target, command.Value, command.Reason); err != nil {
result = err.Error()
}
if err = s.lease.SaveCommand(ctx, s.world, "", &command, result); err != nil {
s.ready.Store(false)
for _, peer := range s.peers {
peer.close()
}
return err
}
s.lastSave = time.Now()
}
return nil
}