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-5181] Fix sending and receiving of reaction metadata and headers #199

Merged
merged 6 commits into from
Dec 17, 2024

Conversation

lawrence-forooghian
Copy link
Collaborator

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

Resolves #198. See commit messages for more details.

Summary by CodeRabbit

  • New Features

    • Introduced structured handling for room reactions with the new RoomReactionDTO.
    • Enhanced JSON encoding and decoding capabilities with new protocols and error handling.
  • Bug Fixes

    • Improved error handling in message processing and reaction publishing.
  • Tests

    • Added comprehensive tests for RoomReactionDTO and updated existing tests for DefaultRoomReactions and PresenceDataDTO.
  • Chores

    • Removed unnecessary methods and streamlined parameter handling in various classes.

Add a JSONObjectCodable protocol which represents a type that can be
serialised to or deserialised from a [String : JSONValue] dictionary.
As well as slightly simplifying the deserialisation of a type (you don't
have to do the "is it an object" check yourself), this will be necessary
when, in an upcoming commit, we try to pass a serialised value to the
`extras` parameter of ably-cocoa’s publish, which expects an
`ARTJsonCompatible` value.
Will use these in an upcoming commit.
Similar issue to the one which was fixed in 7fcab5c.

Haven’t added tests for the handling of the incoming message, since
there were no existing tests to update and I didn’t feel like writing
them; will leave this for whoever writes these tests in #88.

The approach that I’ve taken here of using a DTO is consistent with the
approach that we use for presence data. I should have done this in
7fcab5c too; will do it separately.

The spec doesn’t describe how to behave if the user doesn’t pass headers
or metadata; I’ve taken the behaviour of passing an empty object from
the JS Chat SDK at 6d1b04a. Have created spec issue [1] for specifying
this.

Resolves #198.

[1] ably/specification#256
Copy link

coderabbitai bot commented Dec 17, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ast-grep (0.31.1)
Sources/AblyChat/DefaultMessages.swift

An unexpected error occurred while running ast-grep.

Walkthrough

The pull request introduces significant changes to the JSON handling and reaction mechanisms in the AblyChat module. The modifications focus on enhancing the robustness of JSON encoding, decoding, and reaction processing. Key changes include introducing new protocols for JSON object handling, creating a structured RoomReactionDTO for reactions, and updating methods to safely extract metadata and headers from JSON objects. The changes improve error handling and provide a more consistent approach to working with JSON data across the module.

Changes

File Change Summary
Sources/AblyChat/DefaultMessages.swift Updated metadata and headers extraction using optionalObjectValueForKey for safer JSON parsing
Sources/AblyChat/DefaultRoomReactions.swift Refactored send and subscribe methods to use RoomReactionDTO for more structured reaction handling
Sources/AblyChat/JSONCodable.swift Added new protocols JSONObjectEncodable and JSONObjectDecodable, introduced JSONValueDecodingError enum
Sources/AblyChat/JSONValue.swift Added methods to convert JSONValue dictionaries to Ably-compatible data structures
Sources/AblyChat/PresenceDataDTO.swift Updated JSON encoding/decoding to use JSONObjectCodable protocol
Sources/AblyChat/RoomReactionDTO.swift Created new DTO for room reactions with structured data and extras
Sources/AblyChat/RoomReactions.swift Removed asJSONObject() method from SendReactionParams extension
Tests/* Updated tests to reflect new JSON handling and reaction mechanisms

Assessment against linked issues

Objective Addressed Explanation
Check reaction headers and metadata
Ensure safe JSON parsing for reactions

Possibly related PRs

Poem

🐰 Hop, hop, through JSON's maze,
Reactions dance in structured ways,
Metadata and headers shine bright,
CodeRabbit's magic takes its flight!
Safe parsing, errors kept at bay 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
Tests/AblyChatTests/RoomReactionDTOTests.swift (2)

4-62: LGTM! Well-structured test suite for RoomReactionDTO.Data.

The test coverage is comprehensive, including:

  • Error handling for invalid inputs
  • Handling of missing optional fields
  • JSON encoding/decoding validation

Consider adding these edge cases:

  • Test with empty string for type
  • Test with empty object for metadata
  • Test with null values in metadata
+    @Test
+    func initWithJSONValue_withEmptyType() throws {
+        #expect(throws: JSONValueDecodingError.self) {
+            try RoomReactionDTO.Data(jsonValue: ["type": ""])
+        }
+    }
+
+    @Test
+    func initWithJSONValue_withEmptyMetadata() throws {
+        let data = try RoomReactionDTO.Data(
+            jsonValue: [
+                "type": "someType",
+                "metadata": [:],
+            ]
+        )
+        #expect(data.metadata?.isEmpty == true)
+    }

64-112: LGTM! Thorough test coverage for RoomReactionDTO.Extras.

The test suite properly validates the Extras structure with similar thoroughness to the Data tests.

Consider adding similar edge cases for headers:

  • Test with empty object for headers
  • Test with null values in headers
+    @Test
+    func initWithJSONValue_withEmptyHeaders() throws {
+        let data = try RoomReactionDTO.Extras(
+            jsonValue: [
+                "headers": [:],
+            ]
+        )
+        #expect(data.headers?.isEmpty == true)
+    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 35350c4 and 6035a1e.

📒 Files selected for processing (11)
  • Sources/AblyChat/DefaultMessages.swift (1 hunks)
  • Sources/AblyChat/DefaultRoomReactions.swift (3 hunks)
  • Sources/AblyChat/JSONCodable.swift (1 hunks)
  • Sources/AblyChat/JSONValue.swift (3 hunks)
  • Sources/AblyChat/PresenceDataDTO.swift (1 hunks)
  • Sources/AblyChat/RoomReactionDTO.swift (1 hunks)
  • Sources/AblyChat/RoomReactions.swift (0 hunks)
  • Tests/AblyChatTests/DefaultRoomReactionsTests.swift (1 hunks)
  • Tests/AblyChatTests/IntegrationTests.swift (1 hunks)
  • Tests/AblyChatTests/PresenceDataDTOTests.swift (1 hunks)
  • Tests/AblyChatTests/RoomReactionDTOTests.swift (1 hunks)
💤 Files with no reviewable changes (1)
  • Sources/AblyChat/RoomReactions.swift
🔇 Additional comments (18)
Sources/AblyChat/DefaultRoomReactions.swift (4)

26-33: Proper construction and publishing of RoomReactionDTO

The send method now correctly constructs a RoomReactionDTO using the provided parameters and publishes it on the channel with the appropriate data and extras. This aligns with the new data structures introduced and ensures that reactions are sent in the expected format.


47-48: Robust error handling for incoming messages

The added guard statements ensure that essential components of the incoming message (data, clientId, timestamp, and extras) are present before processing. This improves the robustness of the message handling by preventing the processing of incomplete or malformed messages.

Also applies to: 59-59


63-66: Correct parsing of message data into RoomReactionDTO

The code correctly initializes a RoomReactionDTO from the message's data and extras, handling any potential errors during deserialization. This allows for a structured and reliable way to convert incoming messages into reaction objects.


70-72: Accurate creation of Reaction object

The Reaction object is accurately constructed using the data from dto, with appropriate default values for metadata and headers when they are nil. This ensures that all necessary information is included when emitting reactions to subscribers.

Sources/AblyChat/JSONCodable.swift (4)

10-21: Introduction of JSONObjectEncodable improves JSON serialization

The addition of the JSONObjectEncodable protocol and its default implementation enhances the JSON encoding process by providing a standardized way to convert objects to JSON dictionaries. This promotes code reuse and consistency across the module.


22-41: Addition of JSONObjectDecodable streamlines JSON deserialization

By introducing the JSONObjectDecodable protocol with a default initializer, the code simplifies the deserialization of JSON objects. The JSONValueDecodingError enum provides clear error cases, improving error handling during the decoding process.


43-44: Typealias JSONObjectCodable enhances code clarity

The JSONObjectCodable typealias consolidates the encodable and decodable protocols, making it easier to declare types that conform to both, thereby improving code readability.


46-230: Comprehensive helper methods for JSON value extraction

The extension on [String: JSONValue] provides robust helper methods for extracting typed values from a JSON dictionary. This reduces boilerplate code and standardizes JSON parsing throughout the codebase.

Sources/AblyChat/PresenceDataDTO.swift (1)

6-24: Updated conformance to JSONObjectCodable simplifies JSON handling

Changing the conformance from JSONCodable to JSONObjectCodable and adjusting the initializer and serialization methods enhances the clarity and simplicity of the PresenceDataDTO structure. The code now directly works with JSON objects, reducing complexity in JSON transformations.

Sources/AblyChat/RoomReactionDTO.swift (1)

1-70: Well-structured implementation of RoomReactionDTO

The introduction of RoomReactionDTO along with its nested Data and Extras structs provides a clear and organized way to represent room reactions. The implementations of JSONObjectCodable for these structs facilitate reliable JSON serialization and deserialization.

Tests/AblyChatTests/PresenceDataDTOTests.swift (1)

19-24: LGTM! Good addition of error handling test.

The new test case properly validates that non-object JSON values are rejected with the appropriate error type. This aligns with the broader changes to standardize JSON handling across the codebase.

Tests/AblyChatTests/DefaultRoomReactionsTests.swift (2)

33-34: LGTM! More descriptive test data.

The test data now uses clearer key names that better indicate their purpose (e.g., "someMetadataKey", "someHeadersKey").


42-43: Verify the message format matches the API specification.

The test expectations now properly separate the reaction data and extras into their respective structures. However, let's verify this matches the API specification.

✅ Verification successful

Let me gather more information about the message format specification by looking at the test file mentioned in the results.


Let me check the implementation of the reaction data structure to fully verify the format.


Message format matches the API specification

The test expectations correctly match the internal message format defined in RoomReactionDTO, which separates reaction data (type and metadata) from extras (headers) as per specification CHA-ER3a. The format aligns with the Reaction type structure and its JSON encoding implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for API documentation or interface definitions that specify the expected message format

# Look for API interface definitions
rg -A 5 "interface.*Reaction|type.*Reaction|protocol.*Reaction"

# Look for documentation comments about reaction message format
rg -B 2 -A 2 "@spec CHA-ER"

Length of output: 5044


Script:

#!/bin/bash
# Look at the test file content to understand the specification requirements
cat Tests/AblyChatTests/DefaultRoomReactionsTests.swift

Length of output: 3671


Script:

#!/bin/bash
# Look at the RoomReactionDTO and Reaction implementations
cat Sources/AblyChat/RoomReactionDTO.swift Sources/AblyChat/Reaction.swift

Length of output: 2786

Sources/AblyChat/JSONValue.swift (2)

170-174: LGTM: Improved code organization

The change to use toAblyCocoaDataDictionary improves code organization by extracting the dictionary conversion logic into a dedicated method.


189-205: LGTM: Well-structured extension with clear separation of concerns

The new extension provides two well-documented methods:

  1. toAblyCocoaDataDictionary: Handles conversion to Ably Cocoa's data format
  2. toARTJsonCompatible: Provides type-safe casting to ARTJsonCompatible

The implementation is clean and follows Swift best practices.

Sources/AblyChat/DefaultMessages.swift (1)

Line range hint 80-89: LGTM: Improved error handling for metadata and headers extraction

The changes enhance robustness by:

  • Using optionalObjectValueForKey for safer extraction
  • Properly handling optional values with clear nil-coalescing
  • Maintaining consistent error handling patterns across metadata and headers
Tests/AblyChatTests/IntegrationTests.swift (2)

168-174: LGTM: Comprehensive reaction sending test

The test properly includes metadata and headers in the reaction parameters, maintaining consistency with the message sending tests above.


177-178: LGTM: Clear assertions for metadata and headers

The assertions properly verify that both metadata and headers are correctly received and match the sent data.

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.

nice one!

@lawrence-forooghian lawrence-forooghian merged commit 315d162 into main Dec 17, 2024
17 checks passed
@lawrence-forooghian lawrence-forooghian deleted the 198-reaction-headers-and-metadata branch December 17, 2024 13: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.

Check that reaction headers and metadata are working
2 participants