fix(server): keep live game sessions active during long battles

This commit is contained in:
Flechazo committed 2026-10-25 20:59:35 +08:00
1 parent 03b2471106
commit 8123ddf321
8 files changed
+205 -1

No files matched your search

+20
View File
@@ -141,6 +141,26 @@ func (r *playerRegistry) Acquire(ctx context.Context, accountID string) (*player
}
}
// Touch records authenticated traffic without loading an absent player.
func (r *playerRegistry) Touch(accountID string, generation uint64) bool {
r.mu.Lock()
defer r.mu.Unlock()
slot := r.players[accountID]
if r.closing || slot == nil || slot.retiring {
return false
}
select {
case <-slot.ready:
if slot.err != nil || slot.runtime == nil || slot.runtime.Generation() != generation {
return false
}
slot.lastUsed = time.Now()
return true
default:
return false
}
}
func (r *playerRegistry) load(accountID string, slot *playerSlot) {
r.mu.Lock()
if r.closing {
@@ -304,3 +304,59 @@ func TestRegistryShutdownClosesLoadingAndLeasedAccountWriters(t *testing.T) {
}
}
}
func TestRegistryHeartbeatKeepsGenerationUntilTrafficStops(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
registry := newPlayerRegistry(factory, 15*time.Minute)
t.Cleanup(func() {
if err := registry.Close(context.Background()); err != nil {
t.Error(err)
}
})
runtime, release, err := registry.Acquire(context.Background(), accounts[0])
if err != nil {
t.Fatal(err)
}
generation := runtime.Generation()
release()
registry.mu.Lock()
slot := registry.players[accounts[0]]
slot.lastUsed = time.Now().Add(-21 * time.Minute)
stale := slot.lastUsed
registry.mu.Unlock()
if registry.Touch("absent-player", generation) || registry.Touch(accounts[0], generation+1) {
t.Fatal("unknown player or stale generation accepted")
}
registry.mu.Lock()
unchanged := slot.lastUsed.Equal(stale) && slot.leases == 0 && len(registry.players) == 1
registry.mu.Unlock()
if !unchanged {
t.Fatal("invalid heartbeat loaded or renewed a player")
}
if !registry.Touch(accounts[0], generation) {
t.Fatal("current resident heartbeat rejected")
}
registry.expire(time.Now())
current, release, err := registry.Acquire(context.Background(), accounts[0])
if err != nil {
t.Fatal(err)
}
if current != runtime || current.Generation() != generation {
release()
t.Fatal("active game replaced during local battle")
}
registryExecute(t, current, registryCommand(accounts[0], "after-long-local-battle", "/EquipInfo", appScalar(1, 1)))
release()
registry.expire(time.Now().Add(16 * time.Minute))
if registry.Touch(accounts[0], generation) {
t.Fatal("expired player resurrected")
}
replacement, release, err := registry.Acquire(context.Background(), accounts[0])
if err != nil {
t.Fatal(err)
}
defer release()
if replacement.Generation() == generation || registry.Touch(accounts[0], generation) {
t.Fatal("old generation accepted after reload")
}
}
+2 -1
View File
@@ -102,6 +102,7 @@ func Serve(args []string) (serveErr error) {
if err != nil {
return err
}
game.TouchPlayer = registry.Touch
shared.friends.AttachPresence(game.AccountOnline)
var authHandler http.Handler
@@ -167,7 +168,7 @@ func Serve(args []string) (serveErr error) {
}
dispatcher := transport.Bootstrap{Config: c.bootstrap, Notices: c.notices, LoginsClosed: loginsClosed, Broadcast: game.Broadcast}
handler := transport.HTTP{
Dispatcher: dispatcher, Raw: game, Authentication: c.authentication,
Dispatcher: dispatcher, Raw: game, SessionActivity: game.RecordCookieActivity, Authentication: c.authentication,
AuthenticationHandler: authHandler, ResourcePolicy: c.publicResources,
CommerceManifest: func() any { return design.cashCatalog.Manifest() }, Availability: availability, InstanceID: instanceID, RealtimeTickets: realtimeTickets,
StoryCheckpoints: storyCheckpoints{game: game, players: registry}, Console: console.Handler(),
@@ -35,6 +35,9 @@ func TestPresenceExpiresWithoutActivityAndOnlyValidSessionsRenewIt(t *testing.T)
if err != nil {
t.Fatal(err)
}
server.TouchPlayer = func(account string, generation uint64) bool {
return account == "present-player" && generation == runtime.Generation()
}
now := time.Date(2026, 10, 23, 12, 0, 0, 0, time.UTC)
server.now = func() time.Time { return now }
game, token, err := newGameSession("present-player", now, 24*time.Hour)
@@ -84,3 +87,59 @@ func TestPresenceExpiresWithoutActivityAndOnlyValidSessionsRenewIt(t *testing.T)
t.Fatal("expired game session retained presence")
}
}
func TestCookieHeartbeatRequiresCurrentResidentSession(t *testing.T) {
server, err := NewServer(presenceRouter{}, nil)
if err != nil {
t.Fatal(err)
}
now := time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
server.now = func() time.Time { return now }
game, token, err := newGameSession("heartbeat-player", now, time.Hour)
if err != nil {
t.Fatal(err)
}
game.generation = 7
server.sessions[sessionTokenKey(token)] = game
resident := true
calls := 0
server.TouchPlayer = func(account string, generation uint64) bool {
calls++
if account != game.accountID || generation != 7 {
t.Fatalf("wrong identity: %s/%d", account, generation)
}
return resident
}
now = now.Add(2 * time.Minute)
for _, cookie := range []string{"", "s=invalid", "s=" + token + "; s=" + token} {
server.RecordCookieActivity(cookie)
}
if calls != 0 || server.AccountOnline(game.accountID) {
t.Fatal("invalid cookies renewed activity")
}
server.RecordCookieActivity("s=" + token)
if calls != 1 || !server.AccountOnline(game.accountID) {
t.Fatal("valid cookie did not renew presence")
}
now = now.Add(2 * time.Minute)
resident = false
previous := game.lastUsed
server.RecordCookieActivity("s=" + token)
server.RecordActivity(Principal{AccountID: game.accountID, SessionID: game.id, Generation: game.generation})
if !game.lastUsed.Equal(previous) || server.AccountOnline(game.accountID) {
t.Fatal("absent or replaced runtime renewed activity")
}
resident = true
delete(server.sessions, sessionTokenKey(token))
calls = 0
server.RecordCookieActivity("s=" + token)
if calls != 0 {
t.Fatal("superseded cookie reached player")
}
server.sessions[sessionTokenKey(token)] = game
now = game.expiresAt
server.RecordCookieActivity("s=" + token)
if calls != 0 || !game.lastUsed.Equal(previous) {
t.Fatal("expired cookie renewed activity")
}
}
@@ -49,7 +49,27 @@ func (s *Server) ValidatePrincipal(ctx context.Context, p Principal) error {
return nil
}
func (s *Server) RecordCookieActivity(cookie string) {
token, err := parseSessionCookie(cookie)
if err != nil {
return
}
s.mu.Lock()
game := s.sessions[sessionTokenKey(token)]
var p Principal
if game != nil && s.now().Before(game.expiresAt) {
p = Principal{AccountID: game.accountID, SessionID: game.id, Generation: game.generation}
}
s.mu.Unlock()
if p.SessionID != "" {
s.RecordActivity(p)
}
}
func (s *Server) RecordActivity(p Principal) {
if !s.containsPrincipal(p) || s.TouchPlayer == nil || !s.TouchPlayer(p.AccountID, p.Generation) {
return
}
s.mu.Lock()
defer s.mu.Unlock()
now := s.now()
@@ -58,6 +58,7 @@ type Server struct {
now func() time.Time
sessionTTL time.Duration
maxSessions int
TouchPlayer func(accountID string, generation uint64) bool
// Broadcast returns Notify fields appended to every game response.
Broadcast func() []byte
// LoggedIn receives an account's LoginUserRequest.language_type.
@@ -3,6 +3,10 @@ package transport
import (
"bytes"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
@@ -21,3 +25,42 @@ func TestServerNowTimeCarriesTheBroadcastNotify(t *testing.T) {
t.Fatalf("ServerNowTime Notify = %q (%v), want base64 of the broadcast fields", reply.Notify, err)
}
}
func TestTimeHeartbeatRecordsActivityOnlyAfterSuccessfulDispatch(t *testing.T) {
calls := 0
broadcast := []byte{0x38, 0x2a}
handler := HTTP{Dispatcher: Bootstrap{Broadcast: func() []byte { return broadcast }}, SessionActivity: func(cookie string) {
calls++
if cookie != "s=heartbeat" && cookie != "" {
t.Fatalf("unexpected cookie %q", cookie)
}
}}.Handler()
for _, tc := range []struct {
path, body, cookie string
status, activity int
}{
{"/game/ServerNowTime", "", "s=heartbeat", http.StatusOK, 1},
{"/game/ServerNowTime", "", "", http.StatusOK, 1},
{"/game/ServerNowTime", "!invalid!", "s=heartbeat", http.StatusBadRequest, 0},
{"/game/NoticeInfo", "", "s=heartbeat", http.StatusOK, 0},
} {
before := calls
request := httptest.NewRequest(http.MethodPut, tc.path, strings.NewReader(tc.body))
request.Header.Set("Cookie", tc.cookie)
response := httptest.NewRecorder()
handler.ServeHTTP(response, request)
if response.Code != tc.status || calls-before != tc.activity {
t.Fatalf("%s: status=%d activity=%d", tc.path, response.Code, calls-before)
}
if tc.status == http.StatusOK && tc.path == "/game/ServerNowTime" {
var answer Envelope
if err := json.Unmarshal(response.Body.Bytes(), &answer); err != nil {
t.Fatal(err)
}
notify, err := base64.StdEncoding.DecodeString(answer.Notify)
if err != nil || !bytes.Equal(notify, broadcast) {
t.Fatal("heartbeat lost maintenance notification")
}
}
}
}
@@ -132,6 +132,7 @@ func (b Bootstrap) now() time.Time {
type HTTP struct {
Dispatcher Dispatcher
Raw RawDispatcher
SessionActivity func(cookie string)
Logger *slog.Logger
Now func() time.Time
Authentication authconfig.Config
@@ -452,6 +453,9 @@ func (h HTTP) game(w http.ResponseWriter, r *http.Request) {
Secure: h.secureCookies(), SameSite: http.SameSiteLaxMode,
})
}
if path == "/ServerNowTime" && h.SessionActivity != nil {
h.SessionActivity(r.Header.Get("Cookie"))
}
answer := Envelope{PacketCode: reply.PacketCode, Data: base64.StdEncoding.EncodeToString(reply.Data), ServerNowTime: h.now().UnixMilli(), Notify: reply.Notify}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(answer); err != nil {