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

[RTL13] Fix existing impl. for server sent DETACH #1054

Merged
merged 3 commits into from
Jan 13, 2025

Conversation

sacOO7
Copy link
Collaborator

@sacOO7 sacOO7 commented Dec 12, 2024

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced handling of channel state transitions and error information during attachment and detachment processes.
    • Added a new test to verify channel behavior during detach events in suspended state.
  • Bug Fixes

    • Streamlined reattachment logic for channels after unexpected detach events.
    • Improved error handling to ensure accurate propagation during channel state changes.
  • Refactor

    • Clarified state management logic and updated method signatures for better clarity and efficiency.

Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The pull request modifies the ChannelBase class in the Ably Java library, focusing on enhancing error handling and state management during channel attachment and detachment processes. Key changes include the addition of an ErrorInfo parameter to several methods, improving the handling of unexpected detach events, and refining the logic for reattachment. The RealtimeChannelTest class has also been updated to include new tests for channel state transitions, ensuring robust validation of behavior during server-initiated detach events.

Changes

File Change Summary
lib/src/main/java/io/ably/lib/realtime/ChannelBase.java - Added ErrorInfo reattachmentReason parameter to attachImpl, attachWithTimeout, and attach methods.
- Refined handling of unexpected detach events, improving reattachment logic.
- Updated detachImpl to throw AblyException if the connection manager is inactive.
- Enhanced error handling in detachWithTimeout.
lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java - Renamed channel_server_initiated_detached to server_initiated_detach_for_attached_channel.
- Added server_initiated_detach_for_suspended_channel test method.
- Enhanced assertions for channel state transitions during server-initiated detach events.

Possibly related issues

Poem

🐰 In the realm of channels, a rabbit's delight,
State transitions now dance with might!
Detach and attach, a graceful ballet,
Code flows smoother, hip-hooray! 🎉
Ably's Java SDK, now more refined.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1f94b58 and 8eec5b5.

📒 Files selected for processing (2)
  • lib/src/main/java/io/ably/lib/realtime/ChannelBase.java (9 hunks)
  • lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: check-realtime-okhttp
  • GitHub Check: check-realtime
🔇 Additional comments (7)
lib/src/main/java/io/ably/lib/realtime/ChannelBase.java (3)

197-197: LGTM!

The change correctly initializes the reattachment reason as null for regular attach operations.


Line range hint 220-282: LGTM!

The attachImpl method has been enhanced to handle error propagation during channel state transitions. The changes correctly:

  1. Accept an ErrorInfo reattachmentReason parameter
  2. Pass the error information when setting the channel state
  3. Maintain proper state transitions as per RTL4 specifications

1301-1307: LGTM!

The implementation correctly handles server-initiated detach for attached and suspended states (RTL13a):

  1. Attempts immediate reattachment with the error from the detach message
  2. Logs the event appropriately
  3. Maintains proper state transitions
lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java (4)

948-950: LGTM!

Added spec references to improve test documentation:

  • RTL4g: Channel attach behavior
  • RTL5j: Channel detach behavior in suspended state
  • RTL5b: Channel detach behavior in failed state

Also applies to: 1076-1078, 1116-1118


1160-1231: LGTM!

New test detach_fail_callback_for_connection_invalid_state correctly verifies RTL5g:

  1. Tests detach behavior when connection is in closing/failed states
  2. Verifies error propagation in completion callbacks
  3. Validates error codes and messages

Line range hint 1791-1840: LGTM!

Enhanced test server_initiated_detach_for_attached_channel correctly verifies RTL13a:

  1. Tests server-initiated detach for attached channel
  2. Verifies error propagation
  3. Validates state transition sequence

Line range hint 1842-1901: LGTM!

New test server_initiated_detach_for_suspended_channel correctly verifies RTL13a:

  1. Tests server-initiated detach for suspended channel
  2. Verifies error propagation
  3. Validates state transition sequence

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

@github-actions github-actions bot temporarily deployed to staging/pull/1054/features December 12, 2024 12:58 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1054/javadoc December 12, 2024 12:59 Inactive
@sacOO7 sacOO7 force-pushed the fix/RTL13-channel-detach branch from 2479c47 to e8cb69a Compare December 16, 2024 11:51
@github-actions github-actions bot temporarily deployed to staging/pull/1054/features December 16, 2024 11:51 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1054/javadoc December 16, 2024 11:52 Inactive
@sacOO7 sacOO7 marked this pull request as ready for review December 16, 2024 12:49
@sacOO7 sacOO7 force-pushed the fix/RTL13-channel-detach branch from e8cb69a to 9b46c4f Compare December 16, 2024 13:24
@github-actions github-actions bot temporarily deployed to staging/pull/1054/features December 16, 2024 13:25 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1054/javadoc December 16, 2024 13:25 Inactive
@sacOO7 sacOO7 force-pushed the fix/RTL13-channel-detach branch from 9b46c4f to 9eb265b Compare December 17, 2024 12:40
@github-actions github-actions bot temporarily deployed to staging/pull/1054/features December 17, 2024 12:41 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1054/javadoc December 17, 2024 12:42 Inactive
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: 0

🧹 Nitpick comments (2)
lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java (2)

1739-1745: Refactor state sequence assertions to improve test robustness

Asserting the exact size and order of channelStates can make the test brittle to future changes in state transitions. Consider verifying the sequence of key states without hardcoding their positions.

Apply this diff to refactor the assertions:

- Assert.assertEquals(4, channelStates.size());
- Assert.assertEquals(ChannelState.attaching, channelStates.get(0));
- Assert.assertEquals(ChannelState.attached, channelStates.get(1));
- Assert.assertEquals(ChannelState.attaching, channelStates.get(2));
- Assert.assertEquals(ChannelState.attached, channelStates.get(3));
+ List<ChannelState> expectedStates = Arrays.asList(
+     ChannelState.attaching,
+     ChannelState.attached,
+     ChannelState.attaching,
+     ChannelState.attached
+ );
+ Assert.assertTrue(channelStates.containsAll(expectedStates));

1795-1802: Refactor assertions to enhance test maintainability

Directly asserting the size and exact order of channelStates may lead to brittle tests. It's advisable to verify the presence and order of important states to make the test more resilient to future changes.

Consider the following refactor:

- Assert.assertEquals(5, channelStates.size());
- Assert.assertEquals(ChannelState.attaching, channelStates.get(0));
- Assert.assertEquals(ChannelState.attached, channelStates.get(1));
- Assert.assertEquals(ChannelState.suspended, channelStates.get(2));
- Assert.assertEquals(ChannelState.attaching, channelStates.get(3));
- Assert.assertEquals(ChannelState.attached, channelStates.get(4));
+ List<ChannelState> expectedStates = Arrays.asList(
+     ChannelState.attaching,
+     ChannelState.attached,
+     ChannelState.suspended,
+     ChannelState.attaching,
+     ChannelState.attached
+ );
+ Assert.assertTrue(channelStates.containsAll(expectedStates));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9b46c4f and 9eb265b.

📒 Files selected for processing (2)
  • lib/src/main/java/io/ably/lib/realtime/ChannelBase.java (2 hunks)
  • lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java (3 hunks)
🔇 Additional comments (5)
lib/src/main/java/io/ably/lib/realtime/ChannelBase.java (2)

247-248: Appropriate handling of connection states during attach

The added check for ConnectionState.connecting and ConnectionState.disconnected ensures that the channel correctly handles attaching when the connection is in these states, enhancing robustness during state transitions.


1299-1304: Correct reattach logic on unexpected DETACH in attached or suspended states

The implementation properly reattaches the channel when an unexpected DETACH is received while the channel is in the attached or suspended state, adhering to the specification RTL13a.

lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java (3)

29-29: Added necessary import statements

The addition of org.junit.Assert import statements supports the use of assertion methods in the test cases, ensuring code clarity and reducing the need for fully qualified class names.


Line range hint 1707-1751: Comprehensive test for server-initiated DETACH in attached state

The new test server_initiated_detach_for_attached_channel effectively verifies the channel state transitions when a server-initiated DETACH is received while the channel is attached, ensuring correct reattachment behavior as per RTL13a.


1753-1802: Added test for server-initiated DETACH in suspended state

The new test server_initiated_detach_for_suspended_channel correctly checks the channel's behavior upon receiving a server-initiated DETACH while in the suspended state, ensuring compliance with specification RTL13a.

@sacOO7 sacOO7 requested a review from ttypic December 17, 2024 13:02
1. Removed use of explicitly setting detached state
2. Fixed attachWithTimeout method call, set forcedAttach flag to true
3. Updated tests to track channel state changes on server sent DETACH
…RTL5g)

1. Added missing callCompletionListenerError when detachImpl throws exception
on invalid connection state
2. Added separate test case for the spec RTL5g
3. Annotated channel detach tests with appropriate spec
@sacOO7 sacOO7 force-pushed the fix/RTL13-channel-detach branch from 9eb265b to a6bbcb2 Compare December 17, 2024 14:16
@github-actions github-actions bot temporarily deployed to staging/pull/1054/features December 17, 2024 14:17 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1054/javadoc December 17, 2024 14:18 Inactive
Copy link
Contributor

@ttypic ttypic left a comment

Choose a reason for hiding this comment

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

Looks good to me, but we’re still not fully spec-compliant. The error reason from the detach message should be propagated in the state change

@sacOO7
Copy link
Collaborator Author

sacOO7 commented Jan 10, 2025

Looks good to me, but we’re still not fully spec-compliant. The error reason from the detach message should be propagated in the state change

Fixed 1360bc6

@github-actions github-actions bot temporarily deployed to staging/pull/1054/features January 10, 2025 12:16 Inactive
@github-actions github-actions bot temporarily deployed to staging/pull/1054/javadoc January 10, 2025 12:17 Inactive
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: 0

🧹 Nitpick comments (3)
lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java (3)

Line range hint 1791-1840: Consider a more descriptive test name.

The test thoroughly validates the channel state transitions and error propagation. However, consider renaming it to better describe the test scenario, e.g., test_server_initiated_detach_transitions_attached_channel_through_attaching_to_attached.


Line range hint 1849-1902: Consider extracting common setup code.

The test thoroughly validates the channel state transitions and error propagation. However, there's significant setup code duplication with server_initiated_detach_for_attached_channel. Consider extracting the common setup into a helper method.

+    private void setupChannelAndWaitForState(String channelName, ChannelState targetState, ErrorInfo error) throws AblyException {
+        Channel channel = ably.channels.get(channelName);
+        ChannelWaiter channelWaiter = new ChannelWaiter(channel);
+        channel.attach();
+        channelWaiter.waitFor(ChannelState.attached);
+        if (error != null) {
+            channel.setSuspended(error, true);
+            channelWaiter.waitFor(targetState);
+        }
+        return new ChannelTestContext(channel, channelWaiter);
+    }

1164-1231: Enhance assertion messages for better test failure diagnostics.

The test thoroughly validates error handling in detach operations. However, the assertions could benefit from more descriptive messages to help diagnose test failures.

-            assertFalse(detachWaiter1.success);
-            assertNotNull(detachWaiter1.error);
-            assertEquals("Connection is closing", detachWaiter1.error.message);
-            assertEquals(80001, detachWaiter1.error.code);
+            assertFalse("Detach should fail when connection is closing", detachWaiter1.success);
+            assertNotNull("Error should be present for failed detach", detachWaiter1.error);
+            assertEquals("Error message should indicate connection closing", "Connection is closing", detachWaiter1.error.message);
+            assertEquals("Error code should be CONNECTION_CLOSING(80001)", 80001, detachWaiter1.error.code);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a6bbcb2 and 1360bc6.

📒 Files selected for processing (2)
  • lib/src/main/java/io/ably/lib/realtime/ChannelBase.java (7 hunks)
  • lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: check (29)
  • GitHub Check: check-rest
  • GitHub Check: check (24)
  • GitHub Check: check-realtime-okhttp
  • GitHub Check: check (21)
  • GitHub Check: check-rest-okhttp
  • GitHub Check: check-realtime
  • GitHub Check: build
  • GitHub Check: check (19)
  • GitHub Check: check
🔇 Additional comments (3)
lib/src/main/java/io/ably/lib/realtime/ChannelBase.java (3)

93-101: LGTM! Well-structured error handling implementation.

The implementation follows good practices with proper encapsulation and thread-safe error handling. The getter method appropriately clears the error after retrieval, which is good for one-time error handling.


1312-1318: LGTM! Proper implementation of RTL13a spec requirement.

The code correctly handles server-initiated detach for both attached and suspended states by:

  1. Storing the error from the detach message
  2. Attempting immediate reattachment

624-624: LGTM! Proper error handling as per RTL5g.

The implementation correctly propagates error information to the completion listener.

Copy link
Contributor

@ttypic ttypic left a comment

Choose a reason for hiding this comment

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

I think the latest changes look like workaround, I think we should avoid this

lib/src/main/java/io/ably/lib/realtime/ChannelBase.java Outdated Show resolved Hide resolved
lib/src/main/java/io/ably/lib/realtime/ChannelBase.java Outdated Show resolved Hide resolved
@sacOO7 sacOO7 force-pushed the fix/RTL13-channel-detach branch from 1360bc6 to 0dfc6c3 Compare January 13, 2025 12:14
@github-actions github-actions bot temporarily deployed to staging/pull/1054/features January 13, 2025 12:14 Inactive
@sacOO7 sacOO7 requested a review from ttypic January 13, 2025 12:14
@github-actions github-actions bot temporarily deployed to staging/pull/1054/javadoc January 13, 2025 12:15 Inactive
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: 0

🧹 Nitpick comments (2)
lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java (2)

Line range hint 1786-1840: Consider enhancing test readability and error validation.

The test implementation for RTL13a looks good, but consider these improvements:

  1. Add a descriptive comment explaining the expected behavior when a server sends a DETACH message with an error.
  2. Use a more descriptive error message that indicates the test scenario.
  3. Add assertions to verify that the error is properly propagated during each state transition.
 /*
  * Establish connection, attach channel, simulate sending detached messages
  * from the server for channel in attached state.
+ *
+ * Expected behavior:
+ * 1. When server sends DETACH with error, channel should transition to ATTACHING
+ * 2. Error from DETACH should be propagated during state change
+ * 3. Channel should automatically attempt to reattach
+ * 4. Final state should be ATTACHED after successful reattachment
  *
  * Tests RTL13a
  */
@Test
public void server_initiated_detach_for_attached_channel() throws AblyException {
     // ...
     ProtocolMessage detachedMessage = new ProtocolMessage() {{
         action = Action.detached;
         channel = channelName;
-        error = new ErrorInfo("Simulated detach", 40000);
+        error = new ErrorInfo("Server initiated DETACH with error during test", 40000);
     }};
     // ...
+    // Verify error propagation in state transitions
+    ChannelStateListener.ChannelStateChange stateChange = channelWaiter.getLastStateChange();
+    Assert.assertEquals("Error should be propagated", detachErr, stateChange.reason);

Line range hint 1842-1902: Consider enhancing test readability and error validation.

The test implementation for RTL13a looks good, but consider these improvements:

  1. Add a descriptive comment explaining the expected behavior when a server sends a DETACH message to a suspended channel.
  2. Use more descriptive error messages that indicate the test scenario.
  3. Add assertions to verify that the error is properly propagated during each state transition.
 /*
  * Establish connection, attach channel, simulate sending detached messages
  * from the server for channel in suspended state.
+ *
+ * Expected behavior:
+ * 1. When server sends DETACH with error to a suspended channel, it should transition to ATTACHING
+ * 2. Error from DETACH should be propagated during state change
+ * 3. Channel should automatically attempt to reattach
+ * 4. Final state should be ATTACHED after successful reattachment
  *
  * Tests RTL13a
  */
@Test
public void server_initiated_detach_for_suspended_channel() throws AblyException {
     // ...
-    channel.setSuspended(new ErrorInfo("Set state to suspended", 400), true);
+    channel.setSuspended(new ErrorInfo("Channel suspended during test setup", 400), true);
     // ...
     ProtocolMessage detachedMessage = new ProtocolMessage() {{
         action = Action.detached;
         channel = channelName;
-        error = new ErrorInfo("Simulated detach", 40000);
+        error = new ErrorInfo("Server initiated DETACH with error during test", 40000);
     }};
     // ...
+    // Verify error propagation in state transitions
+    ChannelStateListener.ChannelStateChange stateChange = channelWaiter.getLastStateChange();
+    Assert.assertEquals("Error should be propagated", detachError, stateChange.reason);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1360bc6 and 0dfc6c3.

📒 Files selected for processing (2)
  • lib/src/main/java/io/ably/lib/realtime/ChannelBase.java (9 hunks)
  • lib/src/test/java/io/ably/lib/test/realtime/RealtimeChannelTest.java (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: check-rest-okhttp
  • GitHub Check: check (29)
  • GitHub Check: check-rest
  • GitHub Check: check (24)
  • GitHub Check: check (21)
  • GitHub Check: check-realtime-okhttp
  • GitHub Check: check (19)
  • GitHub Check: check-realtime
  • GitHub Check: check
🔇 Additional comments (5)
lib/src/main/java/io/ably/lib/realtime/ChannelBase.java (5)

197-197: LGTM!

The change maintains backward compatibility while supporting the new error propagation functionality.


247-252: LGTM! Correctly implements RTL4i specification.

The code now properly propagates the error during state transition when the connection is in connecting or disconnected state.


280-280: LGTM!

The change consistently propagates the error during the state transition to attaching.


353-355: LGTM! Correctly implements RTL5g specification.

The code now properly propagates connection errors during detach operations when the connection manager is not active.


1301-1306: LGTM! Correctly implements RTL13a specification.

The code now properly handles server-initiated detach for attached and suspended states, attempting immediate reattachment with the error from the detach message.

@sacOO7 sacOO7 force-pushed the fix/RTL13-channel-detach branch from 0dfc6c3 to 1f94b58 Compare January 13, 2025 14:02
@github-actions github-actions bot temporarily deployed to staging/pull/1054/features January 13, 2025 14:03 Inactive
@sacOO7 sacOO7 requested a review from ttypic January 13, 2025 14:04
@github-actions github-actions bot temporarily deployed to staging/pull/1054/javadoc January 13, 2025 14:04 Inactive
1. Updated `attachWithTimeout` and `attachImpl` method to accept attachReason param
2. Updated test assertions for spec RTL13a accordingly
@sacOO7 sacOO7 merged commit 15bc122 into main Jan 13, 2025
9 of 12 checks passed
@sacOO7 sacOO7 deleted the fix/RTL13-channel-detach branch January 13, 2025 15:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

Flaky realtime tests for RealtimeChannelTest [RTL13] Handle server sent DETACHED event
2 participants