Revert "perf: take the admin-command DB poll off the world tick's global lock"

This reverts commit 9454b51914.
This commit is contained in:
dingo
2026-09-06 14:02:00 -04:00
parent 9454b51914
commit 7375fc6638
+17 -46
View File
@@ -22,13 +22,14 @@ type peer struct {
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{}
mu sync.Mutex
world *game.World
lease *store.Lease
peers map[string]*peer
ready atomic.Bool
lastSave time.Time
lastControl time.Time
done chan struct{}
}
func NewService(w *game.World, l *store.Lease) *Service {
@@ -51,12 +52,6 @@ func (s *Service) persist(ctx context.Context, claim string) error {
}
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()
@@ -72,6 +67,14 @@ func (s *Service) Run(ctx context.Context) {
}
s.world.Advance(now, now.Sub(last).Seconds())
last = now
if now.Sub(s.lastControl) >= time.Second {
if err := s.controls(ctx); err != nil {
s.ready.Store(false)
s.mu.Unlock()
return
}
s.lastControl = now
}
if s.world.Dirty() || now.Sub(s.lastSave) >= time.Second {
saveCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := s.persist(saveCtx, "")
@@ -177,45 +180,13 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
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 {
if err != nil {
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 {