Repository navigation
fix (gql-middleware): Introducing synchronous graphql reconnection endpoint to resolve race condition issues - #21816
Conversation
… and refresh session vars
WalkthroughThe changes in this pull request introduce significant modifications to the handling of GraphQL reconnections across various components of the application. A new Additionally, a new configuration entry for Suggested reviewers
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Outside diff range and nitpick comments (6)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UsersApp.scala (1)
78-84: Consider adding error handling for GraphQL reconnectionThe current implementation doesn't handle potential failures in the GraphQL reconnection request. Consider wrapping the call in a try-catch block to handle network issues or server errors gracefully.
Here's a suggested improvement:
if(regUser.joined) { - GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "assigned_presenter_automatically") + try { + GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "assigned_presenter_automatically") + } catch { + case e: Exception => + log.error(s"Failed to reconnect GraphQL for user ${regUser.id}: ${e.getMessage}") + // Consider if additional error handling is needed + } }akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/EjectUserFromBreakoutInternalMsgHdlr.scala (2)
Line range hint
31-31: Implement the TODO about informing reasonThere's an unimplemented TODO comment about informing the reason for ejection.
Would you like me to help implement the reason notification system? I can propose a solution that integrates with your existing messaging system.
Based on the code analysis, I can now provide the final response:
Race condition concern is valid, but implementation needs improvement
The current implementation of
GraphqlMiddleware.requestGraphqlReconnectionlacks error handling and doesn't provide any feedback about the success or failure of the operation. This makes the suggested order-of-operations change essential, as the current implementation could leave the system in an inconsistent state if the GraphQL reconnection fails after the soft delete.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/graphql/GraphqlMiddleware.scala: Add error handling and make the method return a Try/Either type instead of Unitakka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/EjectUserFromBreakoutInternalMsgHdlr.scala: Implement the suggested order change with proper error handling🔗 Analysis chain
Line range hint
31-40: Review order of operations for race condition preventionThe current order of operations (soft delete before GraphQL reconnection) might still allow a race condition if the user makes requests between these operations.
Let's verify the impact:
Consider this order instead:
- UserDAO.softDelete(registeredUser.meetingId, registeredUser.id) - - // Force reconnection with graphql to refresh permissions - GraphqlMiddleware.requestGraphqlReconnection(registeredUser.sessionToken, msg.reasonCode) + // Force reconnection with graphql to refresh permissions first + try { + GraphqlMiddleware.requestGraphqlReconnection(Vector(registeredUser.sessionToken), msg.reasonCode) + // Only proceed with soft delete after successful reconnection + UserDAO.softDelete(registeredUser.meetingId, registeredUser.id) + } catch { + case e: Exception => + log.error(s"Failed to complete user ejection process for ${registeredUser.id}", e) + // Consider if we need to take any recovery actions + }
Let me gather more information about the GraphQL reconnection implementation to better understand the race condition potential.
Let me check the implementation of GraphqlMiddleware to understand its error handling.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for other places where UserDAO.softDelete is called rg "UserDAO.softDelete" -A 5 -B 5Length of output: 6555
Script:
#!/bin/bash # Search for GraphqlMiddleware.requestGraphqlReconnection implementation and usage rg "requestGraphqlReconnection" -A 5 -B 5 # Also search for any error handling related to GraphQL reconnection ast-grep --pattern 'try { $$$ GraphqlMiddleware.requestGraphqlReconnection($$$) $$$ }'Length of output: 24922
Script:
#!/bin/bash # Search for GraphqlMiddleware implementation rg -A 10 "object GraphqlMiddleware" # Also search for any HTTP client error handling ast-grep --pattern 'try { $$$ HttpClient.$$$ $$$ } catch { $$$ }'Length of output: 1487
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UserLeaveReqMsgHdlr.scala (1)
Line range hint
19-29: Add error handling for GraphQL connection status updateThe
handleUserClosedAllGraphqlConnectionsInternalMsgmethod updates the GraphQL connection status without verifying if the update was successful.Consider adding error handling:
for { regUser <- RegisteredUsers.findWithUserId(msg.userId, liveMeeting.registeredUsers) } yield { - RegisteredUsers.updateUserConnectedToGraphql(liveMeeting.registeredUsers, regUser, graphqlConnected = false) + val updateSuccess = RegisteredUsers.updateUserConnectedToGraphql(liveMeeting.registeredUsers, regUser, graphqlConnected = false) + if (!updateSuccess) { + log.error(s"Failed to update GraphQL connection status for user ${msg.userId}") + // Consider appropriate error handling strategy + } }akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeLockSettingsInMeetingCmdMsgHdlr.scala (1)
261-261: LGTM! Consider adding error handling for the GraphQL reconnection request.The change correctly uses the new synchronous GraphQL reconnection endpoint for locked viewers when lock settings change.
Consider adding error handling to gracefully handle failed reconnection requests:
- GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "lockSettings_changed") + try { + GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "lockSettings_changed") + } catch { + case e: Exception => + log.error(s"Failed to request GraphQL reconnection for user ${regUser.id}: ${e.getMessage}") + }akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala (1)
1180-1180: LGTM! Consider adding logging for the GraphQL reconnection request.The change correctly uses the new synchronous GraphQL reconnection endpoint when handling user inactivity.
Consider adding logging to track the GraphQL reconnection request:
- GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, EjectReasonCode.USER_INACTIVITY) + log.info(s"Requesting GraphQL reconnection for inactive user ${regUser.id}") + try { + GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, EjectReasonCode.USER_INACTIVITY) + log.debug(s"Successfully requested GraphQL reconnection for user ${regUser.id}") + } catch { + case e: Exception => + log.error(s"Failed to request GraphQL reconnection for user ${regUser.id}: ${e.getMessage}") + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (28)
akka-bbb-apps/src/main/scala/org/bigbluebutton/SystemConfiguration.scala(1 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/ExternalVideoModel.scala(1 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/PermissionCheck.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/ScreenshareModel.scala(0 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/EjectUserFromBreakoutInternalMsgHdlr.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/UpdateBreakoutRoomsTimeMsgHdlr.scala(1 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/screenshare/ScreenshareRtmpBroadcastStoppedVoiceConfEvtMsgHdlr.scala(0 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/AssignPresenterReqMsgHdlr.scala(3 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeLockSettingsInMeetingCmdMsgHdlr.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserAwayReqMsgHdlr.scala(0 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserRaiseHandReqMsgHdlr.scala(0 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserRoleCmdMsgHdlr.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/EjectUserFromMeetingCmdMsgHdlr.scala(4 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/GenerateLiveKitTokenRespMsgHdlr.scala(0 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/LockUserInMeetingCmdMsgHdlr.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/MuteUserCmdMsgHdlr.scala(0 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/RegisterUserReqMsgHdlr.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UserJoinMeetingReqMsgHdlr.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UserLeaveReqMsgHdlr.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UsersApp.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/webcam/UpdateWebcamsOnlyForModeratorCmdMsgHdlr.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/graphql/GraphqlMiddleware.scala(1 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala(2 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/message/handlers/guests/GetGuestsWaitingApprovalReqMsgHdlr.scala(1 hunks)akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/testdata/FakeUserGenerator.scala(1 hunks)akka-bbb-apps/src/universal/conf/application.conf(1 hunks)bbb-graphql-middleware/cmd/bbb-graphql-middleware/main.go(2 hunks)bbb-graphql-middleware/internal/websrv/reconnectionHandler.go(1 hunks)
💤 Files with no reviewable changes (6)
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/GenerateLiveKitTokenRespMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/MuteUserCmdMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/screenshare/ScreenshareRtmpBroadcastStoppedVoiceConfEvtMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/ScreenshareModel.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserRaiseHandReqMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserAwayReqMsgHdlr.scala
✅ Files skipped from review due to trivial changes (3)
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/testdata/FakeUserGenerator.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/message/handlers/guests/GetGuestsWaitingApprovalReqMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/ExternalVideoModel.scala
👮 Files not reviewed due to content moderation or server errors (6)
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserRoleCmdMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/EjectUserFromMeetingCmdMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/UpdateBreakoutRoomsTimeMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/AssignPresenterReqMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/RegisterUserReqMsgHdlr.scala
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UserJoinMeetingReqMsgHdlr.scala
🔇 Additional comments (5)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UsersApp.scala (1)
17-17: LGTM: Import statement for GraphQL middleware
The addition of the GraphqlMiddleware import aligns with the PR's objective to implement synchronous GraphQL reconnection.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/webcam/UpdateWebcamsOnlyForModeratorCmdMsgHdlr.scala (1)
91-91: Implementation aligns with race condition fix strategy
The change from Sender to GraphqlMiddleware.requestGraphqlReconnection is consistent with the PR's objective to prevent race conditions through synchronous reconnection requests.
Let's verify the GraphQL middleware endpoint configuration:
✅ Verification successful
GraphQL middleware implementation is properly configured and consistently used
The change is part of a well-integrated GraphQL middleware system that:
- Has proper configuration in
application.confwith endpoint athttp://127.0.0.1:8378 - Is consistently used across multiple user management scenarios (role changes, ejections, lock settings, etc.)
- Follows the same pattern for synchronous reconnection requests with specific reason codes
- The implementation in
UpdateWebcamsOnlyForModeratorCmdMsgHdlr.scalaaligns with this established pattern
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify GraphQL middleware endpoint configuration
# Expected: Configuration should match the endpoint mentioned in PR objectives
rg -l "graphqlMiddlewareAPI.*8378" --type-add 'conf:*.conf' --type conf
Length of output: 123
Script:
#!/bin/bash
# Let's examine the actual configuration content to verify the GraphQL middleware setup
cat akka-bbb-apps/src/universal/conf/application.conf | grep -A 5 "graphqlMiddlewareAPI"
# Also check for any GraphqlMiddleware implementation to verify the method usage
rg -A 3 "object GraphqlMiddleware"
Length of output: 812
Script:
#!/bin/bash
# Let's check the implementation details of requestGraphqlReconnection method
ast-grep --pattern 'def requestGraphqlReconnection($$$) {
$$$
}'
# Also check for any other usages of this method in the codebase
rg "GraphqlMiddleware.requestGraphqlReconnection" -A 2
Length of output: 6682
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/PermissionCheck.scala (1)
95-95: Verify permission refresh synchronization
The implementation ensures that permission changes are synchronized with GraphQL reconnections, preventing potential security issues where a user might retain outdated permissions.
Let's verify the permission refresh implementation:
✅ Verification successful
Permission refresh synchronization is properly implemented
The verification confirms that the GraphQL reconnection mechanism is consistently used across the codebase to refresh permissions. The implementation in PermissionCheck.scala is part of a well-coordinated system where:
- All permission-related changes trigger a GraphQL reconnection
- The synchronization is handled uniformly through the GraphqlMiddleware
- The implementation is used consistently across various permission-changing scenarios:
- Role changes
- Lock settings updates
- User ejections
- Presenter assignments
- Permission violations
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for consistent permission refresh handling
# Expected: All permission-related reconnections should use GraphqlMiddleware
rg "requestGraphqlReconnection.*permission" -B 2 -A 2
Length of output: 55
Script:
#!/bin/bash
# Let's first check all usages of requestGraphqlReconnection to understand the context
rg "requestGraphqlReconnection" -B 3 -A 3
# Also search for permission-related reconnection patterns
rg "reconnection.*permission|permission.*reconnection" -B 3 -A 3
# Check the GraphqlMiddleware implementation
fd "GraphqlMiddleware" --exec cat {}
Length of output: 28941
akka-bbb-apps/src/universal/conf/application.conf (1)
69-69: Review security implications of GraphQL middleware endpoint
While the localhost binding is appropriate for internal service communication, consider the following security aspects:
- Ensure the port 8378 is not exposed externally
- Consider adding authentication for internal service communication
Let's verify the endpoint security configuration:
✅ Verification successful
GraphQL middleware endpoint configuration appears secure for internal communication
The verification reveals that:
- The GraphQL middleware is part of an internal communication system between akka-apps and bbb-graphql-middleware, with built-in health checks and connection management.
- The endpoint is correctly configured for localhost (127.0.0.1) communication, ensuring it's not externally accessible.
- Authentication is handled through session tokens and middleware UIDs, as evidenced by the connection management code.
The current configuration aligns with secure internal service communication practices:
- Internal-only binding on localhost
- Session-based authentication system
- Proper connection tracking and management
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for potential security configurations
# Expected: The endpoint should only be accessible internally
# Check for any external bindings or security configurations
rg -l "127.0.0.1:8378" --type-add 'conf:*.conf' --type conf
rg "graphqlMiddleware.*security" --type scala
Length of output: 157
Script:
#!/bin/bash
# Let's check for any authentication or security-related configurations in the application.conf
# and related configuration files
rg -A 5 -B 5 "graphql" --type-add 'conf:*.conf' --type conf
# Check for any security-related code or middleware in Scala files
rg -A 5 "graphql.*middleware" --type scala
# Look for any network binding configurations that might restrict access
rg "bind.*address|listen.*address" --type-add 'conf:*.conf' --type conf
# Check for any authentication configurations
rg "auth.*token|security.*token|authentication" --type-add 'conf:*.conf' --type conf
Length of output: 9560
akka-bbb-apps/src/main/scala/org/bigbluebutton/SystemConfiguration.scala (1)
21-22: LGTM! Configuration for the new GraphQL middleware endpoint.
The configuration addition aligns with the PR objectives for introducing a synchronous GraphQL reconnection endpoint.
Let's verify if this configuration is properly set in the deployment configuration:
✅ Verification successful
Configuration for GraphQL middleware endpoint is properly set
The configuration is correctly defined in the deployment configuration file (akka-bbb-apps/src/universal/conf/application.conf) under the services section with the same default value:
services {
graphqlMiddlewareAPI = "http://127.0.0.1:8378"
}
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if the GraphQL middleware API configuration exists in deployment configs
# Look for the configuration in common deployment config files
rg -l "graphqlMiddlewareAPI"
Length of output: 235
Script:
#!/bin/bash
# Let's check the content of application.conf to see how the configuration is defined
cat akka-bbb-apps/src/universal/conf/application.conf
Length of output: 4311
| // Force reconnection with graphql to refresh permissions (if user already joined) | ||
| for { | ||
| regUser <- RegisteredUsers.findWithUserId(newPresenter.intId, liveMeeting.registeredUsers) | ||
| } yield { | ||
| Sender.sendForceUserGraphqlReconnectionSysMsg(liveMeeting.props.meetingProp.intId, regUser.id, regUser.sessionToken, "role_changed", outGW) | ||
| if(regUser.joined) { | ||
| GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "assigned_presenter_automatically") | ||
| } |
There was a problem hiding this comment.
💡 Codebase verification
GraphQL reconnection implementation needs error handling improvements
The implementation in GraphqlMiddleware is synchronous and could potentially impact performance. The client.send() call blocks until the HTTP request completes, and while errors are logged, they're not propagated to the caller. Specific concerns:
- Synchronous HTTP requests could block the actor processing thread
- No timeout configuration for the HTTP client
- Basic error handling that only prints to console
- No retry mechanism for failed requests
Suggested improvements:
- Convert to asynchronous HTTP client usage
- Add proper error handling with logging
- Configure request timeouts
- Consider implementing retries for failed requests
🔗 Analysis chain
LGTM: GraphQL reconnection implementation for presenter assignment
The implementation correctly checks if the user has joined before requesting GraphQL reconnection, which aligns with the PR's goal of preventing race conditions. The reason "assigned_presenter_automatically" clearly indicates the context of the reconnection.
Let's verify the synchronous nature of the GraphqlMiddleware implementation:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for the implementation of requestGraphqlReconnection to verify it's synchronous
ast-grep --pattern 'def requestGraphqlReconnection($_, $_) {
$$$
}'
Length of output: 71
Script:
#!/bin/bash
# Let's try to find the GraphqlMiddleware implementation with a broader search
rg -l "GraphqlMiddleware"
# Then search for requestGraphqlReconnection method with context
rg "requestGraphqlReconnection" -A 5
Length of output: 15093
Script:
#!/bin/bash
# Let's examine the implementation of requestGraphqlReconnection in GraphqlMiddleware
cat akka-bbb-apps/src/main/scala/org/bigbluebutton/core/graphql/GraphqlMiddleware.scala
Length of output: 990
| func ReconnectionHandler(w http.ResponseWriter, r *http.Request) { | ||
| if r.Method != http.MethodGet { | ||
| http.Error(w, "Only GET method is allowed", http.StatusMethodNotAllowed) | ||
| return | ||
| } | ||
|
|
||
| sessionToken := r.URL.Query().Get("sessionToken") | ||
| if sessionToken == "" { | ||
| http.Error(w, "Missing 'sessionToken' parameter", http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| reason := r.URL.Query().Get("reason") | ||
|
|
||
| log.Debugf("Reconnection request received for sessionToken: %s, reason: %s", sessionToken, reason) | ||
|
|
||
| go InvalidateSessionTokenHasuraConnections(sessionToken) | ||
| } |
There was a problem hiding this comment.
Handler needs improvements for synchronous operation and proper response handling
The current implementation has several issues that could affect its reliability as a synchronous endpoint:
- The handler launches InvalidateSessionTokenHasuraConnections asynchronously with
gobut returns immediately, which doesn't fulfill the synchronous requirement mentioned in the PR objectives. - No success response is sent back to the client.
- No timeout handling for the goroutine.
- No validation of sessionToken format.
- No rate limiting to prevent abuse.
Consider this implementation instead:
func ReconnectionHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Only GET method is allowed", http.StatusMethodNotAllowed)
return
}
sessionToken := r.URL.Query().Get("sessionToken")
if sessionToken == "" {
http.Error(w, "Missing 'sessionToken' parameter", http.StatusBadRequest)
return
}
+ // Validate sessionToken format
+ if !isValidSessionToken(sessionToken) {
+ http.Error(w, "Invalid session token format", http.StatusBadRequest)
+ return
+ }
+
reason := r.URL.Query().Get("reason")
log.Debugf("Reconnection request received for sessionToken: %s, reason: %s", sessionToken, reason)
- go InvalidateSessionTokenHasuraConnections(sessionToken)
+ // Use context with timeout for synchronous operation
+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
+ defer cancel()
+
+ done := make(chan error)
+ go func() {
+ done <- InvalidateSessionTokenHasuraConnections(ctx, sessionToken)
+ }()
+
+ // Wait for completion or timeout
+ select {
+ case err := <-done:
+ if err != nil {
+ log.Errorf("Failed to invalidate session: %v", err)
+ http.Error(w, "Internal server error", http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ case <-ctx.Done():
+ log.Errorf("Timeout while invalidating session: %v", ctx.Err())
+ http.Error(w, "Request timeout", http.StatusGatewayTimeout)
+ }
}Consider adding rate limiting to prevent abuse:
var limiter = rate.NewLimiter(rate.Every(time.Second), 10) // 10 requests per second
func ReconnectionHandler(w http.ResponseWriter, r *http.Request) {
if !limiter.Allow() {
http.Error(w, "Too many requests", http.StatusTooManyRequests)
return
}
// ... rest of the handler
}| def requestGraphqlReconnection(sessionTokens: Vector[String], reason: String): Unit = { | ||
| for { | ||
| sessionToken <- sessionTokens | ||
| } yield { | ||
| val url = s"${graphqlMiddlewareAPI}/graphql-reconnection?sessionToken=$sessionToken&reason=${reason}" | ||
|
|
||
| val client = HttpClient.newHttpClient() | ||
| val request = HttpRequest.newBuilder() | ||
| .uri(URI.create(url)) | ||
| .GET() | ||
| .build() | ||
|
|
||
| val response = client.send(request, HttpResponse.BodyHandlers.ofString()) | ||
| if (response.statusCode() != 200) { | ||
| println(s"Error on requesting graphql reconnection for ${sessionToken}. Response Code: ${response.statusCode()}") | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Improve error handling, logging, and performance in GraphQL middleware
Several improvements are needed for robustness and reliability:
- Error handling for URI creation is missing
- HTTP client needs timeout configuration
- Using println for error logging is not production-grade
- No retry mechanism for failed requests
- Blocking HTTP calls in a for-yield loop could impact performance
Consider this implementation instead:
object GraphqlMiddleware extends SystemConfiguration {
+ private val logger = LoggerFactory.getLogger(this.getClass)
+ private val client = HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(5))
+ .build()
+
def requestGraphqlReconnection(sessionTokens: Vector[String], reason: String): Unit = {
- for {
- sessionToken <- sessionTokens
- } yield {
+ // Process requests in parallel
+ Future.sequence(sessionTokens.map { sessionToken =>
+ Future {
+ try {
+ val encodedReason = URLEncoder.encode(reason, StandardCharsets.UTF_8.toString)
+ val url = s"${graphqlMiddlewareAPI}/graphql-reconnection?sessionToken=$sessionToken&reason=$encodedReason"
+
+ val request = HttpRequest.newBuilder()
+ .uri(new URI(url))
+ .timeout(Duration.ofSeconds(5))
+ .GET()
+ .build()
+
+ // Implement retry with exponential backoff
+ retry(3, 1.seconds) {
+ val response = client.send(request, HttpResponse.BodyHandlers.ofString())
+ if (response.statusCode() != 200) {
+ logger.error(s"Error requesting graphql reconnection for $sessionToken. Response Code: ${response.statusCode()}")
+ throw new RuntimeException(s"Failed with status ${response.statusCode()}")
+ }
+ response
+ }
+ } catch {
+ case e: Exception =>
+ logger.error(s"Failed to process reconnection for $sessionToken", e)
+ throw e
+ }
+ }
+ })(ExecutionContext.global)
}
+
+ private def retry[T](maxAttempts: Int, delay: FiniteDuration)(f: => T): T = {
+ try {
+ f
+ } catch {
+ case e if maxAttempts > 1 =>
+ Thread.sleep(delay.toMillis)
+ retry(maxAttempts - 1, delay * 2)(f)
+ }
+ }
}Consider adding metrics for monitoring:
private def recordMetrics(sessionToken: String, startTime: Long, success: Boolean): Unit = {
val duration = System.currentTimeMillis() - startTime
MetricsRegistry.defaultRegistry.counter("graphql.reconnection.requests").inc()
MetricsRegistry.defaultRegistry.histogram("graphql.reconnection.duration").update(duration)
if (!success) {
MetricsRegistry.defaultRegistry.counter("graphql.reconnection.failures").inc()
}
}|
|
||
| // Force reconnection with graphql to refresh permissions | ||
| Sender.sendForceUserGraphqlReconnectionSysMsg(liveMeeting.props.meetingProp.intId, registeredUser.id, registeredUser.sessionToken, msg.reasonCode, outGW) | ||
| GraphqlMiddleware.requestGraphqlReconnection(registeredUser.sessionToken, msg.reasonCode) |
There was a problem hiding this comment.
Add error handling for GraphQL reconnection request
The GraphQL reconnection request lacks error handling which could lead to silent failures.
Consider wrapping the call with error handling:
- GraphqlMiddleware.requestGraphqlReconnection(registeredUser.sessionToken, msg.reasonCode)
+ try {
+ GraphqlMiddleware.requestGraphqlReconnection(Vector(registeredUser.sessionToken), msg.reasonCode)
+ } catch {
+ case e: Exception =>
+ log.error(s"Failed to request GraphQL reconnection for user ${registeredUser.id}", e)
+ // Consider if we need to take any recovery actions
+ }Committable suggestion skipped: line range outside the PR's diff.
| websrv.ConnectionHandler(w, r) | ||
| }) | ||
|
|
||
| http.HandleFunc("/graphql-reconnection", websrv.ReconnectionHandler) |
There was a problem hiding this comment.
Consider adding rate limiting to the reconnection endpoint
While the /graphql endpoint has rate limiting protection, the new /graphql-reconnection endpoint doesn't. This could potentially be exploited for DoS attacks.
Consider applying the same rate limiter:
-http.HandleFunc("/graphql-reconnection", websrv.ReconnectionHandler)
+http.HandleFunc("/graphql-reconnection", func(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 120*time.Second)
+ defer cancel()
+
+ if err := rateLimiter.Wait(ctx); err != nil {
+ if !errors.Is(err, context.Canceled) {
+ http.Error(w, "Request cancelled or rate limit exceeded", http.StatusTooManyRequests)
+ }
+ return
+ }
+
+ websrv.ReconnectionHandler(w, r)
+})Committable suggestion skipped: line range outside the PR's diff.
| u <- RegisteredUsers.findWithUserId(uvo.intId, liveMeeting.registeredUsers) | ||
| } yield { | ||
| Sender.sendForceUserGraphqlReconnectionSysMsg(liveMeeting.props.meetingProp.intId, uvo.intId, u.sessionToken, "lock_user_changed", outGW) | ||
| GraphqlMiddleware.requestGraphqlReconnection(u.sessionToken, "lock_user_changed") |
There was a problem hiding this comment.
Add error handling for GraphQL reconnection request
The GraphQL reconnection request lacks error handling. If the request fails, the lock status change would proceed without the necessary GraphQL permission update, potentially leading to the race condition this PR aims to fix.
Consider handling the response:
-GraphqlMiddleware.requestGraphqlReconnection(u.sessionToken, "lock_user_changed")
+val reconnectionSuccess = GraphqlMiddleware.requestGraphqlReconnection(u.sessionToken, "lock_user_changed")
+if (!reconnectionSuccess) {
+ log.error(s"Failed to reconnect GraphQL for user ${uvo.intId} after lock status change")
+ // Consider appropriate error handling strategy
+}Committable suggestion skipped: line range outside the PR's diff.
| } yield { | ||
| RegisteredUsers.setUserLoggedOutFlag(liveMeeting.registeredUsers, ru) | ||
| Sender.sendForceUserGraphqlReconnectionSysMsg(liveMeeting.props.meetingProp.intId, ru.id, ru.sessionToken, "user_loggedout", outGW) | ||
| GraphqlMiddleware.requestGraphqlReconnection(ru.sessionToken, "user_loggedout") |
There was a problem hiding this comment.
Consider reversing the sequence of operations
The code updates the user's logged-out flag before ensuring the GraphQL reconnection is successful. This could lead to a state inconsistency if the reconnection fails.
Consider reversing the sequence:
-RegisteredUsers.setUserLoggedOutFlag(liveMeeting.registeredUsers, ru)
-GraphqlMiddleware.requestGraphqlReconnection(ru.sessionToken, "user_loggedout")
+val reconnectionSuccess = GraphqlMiddleware.requestGraphqlReconnection(ru.sessionToken, "user_loggedout")
+if (reconnectionSuccess) {
+ RegisteredUsers.setUserLoggedOutFlag(liveMeeting.registeredUsers, ru)
+} else {
+ log.error(s"Failed to reconnect GraphQL for user ${ru.id} during logout")
+ // Consider appropriate error handling strategy
+}Committable suggestion skipped: line range outside the PR's diff.
Automated tests Summary✅ All the CI tests have passed! |



Currently, when a user joins, changes roles, becomes a presenter, or leaves, Akka-Apps:
graphql-middlewareto invalidate and restart the GraphQL connection with Hasura.This ensures the connection reflects the new session variables (e.g., role changes). However, the current approach is asynchronous and does not guarantee that the GraphQL connection will restart before the client receives the new status and begins sending queries with expectations of the updated role.
In cases where the server is slow, this creates a race condition where the client queries using outdated session variables.
Solution
This PR introduces a new synchronous HTTP endpoint in
graphql-middlewareto manage GraphQL reconnections. The new flow ensures Akka-Apps can:graphql-middlewareto restart the GraphQL connection via the HTTP endpoint.The synchronous nature of HTTP requests resolves the race condition issue because it guarantees the GraphQL connection is updated before the client acts on the new status.
Implementation
URL:
http://127.0.0.1:8378/graphql-reconnectionParameters:
sessionToken: Identifies the session to reconnect.reason: Explains why the reconnection is required (e.g.,user_joined).Example Request
This change mainly addresses the
/joinflow and resolves the race condition issue highlighted during stress tests conducted by @schrd and @TiagoJacobs.