diff --git a/api/admin.go b/api/admin.go index 1834bf4..596860e 100644 --- a/api/admin.go +++ b/api/admin.go @@ -30,6 +30,7 @@ type Admin struct { players *Players sockets *Sockets game *Game + lifecycle *Lifecycle connections map[adminSocketConnection]struct{} password string @@ -39,9 +40,10 @@ type Admin struct { socketMutex sync.Mutex } -func (a *Admin) Init(players *Players, sockets *Sockets, password string, games ...*Game) { +func (a *Admin) Init(players *Players, sockets *Sockets, password string, lifecycle *Lifecycle, games ...*Game) { a.players = players a.sockets = sockets + a.lifecycle = lifecycle a.password = password a.cookieValue = base64.RawURLEncoding.EncodeToString([]byte(password)) a.registered = false diff --git a/api/admin_socket.go b/api/admin_socket.go index b083ad3..4edcb90 100644 --- a/api/admin_socket.go +++ b/api/admin_socket.go @@ -3,6 +3,7 @@ package api import ( "encoding/json" "net/http" + "time" ws "github.com/gorilla/websocket" ) @@ -44,6 +45,13 @@ func (a *Admin) ServeSocket(w http.ResponseWriter, r *http.Request) { if err != nil { return } + if a.lifecycle != nil { + if !a.lifecycle.Track(connection) { + _ = connection.Close() + return + } + defer a.lifecycle.Untrack(connection) + } if !a.addConnection(connection) { return } @@ -127,6 +135,7 @@ func (a *Admin) broadcastSocketMessage(message AdminSocketMessage) { a.socketMutex.Lock() defer a.socketMutex.Unlock() for connection := range a.connections { + setAdminWriteDeadline(connection) if err := connection.WriteMessage(ws.TextMessage, JSON); err != nil { delete(a.connections, connection) _ = connection.Close() @@ -139,5 +148,17 @@ func writeAdminSocketMessage(connection adminSocketConnection, message AdminSock if err != nil { return false } + setAdminWriteDeadline(connection) return connection.WriteMessage(ws.TextMessage, JSON) == nil } + +// setAdminWriteDeadline applies the normal write timeout without holding the +// registry mutex during I/O. Connections without a deadline API keep the +// previous behavior for test doubles. +func setAdminWriteDeadline(connection adminSocketConnection) { + if deadlineWriter, ok := connection.(interface { + SetWriteDeadline(time.Time) error + }); ok { + _ = deadlineWriter.SetWriteDeadline(time.Now().Add(socketWriteTimeout)) + } +} diff --git a/api/admin_test.go b/api/admin_test.go index e6bc556..8a6fd50 100644 --- a/api/admin_test.go +++ b/api/admin_test.go @@ -28,8 +28,8 @@ func newAdminTestState(t *testing.T, password string) (*Players, *Admin) { sockets := new(Sockets) admin := new(Admin) players.Init() - sockets.Init(players) - admin.Init(players, sockets, password) + sockets.Init(players, nil) + admin.Init(players, sockets, password, nil) return players, admin } @@ -145,9 +145,9 @@ func TestAdminResetPreservesLeadersAndClearsFlag(t *testing.T) { players.Init() game := new(Game) sockets := new(Sockets) - sockets.Init(players, game) + sockets.Init(players, nil, game) admin := new(Admin) - admin.Init(players, sockets, "top-secret", game) + admin.Init(players, sockets, "top-secret", nil, game) cookie := registerTestAdmin(t, admin, "top-secret") for _, playerType := range []PlayerType{TypeLeader, TypeAntiPacLeader, TypeFlagLeader} { players.New(playerType, TypeString(playerType), StatusDisc) @@ -174,14 +174,70 @@ func TestAdminResetPreservesLeadersAndClearsFlag(t *testing.T) { } } +func TestAdminResetPreservesConnectedSessionsAndLeaderAuthorization(t *testing.T) { + players := new(Players) + players.Init() + game := new(Game) + sockets := new(Sockets) + sockets.Init(players, nil, game) + admin := new(Admin) + admin.Init(players, sockets, "top-secret", nil, game) + cookie := registerTestAdmin(t, admin, "top-secret") + + leaderID := players.New(TypeAntiPacLeader, "Leader", StatusDisc) + activeID := players.New(TypePacman, "Active", StatusDisc) + leaderConnection := newTestConnection(leaderID) + activeConnection := newTestConnection(activeID) + sockets.hub.registerConnection(leaderConnection) + sockets.hub.registerConnection(activeConnection) + drainTestMessages(leaderConnection) + drainTestMessages(activeConnection) + + request := httptest.NewRequest(http.MethodPost, "/api/admin/reset", nil) + request.AddCookie(cookie) + response := httptest.NewRecorder() + admin.ServeHTTP(response, request) + if response.Code != http.StatusNoContent { + t.Fatalf("reset status = %d, want 204", response.Code) + } + + if len(players.players) != 2 { + t.Errorf("player count after reset = %d, want 2", len(players.players)) + } + if leader := players.Get(leaderID); leader == nil || leader.Type != TypeAntiPacLeader { + t.Errorf("leader after reset = %#v, want AntiPac Leader", leader) + } + if active := players.Get(activeID); active == nil || active.Type != TypeGhost { + t.Errorf("active player after reset = %#v, want Ghost", active) + } + if !sockets.hub.hasConnectionForID(leaderID) || !sockets.hub.hasConnectionForID(activeID) { + t.Error("admin reset replaced a connected player session") + } + if leader, _, authorized := players.LeaderState(leaderID); !authorized || leader.ID != leaderID || leader.Type != TypeAntiPacLeader { + t.Errorf("leader authorization after reset = %#v, authorized %v", leader, authorized) + } + + leaderUpdate := informPlayer(t, receiveTestMessage(t, leaderConnection)) + if leaderUpdate.ID != activeID || leaderUpdate.Type != TypeGhost { + t.Errorf("leader's active-player reset update = %#v, want Ghost for %q", leaderUpdate, activeID) + } + updated := informPlayer(t, receiveTestMessage(t, activeConnection)) + if updated.ID != activeID || updated.Type != TypeGhost { + t.Errorf("active reset update = %#v, want Ghost for %q", updated, activeID) + } + if len(leaderConnection.send) != 0 || len(activeConnection.send) != 0 { + t.Errorf("unexpected extra reset messages: leader=%d active=%d", len(leaderConnection.send), len(activeConnection.send)) + } +} + func TestAdminFlagUpdatesSharedStateAndSocketClients(t *testing.T) { players := new(Players) players.Init() game := new(Game) sockets := new(Sockets) - sockets.Init(players, game) + sockets.Init(players, nil, game) admin := new(Admin) - admin.Init(players, sockets, "top-secret", game) + admin.Init(players, sockets, "top-secret", nil, game) cookie := registerTestAdmin(t, admin, "top-secret") connection := new(recordingAdminConnection) if !admin.addConnection(connection) { @@ -242,9 +298,9 @@ func TestAdminResetClearsOfflineLocationsButPreservesActiveCoordinates(t *testin players.Init() game := new(Game) sockets := new(Sockets) - sockets.Init(players, game) + sockets.Init(players, nil, game) admin := new(Admin) - admin.Init(players, sockets, "top-secret", game) + admin.Init(players, sockets, "top-secret", nil, game) cookie := registerTestAdmin(t, admin, "top-secret") activeID := players.New(TypeLeader, "Active", StatusDisc) diff --git a/api/etc.go b/api/etc.go index 15c1b9e..eb560b6 100644 --- a/api/etc.go +++ b/api/etc.go @@ -21,6 +21,10 @@ const ( CMD_INFORM = "inform" // inform another player change/connection CMD_REMOVE = "remove" // remove a player marker without disclosing a location CMD_STATE = "state" // inform clients of shared game state + // CMD_SHUTDOWN is the legacy JSON shutdown command. New servers notify + // shutdown with a 1001 Going Away close frame; clients still accept this + // command for compatibility. + CMD_SHUTDOWN = "shutdown" // inform clients of server shutdown // player type TypeHidden PlayerType = 0 diff --git a/api/hub.go b/api/hub.go index b55b4b7..85bbe18 100644 --- a/api/hub.go +++ b/api/hub.go @@ -298,6 +298,7 @@ func (h *Hub) enqueue(connection *Conn, message []byte) bool { case connection.send <- message: return true default: + // Channel buffer is full. Client cannot keep up with real-time updates. return false } } @@ -420,3 +421,5 @@ func (h *Hub) clearOfflineLocations() { h.broadcastRemove(playerID, onlyViewers, nil) } } + + diff --git a/api/leader.go b/api/leader.go index 0800505..8fd73a1 100644 --- a/api/leader.go +++ b/api/leader.go @@ -51,18 +51,20 @@ type leaderSocketConnection interface { } type Leader struct { - players *Players - game *Game - sockets *Sockets + players *Players + game *Game + sockets *Sockets + lifecycle *Lifecycle connections map[leaderSocketConnection]PlayerID socketMutex sync.Mutex } -func (l *Leader) Init(players *Players, game *Game, sockets *Sockets) { +func (l *Leader) Init(players *Players, game *Game, sockets *Sockets, lifecycle *Lifecycle) { l.players = players l.game = game l.sockets = sockets + l.lifecycle = lifecycle l.connections = make(map[leaderSocketConnection]PlayerID) players.AddObserver(l.BroadcastPlayer) players.AddRemovalObserver(l.BroadcastRemoval) @@ -230,6 +232,13 @@ func (l *Leader) ServeSocket(w http.ResponseWriter, r *http.Request) { if err != nil { return } + if l.lifecycle != nil { + if !l.lifecycle.Track(connection) { + _ = connection.Close() + return + } + defer l.lifecycle.Untrack(connection) + } if !l.addConnection(connection, state.Leader.ID) { return } diff --git a/api/leader_test.go b/api/leader_test.go index bf87d39..bd2ad6b 100644 --- a/api/leader_test.go +++ b/api/leader_test.go @@ -46,9 +46,9 @@ func newLeaderTestState() (*Players, *Game, *Sockets, *Leader) { players.Init() game := new(Game) sockets := new(Sockets) - sockets.Init(players, game) + sockets.Init(players, nil, game) leader := new(Leader) - leader.Init(players, game, sockets) + leader.Init(players, game, sockets, nil) return players, game, sockets, leader } diff --git a/api/lifecycle.go b/api/lifecycle.go new file mode 100644 index 0000000..2b977ae --- /dev/null +++ b/api/lifecycle.go @@ -0,0 +1,149 @@ +package api + +import ( + "sync" + "time" + + ws "github.com/gorilla/websocket" +) + +// Shutdown budgets. CloseWriteTimeout bounds the WebSocket close-frame write +// for every connection sharing one absolute deadline. ShutdownTimeout bounds +// HTTP draining plus WebSocket worker cleanup in main. +const ( + WebsocketCloseWriteTimeout = 1 * time.Second + ShutdownTimeout = 5 * time.Second +) + +// websocketConn is the subset of Gorilla's API used during shutdown. +// WriteControl and Close are safe for concurrent use with other connection +// methods, which lets shutdown bypass a stalled write pump. +type websocketConn interface { + WriteControl(messageType int, data []byte, deadline time.Time) error + Close() error +} + +// Lifecycle tracks live WebSocket connections and their handler workers so +// server shutdown can notify every endpoint with a deadline-bounded close +// frame instead of sleeping an arbitrary duration. +type Lifecycle struct { + mutex sync.Mutex + shuttingDown bool + connections map[websocketConn]struct{} + wait sync.WaitGroup +} + +// NewLifecycle returns an idle lifecycle ready to track connections. +func NewLifecycle() *Lifecycle { + return &Lifecycle{connections: make(map[websocketConn]struct{})} +} + +// Track registers a connection worker. It returns false when shutdown has +// started, in which case the caller must close the connection and must not +// call Untrack. Each successful Track requires exactly one Untrack call. +func (l *Lifecycle) Track(connection websocketConn) bool { + if l == nil || connection == nil { + return false + } + l.mutex.Lock() + defer l.mutex.Unlock() + if l.shuttingDown { + return false + } + if l.connections == nil { + l.connections = make(map[websocketConn]struct{}) + } + l.connections[connection] = struct{}{} + l.wait.Add(1) + return true +} + +// Untrack removes one worker registration. It is safe to call for a +// connection that is no longer in the snapshot; the WaitGroup accounting +// still pairs with its Track call. +func (l *Lifecycle) Untrack(connection websocketConn) { + if l == nil || connection == nil { + return + } + l.mutex.Lock() + delete(l.connections, connection) + l.mutex.Unlock() + l.wait.Done() +} + +// ShuttingDown reports whether Shutdown has started. New upgrades must be +// rejected once this returns true. +func (l *Lifecycle) ShuttingDown() bool { + if l == nil { + return false + } + l.mutex.Lock() + defer l.mutex.Unlock() + return l.shuttingDown +} + +// ConnectionCount returns the number of distinct tracked connections. It +// exists for tests; production code uses Shutdown. +func (l *Lifecycle) ConnectionCount() int { + if l == nil { + return 0 + } + l.mutex.Lock() + defer l.mutex.Unlock() + return len(l.connections) +} + +// Shutdown sends a Going Away close frame to every tracked connection using +// one shared absolute deadline, closes the underlying sockets, then waits +// until deadline for tracked workers to finish cleanup. It returns true when +// every worker finished before deadline. It is idempotent. +func (l *Lifecycle) Shutdown(deadline time.Time) bool { + if l == nil { + return true + } + l.mutex.Lock() + l.shuttingDown = true + snapshot := make([]websocketConn, 0, len(l.connections)) + for connection := range l.connections { + snapshot = append(snapshot, connection) + } + l.mutex.Unlock() + + var closeWait sync.WaitGroup + for _, connection := range snapshot { + closeWait.Add(1) + go func(connection websocketConn) { + defer closeWait.Done() + _ = connection.WriteControl( + ws.CloseMessage, + ws.FormatCloseMessage(ws.CloseGoingAway, "Server shutting down"), + deadline, + ) + _ = connection.Close() + }(connection) + } + closeWait.Wait() + + done := make(chan struct{}) + go func() { + l.wait.Wait() + close(done) + }() + timeout := time.Until(deadline) + if timeout <= 0 { + select { + case <-done: + return true + default: + return false + } + } + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case <-done: + return true + case <-timer.C: + return false + } +} diff --git a/api/lifecycle_test.go b/api/lifecycle_test.go new file mode 100644 index 0000000..f163830 --- /dev/null +++ b/api/lifecycle_test.go @@ -0,0 +1,203 @@ +package api + +import ( + "sync" + "testing" + "time" + + ws "github.com/gorilla/websocket" +) + +type recordingShutdownConnection struct { + mutex sync.Mutex + writeCalls int + closeCalls int + code int + deadline time.Time + writeErr error + blockWrite chan struct{} + writeStarted chan struct{} +} + +func (c *recordingShutdownConnection) WriteControl(messageType int, data []byte, deadline time.Time) error { + c.mutex.Lock() + c.writeCalls++ + c.deadline = deadline + c.mutex.Unlock() + if c.writeStarted != nil { + close(c.writeStarted) + } + if c.blockWrite != nil { + <-c.blockWrite + } + if messageType == ws.CloseMessage && len(data) >= 2 { + c.mutex.Lock() + c.code = int(data[0])<<8 | int(data[1]) + c.mutex.Unlock() + } + return c.writeErr +} + +func (c *recordingShutdownConnection) Close() error { + c.mutex.Lock() + c.closeCalls++ + c.mutex.Unlock() + return nil +} + +func (c *recordingShutdownConnection) counts() (writes, closes, code int) { + c.mutex.Lock() + defer c.mutex.Unlock() + return c.writeCalls, c.closeCalls, c.code +} + +func TestLifecycleShutdownNotifiesHealthyConnections(t *testing.T) { + lifecycle := NewLifecycle() + first := &recordingShutdownConnection{} + second := &recordingShutdownConnection{} + if !lifecycle.Track(first) || !lifecycle.Track(second) { + t.Fatal("track healthy connections") + } + before := time.Now() + deadline := before.Add(WebsocketCloseWriteTimeout) + done := make(chan bool, 1) + go func() { + done <- lifecycle.Shutdown(deadline) + }() + // Simulate handler workers finishing after the close frame is written. + // Untrack must happen after Shutdown snapshots, mirroring production + // where handlers exit in response to the socket close. + for _, connection := range []*recordingShutdownConnection{first, second} { + deadline := time.Now().Add(2 * time.Second) + for { + writes, _, _ := connection.counts() + if writes > 0 { + break + } + if time.Now().After(deadline) { + t.Fatal("timed out waiting for close frame") + } + time.Sleep(time.Millisecond) + } + lifecycle.Untrack(connection) + } + if !<-done { + t.Fatal("shutdown did not complete before deadline") + } + for index, connection := range []*recordingShutdownConnection{first, second} { + writes, closes, code := connection.counts() + if writes != 1 || closes != 1 { + t.Errorf("connection %d writes=%d closes=%d, want 1 and 1", index, writes, closes) + } + if code != ws.CloseGoingAway { + t.Errorf("connection %d close code=%d, want %d", index, code, ws.CloseGoingAway) + } + if connection.deadline.Before(before) || connection.deadline.After(deadline.Add(time.Second)) { + t.Errorf("connection %d deadline=%v, want shared deadline %v", index, connection.deadline, deadline) + } + } +} + +func TestLifecycleShutdownSharesOneDeadlineAcrossConnections(t *testing.T) { + lifecycle := NewLifecycle() + first := &recordingShutdownConnection{} + second := &recordingShutdownConnection{} + if !lifecycle.Track(first) || !lifecycle.Track(second) { + t.Fatal("track connections") + } + deadline := time.Now().Add(WebsocketCloseWriteTimeout) + go func() { + lifecycle.Untrack(first) + lifecycle.Untrack(second) + }() + if !lifecycle.Shutdown(deadline) { + t.Fatal("shutdown did not complete") + } + if !first.deadline.Equal(deadline) || !second.deadline.Equal(deadline) { + t.Errorf("deadlines = %v and %v, want shared %v", first.deadline, second.deadline, deadline) + } +} + +func TestLifecycleRejectsNewConnectionsDuringShutdown(t *testing.T) { + lifecycle := NewLifecycle() + stuck := &recordingShutdownConnection{} + if !lifecycle.Track(stuck) { + t.Fatal("track connection") + } + deadline := time.Now().Add(100 * time.Millisecond) + done := make(chan bool, 1) + go func() { + done <- lifecycle.Shutdown(deadline) + }() + // Wait until Shutdown has marked the lifecycle so the racing admission + // observes the shutting-down state. + admissionDeadline := time.Now().Add(2 * time.Second) + for !lifecycle.ShuttingDown() { + if time.Now().After(admissionDeadline) { + t.Fatal("timed out waiting for shutdown to start") + } + time.Sleep(time.Millisecond) + } + if lifecycle.Track(&recordingShutdownConnection{}) { + t.Error("Track succeeded after shutdown started") + } + select { + case result := <-done: + if result { + t.Error("shutdown reported success with an unfinished worker") + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for shutdown timeout") + } + lifecycle.Untrack(stuck) + racing := &recordingShutdownConnection{} + if lifecycle.Track(racing) { + t.Error("Track succeeded after shutdown completed") + lifecycle.Untrack(racing) + } +} + +func TestLifecycleShutdownWithZeroConnectionsCompletes(t *testing.T) { + lifecycle := NewLifecycle() + if !lifecycle.Shutdown(time.Now().Add(WebsocketCloseWriteTimeout)) { + t.Error("zero-connection shutdown did not complete") + } + if !lifecycle.ShuttingDown() { + t.Error("ShuttingDown = false after shutdown") + } +} + +func TestLifecycleShutdownIsIdempotent(t *testing.T) { + lifecycle := NewLifecycle() + connection := &recordingShutdownConnection{} + if !lifecycle.Track(connection) { + t.Fatal("track connection") + } + deadline := time.Now().Add(WebsocketCloseWriteTimeout) + done := make(chan bool, 1) + go func() { + done <- lifecycle.Shutdown(deadline) + }() + writeDeadline := time.Now().Add(2 * time.Second) + for { + writes, _, _ := connection.counts() + if writes > 0 { + break + } + if time.Now().After(writeDeadline) { + t.Fatal("timed out waiting for close frame") + } + time.Sleep(time.Millisecond) + } + lifecycle.Untrack(connection) + if !<-done { + t.Fatal("first shutdown did not complete") + } + if !lifecycle.Shutdown(time.Now().Add(WebsocketCloseWriteTimeout)) { + t.Error("second shutdown did not complete") + } + writes, closes, _ := connection.counts() + if writes != 1 || closes != 1 { + t.Errorf("writes=%d closes=%d, want exactly one close attempt per tracked connection", writes, closes) + } +} diff --git a/api/shutdown_test.go b/api/shutdown_test.go new file mode 100644 index 0000000..2d13db2 --- /dev/null +++ b/api/shutdown_test.go @@ -0,0 +1,129 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + ws "github.com/gorilla/websocket" +) + +func newShutdownTestAPI() (*Players, *Sockets, *Admin, *Leader, *Lifecycle) { + players := new(Players) + players.Init() + lifecycle := NewLifecycle() + sockets := new(Sockets) + sockets.Init(players, lifecycle) + game := new(Game) + admin := new(Admin) + admin.Init(players, sockets, "top-secret", lifecycle, game) + leader := new(Leader) + leader.Init(players, game, sockets, lifecycle) + return players, sockets, admin, leader, lifecycle +} + +func dialTestSocket(t *testing.T, url string, cookie *http.Cookie) *ws.Conn { + t.Helper() + header := http.Header{} + if cookie != nil { + header.Set("Cookie", cookie.Name+"="+cookie.Value) + } + connection, _, err := ws.DefaultDialer.Dial(url, header) + if err != nil { + t.Fatalf("dial %s: %v", url, err) + } + return connection +} + +func expectGoingAwayClose(t *testing.T, connection *ws.Conn) { + t.Helper() + _ = connection.SetReadDeadline(time.Now().Add(3 * time.Second)) + for { + _, _, err := connection.ReadMessage() + if err == nil { + // Snapshot or gameplay frame queued before shutdown; keep reading. + continue + } + closeErr, ok := err.(*ws.CloseError) + if !ok { + t.Fatalf("read error = %#v, want CloseError", err) + } + if closeErr.Code != ws.CloseGoingAway { + t.Fatalf("close code = %d, want %d", closeErr.Code, ws.CloseGoingAway) + } + return + } +} + +func TestShutdownNotifiesAllWebSocketEndpoints(t *testing.T) { + players, sockets, admin, leader, lifecycle := newShutdownTestAPI() + playerID := players.New(TypeGhost, "Player", StatusDisc) + leaderID := players.New(TypeAntiPacLeader, "Leader", StatusDisc) + + mux := http.NewServeMux() + mux.Handle("/api/ws/", sockets) + mux.Handle("/api/admin/ws", http.HandlerFunc(admin.ServeSocket)) + mux.Handle("/api/admin/map/ws", http.HandlerFunc(admin.ServeMapSocket)) + mux.Handle("/api/leader/ws", http.HandlerFunc(leader.ServeSocket)) + server := httptest.NewServer(mux) + defer server.Close() + wsBase := "ws" + strings.TrimPrefix(server.URL, "http") + + adminCookie := registerTestAdmin(t, admin, "top-secret") + player := dialTestSocket(t, wsBase+"/api/ws/"+string(playerID), nil) + defer player.Close() + viewer := dialTestSocket(t, wsBase+"/api/admin/map/ws", adminCookie) + defer viewer.Close() + status := dialTestSocket(t, wsBase+"/api/admin/ws", adminCookie) + defer status.Close() + leaderConn := dialTestSocket(t, wsBase+"/api/leader/ws", &http.Cookie{Name: leaderCookieName, Value: string(leaderID)}) + defer leaderConn.Close() + + // Wait until every endpoint registered its connection worker. + admissionDeadline := time.Now().Add(2 * time.Second) + for lifecycle.ConnectionCount() != 4 { + if time.Now().After(admissionDeadline) { + t.Fatalf("tracked connections = %d, want 4", lifecycle.ConnectionCount()) + } + time.Sleep(time.Millisecond) + } + + done := make(chan bool, 1) + go func() { + done <- lifecycle.Shutdown(time.Now().Add(WebsocketCloseWriteTimeout)) + }() + select { + case ok := <-done: + if !ok { + t.Fatal("shutdown did not complete before deadline") + } + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for shutdown") + } + + for index, connection := range []*ws.Conn{player, viewer, status, leaderConn} { + expectGoingAwayClose(t, connection) + _ = index + } + + if lifecycle.ConnectionCount() != 0 { + t.Errorf("tracked connections after shutdown = %d, want 0", lifecycle.ConnectionCount()) + } + if !lifecycle.ShuttingDown() { + t.Error("ShuttingDown = false after shutdown") + } + racing := &recordingShutdownConnection{} + if lifecycle.Track(racing) { + t.Error("Track succeeded after shutdown") + lifecycle.Untrack(racing) + } +} + +func TestShutdownCompletesWithZeroConnections(t *testing.T) { + _, _, _, _, lifecycle := newShutdownTestAPI() + if !lifecycle.Shutdown(time.Now().Add(WebsocketCloseWriteTimeout)) { + t.Error("zero-connection shutdown did not complete") + } +} diff --git a/api/socket.go b/api/socket.go index 89c777e..0570f96 100644 --- a/api/socket.go +++ b/api/socket.go @@ -32,12 +32,14 @@ const ( type Sockets struct { // private - players *Players - hub *Hub + players *Players + hub *Hub + lifecycle *Lifecycle } -func (s *Sockets) Init(players *Players, games ...*Game) { +func (s *Sockets) Init(players *Players, lifecycle *Lifecycle, games ...*Game) { s.players = players + s.lifecycle = lifecycle s.hub = NewHub(players, games...) go s.hub.Run() @@ -127,6 +129,24 @@ func (c *Conn) readPump(hub *Hub) error { } } +// trackGameSocket registers the read handler and write pump with the shared +// lifecycle. The caller must already hold one Track for the read handler when +// calling this; it acquires the second Track for the write pump. +func (s *Sockets) trackGameSocket(socket *ws.Conn, connection *Conn) bool { + if s.lifecycle == nil { + go connection.writePump(s.hub) + return true + } + if !s.lifecycle.Track(socket) { + return false + } + go func() { + defer s.lifecycle.Untrack(socket) + connection.writePump(s.hub) + }() + return true +} + // WS /api/ws/ // ServeHTTP upgrades the connection to a websocket connection func (s *Sockets) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -146,6 +166,13 @@ func (s *Sockets) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err != nil { return } + if s.lifecycle != nil { + if !s.lifecycle.Track(socket) { + _ = socket.Close() + return + } + defer s.lifecycle.Untrack(socket) + } connection := &Conn{ socket: socket, @@ -154,7 +181,10 @@ func (s *Sockets) ServeHTTP(w http.ResponseWriter, r *http.Request) { send: make(chan []byte, socketSendQueueSize), } - go connection.writePump(s.hub) + if !s.trackGameSocket(socket, connection) { + _ = socket.Close() + return + } s.hub.register <- connection fmt.Printf("Sockets\tServeHTTP (/api/ws/):\tID %q: Connection opened.\n", playerID) @@ -173,6 +203,13 @@ func (s *Sockets) ServeViewer(w http.ResponseWriter, r *http.Request) { if err != nil { return } + if s.lifecycle != nil { + if !s.lifecycle.Track(socket) { + _ = socket.Close() + return + } + defer s.lifecycle.Untrack(socket) + } connection := &Conn{ socket: socket, @@ -180,7 +217,10 @@ func (s *Sockets) ServeViewer(w http.ResponseWriter, r *http.Request) { send: make(chan []byte, socketSendQueueSize), } - go connection.writePump(s.hub) + if !s.trackGameSocket(socket, connection) { + _ = socket.Close() + return + } s.hub.register <- connection fmt.Print("Sockets\tServeViewer (/api/admin/map/ws):\tConnection opened.\n") diff --git a/api/socket_test.go b/api/socket_test.go index 0ea15a0..d25d455 100644 --- a/api/socket_test.go +++ b/api/socket_test.go @@ -31,6 +31,84 @@ func TestPlayerStaysConnectedUntilLastSocketDisconnects(t *testing.T) { } } +func TestRemoveBroadcastPreservesQueuedMessages(t *testing.T) { + players := new(Players) + players.Init() + hub := NewHub(players) + viewer := &Conn{ + role: viewerConnection, + send: make(chan []byte, 2), + } + hub.connections[viewer] = struct{}{} + queued := []byte("queued state") + viewer.send <- queued + + playerID := PlayerID("offline") + hub.broadcastRemove(playerID, onlyViewers, nil) + + if got := receiveTestData(t, viewer); string(got) != string(queued) { + t.Fatalf("first queued message = %q, want %q", got, queued) + } + removed := receiveTestMessage(t, viewer) + if removed.Command != CMD_REMOVE || removed.Data != string(playerID) { + t.Errorf("offline marker removal = %#v", removed) + } +} + +func TestRemoveBroadcastDoesNotEvictFullQueue(t *testing.T) { + players := new(Players) + players.Init() + hub := NewHub(players) + viewer := &Conn{ + role: viewerConnection, + send: make(chan []byte, 1), + } + hub.connections[viewer] = struct{}{} + queued := []byte("queued state") + viewer.send <- queued + + hub.broadcastRemove(PlayerID("offline"), onlyViewers, nil) + + if _, exists := hub.connections[viewer]; exists { + t.Fatal("slow viewer remains registered") + } + if len(viewer.send) != 1 { + t.Fatalf("queued messages = %d, want 1", len(viewer.send)) + } + if got := receiveTestData(t, viewer); string(got) != string(queued) { + t.Fatalf("queued message = %q, want %q", got, queued) + } +} + +func TestInformBroadcastDoesNotEvictFullQueue(t *testing.T) { + players := new(Players) + players.Init() + playerID := players.New(TypePacman, "Active", StatusConn) + hub := NewHub(players) + owner := newTestConnection(playerID) + viewer := &Conn{ + role: viewerConnection, + send: make(chan []byte, 1), + } + hub.connections[owner] = struct{}{} + hub.connections[viewer] = struct{}{} + hub.coordinates[playerID] = Coordinate{Latitude: 49.27, Longitude: -122.91} + queued := []byte("queued move") + viewer.send <- queued + + hub.broadcastInform(playerID, owner) + + if _, exists := hub.connections[viewer]; exists { + t.Fatal("slow viewer remains registered") + } + if len(viewer.send) != 1 { + t.Fatalf("queued messages = %d, want 1", len(viewer.send)) + } + if got := receiveTestData(t, viewer); string(got) != string(queued) { + t.Fatalf("queued message = %q, want %q", got, queued) + } +} + func TestGameStateSnapshotAndBroadcastDoNotChangePlayerConnectionCounts(t *testing.T) { players := new(Players) players.Init() diff --git a/frontend/src/app/core/credentials.service.spec.ts b/frontend/src/app/core/credentials.service.spec.ts index 3b3ddae..18fbdf8 100644 --- a/frontend/src/app/core/credentials.service.spec.ts +++ b/frontend/src/app/core/credentials.service.spec.ts @@ -1,12 +1,146 @@ -import { readCookie } from './credentials.service'; +import { DOCUMENT } from '@angular/common'; +import { TestBed } from '@angular/core/testing'; + +import { PAC_WINDOW } from './browser-window.token'; +import { CredentialsService, readCookie } from './credentials.service'; describe('readCookie', () => { it('reads and decodes an exact cookie name', () => { - expect(readCookie('theme=dark; id=AB%20CD; userid=wrong', 'id')).toBe('AB CD'); + expect(readCookie('pacmacro_admin=token; id=AB%20CD; userid=wrong', 'id')).toBe('AB CD'); }); it('returns an empty string for missing or malformed values', () => { expect(readCookie('id=%E0%A4%A', 'id')).toBe(''); - expect(readCookie('theme=dark', 'id')).toBe(''); + expect(readCookie('pacmacro_admin=token', 'id')).toBe(''); + }); +}); + +describe('CredentialsService', () => { + let service: CredentialsService; + let mockDocument: { cookie: string }; + let mockStorage: Record; + let mockWindow: { + location: { protocol: string }; + localStorage: { + getItem: (key: string) => string | null; + setItem: (key: string, value: string) => void; + }; + }; + + beforeEach(() => { + mockDocument = { cookie: '' }; + mockStorage = {}; + mockWindow = { + location: { protocol: 'http:' }, + localStorage: { + getItem: (key) => mockStorage[key] ?? null, + setItem: (key, value) => { + mockStorage[key] = value; + }, + }, + }; + + TestBed.configureTestingModule({ + providers: [ + CredentialsService, + { provide: DOCUMENT, useValue: mockDocument }, + { provide: PAC_WINDOW, useValue: mockWindow }, + ], + }); + service = TestBed.inject(CredentialsService); + }); + + it.each(['http:', 'https:'] as const)('expires the id cookie over %s', (protocol) => { + mockWindow.location.protocol = protocol; + mockDocument.cookie = 'id=ABC; pacmacro_admin=token'; + + service.clear(); + + const secure = protocol === 'https:' ? '; Secure' : ''; + expect(mockDocument.cookie).toBe(`id=; Path=/; SameSite=Lax${secure}; Max-Age=0`); + }); + + it('leaves the cookie untouched when PAC_WINDOW is null', () => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + CredentialsService, + { provide: DOCUMENT, useValue: mockDocument }, + { provide: PAC_WINDOW, useValue: null }, + ], + }); + service = TestBed.inject(CredentialsService); + mockDocument.cookie = 'id=ABC'; + + service.clear(); + + expect(mockDocument.cookie).toBe('id=ABC'); + }); + + it('saves and retrieves the player name for auto re-registration', () => { + service.savePlayerName('Odin'); + + expect(service.getPlayerName()).toBe('Odin'); + }); + + it('returns an empty player name when localStorage throws on get', () => { + TestBed.resetTestingModule(); + const throwingWindow = { + location: { protocol: 'http:' }, + localStorage: { + getItem: () => { + throw new Error('unavailable'); + }, + setItem: () => undefined, + }, + }; + TestBed.configureTestingModule({ + providers: [ + CredentialsService, + { provide: DOCUMENT, useValue: mockDocument }, + { provide: PAC_WINDOW, useValue: throwingWindow }, + ], + }); + service = TestBed.inject(CredentialsService); + + expect(service.getPlayerName()).toBe(''); + }); + + it('silently ignores localStorage errors when saving the player name', () => { + TestBed.resetTestingModule(); + const throwingWindow = { + location: { protocol: 'http:' }, + localStorage: { + getItem: () => null, + setItem: () => { + throw new Error('quota exceeded'); + }, + }, + }; + TestBed.configureTestingModule({ + providers: [ + CredentialsService, + { provide: DOCUMENT, useValue: mockDocument }, + { provide: PAC_WINDOW, useValue: throwingWindow }, + ], + }); + service = TestBed.inject(CredentialsService); + + expect(() => service.savePlayerName('Odin')).not.toThrow(); + }); + + it('returns an empty player name and ignores saves when PAC_WINDOW is null', () => { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + CredentialsService, + { provide: DOCUMENT, useValue: mockDocument }, + { provide: PAC_WINDOW, useValue: null }, + ], + }); + service = TestBed.inject(CredentialsService); + + expect(service.getPlayerName()).toBe(''); + expect(() => service.savePlayerName('Odin')).not.toThrow(); }); }); diff --git a/frontend/src/app/core/credentials.service.ts b/frontend/src/app/core/credentials.service.ts index 1c0b881..e7fba9f 100644 --- a/frontend/src/app/core/credentials.service.ts +++ b/frontend/src/app/core/credentials.service.ts @@ -4,6 +4,8 @@ import { inject, Service } from '@angular/core'; import { PAC_WINDOW } from './browser-window.token'; import { Credentials } from './game.models'; +const PLAYER_NAME_KEY = 'playerName'; + export function readCookie(cookieHeader: string, name: string): string { const prefix = `${name}=`; const value = cookieHeader @@ -47,4 +49,29 @@ export class CredentialsService { const attributes = `; Path=/; SameSite=Lax${secure}`; this.document.cookie = `id=${encodeURIComponent(credentials.id)}${attributes}`; } + + getPlayerName(): string { + try { + return this.browserWindow?.localStorage.getItem(PLAYER_NAME_KEY) ?? ''; + } catch { + return ''; + } + } + + savePlayerName(name: string): void { + try { + this.browserWindow?.localStorage.setItem(PLAYER_NAME_KEY, name); + } catch { + // Local storage may be unavailable or full; re-registration can fall back to the form. + } + } + + clear(): void { + if (!this.browserWindow) { + return; + } + + const secure = this.browserWindow.location.protocol === 'https:' ? '; Secure' : ''; + this.document.cookie = `id=; Path=/; SameSite=Lax${secure}; Max-Age=0`; + } } diff --git a/frontend/src/app/core/game.models.ts b/frontend/src/app/core/game.models.ts index 54a801c..e358e26 100644 --- a/frontend/src/app/core/game.models.ts +++ b/frontend/src/app/core/game.models.ts @@ -52,7 +52,7 @@ export interface LivePlayer { export interface SocketMessage { coordinate?: Coordinate; - command: 'inform' | 'move' | 'remove' | 'state' | string; + command: 'inform' | 'move' | 'remove' | 'state' | 'shutdown' | string; data: string; } diff --git a/frontend/src/app/core/sockets/admin-socket.service.spec.ts b/frontend/src/app/core/sockets/admin-socket.service.spec.ts index 748ed12..eb9becd 100644 --- a/frontend/src/app/core/sockets/admin-socket.service.spec.ts +++ b/frontend/src/app/core/sockets/admin-socket.service.spec.ts @@ -118,6 +118,21 @@ describe('sockets/AdminSocketService', () => { expect(MockAdminWebSocket.instances).toHaveLength(1); }); + it('enters shutdown without reconnecting on a 1001 close', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + socket.message({ event: 'snapshot', isFlagFound: false, players: [] }); + expect(service.isReady()).toBe(true); + + socket.serverClose(true, 1001, 'Server shutting down'); + vi.runAllTimers(); + + expect(service.state()).toBe('shutdown'); + expect(service.isReady()).toBe(false); + expect(service.status()).toBe('The server has stopped this connection.'); + expect(MockAdminWebSocket.instances).toHaveLength(1); + }); + it('applies and sorts a complete snapshot including flag state', () => { socket.message({ event: 'snapshot', diff --git a/frontend/src/app/core/sockets/game-socket.service.spec.ts b/frontend/src/app/core/sockets/game-socket.service.spec.ts index e0b6040..7ff9692 100644 --- a/frontend/src/app/core/sockets/game-socket.service.spec.ts +++ b/frontend/src/app/core/sockets/game-socket.service.spec.ts @@ -93,6 +93,10 @@ describe('GameSocketService', () => { } }); + function advanceToNextReconnect(): void { + vi.advanceTimersToNextTimer(); + } + it('uses the player URL, invokes the callback, and sends coordinates as JSON', () => { const onConnected = vi.fn(); service.start('A B/C', onConnected); @@ -203,6 +207,80 @@ describe('GameSocketService', () => { expect(service.status()).toContain('invalid game update'); }); + it('ends a player session when the server sends shutdown', () => { + vi.useFakeTimers(); + MockGameWebSocket.closeSynchronously = false; + const onSessionExpired = vi.fn(); + const onServerShutdown = vi.fn(); + service.start('ABCD', () => undefined, onSessionExpired, onServerShutdown); + const first = MockGameWebSocket.instances[0]; + first.open(); + const lateClose = first.onclose; + + first.message({ command: 'shutdown', data: '' }); + lateClose?.(new CloseEvent('close', { code: 1006, wasClean: false })); + service.resume(); + vi.runAllTimers(); + + expect(service.state()).toBe('shutdown'); + expect(service.status()).toBe('The server stopped. Register to join the next game.'); + expect(MockGameWebSocket.instances).toHaveLength(1); + expect(onServerShutdown).toHaveBeenCalledOnce(); + expect(onSessionExpired).not.toHaveBeenCalled(); + expect(service.sendCoordinate({ latitude: 49.2, longitude: -123 })).toBe(false); + }); + + it('ends a viewer session when the server sends shutdown', () => { + vi.useFakeTimers(); + service.startViewer(); + const first = MockGameWebSocket.instances[0]; + first.open(); + + first.message({ command: 'shutdown', data: '' }); + service.resume(); + vi.runAllTimers(); + + expect(service.state()).toBe('shutdown'); + expect(service.status()).toBe('The server stopped the admin map connection.'); + expect(MockGameWebSocket.instances).toHaveLength(1); + }); + + it('ends a player session on a 1001 close without counting a failure', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + const onSessionExpired = vi.fn(); + const onServerShutdown = vi.fn(); + service.start('ABCD', () => undefined, onSessionExpired, onServerShutdown); + const first = MockGameWebSocket.instances[0]; + first.open(); + + first.serverClose(true, 1001, 'Server shutting down'); + vi.runAllTimers(); + + expect(service.state()).toBe('shutdown'); + expect(service.status()).toBe('The server stopped. Register to join the next game.'); + expect(MockGameWebSocket.instances).toHaveLength(1); + expect(onServerShutdown).toHaveBeenCalledOnce(); + expect(onSessionExpired).not.toHaveBeenCalled(); + expect(service.sessionExpired()).toBe(false); + expect(service.sendCoordinate({ latitude: 49.2, longitude: -123 })).toBe(false); + }); + + it('ends a viewer session on a 1001 close', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + service.startViewer(); + const first = MockGameWebSocket.instances[0]; + first.open(); + + first.serverClose(true, 1001, 'Server shutting down'); + vi.runAllTimers(); + + expect(service.state()).toBe('shutdown'); + expect(service.status()).toBe('The server stopped the admin map connection.'); + expect(MockGameWebSocket.instances).toHaveLength(1); + }); + it.each([ ['clean', true], ['abnormal', false], @@ -227,7 +305,7 @@ describe('GameSocketService', () => { first.serverClose(wasClean); expect(service.status()).toContain('Admin map connection lost'); - vi.advanceTimersByTime(1000); + advanceToNextReconnect(); expect(MockGameWebSocket.instances).toHaveLength(2); const second = MockGameWebSocket.instances[1]; @@ -297,4 +375,102 @@ describe('GameSocketService', () => { expect(service.state()).toBe('error'); expect(service.status()).toContain('Register as admin again in this browser'); }); + + it('expires the session after three consecutive failed player connections', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const onSessionExpired = vi.fn(); + service.start('ABCD', () => undefined, onSessionExpired); + + MockGameWebSocket.instances[0].serverClose(false); + advanceToNextReconnect(); + MockGameWebSocket.instances[1].serverClose(false); + advanceToNextReconnect(); + MockGameWebSocket.instances[2].serverClose(false); + + expect(service.sessionExpired()).toBe(true); + expect(service.state()).toBe('error'); + expect(service.status()).toContain('Session has expired as game server restarted.'); + expect(MockGameWebSocket.instances).toHaveLength(3); + expect(onSessionExpired).toHaveBeenCalledOnce(); + }); + + it('reconnects without expiring the session after fewer than three failures', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const onSessionExpired = vi.fn(); + service.start('ABCD', () => undefined, onSessionExpired); + + MockGameWebSocket.instances[0].serverClose(false); + advanceToNextReconnect(); + MockGameWebSocket.instances[1].serverClose(false); + advanceToNextReconnect(); + + expect(service.sessionExpired()).toBe(false); + expect(onSessionExpired).not.toHaveBeenCalled(); + expect(service.state()).toBe('connecting'); + expect(MockGameWebSocket.instances).toHaveLength(3); + }); + + it('resets the failure counter when a player connection succeeds', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + service.start('ABCD', () => undefined); + + MockGameWebSocket.instances[0].serverClose(false); + advanceToNextReconnect(); + MockGameWebSocket.instances[1].serverClose(false); + advanceToNextReconnect(); + + MockGameWebSocket.instances[2].open(); + MockGameWebSocket.instances[2].serverClose(false); + advanceToNextReconnect(); + MockGameWebSocket.instances[3].serverClose(false); + advanceToNextReconnect(); + + expect(service.sessionExpired()).toBe(false); + expect(MockGameWebSocket.instances).toHaveLength(5); + }); + + it('never expires the session for a viewer socket', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + service.startViewer(); + + MockGameWebSocket.instances[0].serverClose(false); + advanceToNextReconnect(); + MockGameWebSocket.instances[1].serverClose(false); + advanceToNextReconnect(); + MockGameWebSocket.instances[2].serverClose(false); + advanceToNextReconnect(); + + expect(service.sessionExpired()).toBe(false); + expect(MockGameWebSocket.instances).toHaveLength(4); + }); + + it('start and stop clear an expired session', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + service.start('ABCD', () => undefined); + + MockGameWebSocket.instances[0].serverClose(false); + advanceToNextReconnect(); + MockGameWebSocket.instances[1].serverClose(false); + advanceToNextReconnect(); + MockGameWebSocket.instances[2].serverClose(false); + + expect(service.sessionExpired()).toBe(true); + + service.stop(); + expect(service.sessionExpired()).toBe(false); + + service.start('ABCD', () => undefined); + expect(service.sessionExpired()).toBe(false); + expect(MockGameWebSocket.instances).toHaveLength(4); + }); }); diff --git a/frontend/src/app/core/sockets/game-socket.service.ts b/frontend/src/app/core/sockets/game-socket.service.ts index 15a74f8..212e430 100644 --- a/frontend/src/app/core/sockets/game-socket.service.ts +++ b/frontend/src/app/core/sockets/game-socket.service.ts @@ -29,18 +29,32 @@ export class GameSocketService extends WebSocketService { private playerId: string | null = null; private mode: SocketMode | null = null; private onConnected: (() => void) | null = null; + private onSessionExpired: (() => void) | null = null; + private onServerShutdown: (() => void) | null = null; private reconnecting = false; private suspendedReason = 'Paused while the browser is offline.'; + private consecutiveFailures = 0; private readonly statusMessage = signal(null); readonly players = signal>({}); readonly isFlagFound = signal(false); - - start(id: string, onConnected: () => void): void { + readonly sessionExpired = signal(false); + readonly MAX_FAILED_ATTEMPTS = 3; + + start( + id: string, + onConnected: () => void, + onSessionExpired: () => void = () => undefined, + onServerShutdown: () => void = () => undefined, + ): void { this.stop(); this.mode = 'player'; this.playerId = id; this.onConnected = onConnected; + this.onSessionExpired = onSessionExpired; + this.onServerShutdown = onServerShutdown; + this.consecutiveFailures = 0; + this.sessionExpired.set(false); this.resume(); } @@ -72,8 +86,12 @@ export class GameSocketService extends WebSocketService { this.mode = null; this.playerId = null; this.onConnected = null; + this.onSessionExpired = null; + this.onServerShutdown = null; this.reconnecting = false; this.statusMessage.set(null); + this.consecutiveFailures = 0; + this.sessionExpired.set(false); this.disconnect(); } @@ -81,6 +99,54 @@ export class GameSocketService extends WebSocketService { return this.mode === 'player' && isCoordinate(coordinate) && this.sendMessage(coordinate); } + private endForServerShutdown(): void { + const { mode, onServerShutdown } = this.clearShutdownSession(); + + // Incrementing the connection identity before unsubscribing makes any + // queued retry or late close event belong to an obsolete connection. + this.disconnect(); + this.state.set('shutdown'); + this.statusMessage.set( + mode === 'player' + ? 'The server stopped. Register to join the next game.' + : 'The server stopped the admin map connection.', + ); + + if (mode === 'player') { + onServerShutdown?.(); + } + } + + private clearShutdownSession(): { + mode: SocketMode | null; + onServerShutdown: (() => void) | null; + } { + const mode = this.mode; + const onServerShutdown = this.onServerShutdown; + + this.mode = null; + this.playerId = null; + this.onConnected = null; + this.onSessionExpired = null; + this.onServerShutdown = null; + this.reconnecting = false; + this.consecutiveFailures = 0; + this.sessionExpired.set(false); + return { mode, onServerShutdown }; + } + + protected override onShutdown(): void { + const { mode, onServerShutdown } = this.clearShutdownSession(); + this.statusMessage.set( + mode === 'player' + ? 'The server stopped. Register to join the next game.' + : 'The server stopped the admin map connection.', + ); + if (mode === 'player') { + onServerShutdown?.(); + } + } + setInitialState(state: GameState): void { this.isFlagFound.set(state.isFlagFound); } @@ -96,6 +162,7 @@ export class GameSocketService extends WebSocketService { this.players.set({}); this.reconnecting = false; this.statusMessage.set(null); + this.consecutiveFailures = 0; this.onConnected?.(); } @@ -103,6 +170,24 @@ export class GameSocketService extends WebSocketService { this.reconnecting = true; } + protected override shouldReconnect(closeEvent: CloseEvent): boolean { + if (this.mode !== 'player') { + return true; + } + + this.consecutiveFailures++; + + if (this.consecutiveFailures >= this.MAX_FAILED_ATTEMPTS) { + this.sessionExpired.set(true); + this.statusMessage.set( + 'Session has expired as game server restarted.', + ); + this.onSessionExpired?.(); + return false; + } + return true; + } + protected override onSocketError(): void { this.statusMessage.set( this.mode === 'viewer' @@ -170,6 +255,11 @@ export class GameSocketService extends WebSocketService { return; } + if (message.command === 'shutdown') { + this.endForServerShutdown(); + return; + } + if (message.command === 'remove') { this.players.update((players) => { if (!(message.data in players)) { @@ -232,6 +322,7 @@ function isSocketMessage(value: unknown): value is SocketMessage { switch (value['command']) { case 'remove': + case 'shutdown': return true; case 'inform': case 'move': diff --git a/frontend/src/app/core/sockets/leader-socket.service.spec.ts b/frontend/src/app/core/sockets/leader-socket.service.spec.ts index c5d1954..6566ea3 100644 --- a/frontend/src/app/core/sockets/leader-socket.service.spec.ts +++ b/frontend/src/app/core/sockets/leader-socket.service.spec.ts @@ -3,6 +3,7 @@ import { TestBed } from '@angular/core/testing'; import { PAC_WINDOW } from '../browser-window.token'; import { LeaderState, PlayerStatus, PlayerType } from '../game.models'; import { LeaderSocketService } from './leader-socket.service'; +import { WebSocketService } from './websocket.service'; class MockLeaderWebSocket { static readonly CONNECTING = 0; @@ -67,6 +68,11 @@ const player = { status: PlayerStatus.Connected, }; +function reconnectDelay(attempt: number): number { + const delays = WebSocketService.RECONNECT_DELAYS; + return delays[Math.min(attempt - 1, delays.length - 1)]; +} + describe('LeaderSocketService', () => { let service: LeaderSocketService; let originalWebSocket: typeof WebSocket; @@ -204,7 +210,7 @@ describe('LeaderSocketService', () => { first.serverClose(wasClean); expect(service.status()).toContain('Leader feed lost'); - vi.advanceTimersByTime(1000); + vi.advanceTimersByTime(reconnectDelay(1)); expect(MockLeaderWebSocket.instances).toHaveLength(2); MockLeaderWebSocket.instances[1].open(); @@ -257,7 +263,7 @@ describe('LeaderSocketService', () => { expect(service.players()).toEqual([]); expect(service.isFlagFound()).toBe(false); expect(service.status()).toContain('Waiting for the role to be restored'); - vi.advanceTimersByTime(1000); + vi.advanceTimersByTime(reconnectDelay(1)); const restoredSocket = MockLeaderWebSocket.instances[1]; restoredSocket.open(); @@ -286,10 +292,27 @@ describe('LeaderSocketService', () => { socket.serverClose(true, 1008, 'Leader authentication required'); expect(service.state()).toBe('revoked'); expect(service.status()).toContain('Leader access was revoked'); - vi.advanceTimersByTime(1000); + vi.advanceTimersByTime(reconnectDelay(1)); expect(MockLeaderWebSocket.instances).toHaveLength(2); MockLeaderWebSocket.instances[1].open(); expect(service.state()).toBe('revoked'); }); + + it('enters shutdown without reconnecting on a 1001 close', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + service.start(); + const socket = MockLeaderWebSocket.instances[0]; + socket.open(); + socket.message({ event: 'snapshot', leader, players: [player], isFlagFound: false }); + + socket.serverClose(true, 1001, 'Server shutting down'); + vi.runAllTimers(); + + expect(service.state()).toBe('shutdown'); + expect(service.status()).toBe('The server has stopped this connection.'); + expect(MockLeaderWebSocket.instances).toHaveLength(1); + }); }); diff --git a/frontend/src/app/core/sockets/leader-socket.service.ts b/frontend/src/app/core/sockets/leader-socket.service.ts index f139395..08069cc 100644 --- a/frontend/src/app/core/sockets/leader-socket.service.ts +++ b/frontend/src/app/core/sockets/leader-socket.service.ts @@ -84,6 +84,10 @@ export class LeaderSocketService extends WebSocketService { } } + protected override onShutdown(): void { + this.reconnecting = false; + } + protected override onSocketError(): void { this.statusMessage.set( 'Could not authenticate the leader feed. Open the game with a current Leader identity, then retry.', diff --git a/frontend/src/app/core/sockets/websocket.service.spec.ts b/frontend/src/app/core/sockets/websocket.service.spec.ts index 37cc803..64190b6 100644 --- a/frontend/src/app/core/sockets/websocket.service.spec.ts +++ b/frontend/src/app/core/sockets/websocket.service.spec.ts @@ -99,6 +99,11 @@ class MockRxWebSocket { } } +function reconnectDelay(attempt: number): number { + const delays = WebSocketService.RECONNECT_DELAYS; + return delays[Math.min(attempt - 1, delays.length - 1)]; +} + describe('WebSocketService', () => { let service: TestWebSocketService; let originalWebSocket: typeof WebSocket; @@ -200,7 +205,7 @@ describe('WebSocketService', () => { first.serverClose(wasClean); expect(service.transportState()).toBe('connecting'); - vi.advanceTimersByTime(999); + vi.advanceTimersByTime(reconnectDelay(1) - 1); expect(MockRxWebSocket.instances).toHaveLength(1); vi.advanceTimersByTime(1); @@ -225,7 +230,7 @@ describe('WebSocketService', () => { Object.defineProperty(window.navigator, 'onLine', { configurable: true, value: true }); window.dispatchEvent(new Event('online')); - vi.advanceTimersByTime(999); + vi.advanceTimersByTime(reconnectDelay(1) - 1); expect(MockRxWebSocket.instances).toHaveLength(1); vi.advanceTimersByTime(1); expect(MockRxWebSocket.instances).toHaveLength(2); @@ -257,7 +262,7 @@ describe('WebSocketService', () => { expect(service.requestReconnect('revoked')).toBe(true); expect(service.transportState()).toBe('revoked'); - vi.advanceTimersByTime(999); + vi.advanceTimersByTime(reconnectDelay(1) - 1); expect(MockRxWebSocket.instances).toHaveLength(1); vi.advanceTimersByTime(1); @@ -296,6 +301,38 @@ describe('WebSocketService', () => { expect(service.transportState()).toBe('idle'); }); + it('enters shutdown without reconnecting on a 1001 close', () => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => undefined); + vi.spyOn(console, 'warn').mockImplementation(() => undefined); + service.connect(); + const socket = MockRxWebSocket.instances[0]; + socket.open(); + + socket.serverClose(true, WebSocketService.SHUTDOWN_CODE, 'Server shutting down'); + expect(service.transportState()).toBe('shutdown'); + expect(service.status()).toBe('The server has stopped this connection.'); + vi.runAllTimers(); + + expect(MockRxWebSocket.instances).toHaveLength(1); + }); + + it('ignores a late close after a 1001 shutdown', () => { + vi.spyOn(console, 'log').mockImplementation(() => undefined); + MockRxWebSocket.closeSynchronously = false; + service.connect(); + const socket = MockRxWebSocket.instances[0]; + socket.open(); + const lateClose = socket.onclose; + + socket.serverClose(true, WebSocketService.SHUTDOWN_CODE, 'Server shutting down'); + expect(service.transportState()).toBe('shutdown'); + lateClose?.(new CloseEvent('close', { code: 1006, wasClean: false })); + + expect(service.transportState()).toBe('shutdown'); + expect(MockRxWebSocket.instances).toHaveLength(1); + }); + it('closes the active socket when its injection context is destroyed', () => { service.connect(); const socket = MockRxWebSocket.instances[0]; diff --git a/frontend/src/app/core/sockets/websocket.service.ts b/frontend/src/app/core/sockets/websocket.service.ts index 8c090c8..5ebf3a6 100644 --- a/frontend/src/app/core/sockets/websocket.service.ts +++ b/frontend/src/app/core/sockets/websocket.service.ts @@ -11,6 +11,7 @@ export type TransportState = | 'offline' // No network activity detected | 'suspended' // The client has deliberately paused transport | 'revoked' // For leaders that have been demoted to non-leaders + | 'shutdown' // The server deliberately ended the session | 'error'; // An error has occurred, the client may be attempting to reconnect @Service({ autoProvided: false }) @@ -19,6 +20,7 @@ export abstract class WebSocketService { static readonly WEBSOCKET_OPEN = 1; static readonly WEBSOCKET_CLOSING = 2; static readonly POLICY_VIOLATION_CODE = 1008; + static readonly SHUTDOWN_CODE = 1001; readonly status = computed(() => this.getStatus(this.state())); @@ -47,6 +49,8 @@ export abstract class WebSocketService { protected onSocketClose(_closeEvent: CloseEvent): void {} + protected onShutdown(): void {} + protected onSocketError(_error: unknown): void {} protected onInvalidMessage(_message: unknown, _error: unknown): void {} @@ -137,6 +141,10 @@ export abstract class WebSocketService { if (!this.isCurrentConnection(connectionId, socketSubject$)) { return; } + if (closeEvent.code === WebSocketService.SHUTDOWN_CODE) { + this.handleServerShutdown(connectionId, socketSubject$, closeEvent); + return; + } this.socketOpen = false; console.log('WebSocket closed: ', closeEvent); this.onSocketClose(closeEvent); @@ -281,6 +289,9 @@ export abstract class WebSocketService { case 'revoked': { return 'Websocket access revoked.'; } + case 'shutdown': { + return 'The server has stopped this connection.'; + } case 'error': { return 'Error with the websocket.'; } @@ -343,6 +354,23 @@ export abstract class WebSocketService { return this.requestedReconnectState ?? this.getReconnectState(); } + private handleServerShutdown( + connectionId: number, + socketSubject$: WebSocketSubject, + closeEvent: CloseEvent, + ): void { + if (!this.isCurrentConnection(connectionId, socketSubject$)) { + return; + } + this.socketOpen = false; + console.log('WebSocket closed: ', closeEvent); + this.onSocketClose(closeEvent); + this.reconnectAllowed = false; + this.requestedReconnectState = undefined; + this.onShutdown(); + this.state.set('shutdown'); + } + private isCurrentConnection( connectionId: number, socketSubject$: WebSocketSubject, diff --git a/frontend/src/app/pages/game-page/game-page.component.spec.ts b/frontend/src/app/pages/game-page/game-page.component.spec.ts index 5d040de..50ed35e 100644 --- a/frontend/src/app/pages/game-page/game-page.component.spec.ts +++ b/frontend/src/app/pages/game-page/game-page.component.spec.ts @@ -1,7 +1,7 @@ import { signal } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { Router } from '@angular/router'; -import { of } from 'rxjs'; +import { of, throwError } from 'rxjs'; import { ApiService } from '../../core/api.service'; import { CredentialsService } from '../../core/credentials.service'; @@ -11,50 +11,98 @@ import { MapInfo, PlayerStatus, PlayerType } from '../../core/game.models'; import { WakeLockService } from '../../core/wake-lock.service'; import { GamePageComponent } from './game-page.component'; +const map: MapInfo = { + min: { latitude: 49.27, longitude: -122.92 }, + max: { latitude: 49.28, longitude: -122.9 }, + width: 32, + height: 32, + isFlagFound: false, +}; +const api = { + getMap: vi.fn(() => of(map)), + registerPlayer: vi.fn(() => of({ id: 'NEWID' })), +}; +const credentials = { + get: vi.fn(() => ({ id: 'SELF' })), + save: vi.fn(), + getPlayerName: vi.fn(() => ''), + savePlayerName: vi.fn(), + clear: vi.fn(), +}; +const router = { navigateByUrl: vi.fn() }; +let triggerSessionExpired: (() => void) | null = null; +let triggerServerShutdown: (() => void) | null = null; +const gameSocket = { + players: signal({ + SELF: { + coordinate: { latitude: 49.275, longitude: -122.91 }, + player: { + id: 'SELF', + name: 'Leader', + type: PlayerType.Ghost, + status: PlayerStatus.Connected, + }, + }, + }), + status: signal('Connected.'), + isFlagFound: signal(false), + sessionExpired: signal(false), + start: vi.fn( + ( + _id: string, + _onConnected: () => void, + onSessionExpired: () => void, + onServerShutdown: () => void, + ) => { + triggerSessionExpired = onSessionExpired; + triggerServerShutdown = onServerShutdown; + gameSocket.sessionExpired.set(false); + }, + ), + stop: vi.fn(() => gameSocket.sessionExpired.set(false)), + resume: vi.fn(), + suspend: vi.fn(), + sendCoordinate: vi.fn(), + setInitialState: vi.fn(), +}; +const geolocation = { + status: signal('Ready.'), + start: vi.fn(), + stop: vi.fn(), +}; +const wakeLock = { + supported: signal(true), + enabled: signal(false), + status: signal('Screen wake lock is off.'), + initialize: vi.fn(), + setEnabled: vi.fn(async () => undefined), + handleVisibilityChange: vi.fn(async () => undefined), + release: vi.fn(async () => undefined), +}; + +async function configureTestBed(): Promise { + await TestBed.configureTestingModule({ + imports: [GamePageComponent], + providers: [ + { provide: ApiService, useValue: api }, + { provide: CredentialsService, useValue: credentials }, + { provide: Router, useValue: router }, + ], + }) + .overrideComponent(GamePageComponent, { + set: { + providers: [ + { provide: GameSocketService, useValue: gameSocket }, + { provide: GeolocationService, useValue: geolocation }, + { provide: WakeLockService, useValue: wakeLock }, + ], + }, + }) + .compileComponents(); +} + describe('GamePageComponent leader link', () => { let fixture: ComponentFixture; - const map: MapInfo = { - min: { latitude: 49.27, longitude: -122.92 }, - max: { latitude: 49.28, longitude: -122.9 }, - width: 32, - height: 32, - isFlagFound: false, - }; - const gameSocket = { - players: signal({ - SELF: { - coordinate: { latitude: 49.275, longitude: -122.91 }, - player: { - id: 'SELF', - name: 'Leader', - type: PlayerType.Ghost, - status: PlayerStatus.Connected, - }, - }, - }), - status: signal('Connected.'), - isFlagFound: signal(false), - start: vi.fn(), - stop: vi.fn(), - resume: vi.fn(), - suspend: vi.fn(), - sendCoordinate: vi.fn(), - setInitialState: vi.fn(), - }; - const geolocation = { - status: signal('Ready.'), - start: vi.fn(), - stop: vi.fn(), - }; - const wakeLock = { - supported: signal(true), - enabled: signal(false), - status: signal('Screen wake lock is off.'), - initialize: vi.fn(), - setEnabled: vi.fn(async () => undefined), - handleVisibilityChange: vi.fn(async () => undefined), - release: vi.fn(async () => undefined), - }; beforeEach(async () => { gameSocket.players.update((players) => ({ @@ -65,24 +113,7 @@ describe('GamePageComponent leader link', () => { }, })); - await TestBed.configureTestingModule({ - imports: [GamePageComponent], - providers: [ - { provide: ApiService, useValue: { getMap: vi.fn(() => of(map)) } }, - { provide: CredentialsService, useValue: { get: () => ({ id: 'SELF' }) } }, - { provide: Router, useValue: { navigateByUrl: vi.fn() } }, - ], - }) - .overrideComponent(GamePageComponent, { - set: { - providers: [ - { provide: GameSocketService, useValue: gameSocket }, - { provide: GeolocationService, useValue: geolocation }, - { provide: WakeLockService, useValue: wakeLock }, - ], - }, - }) - .compileComponents(); + await configureTestBed(); }); async function render(playerType: PlayerType): Promise { @@ -110,6 +141,116 @@ describe('GamePageComponent leader link', () => { it('does not show the leader link to a non-leader', async () => { const page = await render(PlayerType.Ghost); - expect(page.querySelector('.game-page__leader-link')).toBeNull(); + const link = page.querySelector('.game-page__leader-link a'); + expect(link?.style.visibility).toBe('hidden'); + }); +}); + +describe('GamePageComponent re-registration', () => { + let fixture: ComponentFixture; + + beforeEach(async () => { + vi.clearAllMocks(); + gameSocket.sessionExpired.set(false); + triggerSessionExpired = null; + triggerServerShutdown = null; + await configureTestBed(); + }); + + async function render(): Promise { + fixture = TestBed.createComponent(GamePageComponent); + fixture.detectChanges(); + await fixture.whenStable(); + fixture.detectChanges(); + return fixture.nativeElement as HTMLElement; + } + + it('clears credentials and redirects to /register when no name is saved', async () => { + credentials.getPlayerName.mockReturnValue(''); + await render(); + + triggerSessionExpired?.(); + await vi.waitFor(() => { + expect(router.navigateByUrl).toHaveBeenCalledWith('/register'); + }); + + expect(credentials.clear).toHaveBeenCalled(); + expect(gameSocket.stop).toHaveBeenCalled(); + }); + + it('re-registers with the saved name and reconnects', async () => { + credentials.getPlayerName.mockReturnValue('Odin'); + api.registerPlayer.mockReturnValue(of({ id: 'NEWID' })); + const page = await render(); + + triggerSessionExpired?.(); + await vi.waitFor(() => { + expect(gameSocket.start).toHaveBeenLastCalledWith( + 'NEWID', + expect.any(Function), + expect.any(Function), + expect.any(Function), + ); + }); + fixture.detectChanges(); + + expect(api.registerPlayer).toHaveBeenCalledWith('Odin'); + expect(credentials.save).toHaveBeenCalledWith({ id: 'NEWID' }); + expect(credentials.clear).not.toHaveBeenCalled(); + expect(page.textContent).toContain('Re-registered. Reconnecting…'); + + const startCalls = gameSocket.start.mock.calls; + const onConnected = startCalls[startCalls.length - 1][1] as () => void; + expect(startCalls[startCalls.length - 1][0]).toBe('NEWID'); + onConnected(); + fixture.detectChanges(); + + expect(geolocation.start).toHaveBeenCalledWith(expect.any(Function)); + expect(page.textContent).toContain('Connected to PacMacro.'); + }); + + it('clears the player session and redirects when the server shuts down', async () => { + await render(); + + triggerServerShutdown?.(); + + expect(geolocation.stop).toHaveBeenCalled(); + expect(credentials.clear).toHaveBeenCalled(); + expect(router.navigateByUrl).toHaveBeenCalledWith('/register', { + state: { serverStopped: true }, + }); + expect(api.registerPlayer).not.toHaveBeenCalled(); + }); + + it('clears credentials and redirects when re-registration fails', async () => { + credentials.getPlayerName.mockReturnValue('Odin'); + api.registerPlayer.mockReturnValue(throwError(() => new Error('API is down'))); + const page = await render(); + + triggerSessionExpired?.(); + await vi.waitFor(() => { + expect(router.navigateByUrl).toHaveBeenCalledWith('/register'); + }); + fixture.detectChanges(); + + expect(credentials.clear).toHaveBeenCalled(); + expect(gameSocket.stop).toHaveBeenCalled(); + expect(page.textContent).toContain('Could not re-register. Redirecting…'); + }); + + it('treats an empty player ID from the API as a failure', async () => { + credentials.getPlayerName.mockReturnValue('Odin'); + api.registerPlayer.mockReturnValue(of({ id: ' ' })); + const page = await render(); + + triggerSessionExpired?.(); + await vi.waitFor(() => { + expect(router.navigateByUrl).toHaveBeenCalledWith('/register'); + }); + fixture.detectChanges(); + + expect(credentials.clear).toHaveBeenCalled(); + expect(gameSocket.stop).toHaveBeenCalled(); + expect(page.textContent).toContain('Could not re-register. Redirecting…'); }); }); diff --git a/frontend/src/app/pages/game-page/game-page.component.ts b/frontend/src/app/pages/game-page/game-page.component.ts index b435cb3..1f2c9e1 100644 --- a/frontend/src/app/pages/game-page/game-page.component.ts +++ b/frontend/src/app/pages/game-page/game-page.component.ts @@ -41,6 +41,7 @@ export class GamePageComponent { protected readonly map = signal(null); protected readonly selfId = signal(''); protected readonly pageStatus = signal('Loading the game map…'); + protected readonly selfSummary = computed(() => { const player = this.socket.players()[this.selfId()]?.player; return player ? `${player.name} (${player.id}) is ${typeLabel(player.type)}` : ''; @@ -58,6 +59,11 @@ export class GamePageComponent { this.geolocation.stop(); this.socket.suspend('Offline. Waiting for a network connection…'); }; + private readonly onServerShutdown = () => { + this.geolocation.stop(); + this.credentials.clear(); + void this.router.navigateByUrl('/register', { state: { serverStopped: true } }); + }; constructor() { afterNextRender(() => void this.initialize()); @@ -68,6 +74,36 @@ export class GamePageComponent { await this.wakeLock.setEnabled((event.target as HTMLInputElement).checked); } + private async autoReregister(): Promise { + const name = this.credentials.getPlayerName(); + if (!name) { + this.credentials.clear(); + this.socket.stop(); + await this.router.navigateByUrl('/register'); + return; + } + + this.pageStatus.set('Re-registering…'); + + try { + const response = await firstValueFrom(this.api.registerPlayer(name)); + const id = response.id.trim(); + if (!id) { + throw new Error('The API returned an empty player ID.'); + } + + this.credentials.save({ id }); + this.selfId.set(id); + this.pageStatus.set('Re-registered. Reconnecting…'); + this.connectAs(id); + } catch { + this.credentials.clear(); + this.socket.stop(); + this.pageStatus.set('Could not re-register. Redirecting…'); + await this.router.navigateByUrl('/register'); + } + } + private async initialize(): Promise { if (!this.browserWindow) { return; @@ -96,10 +132,19 @@ export class GamePageComponent { this.browserWindow.document.addEventListener('visibilitychange', this.onVisibilityChange); this.browserWindow.addEventListener('online', this.onOnline); this.browserWindow.addEventListener('offline', this.onOffline); - this.socket.start(credentials.id, () => { - this.pageStatus.set('Connected to PacMacro.'); - this.geolocation.start((coordinate) => this.socket.sendCoordinate(coordinate)); - }); + this.connectAs(credentials.id); + } + + private connectAs(id: string): void { + this.socket.start( + id, + () => { + this.pageStatus.set('Connected to PacMacro.'); + this.geolocation.start((coordinate) => this.socket.sendCoordinate(coordinate)); + }, + () => void this.autoReregister(), + this.onServerShutdown, + ); } private cleanup(): void { diff --git a/frontend/src/app/pages/register-page/register-page.component.spec.ts b/frontend/src/app/pages/register-page/register-page.component.spec.ts index e560a89..8c4b0df 100644 --- a/frontend/src/app/pages/register-page/register-page.component.spec.ts +++ b/frontend/src/app/pages/register-page/register-page.component.spec.ts @@ -1,3 +1,4 @@ +import { Location } from '@angular/common'; import { WritableSignal } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { Router } from '@angular/router'; @@ -12,16 +13,19 @@ describe('RegisterPageComponent', () => { registerAdmin: vi.fn(() => of(void 0)), registerPlayer: vi.fn(() => of({ id: 'ABCD' })), }; - const credentials = { save: vi.fn() }; + const credentials = { save: vi.fn(), savePlayerName: vi.fn(), getPlayerName: vi.fn(() => '') }; + const location = { getState: vi.fn(() => ({})) }; const router = { navigateByUrl: vi.fn(() => Promise.resolve(true)) }; beforeEach(() => { vi.clearAllMocks(); + location.getState.mockReturnValue({}); TestBed.configureTestingModule({ imports: [RegisterPageComponent], providers: [ { provide: ApiService, useValue: api }, { provide: CredentialsService, useValue: credentials }, + { provide: Location, useValue: location }, { provide: Router, useValue: router }, ], }); @@ -39,6 +43,7 @@ describe('RegisterPageComponent', () => { expect(api.registerPlayer).toHaveBeenCalledWith('Test2'); expect(api.registerAdmin).not.toHaveBeenCalled(); expect(credentials.save).toHaveBeenCalledWith({ id: 'ABCD' }); + expect(credentials.savePlayerName).toHaveBeenCalledWith('Test2'); expect(router.navigateByUrl).toHaveBeenCalledWith('/'); }); @@ -52,6 +57,24 @@ describe('RegisterPageComponent', () => { await component.submit(submitEvent()); expect(api.registerPlayer).not.toHaveBeenCalled(); + expect(credentials.save).not.toHaveBeenCalled(); + expect(credentials.savePlayerName).not.toHaveBeenCalled(); + }); + + it('pre-fills the name from the saved player name', () => { + credentials.getPlayerName.mockReturnValue('SavedPlayer'); + const component = TestBed.createComponent(RegisterPageComponent) + .componentInstance as unknown as RegisterPageHarness; + + expect(component.registrationModel().name).toBe('SavedPlayer'); + }); + + it('shows the shutdown message when routed from a stopped server', () => { + location.getState.mockReturnValue({ serverStopped: true }); + const component = TestBed.createComponent(RegisterPageComponent) + .componentInstance as unknown as RegisterPageHarness; + + expect(component.status()).toBe('The server stopped. Register to join the next game.'); }); }); @@ -59,6 +82,7 @@ interface RegisterPageHarness { registrationModel: WritableSignal<{ name: string; }>; + status: WritableSignal; submit(event: SubmitEvent): Promise; } diff --git a/frontend/src/app/pages/register-page/register-page.component.ts b/frontend/src/app/pages/register-page/register-page.component.ts index c04ca41..180b61f 100644 --- a/frontend/src/app/pages/register-page/register-page.component.ts +++ b/frontend/src/app/pages/register-page/register-page.component.ts @@ -1,3 +1,4 @@ +import { Location } from '@angular/common'; import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core'; import { form, @@ -27,10 +28,11 @@ interface RegistrationModel { export class RegisterPageComponent { private readonly api = inject(ApiService); private readonly credentials = inject(CredentialsService); + private readonly location = inject(Location); private readonly router = inject(Router); protected readonly registrationModel = signal({ - name: '', + name: this.credentials.getPlayerName() ?? '', }); protected readonly registrationForm = form(this.registrationModel, (registration) => { @@ -38,7 +40,11 @@ export class RegisterPageComponent { maxLength(registration.name, 80, { message: 'Your name must be 80 characters or fewer.' }); }); - protected readonly status = signal(''); + protected readonly status = signal( + (this.location.getState() as { serverStopped?: boolean })?.serverStopped + ? 'The server stopped. Register to join the next game.' + : '', + ); protected async submit(event: SubmitEvent): Promise { event.preventDefault(); @@ -62,6 +68,7 @@ export class RegisterPageComponent { throw new Error('The API returned an empty player ID.'); } this.credentials.save({ id }); + this.credentials.savePlayerName(trimmedName); await this.router.navigateByUrl('/'); } catch (error) { this.status.set('Registration failed. Check your details and the API connection.'); diff --git a/main.go b/main.go index 5531ddb..e930cca 100644 --- a/main.go +++ b/main.go @@ -1,10 +1,14 @@ package main import ( + "context" "fmt" "log" "net/http" "os" + "os/signal" + "syscall" + "time" "github.com/joho/godotenv" "pacmacro/api" @@ -53,33 +57,89 @@ func main() { } var ( - players api.Players - game api.Game - admin api.Admin - leader api.Leader - sock api.Sockets + players api.Players + game api.Game + admin api.Admin + leader api.Leader + sock api.Sockets + lifecycle = api.NewLifecycle() ) players.Init() // initialize players handler if err := game.Init(&players); err != nil { log.Fatalf("initialize game: %v", err) } - sock.Init(&players, &game) // initialize sockets handler - admin.Init(&players, &sock, adminPassword, &game) // initialize admin handler - leader.Init(&players, &game, &sock) // initialize leader handler + sock.Init(&players, lifecycle, &game) // initialize sockets handler + admin.Init(&players, &sock, adminPassword, lifecycle, &game) // initialize admin handler + leader.Init(&players, &game, &sock, lifecycle) // initialize leader handler - http.Handle("/api/player/", corsMiddleware(&players)) // /api/player/register; /api/player/list.json - http.Handle("/api/admin/", corsMiddleware(&admin)) // registration and authenticated admin operations - http.Handle("/api/leader/", corsMiddleware(&leader)) // authenticated leader operations - http.Handle("/api/game/", corsMiddleware(&game)) // /api/game/map.json - http.Handle("/api/ws/", corsMiddleware(&sock)) // /api/ws/ + mux := http.NewServeMux() + mux.Handle("/api/player/", corsMiddleware(&players)) // /api/player/register; /api/player/list.json + mux.Handle("/api/admin/", corsMiddleware(&admin)) // registration and authenticated admin operations + mux.Handle("/api/leader/", corsMiddleware(&leader)) // authenticated leader operations + mux.Handle("/api/game/", corsMiddleware(&game)) // /api/game/map.json + mux.Handle("/api/ws/", corsMiddleware(&sock)) // /api/ws/ port := ":49152" + server := &http.Server{Addr: port, Handler: mux} // print to terminal that server started fmt.Printf("Started PacMacro; listening on localhost%s...\n", port) // PacMacro API is served on port 49152. // this should be proxied inside the web server used. - log.Fatal(http.ListenAndServe(port, nil)) + serverErr := make(chan error, 1) + go func() { + serverErr <- server.ListenAndServe() + }() + + // Block until SIGINT (Ctrl+C) or SIGTERM (systemd stop/restart). + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + select { + case err := <-serverErr: + if err != nil && err != http.ErrServerClosed { + shutdownWebSockets(lifecycle) + log.Fatalf("listen and serve: %v", err) + } + return + case <-ctx.Done(): + } + + fmt.Println("Shutdown signal received. Notifying players...") + shutdown(server, lifecycle) + fmt.Println("Server exiting.") +} + +func shutdownWebSockets(lifecycle *api.Lifecycle) { + if !lifecycle.Shutdown(time.Now().Add(api.WebsocketCloseWriteTimeout)) { + fmt.Println("Shutdown timed out waiting for WebSocket workers.") + } +} + +func shutdown(server *http.Server, lifecycle *api.Lifecycle) { + // Close listeners immediately so no new HTTP or WebSocket connections are + // accepted while existing connections drain. + shutdownCtx, cancel := context.WithTimeout(context.Background(), api.ShutdownTimeout) + defer cancel() + + httpDone := make(chan struct{}) + go func() { + _ = server.Shutdown(shutdownCtx) + close(httpDone) + }() + + // Notify WebSocket clients concurrently with HTTP draining. All close + // frames share one absolute deadline so stalled clients share the budget. + wsDone := make(chan bool, 1) + wsDeadline := time.Now().Add(api.WebsocketCloseWriteTimeout) + go func() { + wsDone <- lifecycle.Shutdown(wsDeadline) + }() + + <-httpDone + websocketsClean := <-wsDone + if !websocketsClean { + fmt.Println("Shutdown timed out waiting for WebSocket workers.") + } }