Repository navigation
refactor (gql-middleware): Minor improvements - #24832
gustavotrott merged 8 commits into
Conversation
…ocks In CacheLocks.Unlock, c.mutex was released before rm.mutex.Unlock(), opening a window where a new goroutine could create a fresh refMutex for the same key and immediately acquire it — entering the critical section while the previous holder had not yet fully exited. Fix: call rm.mutex.Unlock() first, then release c.mutex, so no new waiter can observe the key as "available" until the unlock is complete. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…nnections Add(1) and Load() were two separate atomic operations. On a multi-core machine two goroutines could both call Add(1) before either called Load(), causing both to read the same value and produce identical browserConnectionIds. The second write to BrowserConnections would overwrite the first, leaving one connection invisible to Redis handlers and driving the wrong BrowserConnection from the Hasura reconnection loop. Fix: capture the return value of Add(1) directly, which is already the unique post-increment value for this goroutine. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…nection lock BrowserConnection.HasuraConnection was assigned (and cleared) in HasuraClient without holding the embedded RWMutex, while invalidateHasuraConnectionForSessionToken reads it under RLock. This constituted a data race that could cause a stale or nil pointer to be observed by the invalidation path. Fix: wrap both the assignment and the nil-clear in Lock/Unlock. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
When a subscription was re-registered during Hasura reconnection, LastReceivedDataChecksum was correctly preserved but LastReceivedData (the HasuraMessage needed as the base for JSON patch computation) was silently reset to its zero value. As a result, GetPatchedMessage received an empty lastHasuraMessage, skipped patch computation, and sent the full current state to the browser instead of a diff — causing the browser to wrongly replace its entire user list view on every reconnect. Fix: capture LastReceivedData from the existing subscription entry and carry it forward into the re-registered subscription, mirroring the existing treatment of LastReceivedDataChecksum. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ion RLock BBBWebSessionVariables is written in refreshUserSessionVariables under bc.Lock(), but was read in the cursor and role-notification handlers while holding only BrowserConnectionsMutex.RLock() — a different mutex. This constituted a data race: a concurrent map replacement could expose a nil map or a torn pointer to the reader. Fix: bracket every BBBWebSessionVariables map read with bc.RLock() / bc.RUnlock(). The lock order (BrowserConnectionsMutex → bc) is safe because refreshUserSessionVariables never holds BrowserConnectionsMutex when it acquires bc.Lock(). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…changed ConnectionInitMessage (containing the original session token) is sent to Hasura on every reconnect triggered by ForceUserGraphqlReconnectionSysMsg. If bbb-web had updated the token's meeting mapping since the browser first connected, Hasura's auth hook would return a different meetingId, causing Hasura to send Meeting Y's data while the middleware still stored and routed it under Meeting X — the root cause of cross-meeting data leakage visible as a foreign user appearing in the local user list. Fix: at the start of refreshUserSessionVariables, re-verify the session token with bbb-web. If the resolved meetingId differs from the one set at connection init, cancel the browser context immediately. This forces the browser to reconnect from scratch with fresh credentials, rather than continuing to receive data for the wrong meeting. Also remove the duplicated BBBWebSessionVariables assignment and snapshot the immutable connection fields under RLock before releasing it. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…essionVariables A session token in BBB always maps to the same meeting for its entire lifetime, so the meetingId resolved by bbb-web can never change after the initial connection. The extra BBBWebCheckAuthorization call and the meeting-mismatch guard added in the previous commit are therefore unnecessary overhead. Restore refreshUserSessionVariables to its original shape (akka-apps call only), minus the duplicate BBBWebSessionVariables assignment that was present in the original. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
WalkthroughThis pull request adds concurrency protection to several critical code paths by introducing or reordering mutex locks around shared resource access. Changes include reordering lock releases in the CustomCache's Unlock method to prevent race conditions, wrapping pointer mutations to HasuraConnection with locks, tracking LastReceivedData alongside checksums in subscription handling, and adding read locks around session variable access in streaming event handlers. Additionally, minor refactoring simplifies atomic counter usage and removes a duplicate variable assignment. No new features or exported APIs are introduced. Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (2.11.4)level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain main module or its selected dependencies" Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@bbb-graphql-middleware/internal/streaming_server/notificationStream.go`:
- Around line 71-76: The comparison using bc.MeetingId is performed before
acquiring bc.RLock(), causing a race with updates done under Lock(); modify
notificationStream.go so you acquire bc.RLock() first, read bc.MeetingId and
bc.BBBWebSessionVariables while holding the lock, then compute
isModerator/isPresenter and compare the local meetingId to
receivedMessage.Core.Header.MeetingId (or alternatively copy bc.MeetingId into a
local variable under the RLock and perform the comparison and role checks using
those locals), ensuring all accesses to bc.MeetingId and BBBWebSessionVariables
happen under the same lock used by Lock()/RLock().
In `@bbb-graphql-middleware/internal/streaming_server/presPageCursorStream.go`:
- Around line 45-50: The code reads bc.MeetingId before acquiring bc.RLock(),
causing a data race; fix by acquiring bc.RLock() before any access to bc fields:
inside the loop call bc.RLock(), read bc.MeetingId into a local variable (e.g.
currentMeetingId), evaluate userHasViewersCursorLocked using
bc.BBBWebSessionVariables and bc.UserId, then bc.RUnlock(); then compare
currentMeetingId to receivedMessage.Core.Header.MeetingId and proceed to append
bc to browserConnectionsToSendData as before. Ensure you only hold the RLock for
the minimal read portion and use the local copy for subsequent checks.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 97e89024-dc18-46a3-bcd3-7f3091970fe4
📒 Files selected for processing (6)
bbb-graphql-middleware/internal/common/CustomCache.gobbb-graphql-middleware/internal/hasura/client.gobbb-graphql-middleware/internal/hasura/conn/writer/writer.gobbb-graphql-middleware/internal/streaming_server/notificationStream.gobbb-graphql-middleware/internal/streaming_server/presPageCursorStream.gobbb-graphql-middleware/internal/websrv/connhandler.go
|
There was a problem hiding this comment.
♻️ Duplicate comments (2)
bbb-graphql-middleware/internal/streaming_server/presPageCursorStream.go (1)
74-75:⚠️ Potential issue | 🔴 CriticalProtect the cached meeting lookup here too.
SendPreviousCursorPositionstill readsbrowserConnection.MeetingIdwithoutbrowserConnection.RLock(), so this path can still race with connection setup/teardown. Please snapshot the meeting ID under the read lock before callingGetCursorsCache().🔧 Suggested fix
func SendPreviousCursorPosition(browserConnection *common.BrowserConnection, queryId string) { - previousMessages, existsPreviousMessages := GetCursorsCache(browserConnection.MeetingId) + browserConnection.RLock() + meetingId := browserConnection.MeetingId + browserConnection.RUnlock() + + previousMessages, existsPreviousMessages := GetCursorsCache(meetingId) if existsPreviousMessages {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@bbb-graphql-middleware/internal/streaming_server/presPageCursorStream.go` around lines 74 - 75, The function SendPreviousCursorPosition reads browserConnection.MeetingId without holding the connection read-lock; snapshot the meeting ID under browserConnection.RLock()/RUnlock() before calling GetCursorsCache to avoid races. Locate SendPreviousCursorPosition and add a short read-lock scope to set a local meetingId variable from browserConnection.MeetingId, then use that local meetingId when calling GetCursorsCache and elsewhere in the function (leave GetCursorsCache and existing logic unchanged).bbb-graphql-middleware/internal/streaming_server/notificationStream.go (1)
13-62:⚠️ Potential issue | 🔴 CriticalFinish locking the remaining notification filters.
HandleNotifyAllInMeetingEvtMsgandHandleNotifyUserInMeetingEvtMsgstill readbc.MeetingId/bc.UserIdwithoutbc.RLock(), so the same connection-state race remains on those notification paths. Please apply the same lock-and-copy pattern there as well.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@bbb-graphql-middleware/internal/streaming_server/notificationStream.go` around lines 13 - 62, Both HandleNotifyAllInMeetingEvtMsg and HandleNotifyUserInMeetingEvtMsg read bc.MeetingId and bc.UserId without holding bc.RLock(), creating a race; update each function to follow the lock-and-copy pattern: when iterating browserConnections, acquire bc.RLock() for each connection, copy the minimal fields needed (MeetingId, UserId and a pointer/reference to bc if you still need it), then bc.RUnlock() before appending to browserConnectionsToSendData/browserConnectionsToSendCursor so subsequent use (including ActiveStreamings access) is done on a safely-copied snapshot; ensure you call bc.RLock()/RUnlock() on the per-connection lock (same lock used elsewhere) and keep existing ActiveStreamingsMutex usage intact when later reading ActiveStreamings in the send loop.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@bbb-graphql-middleware/internal/streaming_server/notificationStream.go`:
- Around line 13-62: Both HandleNotifyAllInMeetingEvtMsg and
HandleNotifyUserInMeetingEvtMsg read bc.MeetingId and bc.UserId without holding
bc.RLock(), creating a race; update each function to follow the lock-and-copy
pattern: when iterating browserConnections, acquire bc.RLock() for each
connection, copy the minimal fields needed (MeetingId, UserId and a
pointer/reference to bc if you still need it), then bc.RUnlock() before
appending to browserConnectionsToSendData/browserConnectionsToSendCursor so
subsequent use (including ActiveStreamings access) is done on a safely-copied
snapshot; ensure you call bc.RLock()/RUnlock() on the per-connection lock (same
lock used elsewhere) and keep existing ActiveStreamingsMutex usage intact when
later reading ActiveStreamings in the send loop.
In `@bbb-graphql-middleware/internal/streaming_server/presPageCursorStream.go`:
- Around line 74-75: The function SendPreviousCursorPosition reads
browserConnection.MeetingId without holding the connection read-lock; snapshot
the meeting ID under browserConnection.RLock()/RUnlock() before calling
GetCursorsCache to avoid races. Locate SendPreviousCursorPosition and add a
short read-lock scope to set a local meetingId variable from
browserConnection.MeetingId, then use that local meetingId when calling
GetCursorsCache and elsewhere in the function (leave GetCursorsCache and
existing logic unchanged).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: c80d0aef-0257-4432-8797-e97051e24704
📒 Files selected for processing (2)
bbb-graphql-middleware/internal/streaming_server/notificationStream.gobbb-graphql-middleware/internal/streaming_server/presPageCursorStream.go
✅ Automated tests have passed! |



A few minor improvements related with race conditions.
No known issues reported about it but it is still important.