fix(session): race condition.

This commit is contained in:
Houmgaor
2025-10-19 23:49:23 +02:00
parent e654bc47bf
commit 80c3634895
2 changed files with 9 additions and 7 deletions

View File

@@ -8,6 +8,7 @@ import (
"io" "io"
"net" "net"
"sync" "sync"
"sync/atomic"
"time" "time"
"erupe-ce/common/byteframe" "erupe-ce/common/byteframe"
@@ -84,7 +85,8 @@ type Session struct {
mailList []int // Maps accumulated indices to actual mail IDs mailList []int // Maps accumulated indices to actual mail IDs
// Connection state // Connection state
closed bool // Whether connection has been closed (prevents double-cleanup) // Use atomic.Bool for thread-safe access from multiple goroutines
closed atomic.Bool // Whether connection has been closed (prevents double-cleanup)
} }
// NewSession creates and initializes a new Session for an incoming connection. // NewSession creates and initializes a new Session for an incoming connection.
@@ -233,7 +235,7 @@ func (s *Session) QueueAck(ackHandle uint32, data []byte) {
func (s *Session) sendLoop() { func (s *Session) sendLoop() {
for { for {
if s.closed { if s.closed.Load() {
return return
} }
// Send each packet individually with its own terminator // Send each packet individually with its own terminator
@@ -254,7 +256,7 @@ func (s *Session) recvLoop() {
logoutPlayer(s) logoutPlayer(s)
return return
} }
if s.closed { if s.closed.Load() {
logoutPlayer(s) logoutPlayer(s)
return return
} }
@@ -291,7 +293,7 @@ func (s *Session) handlePacketGroup(pktGroup []byte) {
s.logMessage(opcodeUint16, pktGroup, s.Name, "Server") s.logMessage(opcodeUint16, pktGroup, s.Name, "Server")
if opcode == network.MSG_SYS_LOGOUT { if opcode == network.MSG_SYS_LOGOUT {
s.closed = true s.closed.Store(true)
return return
} }
// Get the packet parser and handler for this opcode. // Get the packet parser and handler for this opcode.

View File

@@ -111,13 +111,13 @@ func TestSessionClosedFlag(t *testing.T) {
server := createMockServer() server := createMockServer()
session := createMockSession(1, server) session := createMockSession(1, server)
if session.closed { if session.closed.Load() {
t.Error("new session should not be closed") t.Error("new session should not be closed")
} }
session.closed = true session.closed.Store(true)
if !session.closed { if !session.closed.Load() {
t.Error("session closed flag should be settable") t.Error("session closed flag should be settable")
} }
} }