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-5178] Fix sending and receiving of message headers and metadata #196

Merged
merged 6 commits into from
Dec 16, 2024

Conversation

lawrence-forooghian
Copy link
Collaborator

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

Resolves #193. See commit messages for more details.

Summary by CodeRabbit

  • New Features

    • Enhanced JSON handling for message and presence data, improving type safety and error handling.
    • Added structured data extraction for incoming messages, metadata, and headers.
  • Bug Fixes

    • Improved error messages for missing or malformed data in message handling.
  • Tests

    • Added new tests for validating message sending and subscription functionalities.
    • Updated existing tests to reflect changes in method names and improve clarity.
  • Documentation

    • Updated comments and method signatures for consistency and clarity in JSON handling.

Will be helpful when I add JSONEncodable support to other types.
We (erroneously) never read this argument, but it hasn’t been a problem
because we never pass it either.
For consistency with JSONValue, which seems like the right thing to do
API-wise and also will make some upcoming work easier.
In an upcoming commit, I intend to use these methods in a few more
situations other than just presence.
We were not serializing or deserializing the Chat SDK’s Metadata and
Headers types. This was a mistake in 8b6e56a.

I was surprised to find that there were no existing tests for the
request that ChatAPI makes when you call sendMessage, nor for
DefaultMessages’s handling of messages received over a realtime channel,
which meant that there wasn’t an obvious place to slot in the tests for
the fixes introduced by this commit, nor did the mocks have any support
for writing such tests. I’ve added tests for my fixes but, given my rush
to get this fix done, the changes to the mocks aren’t great. Have
created issue #195 for us come back and write the missing tests and tidy
mine up.

Note that I’ve removed the optionality of Metadata’s values. This
optionality came from 20e7f5f when it was unclear what Metadata would
be. We probably should have removed it in 8b6e56a when we introduced
`null` as a MetadataValue case.

Resolves #193.
Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The pull request introduces significant modifications across multiple files in the AblyChat module, focusing on enhancing type safety and structured data handling, particularly with JSON. Key changes include updating method signatures to utilize a new JSONValue type, improving error handling, and refining the processing of metadata and headers. Additionally, new protocols for JSON encoding and decoding have been implemented, and numerous tests have been added or modified to ensure the functionality of these updates.

Changes

File Path Change Summary
Sources/AblyChat/ChatAPI.swift Updated sendMessage, makeRequest, and makePaginatedRequest methods to use [String: JSONValue] for body parameters. Enhanced type safety and structured handling of JSON data.
Sources/AblyChat/DefaultMessages.swift Modified message handling to utilize JSONValue for safer data extraction. Improved error handling for missing fields in messages.
Sources/AblyChat/DefaultPresence.swift Updated presence data methods to use new serialization approach with JSONValue. Maintained error handling consistency.
Sources/AblyChat/Headers.swift Changed HeadersValue.number from NSNumber to Double for better Codable compatibility. Added extensions for JSONDecodable and JSONEncodable.
Sources/AblyChat/JSONCodable.swift Introduced JSONEncodable and JSONDecodable protocols, along with a JSONCodable type alias.
Sources/AblyChat/JSONValue.swift Renamed methods and parameters related to Ably Cocoa data for clarity.
Sources/AblyChat/Metadata.swift Changed MetadataValue.number from Int to Double. Added extensions for JSON encoding/decoding.
Sources/AblyChat/PresenceDataDTO.swift Updated to conform to JSONCodable protocol. Changed property names for consistency in JSON handling.
Tests/AblyChatTests/ChatAPITests.swift Added tests for sendMessage to verify correct serialization of headers and metadata.
Tests/AblyChatTests/DefaultMessagesTests.swift Added tests for extracting headers and metadata from channel messages.
Tests/AblyChatTests/IntegrationTests.swift Reformatted message sending parameters for clarity and included metadata and headers in messages.
Tests/AblyChatTests/JSONValueTests.swift Refactored method names and comments for consistency in testing JSON handling.
Tests/AblyChatTests/Mocks/MockRealtime.swift Added thread safety features and updated method signatures for clarity.
Tests/AblyChatTests/Mocks/MockRealtimeChannel.swift Introduced a new struct for message emission on subscription.
Tests/AblyChatTests/PresenceDataDTOTests.swift Updated test method names for clarity regarding JSON encoding and decoding.

Assessment against linked issues

Objective Addressed Explanation
Sending a message with metadata or headers doesn't work (#[193], ECO-5178)

Possibly related PRs

Suggested reviewers

  • umair-ably
  • maratal

Poem

🐰 In the code where data flows,
A rabbit hops where JSON grows.
With headers and metadata in sight,
Our messages now take flight!
Type safety shines, errors fade,
In this chat, new paths we've laid! 🌟


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. (Experiment)
  • @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.

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 (9)
Sources/AblyChat/Headers.swift (1)

5-5: Potential Precision Loss with Double for Numeric Values

Changing the number case from NSNumber to Double might introduce precision loss, especially for large integer values that exceed Double's precision. Consider whether it's necessary to represent all numeric values as Double, or if preserving integer types is important for your use case.

Sources/AblyChat/Metadata.swift (1)

6-6: Consideration Needed for Changing number Case to Double

Switching from Int to Double in the number case may lead to unintended precision issues with integer values. Evaluate whether this change may affect the integrity of integer metadata and if alternative solutions are needed.

Tests/AblyChatTests/JSONValueTests.swift (1)

Line range hint 149-154: Consider adding error handling test cases

While the happy path is well tested, consider adding test cases for error scenarios in JSON serialization.

+ @Test
+ func toAblyCocoaData_handlesInvalidJSON() {
+     // Test invalid JSON scenarios
+     let invalidValue: JSONValue = ["invalid": Double.infinity]
+     #expect(throws: JSONSerialization.InvalidJSONError.self) {
+         try JSONSerialization.data(withJSONObject: invalidValue.toAblyCocoaData)
+     }
+ }
Sources/AblyChat/ChatAPI.swift (1)

31-40: LGTM! Consider simplifying the mapValues transformations.

The type-safe JSON handling looks good and correctly follows the CHA-M3b spec for optional metadata/headers.

Consider simplifying the transformations using the JSONValue type's expressible protocol conformance:

-body["metadata"] = .object(metadata.mapValues(\.toJSONValue))
+body["metadata"] = metadata
-body["headers"] = .object(headers.mapValues(\.toJSONValue))
+body["headers"] = headers

This works because Dictionary where Value: JSONEncodable automatically converts to JSONValue.

Sources/AblyChat/JSONValue.swift (1)

Line range hint 131-161: LGTM! Consider adding @throws to documentation.

The initialization logic and type handling look great. The documentation is clear but could be enhanced.

Consider adding @throws documentation to clarify when the preconditionFailure might occur:

/// Creates a `JSONValue` from an ably-cocoa deserialized JSON object.
///
/// Specifically, `ablyCocoaData` can be:
///
/// - a non-`nil` value of `ARTPresenceMessage`'s `data` property
/// - a non-`nil` value of `ARTMessage`'s `data` property
/// - the return value of the `toJSON()` method of a non-`nil` value of `ARTMessage`'s `extras` property
+///
+/// @throws preconditionFailure if the input cannot be converted to a valid JSON value
Tests/AblyChatTests/ChatAPITests.swift (2)

55-76: LGTM! Consider strengthening the assertions.

The test effectively verifies headers serialization with good test structure.

Consider adding assertions for the complete request body structure:

 let requestBody = try #require(realtime.requestArguments.first?.body as? NSDictionary)
 #expect(try #require(requestBody["headers"] as? NSObject) == ["numberKey": 10, "stringKey": "hello"] as NSObject)
+#expect(requestBody.allKeys.count == 2) // Verify only text and headers are present
+#expect(try #require(requestBody["text"] as? String) == "")

78-99: LGTM! Consider strengthening the assertions similarly.

The test effectively verifies metadata serialization with good consistency.

Consider adding assertions for the complete request body structure, similar to the headers test:

 let requestBody = try #require(realtime.requestArguments.first?.body as? NSDictionary)
 #expect(try #require(requestBody["metadata"] as? NSObject) == ["numberKey": 10, "stringKey": "hello"] as NSObject)
+#expect(requestBody.allKeys.count == 2) // Verify only text and metadata are present
+#expect(try #require(requestBody["text"] as? String) == "")
Tests/AblyChatTests/IntegrationTests.swift (1)

118-124: Good test coverage for headers and metadata.

The test effectively verifies sending and receiving of message headers and metadata with different value types (numbers and strings). Consider adding test cases for:

  1. Empty metadata/headers
  2. Nested objects in metadata/headers
  3. Array values in metadata/headers
Sources/AblyChat/DefaultMessages.swift (1)

80-89: Consider adding error handling for invalid value types.

While the parsing logic is solid, consider adding specific error messages when metadata or headers contain invalid value types. This would help developers identify issues during development.

Example improvement:

 let metadata: Metadata? = if let metadataJSONObject = data["metadata"]?.objectValue {
-    try metadataJSONObject.mapValues { try MetadataValue(jsonValue: $0) }
+    try? metadataJSONObject.mapValues { jsonValue in
+        do {
+            return try MetadataValue(jsonValue: jsonValue)
+        } catch {
+            logger.log(message: "Invalid metadata value type: \(error)", level: .error)
+            return nil
+        }
+    }
 } else {
     nil
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0bfc356 and 7fcab5c.

📒 Files selected for processing (15)
  • Sources/AblyChat/ChatAPI.swift (3 hunks)
  • Sources/AblyChat/DefaultMessages.swift (2 hunks)
  • Sources/AblyChat/DefaultPresence.swift (4 hunks)
  • Sources/AblyChat/Headers.swift (1 hunks)
  • Sources/AblyChat/JSONCodable.swift (1 hunks)
  • Sources/AblyChat/JSONValue.swift (2 hunks)
  • Sources/AblyChat/Metadata.swift (1 hunks)
  • Sources/AblyChat/PresenceDataDTO.swift (1 hunks)
  • Tests/AblyChatTests/ChatAPITests.swift (1 hunks)
  • Tests/AblyChatTests/DefaultMessagesTests.swift (1 hunks)
  • Tests/AblyChatTests/IntegrationTests.swift (2 hunks)
  • Tests/AblyChatTests/JSONValueTests.swift (6 hunks)
  • Tests/AblyChatTests/Mocks/MockRealtime.swift (2 hunks)
  • Tests/AblyChatTests/Mocks/MockRealtimeChannel.swift (3 hunks)
  • Tests/AblyChatTests/PresenceDataDTOTests.swift (3 hunks)
🔇 Additional comments (23)
Sources/AblyChat/JSONCodable.swift (1)

1-9: Well-Defined Protocols for JSON Encoding and Decoding

The introduction of JSONEncodable, JSONDecodable, and the JSONCodable typealias provides a clean and structured approach to JSON handling. This design promotes code reusability and clarity.

Sources/AblyChat/PresenceDataDTO.swift (1)

8-32: Implementation of JSONCodable Conformance is Correct

The conformance of PresenceDataDTO to JSONCodable is properly implemented. The initializer and the computed property handle JSON serialization and deserialization effectively.

Tests/AblyChatTests/PresenceDataDTOTests.swift (2)

5-5: LGTM: Improved section headers clarity

The section headers now better reflect the protocol names (JSONDecodable, JSONCodable), making the test organization clearer and more aligned with the implementation.

Also applies to: 25-25


37-39: LGTM: Enhanced type safety in JSON value comparison

The test method has been correctly updated to use toJSONValue and properly compares the result using .object(expectedJSONObject), ensuring type-safe JSON value comparison.

Tests/AblyChatTests/Mocks/MockRealtime.swift (3)

11-13: LGTM: Well-implemented thread safety mechanism

Good implementation of thread safety using NSLock and proper documentation of synchronization requirements.


88-91: LGTM: Proper mutex usage in request handling

The implementation correctly uses mutex locks to ensure thread-safe access to request arguments, both when recording new requests and when accessing the stored arguments.

Also applies to: 99-105


6-6: Verify thread safety implementation with @unchecked Sendable

The @unchecked Sendable attribute indicates that we're manually ensuring thread safety. While the implementation looks correct with mutex usage, we should verify all mutable state is properly synchronized.

✅ Verification successful

Let me gather more specific information about the mutable properties in MockRealtime.swift.


Thread safety implementation is properly verified

The implementation is correctly synchronized:

  • The only mutable state _requestArguments is properly protected with an NSLock
  • All access to this state is guarded by the mutex lock (in the requestArguments getter)
  • Other properties are either computed or immutable
  • The implementation follows the correct pattern for @unchecked Sendable conformance
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any mutable properties in the class that might need synchronization
rg -l "var\s+\w+\s*(:|\=)" | xargs rg "class\s+\w+.*Sendable"

Length of output: 2352


Script:

#!/bin/bash
# Search for var declarations in MockRealtime.swift
rg "var " Tests/AblyChatTests/Mocks/MockRealtime.swift -A 2

# Search for mutex/lock usage
rg "NSLock|DispatchQueue|actor" Tests/AblyChatTests/Mocks/MockRealtime.swift

Length of output: 836

Tests/AblyChatTests/JSONValueTests.swift (2)

6-6: LGTM: Improved clarity in test organization

The section headers have been updated to reflect the broader scope of JSON conversion, making the test structure clearer and more maintainable.

Also applies to: 78-78


26-27: LGTM: Consistent renaming for broader applicability

The method names have been updated to remove "Presence" specificity, making them more generic and reusable. The implementation remains correct while becoming more versatile.

Also applies to: 32-32, 98-99

Sources/AblyChat/ChatAPI.swift (2)

66-75: LGTM! Clean type-safe conversion to Ably Cocoa format.

The body conversion and request execution are well-implemented with proper error handling.


102-102: LGTM! Good cleanup removing unused parameter.

Removing the unused body parameter improves the API clarity.

Sources/AblyChat/JSONValue.swift (1)

163-174: LGTM! Well-documented conversion logic.

The property documentation and implementation correctly handle all JSON value types.

Tests/AblyChatTests/DefaultMessagesTests.swift (2)

72-104: Well-structured test for header extraction!

The test effectively validates the extraction and type-safe conversion of message headers, covering both numeric and string values.


106-137: Consistent test implementation for metadata extraction!

The test maintains consistency with the headers test pattern while properly validating metadata extraction from the message data field.

Tests/AblyChatTests/Mocks/MockRealtimeChannel.swift (3)

34-42: LGTM! Clean initializer update.

The initializer properly integrates the new message emission capability while maintaining backward compatibility.


145-154: LGTM! Comprehensive message construction.

The subscribe method properly constructs the ARTMessage with all necessary fields from MessageToEmit.


20-27: Track the TODO for type safety improvements.

The @unchecked Sendable annotation is a temporary solution. The referenced issue #195 should address proper type constraints.

✅ Verification successful

Issue #195 is still open and needs attention for type safety improvements

The TODO comment references issue #195 which is currently open with the title "Improve testing for messages functionality". The temporary use of @unchecked Sendable should be addressed as part of this issue to improve type safety.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if issue #195 is still open
gh issue view 195 --json state,title

Length of output: 108

Sources/AblyChat/DefaultPresence.swift (3)

118-118: LGTM! Improved JSON value handling.

The change properly utilizes the new JSON value conversion chain for presence data.


152-152: LGTM! Consistent JSON value handling across methods.

The update and leave methods maintain consistency with the new JSON value conversion approach.

Also applies to: 186-186


240-240: LGTM! Consistent decoder update.

The decoder properly adopts the new JSON value initialization approach.

Tests/AblyChatTests/IntegrationTests.swift (1)

104-108: LGTM! Improved code formatting.

The multi-line formatting enhances readability while maintaining the same functionality.

Sources/AblyChat/DefaultMessages.swift (2)

59-61: LGTM! Improved type safety with JSONValue.

The use of JSONValue for parsing message data enhances type safety and provides better error handling compared to direct dictionary casting.


66-68: LGTM! Consistent use of JSONValue for extras parsing.

The parsing of extras follows the same pattern as message data, maintaining consistency and type safety.

Sources/AblyChat/Headers.swift Show resolved Hide resolved
Sources/AblyChat/Headers.swift Show resolved Hide resolved
Sources/AblyChat/Metadata.swift Show resolved Hide resolved
Sources/AblyChat/Metadata.swift Show resolved Hide resolved
Copy link
Collaborator

@maratal maratal left a comment

Choose a reason for hiding this comment

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

LGTM

@lawrence-forooghian lawrence-forooghian merged commit 102ac3b into main Dec 16, 2024
16 checks passed
@lawrence-forooghian lawrence-forooghian deleted the 193-fix-message-metadata-and-headers branch December 16, 2024 12:21
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.

Sending a message with metadata or headers doesn't work
2 participants