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

Add an “all features enabled” room option #170

Merged
merged 1 commit into from
Dec 4, 2024

Conversation

lawrence-forooghian
Copy link
Collaborator

@lawrence-forooghian lawrence-forooghian commented Dec 2, 2024

In 20e7f5f I said

RoomOptionsDefaults in JS is instead implemented here by giving the
*Options types a no-args initializer that populates the default values.

but I had not noticed that JS’s RoomOptionsDefaults is not actually a “default”, since the JS SDK does not even have a concept of a “default” RoomOptions. What it actually is is a RoomOptions in which all of the room features are switched on; we discussed this today in standup and Andy said that the intention of this value was to give users who are just playing around with the SDK an easy way to turn all features on. So, here, I add such an API for Swift, but with a name that more accurately describes its intention. Andy’s created [1] to revisit the JS naming.

[1] https://ably.atlassian.net/browse/CHA-766

Summary by CodeRabbit

  • New Features

    • Simplified room data retrieval with a new allFeaturesEnabled option for room configurations.
    • Enhanced chat interface with dynamic reaction behaviors through new properties for rotation speed and angle.
  • Bug Fixes

    • Maintained existing error handling and control flow to ensure application stability.

Copy link

coderabbitai bot commented Dec 2, 2024

Warning

Rate limit exceeded

@lawrence-forooghian has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 55 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 3c46c60 and c595df1.

Walkthrough

The changes in this pull request involve modifications to the ContentView and RoomOptions structs. The room() function in ContentView.swift has been simplified by replacing a detailed options structure with a single call to allFeaturesEnabled. The Reaction struct has been updated to include rotationSpeed and rotationAngle properties, enhancing the visual dynamics of reactions. Additionally, a new static property allFeaturesEnabled has been added to RoomOptions, providing a convenient way to access a fully enabled configuration.

Changes

File Change Summary
Example/AblyChatExample/ContentView.swift Updated room() function to use allFeaturesEnabled for room data retrieval; modified Reaction struct to include rotationSpeed and rotationAngle properties.
Sources/AblyChat/RoomOptions.swift Added a static property allFeaturesEnabled to RoomOptions, providing a pre-configured instance with all features enabled.

Assessment against linked issues

Objective Addressed Explanation
Consider a rename of DefaultRoomOptions (CHA-766) The PR does not address the renaming issue.

Possibly related PRs

Suggested reviewers

  • umair-ably
  • maratal

Poem

In the chat where reactions play,
New spins and twirls brighten the day.
With features all set, oh what a sight,
Our rooms now dance, a joyful delight! 🐇✨


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.

@lawrence-forooghian
Copy link
Collaborator Author

CI failing due to #169.

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

🧹 Outside diff range and nitpick comments (1)
Example/AblyChatExample/ContentView.swift (1)

Documentation needs to be updated for the new mock case

The codebase inspection reveals that while there is inline documentation for RoomOptions and its components, the newly added mock case in the enum is not properly documented in:

  • The README.md which should mention the mock functionality for testing/development
  • The inline documentation in the source file where the enum is defined

Specific locations that need documentation updates:

  • Add mock functionality description in README.md under a new "Development and Testing" section
  • Add XML documentation for the mock case in the enum definition, explaining its purpose and usage
🔗 Analysis chain

Line range hint 9-15: Verify documentation coverage for the new API

While the implementation looks good, let's ensure all relevant documentation is updated to reflect this new option.


Let me check the README.md content to verify the documentation coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential documentation files that might need updates
echo "Searching for documentation files..."
fd -e md -e txt . | grep -i -E 'doc|guide|readme|changelog'

# Search for other potential usages of RoomOptions that might benefit from this change
echo "Searching for other RoomOptions usage..."
rg "RoomOptions" --type swift

Length of output: 4810


Script:

#!/bin/bash
# Check README.md content for RoomOptions documentation
echo "Checking README content..."
cat README.md

# Check if there are any inline documentation comments for RoomOptions
echo -e "\nChecking inline documentation..."
rg -A 5 "RoomOptions" --type swift Sources/AblyChat/RoomOptions.swift

Length of output: 3171

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5676cac and 2fe43db.

📒 Files selected for processing (2)
  • Example/AblyChatExample/ContentView.swift (1 hunks)
  • Sources/AblyChat/RoomOptions.swift (1 hunks)
🔇 Additional comments (2)
Sources/AblyChat/RoomOptions.swift (1)

9-15: Well-structured implementation with clear naming!

The new allFeaturesEnabled static property accurately reflects its purpose of enabling all room features with their default settings. The naming choice is better than "defaults" as it clearly communicates the intent to users.

Example/AblyChatExample/ContentView.swift (1)

59-59: Clean implementation demonstrating the new API!

The simplified room initialization provides a good example of how to use the new allFeaturesEnabled option, making the code more maintainable while serving as clear documentation for SDK users.

@lawrence-forooghian lawrence-forooghian force-pushed the add-all-features-enabled-room-options branch from 2fe43db to edae406 Compare December 4, 2024 18:03
@lawrence-forooghian lawrence-forooghian changed the base branch from main to 119-CHA-RL1h5-asynchronously December 4, 2024 18:03
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (16)
Tests/AblyChatTests/Mocks/MockRoom.swift (2)

56-61: Consider using a precondition instead of fatalError

The implementation looks good, but consider using precondition instead of fatalError for the guard clause. This would make the failure condition more explicit as a test requirement.

- fatalError("releaseImplementation must be set before calling `release`")
+ precondition(releaseImplementation != nil, "releaseImplementation must be set before calling `release`")

63-68: Enhance documentation with usage example

The documentation is clear but could be more helpful with a usage example. Consider adding an example showing how to consume this sequence in tests.

 /// Emits an element each time ``release()`` is called.
+///
+/// Example usage:
+/// ```swift
+/// for await _ in mockRoom.releaseCallsAsyncSequence {
+///     // Handle release call
+/// }
+/// ```
Sources/AblyChat/Errors.swift (5)

57-90: Add explicit return statements in computed properties for clarity

In the toNumericErrorCode computed property, the switch cases lack explicit return statements. While Swift allows implicit returns in single-expression closures and computed properties, adding return statements can improve readability and prevent potential confusion.

Apply the following diff to add return statements:

internal var toNumericErrorCode: ErrorCode {
    switch self {
    case .inconsistentRoomOptions:
-        .inconsistentRoomOptions
+        return .inconsistentRoomOptions
    case .messagesAttachmentFailed:
-        .messagesAttachmentFailed
+        return .messagesAttachmentFailed
    case .presenceAttachmentFailed:
-        .presenceAttachmentFailed
+        return .presenceAttachmentFailed
    // ... (continue for each case)
    }
}

Consider making similar changes in other computed properties and functions where implicit returns are used.


92-115: Ensure explicit return statements in statusCode computed property

In the statusCode computed property of CaseThatImpliesFixedStatusCode, the switch cases lack explicit return statements. Adding them enhances clarity.

Apply the following diff:

internal var statusCode: Int {
    switch self {
    case .inconsistentRoomOptions,
         .roomInFailedState,
         .roomIsReleasing,
         .roomIsReleased,
         .roomReleasedBeforeOperationCompleted:
-        400
+        return 400
    case .messagesAttachmentFailed,
         .presenceAttachmentFailed,
         .reactionsAttachmentFailed,
         .occupancyAttachmentFailed,
         .typingAttachmentFailed,
         .messagesDetachmentFailed,
         .presenceDetachmentFailed,
         .reactionsDetachmentFailed,
         .occupancyDetachmentFailed,
         .typingDetachmentFailed:
-        500
+        return 500
    }
}

130-146: Add explicit return statements in code computed property

In the code computed property of ErrorCodeAndStatusCode, explicit return statements improve readability.

Apply the following diff:

internal var code: ErrorCode {
    switch self {
    case let .fixedStatusCode(code):
-        code.toNumericErrorCode
+        return code.toNumericErrorCode
    case let .variableStatusCode(code, _):
-        code.toNumericErrorCode
+        return code.toNumericErrorCode
    }
}

147-154: Add explicit return statements in statusCode computed property

Similarly, in the statusCode computed property, add return statements.

Apply the following diff:

internal var statusCode: Int {
    switch self {
    case let .fixedStatusCode(code):
-        code.statusCode
+        return code.statusCode
    case let .variableStatusCode(_, statusCode):
-        statusCode
+        return statusCode
    }
}

215-218: Consider handling optional room status change gracefully

In waitToBeAbleToPerformPresenceOperations, the code comments mention uncertainty about handling a nil nextRoomStatusChange. Consider adding a guard statement or error handling to manage potential nil values explicitly.

For example:

guard let statusChange = nextRoomStatusChange else {
    throw ARTErrorInfo(chatError: .roomTransitionedToInvalidStateForPresenceOperation(cause: nil))
}
Tests/AblyChatTests/DefaultRoomsTests.swift (3)

133-154: Ensure consistent error handling in test get_whenRoomExistsInRoomMap_throwsErrorWhenOptionsDoNotMatch

The test correctly expects an inconsistentRoomOptions error. However, consider adding assertions for the status code to ensure comprehensive testing of error objects.

Update the assertion to check for both the error code and status code:

await #expect {
    try await rooms.get(roomID: roomID, options: differentOptions)
} throws: { error in
    isChatError(error, withCodeAndStatusCode: .fixedStatusCode(.inconsistentRoomOptions))
}

195-197: Remove unnecessary code after test completion

After the test get_whenFutureExistsInRoomMap_throwsErrorWhenOptionsDoNotMatch, the code includes a post-test section to allow the release operation to complete. If this does not impact other tests, consider removing it for clarity.

-// Post-test: Allow the CHA-RC1g release operation to complete
-roomReleaseOperation.complete()

298-349: Improve test coverage for release_withReleaseInProgress_failsPendingGetOperations

The test effectively checks that pending get operations fail when a release is in progress. To enhance the test, consider verifying that the second release reuses the existing release operation and does not trigger a new release.

Add assertions to confirm that:

  • The release operation is not called again on the room.
  • The room state is correctly managed.
Sources/AblyChat/RoomLifecycleManager.swift (2)

Line range hint 195-254: Clarify state transitions in the Status enum

The addition of new cases in the Status enum enhances error handling, but the transitions between states might benefit from additional comments or clarifications. This will help future maintainers understand the flow better.

Consider adding documentation comments explaining when each state is used and how transitions occur between states.


Line range hint 754-772: Ensure proper error handling in scheduleAnOperation method

When scheduling operations like retry and rundown, make sure that any errors thrown are appropriately handled or propagated to prevent the application from entering an inconsistent state.

Review the error handling within the tasks and consider adding do-catch blocks if necessary.

Tests/AblyChatTests/DefaultRoomLifecycleManagerTests.swift (2)

486-511: Enhance the test for attach_whenAttachPutsChannelIntoFailedState_schedulesRundownOperation

The test checks that a RUNDOWN operation is scheduled when a contributor enters a failed state during attachment. To improve the test:

  • Verify that the RUNDOWN operation detaches all non-failed contributors.
  • Confirm that the manager transitions to the correct final state.

Add assertions to check the detach call counts and the final manager status.


1346-1412: Add comments for clarity in the RUNDOWN operation tests

The tests for the RUNDOWN operation are comprehensive but can benefit from additional inline comments explaining each step. This aids readability and understanding for future contributors.

Include comments that describe the purpose of each section within the tests, particularly around the expected outcomes and assertions.

Sources/AblyChat/RoomFeature.swift (1)

44-48: Consider enhancing error documentation with examples

While the documentation updates clearly describe the error conditions, it would be helpful to add code examples demonstrating each error scenario.

Consider adding examples like:

// Example for CHA-PR3d/CHA-RL9:
try await channel.waitToBeAbleToPerformPresenceOperations(requestedByFeature: .presence)
// Throws ChatError.roomTransitionedToInvalidStateForPresenceOperation when room transitions from ATTACHING to FAILED

// Example for CHA-PR3e:
// Returns immediately when room is ATTACHED

// Example for CHA-PR3h:
// Throws ChatError.presenceOperationRequiresRoomAttach when room is DETACHED
Sources/AblyChat/DefaultMessages.swift (1)

237-244: Enhance error logging for better debugging

The error handling implementation looks good with the new ErrorCode.CaseThatImpliesFixedStatusCode.messagesAttachmentFailed case. However, consider including more context in the error message for better debugging.

Consider this enhancement:

     let errorCodeCase = ErrorCode.CaseThatImpliesFixedStatusCode.messagesAttachmentFailed
     nillableContinuation?.resume(
         throwing: ARTErrorInfo.create(
             withCode: errorCodeCase.toNumericErrorCode.rawValue,
             status: errorCodeCase.statusCode,
-            message: "Channel failed to attach"
+            message: "Channel failed to attach. Current state: \(stateChange.current), Previous state: \(stateChange.previous)"
         )
     )
🛑 Comments failed to post (1)
Sources/AblyChat/Rooms.swift (1)

241-244: ⚠️ Potential issue

Handle potential errors from createRoom appropriately

In the createRoom method, if roomFactory.createRoom throws an error, the room state won't be updated, and the error may not be propagated correctly. Ensure that errors are properly handled and the room state is consistent.

Consider wrapping the room creation in a do-catch block and updating the state accordingly:

do {
    let room = try await roomFactory.createRoom(...)
    roomStates[roomID] = .roomMapEntry(.created(room: room))
    return room
} catch {
    // Handle error, possibly update roomStates or propagate the error
    throw error
}

@lawrence-forooghian lawrence-forooghian force-pushed the add-all-features-enabled-room-options branch from edae406 to 3c46c60 Compare December 4, 2024 18:25
@lawrence-forooghian lawrence-forooghian changed the base branch from 119-CHA-RL1h5-asynchronously to main December 4, 2024 18:25
In 20e7f5f I said

> RoomOptionsDefaults in JS is instead implemented here by giving the
> *Options types a no-args initializer that populates the default values.

but I had not noticed that JS’s RoomOptionsDefaults is not actually a
“default”, since the JS SDK does not even have a concept of a “default”
RoomOptions. What it actually is is a RoomOptions in which all of the
room features are switched on; we discussed this today in standup and
Andy said that the intention of this value was to give users who are
just playing around with the SDK an easy way to turn all features on.
So, here, I add such an API for Swift, but with a name that more
accurately describes its intention. Andy’s created [1] to revisit the JS
naming.

[1] https://ably.atlassian.net/browse/CHA-766
@lawrence-forooghian lawrence-forooghian force-pushed the add-all-features-enabled-room-options branch from 3c46c60 to c595df1 Compare December 4, 2024 18:31
@lawrence-forooghian lawrence-forooghian merged commit 2b2bfc0 into main Dec 4, 2024
12 checks passed
@lawrence-forooghian lawrence-forooghian deleted the add-all-features-enabled-room-options branch December 4, 2024 18:36
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.

3 participants