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

[ECO-5116] Switch to V2 Chat API #122

Merged
merged 1 commit into from
Nov 26, 2024
Merged

[ECO-5116] Switch to V2 Chat API #122

merged 1 commit into from
Nov 26, 2024

Conversation

maratal
Copy link
Collaborator

@maratal maratal commented Nov 19, 2024

I've temporarily switched to the branch of ably-cocoa PR It should be merged before this PR so I could remove tmp commit.

Summary by CodeRabbit

  • New Features

    • Enhanced message handling with new properties for reactions and message identifiers.
    • Introduced support for the new chat API version.
    • Updated event handling to reflect new message events.
  • Bug Fixes

    • Corrected message identifier usage in various components.
  • Documentation

    • Updated tests to align with the new message structure and properties.
  • Chores

    • Updated dependencies to point to a new feature branch for improved chat support.

Copy link

coderabbitai bot commented Nov 19, 2024

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

The pull request includes updates to the AblyChat project, focusing on modifying the Package.resolved file and various Swift source files. Key changes involve switching the ably-cocoa dependency to a specific feature branch and renaming properties related to message handling from timeserial to serial. Additionally, new properties such as latestAction have been introduced in relevant structures, and methods have been adjusted to accommodate these changes. The overall structure of the codebase remains intact, with a clear emphasis on transitioning to the new chat API version.

Changes

File Path Change Summary
AblyChat.xcworkspace/xcshareddata/swiftpm/Package.resolved Updated originHash and modified ably-cocoa dependency from main to feature/ECO-5116-chat-support.
Package.swift Changed ably-cocoa dependency branch from main to feature/ECO-5116-chat-support.
Sources/AblyChat/ChatAPI.swift Introduced apiVersionV2, updated getMessages and sendMessage methods to use new endpoint, and renamed timeserial to serial in SendMessageResponse.
Sources/AblyChat/DefaultMessages.swift Removed TimeserialString typealias, replaced with String for serial, and updated related methods.
Sources/AblyChat/Events.swift Changed MessageEvent visibility to public, replaced created case with create, and added fromAction method.
Sources/AblyChat/Message.swift Updated id to derive from serial, added latestAction, and modified initializer and CodingKeys.
Sources/AblyChat/Timeserial.swift Deleted the file containing Timeserial protocol and DefaultTimeserial struct.
Example/AblyChatExample/ContentView.swift Changed message identifier from timeserial to serial and added rotationAngle and rotationSpeed to Reaction.
Example/AblyChatExample/Mocks/Misc.swift Updated MockMessagesPaginatedResult to use serial instead of timeserial and added latestAction.
Example/AblyChatExample/Mocks/MockClients.swift Updated MockMessages methods to reflect changes in message initialization from timeserial to serial.
Tests/AblyChatTests/ChatAPITests.swift Updated tests to reflect changes in Message initialization and removed old timeserial references.
Tests/AblyChatTests/MessageSubscriptionTests.swift Adjusted Message initialization in tests to use serial instead of timeserial.
Tests/AblyChatTests/MessageTests.swift Modified tests to replace timeserial with serial and added latestAction.
Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift Renamed mock data keys from timeserial to serial and added latestAction.

Assessment against linked issues

Objective Addressed Explanation
Switch to V2 Chat API (ECO-5116)

Possibly related PRs

Suggested reviewers

  • umair-ably
  • lawrence-forooghian

Poem

In the chat where messages flow,
A new version helps us grow.
From timeserial to serial bright,
Reactions spin in joyful flight.
With each update, we hop and cheer,
For clearer paths, our goals are near! 🐇✨


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.

@maratal maratal requested a review from umair-ably November 19, 2024 15:03
@umair-ably
Copy link
Collaborator

Looks good. Only things to add would be:

  • We need to remove CHA-M5j (I've confirmed this with Andy, we just need to remove the few lines of code here - search for spec point in code)
  • We can get rid of the timeserial comparison functions e.g. isBefore, isAfter, isEqual... as we can now just compare them lexicographically e.g. using > or ==

@maratal
Copy link
Collaborator Author

maratal commented Nov 19, 2024

This? @umair-ably

@umair-ably
Copy link
Collaborator

This? @umair-ably

yeah that's right. I'd also get rid of the actual functions itself e.g. public func isBefore(_ otherMessage: Message) throws -> Bool... we can directly use the operators instead of nesting them inside these functions

@maratal maratal force-pushed the ECO-5116-V2-Chat-API branch from 5fa1257 to 6c1bb45 Compare November 20, 2024 17:46
@maratal
Copy link
Collaborator Author

maratal commented Nov 20, 2024

@umair-ably I've pushed draft version of all requested changes (apart from those in cocoa). You can preview it now.

@maratal maratal force-pushed the ECO-5116-V2-Chat-API branch 4 times, most recently from 7979e8f to 2044aaf Compare November 21, 2024 00:29
@maratal maratal force-pushed the ECO-5116-V2-Chat-API branch 4 times, most recently from 891a63b to 84bd031 Compare November 21, 2024 14:20
@maratal maratal changed the title Switch to V2 Chat API [ECO-5116] Switch to V2 Chat API Nov 21, 2024
@maratal maratal marked this pull request as ready for review November 21, 2024 14:54
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: 4

🧹 Outside diff range and nitpick comments (11)
Sources/AblyChat/Events.swift (1)

6-21: Consider enhancing the fromAction method implementation.

While the implementation is functionally correct, there are a few improvements that could make it more robust and maintainable:

  1. The implicit return on line 9 could be more explicit
  2. The comment about ignoring other actions could be moved to documentation
  3. Consider adding logging for ignored actions in development
 internal static func fromAction(_ action: ARTMessageAction) -> Self? {
+    /// Currently only supporting chat.message events, other actions are ignored
     switch action {
     case .create:
-        .new
+        return .new
     // ignore any other actions except `chat.message` for now
     case .unset,
          .update,
          .delete,
          .annotationCreate,
          .annotationDelete,
          .metaOccupancy:
+        #if DEBUG
+        print("Ignored message action: \(action)")
+        #endif
         nil
     @unknown default:
+        #if DEBUG
+        print("Unknown message action: \(action)")
+        #endif
         nil
     }
 }
Tests/AblyChatTests/MessageSubscriptionTests.swift (2)

29-29: Consider improving test data meaningfulness

While the Message initialization correctly uses the new parameters, consider these improvements:

  1. Use meaningful test values instead of empty strings for serial and clientID
  2. Consider adding test cases with different latestAction values to ensure proper handling
-        Message(serial: "", latestAction: .new, clientID: "", roomID: "", text: text, createdAt: .init(), metadata: [:], headers: [:])
+        Message(
+            serial: "test-serial-\(text.lowercased())",
+            latestAction: .new,
+            clientID: "test-client-1",
+            roomID: "test-room-1",
+            text: text,
+            createdAt: .init(),
+            metadata: ["testKey": "testValue"],
+            headers: ["X-Test": "true"]
+        )

Line range hint 32-65: Enhance test coverage for V2 Chat API changes

The test suite should be expanded to cover the new V2 Chat API functionality:

  1. Add test cases for different latestAction values
  2. Add tests for message ordering using serial comparison

Consider adding these test cases:

@Test
func messageOrdering() async {
    let messages = [
        Message(serial: "1", latestAction: .new, text: "First"),
        Message(serial: "2", latestAction: .new, text: "Second")
    ]
    
    #expect(messages[0].serial < messages[1].serial)
}

@Test
func differentLatestActions() async {
    let subscription = MessageSubscription(bufferingPolicy: .unbounded) { _ in 
        fatalError("Not implemented") 
    }
    
    let message = Message(serial: "1", latestAction: .edited, text: "Edited")
    subscription.emit(message)
    
    #expect(await subscription.first?.latestAction == .edited)
}
Tests/AblyChatTests/MessageTests.swift (1)

Line range hint 1-89: Consider adding edge case tests

While the basic comparison tests are good, consider adding tests for:

  • Messages with identical timestamps but different suffixes
  • Messages with different prefixes
  • Boundary cases for timestamp values

Would you like me to help create additional test cases for these scenarios?

Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (2)

Line range hint 64-69: Fix incorrect status code in successSendMessage mock

The mock is named successSendMessage but has a status code of 500 (Server Error). This contradicts the success scenario and would cause the success property to return false.

    static let successSendMessage = MockHTTPPaginatedResponse(
        items: [
            [
                "serial": "3446456",
                "createdAt": 1_631_840_000_000,
                "text": "hello",
            ],
        ],
-       statusCode: 500,
+       statusCode: 200,
        headers: [:]
    )

Line range hint 134-150: Update nextPage mock to match V2 Chat API format

The nextPage mock still uses the old "timeserial" key and is missing the "latestAction" field, making it inconsistent with the V2 Chat API format.

    static let nextPage = MockHTTPPaginatedResponse(
        items: [
            [
-               "timeserial": "3446450",
+               "serial": "3446450",
+               "latestAction": "chat.message",
                "roomId": "basketball::$chat::$chatMessages",
                "text": "previous message",
                "metadata": [:],
                "headers": [:],
            ],
            [
-               "timeserial": "3446451",
+               "serial": "3446451",
+               "latestAction": "chat.message",
                "roomId": "basketball::$chat::$chatMessages",
                "text": "previous response",
                "metadata": [:],
                "headers": [:],
            ],
        ],
        statusCode: 200,
        headers: [:]
    )
Tests/AblyChatTests/ChatAPITests.swift (1)

Time serial comparison functions still exist in MessageTests.swift

The PR objective to remove time serial comparison functions is not fully implemented. Found comparison functions in:

  • Tests/AblyChatTests/MessageTests.swift:
    • isBefore_WhenMessageIsBefore_ReturnsTrue()
    • isBefore_WhenMessageIsNotBefore_ReturnsFalse()
    • isAfter_whenMessageIsAfter_ReturnsTrue()
    • isAfter_whenMessageIsNotAfter_ReturnsFalse()
    • isEqual_whenMessageIsEqual_ReturnsTrue()
    • isEqual_whenMessageIsNotEqual_ReturnsFalse()

These comparison functions should be removed and replaced with direct operators as per PR objectives.

🔗 Analysis chain

Line range hint 1-143: Verify removal of time serial comparison functions.

Per PR objectives, time serial comparison functions (isBefore, isAfter, isEqual) should be removed in favor of direct operators.

Let's verify if any comparison functions still exist:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for time serial comparison functions
ast-grep --pattern 'func isBefore($$$) {
  $$$
}'

ast-grep --pattern 'func isAfter($$$) {
  $$$
}'

ast-grep --pattern 'func isEqual($$$) {
  $$$
}'

Length of output: 153


Script:

#!/bin/bash
# Search for any comparison functions or methods in Swift files
rg -t swift "func (isBefore|isAfter|isEqual)" -g "!vendor/*"

# Search for potential comparison method calls
rg -t swift "\.(isBefore|isAfter|isEqual)\(" -g "!vendor/*"

# Look for files that might contain Message or Serial related types
fd -e swift -x cat {} \; | rg "class.*(Message|Serial)|struct.*(Message|Serial)|extension.*(Message|Serial)" -A 5

Length of output: 4956

Sources/AblyChat/ChatAPI.swift (1)

6-6: Document the V1 to V2 migration strategy

While the TODO comment indicates a plan to remove V1 after full transition, it would be helpful to document:

  1. The migration timeline
  2. Why getOccupancy still uses V1
  3. Any breaking changes between V1 and V2

Consider adding a comment block explaining the migration strategy and any compatibility considerations.

Sources/AblyChat/DefaultMessages.swift (3)

Line range hint 84-93: Consider grouping related message parameters

The message construction parameters could be organized better by grouping related fields:

 let message = Message(
-    serial: serial,
-    latestAction: action,
-    clientID: clientID,
-    roomID: self.roomID,
-    text: text,
-    createdAt: message.timestamp,
-    metadata: metadata ?? .init(),
-    headers: headers ?? .init()
+    // Identity fields
+    serial: serial,
+    clientID: clientID,
+    roomID: self.roomID,
+    // Content fields
+    text: text,
+    metadata: metadata ?? .init(),
+    // State fields
+    latestAction: action,
+    createdAt: message.timestamp,
+    headers: headers ?? .init()
 )

201-201: Update error message terminology

The error message still refers to "timeserial" while the codebase has moved to "serial" terminology.

-logger.log(message: "Resolving timeserial on channel attach", level: .debug)
+logger.log(message: "Resolving serial on channel attach", level: .debug)

V2 API compatibility verification complete - issues found

The codebase shows several areas that need attention for V2 API compatibility:

  1. Legacy terminology is still present in the codebase:

    • References to timeserial in comments and variable names
    • Mixed usage of channelSerial and attachSerial for message sequencing
  2. V2 API integration is incomplete:

    • Only basic V2 endpoints are implemented (/chat/v2/rooms/{roomId}/messages)
    • TODO comment indicates partial V2 transition: "remove v1 after full transition to v2"
  3. Error handling needs standardization:

    • Mix of different error codes (40000, 50000) without clear V2 API alignment
    • Some error messages still use legacy terminology
🔗 Analysis chain

Line range hint 1-254: Verify V2 Chat API compatibility requirements

Several TODOs remain in the code that might affect V2 API integration:

  1. Issue Revisit the need for MainActor for DefaultMessages #83: Understanding of @mainactor usage
  2. Issue Find a way to clean up arrays of subscriptions #36: Handle unsubscribing
  3. Issue Revisit the errors thrown by library #32: Error handling review

Please ensure these issues are addressed as part of the V2 API migration.

Run the following to find any remaining V2 API compatibility issues:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for V2 API related TODOs and potential compatibility issues
echo "Searching for remaining TODOs..."
rg -n "TODO|FIXME" --type swift

echo "Checking for old API references..."
rg -n "timeserial|created\.rawValue" --type swift

echo "Verifying message event handling..."
ast-grep --pattern 'MessageEvent.$_' --type swift

Length of output: 22813


Script:

#!/bin/bash
# Let's verify the V2 API compatibility more thoroughly

# Check for V2 API specific patterns
echo "Checking V2 API patterns..."
rg -n "chat/v2|apiVersionV2" --type swift

# Check message event handling
echo "Checking message event handling..."
rg -n "MessageEvent\." --type swift

# Check for any remaining old API references
echo "Checking for old API references..."
rg -n "created\.rawValue|timeserial|channelSerial|attachSerial" --type swift -C 2

# Check for unhandled error cases
echo "Checking error handling..."
rg -n "throw (ARTErrorInfo|MessagesError)" --type swift -C 2

Length of output: 20686

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d2e5ddb and 84bd031.

📒 Files selected for processing (14)
  • AblyChat.xcworkspace/xcshareddata/swiftpm/Package.resolved (1 hunks)
  • Example/AblyChatExample/ContentView.swift (1 hunks)
  • Example/AblyChatExample/Mocks/Misc.swift (1 hunks)
  • Example/AblyChatExample/Mocks/MockClients.swift (2 hunks)
  • Package.swift (1 hunks)
  • Sources/AblyChat/ChatAPI.swift (3 hunks)
  • Sources/AblyChat/DefaultMessages.swift (9 hunks)
  • Sources/AblyChat/Events.swift (1 hunks)
  • Sources/AblyChat/Message.swift (2 hunks)
  • Sources/AblyChat/Timeserial.swift (0 hunks)
  • Tests/AblyChatTests/ChatAPITests.swift (4 hunks)
  • Tests/AblyChatTests/MessageSubscriptionTests.swift (1 hunks)
  • Tests/AblyChatTests/MessageTests.swift (5 hunks)
  • Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (3 hunks)
💤 Files with no reviewable changes (1)
  • Sources/AblyChat/Timeserial.swift
🧰 Additional context used
📓 Learnings (1)
Package.swift (1)
Learnt from: umair-ably
PR: ably-labs/ably-chat-swift#45
File: Package.swift:23-23
Timestamp: 2024-11-12T15:07:39.465Z
Learning: In the Ably Chat Swift project, it's acceptable to use a branch-based dependency ('branch: "main"') for the 'ably-cocoa' package because the team owns that SDK and the code isn't going into production soon.
🔇 Additional comments (28)
Sources/AblyChat/Events.swift (2)

3-3: LGTM! Verify the public API exposure.

The visibility change to public is appropriate for the V2 Chat API migration. The protocol conformance to Codable and Sendable supports serialization and thread safety.

✅ Verification successful

Making MessageEvent public is appropriate and well-integrated

The visibility change to public is justified as the enum is already used in public interfaces:

  • Used as a public property latestAction in Message struct
  • Used in public initializer parameters
  • Integrated with Ably channel subscription system in DefaultMessages
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if this enum is referenced in public interfaces
# Expected: Find references in public API declarations

# Search for public declarations using MessageEvent
ast-grep --pattern 'public $_ $_: MessageEvent'

# Search for public function parameters using MessageEvent
ast-grep --pattern 'public func $_($_: MessageEvent)'

Length of output: 105


Script:

#!/bin/bash
# Let's try a broader search to understand the usage of MessageEvent

# Find all files containing MessageEvent
rg "MessageEvent" -l

# Show the context of MessageEvent usage
rg "MessageEvent" -B 2 -A 2

# Find Swift files that might be using this enum
fd ".swift$" --exec grep -l "MessageEvent" {}

Length of output: 2373


4-4: Verify event subscription updates across the codebase.

The change from created = "message.created" to new = "chat.message" represents a breaking change in the event naming convention. While this aligns with the V2 Chat API, it requires careful migration of existing event subscriptions.

Sources/AblyChat/Message.swift (4)

20-22: LGTM! Initializer changes are consistent

The initializer has been properly updated to include the new parameters and maintains a clean parameter order matching the property declarations.


32-33: LGTM! CodingKeys maintain consistent naming convention

The CodingKeys enum has been properly updated to include the new properties while maintaining the established naming convention for JSON serialization.


Line range hint 1-40: Verify removal of CHA-prefixed components

The file contains a "CHA-M2" comment. Based on PR comments about removing "CHA-M5j", we should verify if other CHA-prefixed components need removal.


9-9: Verify that lexicographical ordering of serial maintains message sequence

The change from timeserial to serial for ID computation looks good, but we should verify that lexicographical comparison of serial strings maintains the correct message ordering.

✅ Verification successful

Lexicographical ordering of serial is verified and maintains correct message sequence

Based on the evidence from the codebase:

  1. The serial format follows a timestamp-based pattern (e.g., "ABC123@1631840000000-5:2") which ensures lexicographical ordering matches temporal ordering
  2. Tests explicitly verify this ordering behavior:
    • MessageTests.swift confirms earlierMessage.serial < laterMessage.serial
    • Multiple test cases validate the correct ordering relationship
  3. The V2 Chat API provides these serials, ensuring consistency with Ably's message ordering guarantees
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any custom sorting or comparison logic that might depend on message ordering
rg -g '*.swift' -A 3 'sort|compare' 

Length of output: 5139


Script:

#!/bin/bash
# Search for message ordering or serial-related code
rg -g '*.swift' -A 5 'serial|message.*order'

# Also check for any array operations on messages
ast-grep --pattern 'messages.$$$sort($$$)'

Length of output: 21787

AblyChat.xcworkspace/xcshareddata/swiftpm/Package.resolved (1)

9-10: Caution: Using feature branch in production code

Using a feature branch (feature/ECO-5116-chat-support) as a dependency source can be risky in production code:

  • Feature branches are typically temporary and may be deleted
  • They can be rebased or force-pushed, breaking your builds
  • Makes it harder to track which version of the API you're using

Consider one of these approaches:

  1. Wait for the V2 Chat API changes to be merged into main
  2. Fork the repository and maintain your own stable branch
  3. Pin to a specific tag once the V2 Chat API is officially released
Package.swift (2)

23-24: Track technical debt for switching back to tag-based versioning.

The TODO comment indicates this branch-based dependency is temporary. While this is acceptable for now (as confirmed by previous feedback), we should ensure this technical debt is properly tracked.

Consider creating a reminder or milestone to switch back to tag-based versioning once the V2 Chat API changes are stable. This will ensure better reproducibility of builds in the future.

✅ Verification successful

Technical debt is already tracked in issue #80

The TODO comment references issue #80 which exists and is currently open with the title "Switch back to using a tag of ably-cocoa". This confirms that the technical debt is being properly tracked in the issue tracker.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if issue #80 exists and is still open
gh issue view 80 --repo ably-labs/ably-chat-swift --json state,title

Length of output: 138


24-24: LGTM! Verify branch existence.

The branch change aligns with the PR objective to switch to V2 Chat API.

✅ Verification successful

Branch exists and is accessible ✓

The feature branch feature/ECO-5116-chat-support exists in the ably-cocoa repository and is accessible, making it safe to use as a dependency.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the feature branch exists in the ably-cocoa repository
gh repo clone ably/ably-cocoa /tmp/ably-cocoa 2>/dev/null || true
cd /tmp/ably-cocoa
git fetch origin feature/ECO-5116-chat-support
git branch -r --contains origin/feature/ECO-5116-chat-support

Length of output: 327

Tests/AblyChatTests/MessageSubscriptionTests.swift (1)

Line range hint 1-65: Verify removal of CHA-M5j related test code

Based on the PR comments about removing the CHA-M5j component, we should verify if any related test code needs to be removed from this file.

Tests/AblyChatTests/MessageTests.swift (4)

56-57: LGTM! Consistent use of comparison operators

The changes maintain consistency with the isBefore tests by using direct comparison operators.

Also applies to: 62-63


42-43: LGTM! Direct comparison operators improve readability

The switch from isBefore function to direct < operator aligns with the PR objectives and simplifies the code.

Let's verify all comparison functions have been removed:

Also applies to: 48-49

✅ Verification successful

LGTM! All comparison functions have been correctly replaced with operators

Looking at the test file, all the test methods now use direct comparison operators (<, >, ==, !=) instead of function calls. The only remaining function with "isEqual" is in ChatClient.swift but it's unrelated (for test purposes only). The changes align with the PR objectives of simplifying comparisons.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining comparison function implementations
ast-grep --pattern 'func isBefore($$$) { $$$ }'
ast-grep --pattern 'func isAfter($$$) { $$$ }'
ast-grep --pattern 'func isEqual($$$) { $$$ }'

Length of output: 147


Script:

#!/bin/bash
# Search for any remaining comparison function declarations or calls
rg -i "func (isbefore|isafter|isequal)" -g "*.swift"

# Search for any method calls of these comparison functions
rg -i "\.(isbefore|isafter|isequal)\(" -g "*.swift"

# Let's also check the test file specifically to understand the context better
cat Tests/AblyChatTests/MessageTests.swift

Length of output: 3197


71-81: Verify intended equality comparison behavior

The tests now compare only the serial field for equality. Please confirm if this is the intended behavior, as messages with different content but same serial are considered equal.

Let's check the previous implementation:

Consider documenting this behavior in the Message class if it hasn't been done already, as it affects message identity semantics.

Also applies to: 86-87

✅ Verification successful

Message equality based on serial is the correct behavior

The implementation is correct and intentional. The Message struct conforms to Equatable protocol without a custom implementation, which means Swift synthesizes the equality operator (==) comparing all stored properties. However, the struct also conforms to Identifiable with id explicitly defined to return the serial property, indicating that serial is intended to be the unique identifier for messages. The test is correctly verifying this design choice, as two messages in the same channel cannot have the same timeserial (as documented in the code comments).

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for previous message equality implementation
git log -p -- "**/Message.swift" | rg -B 5 -A 5 "func.*[iI]s[eE]qual"

Length of output: 0


Script:

#!/bin/bash
# Let's try a different approach to find equality implementation
# First, let's find Message.swift files
fd Message.swift

# Then search for equality implementation in current files
rg -B 5 -A 5 "(?:Equatable|==|[iI]s[eE]qual)" $(fd Message.swift)

# Also search for any tests related to message equality
rg -B 5 -A 5 "(?:test.*[eE]qual|XCTAssert.*[eE]qual)" $(fd Message.swift)

Length of output: 802


Script:

#!/bin/bash
# Let's check the Message.swift file content to understand the equality implementation
cat Sources/AblyChat/Message.swift

# Also check if there are any recent changes to Message.swift
git diff HEAD~5 HEAD -- Sources/AblyChat/Message.swift

Length of output: 1587


6-7: Consider adding serial format validation tests

The serial format appears to follow a specific pattern (prefix@timestamp-suffix), but there are no tests validating this format. The invalidMessage with "invalid" serial suggests format validation might be important.

Let's check if there are any format validation tests elsewhere:

Would you like me to help create test cases for serial format validation?

Also applies to: 17-18, 28-29

Example/AblyChatExample/Mocks/Misc.swift (2)

Line range hint 1-116: Verify test coverage for V2 API changes

Since this is a mock implementation used in tests, ensure that all V2 API scenarios are properly covered, including edge cases with different serial values and action states.


14-15: Verify V2 Chat API message initialization

The changes align with the V2 API transition by replacing timeserial with serial and adding latestAction. However, let's verify if there are any other required parameters for V2 API compliance.

✅ Verification successful

Based on the comprehensive search results, I can now provide a final response regarding the V2 Chat API message initialization verification:

Message initialization is correctly implemented with required V2 API parameters

The Message struct in Sources/AblyChat/Message.swift shows that all required fields are present and properly initialized:

  • serial: String identifier (replacing timeserial)
  • latestAction: MessageEvent type
  • clientID: String for client identification
  • roomID: String for room identification
  • text: String content
  • createdAt: Optional Date
  • metadata: MessageMetadata (type alias for Headers)
  • headers: MessageHeaders (type alias for Headers)

The mock implementation correctly uses these fields and the V2 API transition is properly handled throughout the codebase, including the ChatAPI, DefaultMessages, and test implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Message initialization patterns to ensure consistency
ast-grep --pattern 'Message(
  $$$
  serial: $_,
  latestAction: $_,
  $$$
)'

Length of output: 79


Script:

#!/bin/bash
# Search for Message type declarations and initializations with a broader pattern
rg -U "Message.*\{[\s\S]*?\}" -A 10

# Also search for any Message-related type definitions
rg "class Message|struct Message|typealias Message"

Length of output: 74681

Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (1)

101-102: LGTM! Changes align with V2 Chat API

The renaming of "timeserial" to "serial" and addition of "latestAction" field are consistent with the V2 Chat API migration.

Also applies to: 111-112

Tests/AblyChatTests/ChatAPITests.swift (3)

93-94: LGTM! Consistent Message structure across test cases.

The Message initialization is consistent across test cases, properly using sequential serials ("3446456", "3446457") and maintaining the new V2 API structure.

Also applies to: 103-104


116-116: LGTM! Improved variable naming.

The rename from getMessages to getMessagesResult enhances test readability by avoiding name collision with the method being tested and better describing the variable's purpose.

Also applies to: 119-119


43-44: LGTM! Verify V2 API Message structure.

The changes correctly reflect the new Message structure for V2 Chat API with serial and latestAction properties.

Let's verify the Message structure matches V2 API specification:

✅ Verification successful

Message structure correctly reflects V2 Chat API changes

The codebase analysis confirms that:

  • The Message struct in Sources/AblyChat/Message.swift has been properly updated with serial and latestAction properties
  • The changes are consistently applied across all test files and implementations
  • The migration from timeserial to serial is complete, with proper handling in the DefaultMessages implementation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Message struct definition to confirm structure
ast-grep --pattern 'struct Message {
  $$$
  serial: $_
  latestAction: $_
  $$$
}'

Length of output: 85


Script:

#!/bin/bash
# Let's try a broader search for Message struct definition in Swift files
fd -e swift | xargs rg -l "struct Message"

# Then search for serial and latestAction properties
fd -e swift | xargs rg "serial|latestAction" -A 2 -B 2

Length of output: 19795

Sources/AblyChat/ChatAPI.swift (2)

14-14: LGTM: Clean V2 endpoint update

The endpoint update maintains the existing interface while transitioning to V2.


48-49: Verify Message struct changes and latestAction enum

The Message initialization includes two changes:

  1. Using serial instead of timeserial
  2. Adding latestAction: .new

Let's verify the Message struct definition and the latestAction enum.

✅ Verification successful

Let me gather more information about the MessageEvent enum since we see it's used as the type for latestAction.


Message struct and latestAction enum changes are properly defined

The verification confirms:

  1. Message struct properly includes the latestAction property of type MessageEvent
  2. MessageEvent enum is well-defined with .new case that maps to "chat.message"
  3. The usage is consistent across tests and implementation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Message struct definition and latestAction enum
echo "Checking Message struct definition:"
ast-grep --pattern 'struct Message {
  $$$
}'

echo -e "\nChecking latestAction enum/property definition:"
rg "latestAction" -B 2 -A 2 --type swift

Length of output: 7568


Script:

#!/bin/bash
# Search for MessageEvent enum definition
echo "Checking MessageEvent enum definition:"
ast-grep --pattern 'enum MessageEvent {
  $$$
}'

# Also search for any other references to MessageEvent
echo -e "\nChecking MessageEvent references:"
rg "MessageEvent" -B 2 -A 2 --type swift

Length of output: 2332

Example/AblyChatExample/Mocks/MockClients.swift (2)

106-107: LGTM! Changes align with V2 Chat API migration

The changes to use serial instead of timeserial and addition of latestAction: .new are consistent with the V2 Chat API requirements.


132-133: LGTM! Consistent implementation with createSubscription

The changes mirror those in createSubscription, maintaining consistency across the mock implementation.

Sources/AblyChat/DefaultMessages.swift (2)

3-7: LGTM: Clean rename from timeserial to serial

The rename maintains the structure's purpose while aligning with V2 Chat API conventions.


56-56: Verify message handling behavior with V2 API

The changes introduce two significant modifications:

  1. Switch from MessageEvent.created to MessageEvent.new
  2. Silent return when action can't be mapped to a MessageEvent

Consider logging discarded messages at DEBUG level to aid troubleshooting.

 guard let action = MessageEvent.fromAction(message.action) else {
+    logger.log(message: "Discarding message with unknown action: \(message.action)", level: .debug)
     return
 }

Also applies to: 80-82

Example/AblyChatExample/ContentView.swift (2)

Line range hint 1-4: Verify dependencies on removed components

Based on PR comments, please verify:

  1. Any dependencies on the CHA-M5j component that needs to be removed
  2. Any usage of time serial comparison functions (isBefore, isAfter, isEqual) that should be replaced with direct operators

Let's check for these dependencies:

✅ Verification successful

No dependencies found on removed components

Based on the search results:

  1. No occurrences of CHA-M5j component were found in the codebase
  2. The time comparison functions (isBefore, isAfter, isEqual) found in tests are unrelated to message comparisons, as they are used for testing client options equality
  3. The AblyChat imports are valid and required for the chat functionality
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for CHA-M5j component usage and time comparison functions

# Search for CHA-M5j component
echo "Checking for CHA-M5j component usage:"
rg -l "CHA-M5j"

# Check imports for potential dependencies
echo "Checking imports that might need updating:"
rg "^import.*Chat" 

# Look for any message comparison usage
echo "Checking for message comparison usage:"
rg -A 2 "\.(isBefore|isAfter|isEqual)"

Length of output: 1647


192-192: LGTM! Verify complete migration from timeserial to serial

The change from timeserial to serial is consistent with the V2 Chat API migration.

Let's verify the complete migration across the codebase:

Also applies to: 200-200

✅ Verification successful

Remaining timeserial references need to be addressed

The migration from timeserial to serial is incomplete. Found references that need attention:

  • Sources/AblyChat/DefaultMessages.swift: Contains comments and logging references to timeserial
  • Sources/AblyChat/Message.swift: Contains a comment about timeserial in message identification
  • Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift: Contains mock data using timeserial

Let's verify if these are just documentation artifacts or actual code dependencies:


Migration from timeserial to serial is complete, only documentation needs updating

The codebase scan reveals that all actual code usage has been migrated to serial. The remaining timeserial references are only in:

  • Comments in Message.swift explaining the id property
  • Debug logging messages in DefaultMessages.swift
  • Test mock data that needs updating

No structural definitions or actual code dependencies on timeserial were found. The migration is functionally complete, but documentation should be updated for consistency.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining timeserial references that need to be updated

# Search for any remaining timeserial references
echo "Checking for remaining timeserial references:"
rg "timeserial" 

# Search for any comparison functions that might need updating
echo "Checking for message comparison functions:"
ast-grep --pattern 'func is(Before|After|Equal).*Message.*Bool'

Length of output: 1103


Script:

#!/bin/bash
# Check the actual code usage in these files
echo "Checking DefaultMessages.swift implementation:"
rg -A 2 "timeserial" Sources/AblyChat/DefaultMessages.swift

echo "\nChecking Message.swift implementation:"
rg -A 2 "timeserial" Sources/AblyChat/Message.swift

echo "\nChecking struct/class definitions for timeserial property:"
ast-grep --pattern 'struct $_ {
  $$$
  timeserial: $_
  $$$
}'

ast-grep --pattern 'class $_ {
  $$$
  timeserial: $_
  $$$
}'

Length of output: 1334

Sources/AblyChat/Message.swift Outdated Show resolved Hide resolved
AblyChat.xcworkspace/xcshareddata/swiftpm/Package.resolved Outdated Show resolved Hide resolved
Example/AblyChatExample/Mocks/Misc.swift Show resolved Hide resolved
Sources/AblyChat/ChatAPI.swift Show resolved Hide resolved
@maratal maratal force-pushed the ECO-5116-V2-Chat-API branch from fac5ac1 to 14310b9 Compare November 21, 2024 23:52
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 84bd031 and 14310b9.

📒 Files selected for processing (14)
  • AblyChat.xcworkspace/xcshareddata/swiftpm/Package.resolved (1 hunks)
  • Example/AblyChatExample/ContentView.swift (1 hunks)
  • Example/AblyChatExample/Mocks/Misc.swift (1 hunks)
  • Example/AblyChatExample/Mocks/MockClients.swift (2 hunks)
  • Package.swift (1 hunks)
  • Sources/AblyChat/ChatAPI.swift (3 hunks)
  • Sources/AblyChat/DefaultMessages.swift (9 hunks)
  • Sources/AblyChat/Events.swift (1 hunks)
  • Sources/AblyChat/Message.swift (2 hunks)
  • Sources/AblyChat/Timeserial.swift (0 hunks)
  • Tests/AblyChatTests/ChatAPITests.swift (4 hunks)
  • Tests/AblyChatTests/MessageSubscriptionTests.swift (1 hunks)
  • Tests/AblyChatTests/MessageTests.swift (5 hunks)
  • Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (4 hunks)
💤 Files with no reviewable changes (1)
  • Sources/AblyChat/Timeserial.swift
🚧 Files skipped from review as they are similar to previous changes (12)
  • AblyChat.xcworkspace/xcshareddata/swiftpm/Package.resolved
  • Example/AblyChatExample/ContentView.swift
  • Example/AblyChatExample/Mocks/Misc.swift
  • Example/AblyChatExample/Mocks/MockClients.swift
  • Package.swift
  • Sources/AblyChat/ChatAPI.swift
  • Sources/AblyChat/DefaultMessages.swift
  • Sources/AblyChat/Message.swift
  • Tests/AblyChatTests/ChatAPITests.swift
  • Tests/AblyChatTests/MessageSubscriptionTests.swift
  • Tests/AblyChatTests/MessageTests.swift
  • Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift
🔇 Additional comments (3)
Sources/AblyChat/Events.swift (3)

3-4: LGTM! API changes look appropriate.

The changes to make MessageEvent public with Codable and Sendable conformance are well-considered. The case rename from 'created' to 'create' aligns with V2 Chat API conventions.


24-25: LGTM! Message filtering implementation looks clean.

The new MessageFilter enum with the 'new' case provides a clear way to filter chat messages. The Sendable conformance ensures thread safety.


6-21: Verify the intentional ignoring of other message actions.

The comment indicates that other actions are being ignored intentionally. Please confirm if this aligns with the V2 Chat API requirements and if there are plans to handle these actions in the future.

✅ Verification successful

Intentional ignoring of message actions is verified and aligned with current implementation

Based on the codebase analysis:

  • The code explicitly handles only the create action for messages, with a clear comment indicating this is intentional ("ignore any other actions except chat.message for now")
  • The implementation in DefaultMessages.swift filters out all other message actions by returning early when MessageEvent.fromAction() returns nil
  • No other parts of the codebase are attempting to use the ignored message actions
  • The comment's "for now" suggests this is a deliberate temporary limitation, likely part of an incremental development approach
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any usage of ignored message actions in the codebase
rg -l "ARTMessageAction\.(update|delete|annotationCreate|annotationDelete|metaOccupancy)"

Length of output: 91


Script:

#!/bin/bash
# Let's first check for any documentation or comments about message actions
rg -i "message.*action" -A 5 -B 5

# Also search for ARTMessageAction enum usage
rg "ARTMessageAction" -A 5 -B 5

# Look for any TODOs or FIXMEs related to message actions
rg -i "(todo|fixme).*message.*action"

# Check if there are any test files related to message actions
fd -e swift test | xargs rg "ARTMessageAction"

Length of output: 13394

Sources/AblyChat/Events.swift Outdated Show resolved Hide resolved
@maratal maratal force-pushed the ECO-5116-V2-Chat-API branch from 14310b9 to 8129e9c Compare November 21, 2024 23:59
@maratal
Copy link
Collaborator Author

maratal commented Nov 22, 2024

@coderabbitai pause

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 (4)
Example/AblyChatExample/Mocks/MockClients.swift (1)

106-106: Consider extracting serial generation logic

The timestamp-based serial generation is duplicated and could potentially lead to collisions in rapid succession. Consider extracting this into a shared utility method that implements a more robust serial generation strategy.

 actor MockMessages: Messages {
+    private func generateUniqueSerial() -> String {
+        // Using nanoseconds and a counter to ensure uniqueness
+        let timestamp = Date().timeIntervalSince1970
+        let nanos = UInt64(timestamp * 1_000_000_000)
+        return String(format: "%d", nanos)
+    }
+
     private func createSubscription() -> MockSubscription<Message> {
         let subscription = MockSubscription<Message>(randomElement: {
             Message(
-                serial: "\(Date().timeIntervalSince1970)",
+                serial: generateUniqueSerial(),
                 latestAction: .create,
                 // ...
             )
         }, interval: 3)
     }

     func send(params: SendMessageParams) async throws -> Message {
         let message = Message(
-            serial: "\(Date().timeIntervalSince1970)",
+            serial: generateUniqueSerial(),
             latestAction: .create,
             // ...
         )
     }
 }

Also applies to: 132-132

Sources/AblyChat/DefaultMessages.swift (3)

168-173: Consider standardizing error message capitalization

The channel attachment handling has been properly updated for the V2 API. However, there's a minor inconsistency in error message capitalization:

  • Line 208: "Error resolving serial on channel attach"
  • Other error messages start with capital letters
-                logger.log(message: "Error resolving serial on channel attach: \(error)", level: .error)
+                logger.log(message: "Error resolving Serial on channel attach: \(error)", level: .error)

Also applies to: 199-208


Line range hint 216-250: Address TODO comment regarding error handling

There's a TODO comment referencing issue #32 regarding error handling review. Consider addressing this as part of the V2 API migration to ensure comprehensive error handling.

Would you like me to help create a more detailed error handling strategy for the channel attachment states?


Line range hint 1-250: Consider implementing a message versioning strategy

As you're migrating to the V2 Chat API, consider implementing a versioning strategy for message handling to make future API version migrations smoother. This could involve:

  1. Creating a protocol for message version handling
  2. Implementing version-specific message processors
  3. Adding a factory pattern for creating appropriate message handlers

This would make the codebase more maintainable and future-proof for subsequent API versions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 14310b9 and 8129e9c.

📒 Files selected for processing (14)
  • AblyChat.xcworkspace/xcshareddata/swiftpm/Package.resolved (1 hunks)
  • Example/AblyChatExample/ContentView.swift (1 hunks)
  • Example/AblyChatExample/Mocks/Misc.swift (1 hunks)
  • Example/AblyChatExample/Mocks/MockClients.swift (2 hunks)
  • Package.swift (1 hunks)
  • Sources/AblyChat/ChatAPI.swift (3 hunks)
  • Sources/AblyChat/DefaultMessages.swift (9 hunks)
  • Sources/AblyChat/Events.swift (1 hunks)
  • Sources/AblyChat/Message.swift (2 hunks)
  • Sources/AblyChat/Timeserial.swift (0 hunks)
  • Tests/AblyChatTests/ChatAPITests.swift (4 hunks)
  • Tests/AblyChatTests/MessageSubscriptionTests.swift (1 hunks)
  • Tests/AblyChatTests/MessageTests.swift (5 hunks)
  • Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (4 hunks)
💤 Files with no reviewable changes (1)
  • Sources/AblyChat/Timeserial.swift
🚧 Files skipped from review as they are similar to previous changes (10)
  • AblyChat.xcworkspace/xcshareddata/swiftpm/Package.resolved
  • Example/AblyChatExample/ContentView.swift
  • Example/AblyChatExample/Mocks/Misc.swift
  • Package.swift
  • Sources/AblyChat/Events.swift
  • Sources/AblyChat/Message.swift
  • Tests/AblyChatTests/ChatAPITests.swift
  • Tests/AblyChatTests/MessageSubscriptionTests.swift
  • Tests/AblyChatTests/MessageTests.swift
  • Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift
🔇 Additional comments (10)
Sources/AblyChat/ChatAPI.swift (3)

14-14: LGTM: Correctly updated to V2 endpoint

The endpoint update aligns with the V2 API migration while maintaining the existing method signature.


30-30: Verify the Message.latestAction implementation

The addition of latestAction: .create suggests a new message state tracking mechanism. Let's verify the implementation and usage of this property across the codebase.

Also applies to: 48-49

✅ Verification successful

Let me gather more information about the MessageEvent type to understand the complete implementation.


Let me check one more thing to understand the complete MessageEvent implementation and its action mapping.


latestAction implementation is correctly used and follows the expected pattern

The implementation is well-structured and consistent:

  • MessageEvent is properly defined as an enum with a create case
  • The property is correctly used in the Message struct initialization
  • The conversion from Ably's message actions to MessageEvent is handled via fromAction
  • Currently only handles create actions, explicitly ignoring others as per the comment
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check Message.latestAction implementation and usage
echo "Checking latestAction implementation:"
ast-grep --pattern 'struct Message {
  $$$
  latestAction: $_
  $$$
}'

echo -e "\nChecking latestAction usage:"
rg "latestAction" --type swift -A 2

Length of output: 4833


Script:

#!/bin/bash
# Check MessageEvent implementation
echo "Checking MessageEvent implementation:"
ast-grep --pattern 'enum MessageEvent {
  $$$
}'

echo -e "\nChecking MessageEvent usage patterns:"
rg "MessageEvent\." --type swift -A 2

Length of output: 510


Script:

#!/bin/bash
# Find MessageEvent definition and fromAction implementation
echo "Checking MessageEvent complete implementation:"
rg "MessageEvent" --type swift -B 2 -A 5

echo -e "\nChecking action related code:"
rg "action.*chat\.message" --type swift -A 2

Length of output: 2619


Line range hint 59-62: Document why getOccupancy remains on V1

While other endpoints have been migrated to V2, getOccupancy still uses V1. Please document the reason for this inconsistency or update it to use V2 if appropriate.

Example/AblyChatExample/Mocks/MockClients.swift (2)

106-107: LGTM: Changes align with V2 Chat API migration

The changes correctly implement the V2 Chat API requirements by:

  1. Using serial instead of timeserial
  2. Adding the new latestAction parameter with .create default value

132-133: LGTM: Consistent implementation in send method

The changes maintain consistency with the createSubscription implementation, ensuring uniform behavior across the mock client.

Sources/AblyChat/DefaultMessages.swift (5)

3-7: LGTM: Clean migration from timeserial to serial

The rename from timeserial to serial is consistent with the V2 Chat API migration. The implementation remains clean and well-documented.


19-21: LGTM: Subscription handling properly updated

The subscription points map and creation logic have been correctly updated to use the new serial terminology while maintaining the robust error handling and initialization flow.

Also applies to: 41-52


69-71: LGTM: Error handling properly updated

The error handling for the serial field is comprehensive and provides clear error messages.


117-124: LGTM: Subscription point handling properly updated

The subscription point access and error handling have been correctly updated to use the new serial terminology.


56-56: Verify the new message filter and action handling implementation

The switch to MessageFilter.new and the addition of action handling represent significant changes in the V2 Chat API integration. Please ensure:

  1. The MessageFilter.new constant is properly defined and matches the V2 API specification
  2. All possible message actions are handled appropriately

Also applies to: 80-86

Sources/AblyChat/ChatAPI.swift Show resolved Hide resolved
Copy link

coderabbitai bot commented Nov 22, 2024

✅ Actions performed

Reviews paused.

@umair-ably
Copy link
Collaborator

actually ignore that... this wasn't in the doc as it's part of edit/delete but from looking at ably-js we're going to have a new type which also sounds confusingly similar... we don't need it for this PR but the solution will grow into something like this:

Screenshot 2024-11-22 at 00 36 00

We should just follow the same naming conventions now to avoid both confusion and the headache of coming up with our own names that make sense

@maratal maratal force-pushed the ECO-5116-V2-Chat-API branch from 7692200 to 05167f2 Compare November 22, 2024 14:04
Copy link
Collaborator

@umair-ably umair-ably left a comment

Choose a reason for hiding this comment

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

CI failing is due to https://ably-real-time.slack.com/archives/C03JDBVM5MY/p1732287002273979 and not this PR... approving but wait until CI passes again... Should CI fail again from next week due to expected timeserial changes, then contact @AndyTWF for how to resolve them in line with expected behaviour

@maratal maratal force-pushed the ECO-5116-V2-Chat-API branch from 0f12ac3 to 780be56 Compare November 26, 2024 22:33
@maratal maratal merged commit 5923c21 into main Nov 26, 2024
12 checks passed
@maratal maratal deleted the ECO-5116-V2-Chat-API branch November 26, 2024 22:38
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.

2 participants