Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CHA-RL2][ECO-5010] Room DETACH with retry #44

Open
wants to merge 5 commits into
base: rename/room_and_connection_status
Choose a base branch
from

Conversation

sacOO7
Copy link

@sacOO7 sacOO7 commented Nov 8, 2024

Fixed #22

Summary by CodeRabbit

  • New Features

    • Improved room detachment process with enhanced error handling and retry mechanisms.
    • Simplified room status management by streamlining the status setting process.
  • Bug Fixes

    • Enhanced control flow and error handling for room lifecycle management.
  • Documentation

    • Added comments to clarify the purpose and behavior of new methods.

Copy link

coderabbitai bot commented Nov 8, 2024

Walkthrough

The pull request introduces significant changes to the RoomLifecycleManager and DefaultRoomLifecycle classes. A new detach() function is added to manage room detachment more effectively, ensuring that detachment only occurs under appropriate conditions. Additionally, the setStatus method in RoomStatus is refactored to simplify status updates, enhancing clarity and efficiency. These modifications improve error handling and the overall lifecycle management of rooms within the chat application.

Changes

File Path Change Summary
chat-android/src/main/java/com/ably/chat/RoomLifecycleManager.kt - Added internal suspend fun detach() to manage room detachment with status checks.
- Added private suspend fun doDetach() to handle channel detachment with retry logic.
chat-android/src/main/java/com/ably/chat/RoomStatus.kt - Refactored setStatus method to take RoomStatus and optional ErrorInfo, removing the need for NewRoomStatus.

Assessment against linked issues

Objective Addressed Explanation
Implement Room DETACH operation (22, ECO-5010)

Possibly related issues

  • [CHA-RL1] Implement Room ATTACH operation: The changes in this PR may relate to the overall room lifecycle management, which includes attach operations.
  • [CHA-RL5] Implement Room RETRY operation: The retry mechanism in the doDetach() function could be relevant to the retry operation objectives.
  • [CHA-RL7] Room lifecycle operation precedence: The changes affect the control flow of room operations, which may relate to the precedence of lifecycle operations.
  • [CHA-RL3] Implement Room RELEASE operation: The modifications to detachment could have implications for the release operation as part of the room lifecycle.

Possibly related PRs

Suggested reviewers

  • AndyTWF

Poem

🐰 In the chat room where we play,
A detachment's here to stay.
With retries and statuses clear,
Our room's lifecycle brings us cheer!
Hop along, let errors flee,
For smooth transitions, just wait and see! 🐇


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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sacOO7 sacOO7 changed the title Added basic checks for roomlifecycle detach operation [CHA-RL2][ECO-5010] Channel detach with retry Nov 8, 2024
@sacOO7 sacOO7 changed the base branch from tests/roomlifecycle-attach to rename/room_and_connection_status November 11, 2024 17:41
@sacOO7 sacOO7 changed the title [CHA-RL2][ECO-5010] Channel detach with retry [CHA-RL2][ECO-5010] Room DETACH with retry Nov 12, 2024
@sacOO7 sacOO7 requested a review from ttypic November 12, 2024 13:31
@sacOO7 sacOO7 marked this pull request as ready for review November 12, 2024 13:31
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
chat-android/src/main/java/com/ably/chat/RoomLifecycleManager.kt (2)

558-560: Use a predefined constant for undefined error codes

The condition err.errorInfo?.code != -1 uses a hardcoded value -1, which can be unclear and error-prone. Consider defining a constant for undefined error codes to improve readability and maintainability.

Suggestion: Define a constant in ErrorCodes:

object ErrorCodes {
    const val UndefinedErrorCode = -1
    // Existing error codes...
}

Then update the condition:

 if (err is AblyException && err.errorInfo?.code != ErrorCodes.UndefinedErrorCode && channelFailedError == null) {
     channelFailedError = err
 }

505-511: Consolidate repetitive exception handling into a helper function

The exception handling for different room statuses (Released, Releasing, Failed) is repetitive. Refactoring this into a helper function will reduce code duplication and enhance maintainability.

Suggestion: Create a helper function to handle these checks:

private fun checkInvalidStates(vararg invalidStates: RoomStatus) {
    if (_statusLifecycle.status in invalidStates) {
        val errorCode = when (_statusLifecycle.status) {
            RoomStatus.Released -> ErrorCodes.RoomIsReleased.errorCode
            RoomStatus.Releasing -> ErrorCodes.RoomIsReleasing.errorCode
            RoomStatus.Failed -> ErrorCodes.RoomInFailedState.errorCode
            else -> ErrorCodes.RoomLifecycleError.errorCode
        }
        val errorMessage = "unable to detach room; room is ${_statusLifecycle.status.name.lowercase()}"
        throw AblyException.fromErrorInfo(
            ErrorInfo(
                errorMessage,
                HttpStatusCodes.InternalServerError,
                errorCode,
            ),
        )
    }
}

Then, replace the repetitive checks in detach():

 // Before detachment logic
-check for RoomStatus.Released
-check for RoomStatus.Releasing
-check for RoomStatus.Failed

+checkInvalidStates(RoomStatus.Released, RoomStatus.Releasing, RoomStatus.Failed)

Also applies to: 516-522, 527-533

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3527b1c and a0978f1.

📒 Files selected for processing (2)
  • chat-android/src/main/java/com/ably/chat/RoomLifecycleManager.kt (1 hunks)
  • chat-android/src/main/java/com/ably/chat/RoomStatus.kt (1 hunks)
🔇 Additional comments (3)
chat-android/src/main/java/com/ably/chat/RoomStatus.kt (2)

212-213: LGTM! Clean delegation implementation.

The delegation to the new internal method maintains backward compatibility while enabling the refactoring.


215-220: 🛠️ Refactor suggestion

Consider adding thread safety and state transition validation.

The implementation has two potential areas for improvement:

  1. Thread Safety: The state updates (_status and _error) are not synchronized, which could lead to race conditions in concurrent scenarios.
  2. State Transition Validation: The method accepts any status without validating if the transition is valid according to the room lifecycle state machine.

Consider applying these improvements:

 internal fun setStatus(status: RoomStatus, error: ErrorInfo? = null) {
+    synchronized(this) {
+        // Validate state transition
+        if (!isValidTransition(_status, status)) {
+            throw IllegalStateException("Invalid state transition from ${_status} to ${status}")
+        }
+
         val change = RoomStatusChange(status, _status, error)
         _status = change.current
         _error = change.error
+    }
     internalEmitter.emit(change.current, change)
     externalEmitter.emit(change.current, change)
 }

+ private fun isValidTransition(from: RoomStatus, to: RoomStatus): Boolean {
+     return when (from) {
+         RoomStatus.Initializing -> to == RoomStatus.Initialized
+         RoomStatus.Initialized -> to == RoomStatus.Attaching
+         RoomStatus.Attaching -> setOf(RoomStatus.Attached, RoomStatus.Failed).contains(to)
+         RoomStatus.Attached -> setOf(RoomStatus.Detaching, RoomStatus.Failed, RoomStatus.Suspended).contains(to)
+         RoomStatus.Detaching -> setOf(RoomStatus.Detached, RoomStatus.Failed).contains(to)
+         RoomStatus.Detached -> setOf(RoomStatus.Attaching, RoomStatus.Failed, RoomStatus.Released).contains(to)
+         RoomStatus.Suspended -> setOf(RoomStatus.Attaching, RoomStatus.Failed).contains(to)
+         RoomStatus.Failed -> setOf(RoomStatus.Attaching, RoomStatus.Released).contains(to)
+         RoomStatus.Releasing -> setOf(RoomStatus.Released).contains(to)
+         RoomStatus.Released -> false // Terminal state
+     }
+ }

Let's verify the state transition rules by checking the specifications:

chat-android/src/main/java/com/ably/chat/RoomLifecycleManager.kt (1)

496-546: LGTM! The detach() method handles room status transitions correctly

The implementation of the detach() method appropriately checks the room's status before proceeding with detachment, ensuring that detachment is only attempted when the room is in a valid state. The method also sets the status to Detaching and calls doDetach() as expected.

Comment on lines +553 to +579
private suspend fun doDetach() {
var channelWindDown = kotlin.runCatching { doChannelWindDown() }
var channelFailedError: AblyException? = null
while (channelWindDown.isFailure) {
val err = channelWindDown.exceptionOrNull()
if (err is AblyException && err.errorInfo?.code != -1 && channelFailedError == null) {
channelFailedError = err
}
delay(_retryDurationInMs)
channelWindDown = kotlin.runCatching { doChannelWindDown() }
}

// If we aren't in the failed state, then we're detached
if (_statusLifecycle.status !== RoomStatus.Failed) {
_statusLifecycle.setStatus(RoomStatus.Detached)
return
}

// If we're in the failed state, then we need to throw the error
throw channelFailedError
?: AblyException.fromErrorInfo(
ErrorInfo(
"unknown error in _doDetach",
HttpStatusCodes.InternalServerError,
ErrorCodes.RoomLifecycleError.errorCode,
),
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Prevent potential infinite loop in doDetach()

In the doDetach() method, there's a possibility of an infinite loop if doChannelWindDown() continues to fail indefinitely. This could lead to resource exhaustion or unresponsive behavior.

Suggestion: Introduce a maximum retry limit to prevent an infinite loop. Here's how you can modify the code:

 private suspend fun doDetach() {
     var channelWindDown = kotlin.runCatching { doChannelWindDown() }
     var channelFailedError: AblyException? = null
+    var retryCount = 0
+    val maxRetries = 5
     while (channelWindDown.isFailure && retryCount < maxRetries) {
         val err = channelWindDown.exceptionOrNull()
         if (err is AblyException && err.errorInfo?.code != -1 && channelFailedError == null) {
             channelFailedError = err
         }
         delay(_retryDurationInMs)
         channelWindDown = kotlin.runCatching { doChannelWindDown() }
+        retryCount++
     }

     // Rest of the code remains the same
 }

This ensures that after a certain number of retries, the method will throw an exception and prevent an endless loop.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private suspend fun doDetach() {
var channelWindDown = kotlin.runCatching { doChannelWindDown() }
var channelFailedError: AblyException? = null
while (channelWindDown.isFailure) {
val err = channelWindDown.exceptionOrNull()
if (err is AblyException && err.errorInfo?.code != -1 && channelFailedError == null) {
channelFailedError = err
}
delay(_retryDurationInMs)
channelWindDown = kotlin.runCatching { doChannelWindDown() }
}
// If we aren't in the failed state, then we're detached
if (_statusLifecycle.status !== RoomStatus.Failed) {
_statusLifecycle.setStatus(RoomStatus.Detached)
return
}
// If we're in the failed state, then we need to throw the error
throw channelFailedError
?: AblyException.fromErrorInfo(
ErrorInfo(
"unknown error in _doDetach",
HttpStatusCodes.InternalServerError,
ErrorCodes.RoomLifecycleError.errorCode,
),
)
private suspend fun doDetach() {
var channelWindDown = kotlin.runCatching { doChannelWindDown() }
var channelFailedError: AblyException? = null
var retryCount = 0
val maxRetries = 5
while (channelWindDown.isFailure && retryCount < maxRetries) {
val err = channelWindDown.exceptionOrNull()
if (err is AblyException && err.errorInfo?.code != -1 && channelFailedError == null) {
channelFailedError = err
}
delay(_retryDurationInMs)
channelWindDown = kotlin.runCatching { doChannelWindDown() }
retryCount++
}
// If we aren't in the failed state, then we're detached
if (_statusLifecycle.status !== RoomStatus.Failed) {
_statusLifecycle.setStatus(RoomStatus.Detached)
return
}
// If we're in the failed state, then we need to throw the error
throw channelFailedError
?: AblyException.fromErrorInfo(
ErrorInfo(
"unknown error in _doDetach",
HttpStatusCodes.InternalServerError,
ErrorCodes.RoomLifecycleError.errorCode,
),
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant