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

Fix decoding of Message.createdAt #99

Merged
merged 1 commit into from
Nov 7, 2024

Conversation

lawrence-forooghian
Copy link
Collaborator

@lawrence-forooghian lawrence-forooghian commented Nov 7, 2024

Note: This PR is based on top of #101; please review that one first.

Noticed this when writing an integration test for getPreviousMessages.

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for message sending, ensuring stricter validation of metadata and headers.
    • Improved date decoding process to align with Ably's REST API format.
  • Bug Fixes

    • Updated tests to accurately reflect the createdAt timestamp for messages and ensure robust error handling scenarios.
  • Tests

    • Added new test cases to validate message sending and error handling based on metadata and headers.

Copy link

coderabbitai bot commented Nov 7, 2024

Warning

Rate limit exceeded

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

⌛ How to resolve this issue?

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

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

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

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

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 77456aa and 9454e40.

Walkthrough

The changes made to the ChatAPI class in ChatAPI.swift focus on enhancing functionality and error handling, particularly in the sendMessage and makeRequest methods. These methods now enforce stricter validation for parameters and improve error reporting. Additionally, the DictionaryDecoder struct has been updated to align with Ably's REST API date format. Corresponding updates in the test files ensure that the createdAt timestamps are accurately represented and that error handling is robust for various scenarios.

Changes

File Path Change Summary
Sources/AblyChat/ChatAPI.swift - Updated sendMessage, makeRequest, and makePaginatedRequest method signatures.
- Modified DictionaryDecoder to use a custom date decoding strategy.
Tests/AblyChatTests/ChatAPITests.swift - Updated createdAt property in getMessages_whenGetMessagesReturnsItems_returnsItemsInPaginatedResult test.
- Added sendMessage_whenHeadersHasAnyKeyWithSuffixOfAblyChat_doesNotThrowAnyError test for header validation.
Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift - Updated successGetMessagesWithItems to include a new createdAt timestamp for the first item.

Possibly related PRs

  • [ECO-4942] Send/Receive Messages Spec Complete #45: The changes in the sendMessage method in ChatAPI.swift are related to the implementation of message sending specifications in this PR, which also focuses on the sendMessage functionality.
  • [ECO-4988] Implement (some of) Room Lifecycle Monitoring spec #67: The modifications to the RoomLifecycleManager and its protocols may indirectly relate to the overall message handling and lifecycle management in the chat API, although they do not directly alter the sendMessage method.
  • Add a convention for exposing APIs to tests #72: The introduction of a convention for exposing APIs to tests may relate to the testing improvements in ChatAPITests.swift, where error handling for the sendMessage method is specifically tested.
  • Use main branch of ably-cocoa #81: The switch to the main branch of the ably-cocoa dependency may affect the underlying functionality of the ChatAPI, including the sendMessage method, as it could introduce updates or changes in the dependency that impact message handling.

Suggested reviewers

  • maratal

🐰 In the land of code where rabbits play,
Changes hop in, brightening the day.
With messages sent and errors caught,
Our API's stronger, as it ought!
So let’s celebrate, with a joyful cheer,
For the code is now better, let’s make that clear! 🎉


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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

Line range hint 108-114: Consider adding createdAt to all mock messages.

For comprehensive testing of the Message.createdAt decoding functionality, consider adding the createdAt field to other mock messages in both the main response and the next page. This ensures consistent testing of the date decoding across all mock data.

Apply this diff to add timestamps to other messages:

             [
                 "clientId": "random",
                 "timeserial": "3446457",
+                "createdAt": 1_730_943_049_270,
                 "roomId": "basketball::$chat::$chatMessages",
                 "text": "hello response",
                 "metadata": [:],
                 "headers": [:],
             ],

// In nextPage:
             [
                 "timeserial": "3446450",
+                "createdAt": 1_730_943_049_268,
                 "roomId": "basketball::$chat::$chatMessages",
                 "text": "previous message",
                 "metadata": [:],
                 "headers": [:],
             ],
             [
                 "timeserial": "3446451",
+                "createdAt": 1_730_943_049_267,
                 "roomId": "basketball::$chat::$chatMessages",
                 "text": "previous response",
                 "metadata": [:],
                 "headers": [:],
             ],

Also applies to: 146-154

Sources/AblyChat/ChatAPI.swift (1)

Line range hint 67-76: Consider encapsulating the timestamp conversion logic.

While the conversion from milliseconds to seconds is correct, it would be better to encapsulate this logic to ensure consistency across the codebase and improve maintainability.

Consider creating a dedicated extension:

+ private extension Int64 {
+     var millisecondsToDate: Date {
+         Date(timeIntervalSince1970: TimeInterval(Double(self) / 1000))
+     }
+ }

  let message = Message(
      timeserial: response.timeserial,
      clientID: clientId,
      roomID: roomId,
      text: params.text,
-     createdAt: Date(timeIntervalSince1970: createdAtInSeconds),
+     createdAt: response.createdAt.millisecondsToDate,
      metadata: params.metadata ?? [:],
      headers: params.headers ?? [:]
  )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c6525a2 and 77456aa.

📒 Files selected for processing (3)
  • Sources/AblyChat/ChatAPI.swift (1 hunks)
  • Tests/AblyChatTests/ChatAPITests.swift (1 hunks)
  • Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (1 hunks)
🔇 Additional comments (4)
Tests/AblyChatTests/Mocks/MockHTTPPaginatedResponse.swift (1)

102-102: LGTM: Timestamp format aligns with REST API requirements.

The updated timestamp format (milliseconds since epoch) is correct for testing the Message.createdAt decoding functionality.

Sources/AblyChat/ChatAPI.swift (1)

130-137: LGTM! Correct implementation of timestamp decoding.

The change properly configures the decoder to handle Ably's REST API date format (milliseconds since Unix epoch). The implementation is well-documented and follows best practices.

Let's verify that all date fields in the responses are properly handled:

✅ Verification successful

Let me check the Message model to verify the date field implementation.


Timestamp decoding implementation is correctly configured for all date fields

The verification confirms that:

  1. Message.createdAt is the only date field in the models that needs decoding
  2. The JSONDecoder with .millisecondsSince1970 strategy is consistently used across all decoding paths:
    • Direct JSON decoding via decoder property
    • Dictionary decoding via DictionaryDecoder which uses the same decoder instance
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other date fields in the codebase that might need similar treatment
rg -l "Date" | xargs rg "decode|Codable"

Length of output: 1594


Script:

#!/bin/bash
# Check Message model implementation
cat Sources/AblyChat/Message.swift

Length of output: 2681

Tests/AblyChatTests/ChatAPITests.swift (2)

Line range hint 171-185: LGTM! Good test coverage of timestamp scenarios.

The test effectively covers both cases:

  1. Message with a specific timestamp
  2. Message with nil timestamp

This ensures the decoder can handle both scenarios correctly.


173-173: Verify the timestamp value and timezone handling.

The specific timestamp 1_730_943_049.269 (approximately March 6, 2024) seems to be chosen deliberately. However, we should verify that this matches the format expected by Ably's REST API.

✅ Verification successful

Let me gather more information about timestamp handling in the codebase.


Based on the search results, I can now provide a conclusive response about the timestamp verification:

The timestamp format is correctly aligned with Ably's REST API requirements

The code shows consistent timestamp handling where:

  • The API receives timestamps in milliseconds (e.g., 1_730_943_049_269 in MockHTTPPaginatedResponse)
  • The ChatAPI correctly converts milliseconds to seconds for Date initialization
  • Test cases cover both scenarios: with timestamp (1_730_943_049.269 seconds) and without (nil)

The timestamp value in the test is consistent with the mock response data and properly represents the milliseconds-to-seconds conversion required by the API implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if similar timestamp formats exist in other test files
# This helps verify consistency in timestamp handling across tests

# Search for timestamp patterns in test files
rg -g '**/*Tests.swift' '\d+_\d+\.\d+'

Length of output: 159


Script:

#!/bin/bash
# Check for timestamp-related code in the Message model and decoders
rg -g '*.swift' 'createdAt|timeIntervalSince1970' -A 3 -B 3

# Look for any date formatting or decoding logic
ast-grep --pattern 'class $_ : Codable {
  $$$
  createdAt: $_
  $$$
}'

Length of output: 13737

Noticed this when writing an integration test for getPreviousMessages.
Base automatically changed from fix-CI to main November 7, 2024 12:36
@lawrence-forooghian lawrence-forooghian merged commit 1819da9 into main Nov 7, 2024
12 checks passed
@lawrence-forooghian lawrence-forooghian deleted the fix-Message-createdAt-decoding branch November 7, 2024 12:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants