package server // claim reserves sessionID for clientID. It reports true when the session is // free or already held by the same client (so a client may re-prompt its own // session) and false when another client holds it. The claim map is bounded by // chatMaxTurns with oldest-eviction so a stuck client cannot grow it without // limit. func (h *chatHub) claim(sessionID, clientID string) bool { if sessionID == "" || clientID == "" { return false } h.mu.Lock() defer h.mu.Unlock() if h.claims == nil { h.claims = map[string]string{} } if holder, ok := h.claims[sessionID]; ok { return holder == clientID } h.evictClaimsLocked() h.claims[sessionID] = clientID h.claimOrder = append(h.claimOrder, sessionID) return true } // release drops the same client's claim on sessionID; a claim held by a // different client is left untouched so a stale release cannot free a live one. func (h *chatHub) release(sessionID, clientID string) { h.mu.Lock() defer h.mu.Unlock() if holder, ok := h.claims[sessionID]; !ok || holder != clientID { return } delete(h.claims, sessionID) for i, id := range h.claimOrder { if id == sessionID { h.claimOrder = append(h.claimOrder[:i], h.claimOrder[i+1:]...) break } } } // busyForOther reports whether another client currently holds sessionID. func (h *chatHub) busyForOther(sessionID, clientID string) bool { h.mu.Lock() defer h.mu.Unlock() holder, ok := h.claims[sessionID] return ok && holder != clientID } // evictClaimsLocked drops the oldest claim when the cap is reached, keeping the // claim map bounded like the retained turns. Callers must hold h.mu. func (h *chatHub) evictClaimsLocked() { if len(h.claims) < chatMaxTurns { return } for len(h.claimOrder) > 0 { oldest := h.claimOrder[0] h.claimOrder = h.claimOrder[1:] if _, ok := h.claims[oldest]; ok { delete(h.claims, oldest) return } } }