[WIP] Optimizations: code readiness optimizations

This commit is contained in:
Alex P 2025-10-17 10:09:04 +03:00
parent 0e040a9b54
commit 8f17bbd1f9
2 changed files with 33 additions and 12 deletions

View File

@ -95,6 +95,7 @@ type SessionManager struct {
primaryTimeout time.Duration // 8 bytes primaryTimeout time.Duration // 8 bytes
logger *zerolog.Logger // 8 bytes logger *zerolog.Logger // 8 bytes
sessions map[string]*Session // 8 bytes sessions map[string]*Session // 8 bytes
nicknameIndex map[string]*Session // 8 bytes - O(1) nickname uniqueness lookups
reconnectGrace map[string]time.Time // 8 bytes reconnectGrace map[string]time.Time // 8 bytes
reconnectInfo map[string]*SessionData // 8 bytes reconnectInfo map[string]*SessionData // 8 bytes
transferBlacklist []TransferBlacklistEntry // Prevent demoted sessions from immediate re-promotion transferBlacklist []TransferBlacklistEntry // Prevent demoted sessions from immediate re-promotion
@ -136,6 +137,7 @@ func NewSessionManager(logger *zerolog.Logger) *SessionManager {
sm := &SessionManager{ sm := &SessionManager{
sessions: make(map[string]*Session), sessions: make(map[string]*Session),
nicknameIndex: make(map[string]*Session),
reconnectGrace: make(map[string]time.Time), reconnectGrace: make(map[string]time.Time),
reconnectInfo: make(map[string]*SessionData), reconnectInfo: make(map[string]*SessionData),
transferBlacklist: make([]TransferBlacklistEntry, 0), transferBlacklist: make([]TransferBlacklistEntry, 0),
@ -177,10 +179,10 @@ func (sm *SessionManager) AddSession(session *Session, clientSettings *SessionSe
sm.mu.Lock() sm.mu.Lock()
defer sm.mu.Unlock() defer sm.mu.Unlock()
// Check nickname uniqueness (only for non-empty nicknames) // Check nickname uniqueness using O(1) index (only for non-empty nicknames)
if session.Nickname != "" { if session.Nickname != "" {
for id, existingSession := range sm.sessions { if existingSession, exists := sm.nicknameIndex[session.Nickname]; exists {
if id != session.ID && existingSession.Nickname == session.Nickname { if existingSession.ID != session.ID {
return fmt.Errorf("nickname '%s' is already in use by another session", session.Nickname) return fmt.Errorf("nickname '%s' is already in use by another session", session.Nickname)
} }
} }
@ -351,6 +353,11 @@ func (sm *SessionManager) AddSession(session *Session, clientSettings *SessionSe
// Ensure session has auto-generated nickname if needed // Ensure session has auto-generated nickname if needed
sm.ensureNickname(session) sm.ensureNickname(session)
// Add to nickname index
if session.Nickname != "" {
sm.nicknameIndex[session.Nickname] = session
}
sm.validateSinglePrimary() sm.validateSinglePrimary()
// Clean up grace period after validation completes // Clean up grace period after validation completes
@ -531,20 +538,26 @@ func (sm *SessionManager) ClearGracePeriod(sessionID string) {
// isSessionBlacklisted checks if a session was recently demoted via transfer and should not become primary // isSessionBlacklisted checks if a session was recently demoted via transfer and should not become primary
func (sm *SessionManager) isSessionBlacklisted(sessionID string) bool { func (sm *SessionManager) isSessionBlacklisted(sessionID string) bool {
now := time.Now() now := time.Now()
isBlacklisted := false
// Clean expired entries while we're here // Clean expired entries in-place (zero allocations)
validEntries := make([]TransferBlacklistEntry, 0, len(sm.transferBlacklist)) writeIndex := 0
for _, entry := range sm.transferBlacklist { for readIndex := 0; readIndex < len(sm.transferBlacklist); readIndex++ {
entry := sm.transferBlacklist[readIndex]
if now.Before(entry.ExpiresAt) { if now.Before(entry.ExpiresAt) {
validEntries = append(validEntries, entry) // Keep this entry - still valid
sm.transferBlacklist[writeIndex] = entry
writeIndex++
if entry.SessionID == sessionID { if entry.SessionID == sessionID {
return true // Found active blacklist entry isBlacklisted = true
} }
} }
// Expired entries are automatically skipped (not copied forward)
} }
sm.transferBlacklist = validEntries // Update with only non-expired entries // Truncate to only valid entries
sm.transferBlacklist = sm.transferBlacklist[:writeIndex]
return false return isBlacklisted
} }
// GetPrimarySession returns the current primary session // GetPrimarySession returns the current primary session
@ -1519,10 +1532,17 @@ func (sm *SessionManager) broadcastSessionListUpdate() {
// Now send events without holding lock // Now send events without holding lock
for _, session := range activeSessions { for _, session := range activeSessions {
// Per-session throttling to prevent broadcast storms // Per-session throttling to prevent broadcast storms
if time.Since(session.LastBroadcast) < sessionBroadcastDelay { session.lastBroadcastMu.Lock()
shouldSkip := time.Since(session.LastBroadcast) < sessionBroadcastDelay
if !shouldSkip {
session.LastBroadcast = time.Now()
}
session.lastBroadcastMu.Unlock()
if shouldSkip {
continue continue
} }
session.LastBroadcast = time.Now()
event := SessionsUpdateEvent{ event := SessionsUpdateEvent{
Sessions: infos, Sessions: infos,
YourMode: session.Mode, YourMode: session.Mode,

View File

@ -44,6 +44,7 @@ type Session struct {
rpcRateLimitMu sync.Mutex // Protects rate limit fields rpcRateLimitMu sync.Mutex // Protects rate limit fields
rpcRateLimit int // Count of RPCs in current window rpcRateLimit int // Count of RPCs in current window
rpcRateLimitWin time.Time // Start of current rate limit window rpcRateLimitWin time.Time // Start of current rate limit window
lastBroadcastMu sync.Mutex // Protects LastBroadcast field
peerConnection *webrtc.PeerConnection peerConnection *webrtc.PeerConnection
VideoTrack *webrtc.TrackLocalStaticSample VideoTrack *webrtc.TrackLocalStaticSample