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

Rename fields #427

Merged
merged 3 commits into from
Dec 4, 2024
Merged

Rename fields #427

merged 3 commits into from
Dec 4, 2024

Conversation

vladvelici
Copy link
Contributor

@vladvelici vladvelici commented Dec 3, 2024

Rename Message fields and fix tests for history. Enable materialised history tests.

Jira: CHA-734

Summary by CodeRabbit

Release Notes

  • Documentation

    • Updated the README.md to clarify message handling, including real-time updates and versioning.
  • New Features

    • Enhanced message handling with a focus on versioning for updates and deletions.
    • Introduced new properties in message objects, such as version, operation, and improved error handling.
  • Bug Fixes

    • Improved tests to ensure accurate message handling, including checks for new properties and behaviors.
  • Tests

    • Expanded integration and unit tests to validate new message structures and behaviors, ensuring robustness in message processing.

Copy link

coderabbitai bot commented Dec 3, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces significant updates to the documentation and implementation of the Ably Chat SDK, focusing on message handling. Key changes include the adoption of versioning for message updates, replacing previous action-based logic. The README.md has been revised for clarity, detailing message operations and the handling of discontinuities. Several interfaces and methods have been modified across various files to reflect these updates, including renaming properties and introducing new ones. Additionally, tests have been enhanced to ensure they align with the new message structure and functionality.

Changes

File Path Change Summary
README.md Updated documentation on message handling, clarifying message updates, real-time handling, and room-level reactions. Terminology changes from latestAction to action, and from actionBefore() to version comparisons. Enhanced examples for clarity.
demo/src/containers/Chat/Chat.tsx Modified handleUpdatedMessage to use versionBefore(message) instead of actionBefore(message). Minor comments and formatting adjustments.
src/core/action-metadata.ts Updated documentation comment for ActionMetadata, changing "latestActionDetails" to "operations". No structural changes made.
src/core/chat-api.ts Replaced DeleteMessageResponse with MessageOperationResponse, consolidating response structures for delete and update operations. Updated internal logic for message handling to align with new response types.
src/core/index.ts Renamed MessageActionDetails to Operation and added Operation type to exports.
src/core/message-parser.ts Updated MessagePayload interface to include optional operation and made version mandatory. Enhanced error handling in parseMessage function.
src/core/message.ts Replaced MessageActionDetails with Operation interface. Updated properties and accessors to align with new message structure, renaming action comparison methods to version comparisons.
src/core/messages.ts Adjusted send, update, and delete methods in DefaultMessages for new message instantiation logic, enhancing logging for message actions.
test/core/chat.integration.test.ts Added setTimeout in tests to wait for message history retrieval, ensuring proper timing for Cassandra persistence.
test/core/helpers.test.ts Renamed extractCommonKeys to extractExpectedKeys, simplifying its functionality. Removed expectedErrorInfo function.
test/core/message-parser.test.ts Updated test cases for parseMessage to reflect new expected behavior, focusing on version and action properties.
test/core/message.test.ts Removed a test case for createdAt property parsing. Updated tests to include additional date parameters for DefaultMessage instantiation, reflecting changes in message versioning logic.
test/core/messages.integration.test.ts Enhanced assertions for message properties after updates and deletions. Updated import statement to include Message type.
test/core/messages.test.ts Modified tests to reflect new message serialization format and response structures, verifying the inclusion of version and timestamp fields.
test/helper/expectations.ts Updated extractCommonKeys to focus solely on expected keys.
test/react/hooks/use-messages.integration.test.tsx Updated assertions for message properties in tests related to sending, deleting, and updating messages. Added checks for deletedBy property and new message structure.
test/react/hooks/use-messages.test.tsx Adjusted tests for the useMessages hook to accommodate changes in message event object structure, ensuring mock listeners receive updated formats.

Possibly related PRs

Suggested reviewers

  • splindsay-92
  • AndyTWF

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

github-actions bot commented Dec 3, 2024

Coverage Report

Status Category Percentage Covered / Total
🟢 Lines 93.9% (🎯 92%) 3297 / 3511
🟢 Statements 93.9% (🎯 92%) 3297 / 3511
🟢 Functions 96.15% (🎯 92%) 250 / 260
🟢 Branches 94.41% (🎯 93%) 846 / 896
File Coverage
File Stmts Branches Functions Lines Uncovered Lines
Changed Files
src/core/chat-api.ts 100% 89.28% 100% 100%
src/core/message-parser.ts 92.85% 92.85% 100% 92.85% 57-58, 61-62
src/core/message.ts 100% 100% 100% 100%
src/core/messages.ts 92.77% 92% 100% 92.77% 411-413, 443-447, 459-463, 578-580, 613-615
src/react/hooks/use-messages.ts 96.11% 92.59% 100% 96.11% 145-146, 153-154
Generated in workflow #1843 for commit 2b90c7b by the Vitest Coverage Report Action

@vladvelici vladvelici force-pushed the rename-fields-as-agreed branch 2 times, most recently from 94bb83d to 31967fa Compare December 4, 2024 11:19
@github-actions github-actions bot temporarily deployed to staging/pull/427/typedoc December 4, 2024 11:20 Inactive
@vladvelici vladvelici marked this pull request as ready for review December 4, 2024 11:21
@vladvelici vladvelici force-pushed the rename-fields-as-agreed branch from 31967fa to 91a7a1f Compare December 4, 2024 11:23
@vladvelici
Copy link
Contributor Author

@coderabbitai full review

Copy link

coderabbitai bot commented Dec 4, 2024

✅ Actions performed

Full review triggered.

@github-actions github-actions bot temporarily deployed to staging/pull/427/typedoc December 4, 2024 11:25 Inactive
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: 5

🧹 Outside diff range and nitpick comments (4)
src/core/message.ts (1)

217-221: Document the operation Parameter in Constructor

The operation parameter in the DefaultMessage constructor is used but not explicitly documented. Providing documentation will enhance code readability and maintainability.

Add JSDoc comments for the operation parameter:

/**
 * @param operation - Details of the latest operation that updated the message.
 */
src/core/message-parser.ts (1)

52-54: Improve Error Messaging for Missing version Field

The error message when message.version is missing could be more informative to aid in debugging.

Consider including the message.serial or other identifying information in the error message:

- throw new Ably.ErrorInfo(`received incoming message without version`, 50000, 500);
+ throw new Ably.ErrorInfo(`Message with serial ${message.serial} is missing the 'version' field`, 50000, 500);
test/react/hooks/use-messages.integration.test.tsx (1)

319-319: Consider consolidating persistence wait times into a shared helper function.

There are multiple instances of waiting for persistence with the comment "wait for persistence - this will not be necessary in the future". While this is noted as temporary, consider consolidating these waits into a shared helper function to make future removal easier.

+const waitForPersistence = () => new Promise((resolve) => setTimeout(resolve, 3000));
+
 // Usage:
-await new Promise((resolve) => setTimeout(resolve, 3000)); // wait for persistence
+await waitForPersistence(); // wait for persistence

Also applies to: 391-391, 436-436, 456-456, 528-528, 548-549

test/core/messages.test.ts (1)

Line range hint 92-118: Align mock response with actual API response structure.

Based on previous feedback, the mock response for chatApi.deleteMessage should only include version and timestamp, as these are the only fields returned by the actual API.

Simplify the mock response to match the actual API:

 vi.spyOn(chatApi, 'deleteMessage').mockResolvedValue({
   version: '01672531200001-123@abcdefghij:0',
   timestamp: deleteTimestamp,
-  text: 'hello there',
-  clientId: 'clientId',
-  createdAt: sendTimestamp,
-  roomId: context.room.roomId,
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e838058 and 91a7a1f.

📒 Files selected for processing (17)
  • README.md (2 hunks)
  • demo/src/containers/Chat/Chat.tsx (1 hunks)
  • src/core/action-metadata.ts (1 hunks)
  • src/core/chat-api.ts (2 hunks)
  • src/core/index.ts (1 hunks)
  • src/core/message-parser.ts (3 hunks)
  • src/core/message.ts (3 hunks)
  • src/core/messages.ts (2 hunks)
  • test/core/chat.integration.test.ts (2 hunks)
  • test/core/helpers.test.ts (2 hunks)
  • test/core/message-parser.test.ts (4 hunks)
  • test/core/message.test.ts (14 hunks)
  • test/core/messages.integration.test.ts (18 hunks)
  • test/core/messages.test.ts (12 hunks)
  • test/helper/expectations.ts (3 hunks)
  • test/react/hooks/use-messages.integration.test.tsx (7 hunks)
  • test/react/hooks/use-messages.test.tsx (2 hunks)
🧰 Additional context used
📓 Learnings (1)
test/core/messages.test.ts (1)
Learnt from: vladvelici
PR: ably/ably-chat-js#378
File: test/core/messages.test.ts:0-0
Timestamp: 2024-11-12T07:31:58.636Z
Learning: In `test/core/messages.test.ts`, the mocked response for `chatApi.deleteMessage` in the test case `'should be able to delete a message and get it back from response'` should only include `serial` and `deletedAt`, as the real `deleteMessage` API response does not provide additional properties like `text`, `clientId`, `createdAt`, or `roomId`.
🔇 Additional comments (22)
src/core/chat-api.ts (1)

34-52: Consolidate Response Interfaces for Message Operations

The introduction of the MessageOperationResponse interface consolidates the response structures for both delete and update message operations, improving code maintainability and reducing duplication. This is a positive change that enhances consistency across the API.

test/core/messages.integration.test.ts (2)

118-127: Ensure Consistent Validation of Deleted Message Properties

The assertions for the deleted message properties are thorough. Ensure that all relevant properties, such as operation, are consistently validated to catch potential issues early.


270-289: Ensure Tests Reflect Current Backend Behavior

The comments mention that the history API does not currently materialize deleted or updated messages. If this behavior changes in the backend, the tests might fail unexpectedly.

Double-check whether the backend now supports materialized deleted and updated messages in history. If so, update the tests accordingly.

src/core/action-metadata.ts (1)

Line range hint 2-10: Update Documentation to Reflect Changes in Metadata Usage

The comment now correctly refers to the "operations" field instead of "latestActionDetails," ensuring that the documentation accurately reflects the current codebase.

src/core/message-parser.ts (1)

72-86: Ensure All Required Fields Are Included in DefaultMessage Construction

When constructing the DefaultMessage, all necessary fields are correctly included, and the mapping aligns with the updated Message interface.

src/core/index.ts (1)

32-36: Verify backward compatibility of the Operation type alias

The renaming from MessageActionDetails to Operation with an alias maintains backward compatibility. However, we should ensure all consumers are updated to use the new Operation type.

✅ Verification successful

Let me search for usages of the new Operation type to understand the impact better.


Type renaming is correctly implemented with no compatibility issues

The verification shows that MessageActionDetails is only used as an alias in the export statement, while the new Operation type is properly used throughout the codebase in message.ts, message-parser.ts, and other core files. The alias successfully maintains backward compatibility while the codebase has been updated to use the new type name.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usages of MessageActionDetails
rg "MessageActionDetails" --type ts

Length of output: 90


Script:

#!/bin/bash
# Search for usages of Operation type
rg "Operation[^a-zA-Z]" --type ts -A 2

Length of output: 4624

test/helper/expectations.ts (2)

4-5: LGTM! Function simplification improves clarity

The renaming from extractCommonKeys to extractExpectedKeys and the simplification of its logic makes the code more focused and easier to understand.


43-43: LGTM! Enhanced error message improves debugging

The addition of the received type in the error message will help developers quickly identify type mismatches during testing.

test/core/helpers.test.ts (2)

16-16: LGTM: Version field replaces serial field.

The change from serial to version aligns with the new message versioning strategy.


50-51: Verify timestamp handling in DefaultMessage constructor.

The constructor now takes two date parameters. Ensure that both timestamps are properly utilized in the message lifecycle.

✅ Verification successful

Let me analyze the usage of timestamps in DefaultMessage constructor based on the results.


Based on the gathered information, I can now provide a final response:

Both timestamps are properly handled in DefaultMessage implementation

The DefaultMessage constructor correctly accepts and stores both timestamps:

  • createdAt: Original message creation timestamp
  • timestamp: Current operation timestamp

All instances of DefaultMessage across the codebase consistently provide both timestamps, with proper differentiation in update/delete operations where timestamp reflects the operation time while createdAt preserves the original creation time.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of both timestamps in DefaultMessage
# Look for any instances where DefaultMessage is instantiated to ensure consistent usage

ast-grep --pattern 'new DefaultMessage($$$)' 

Length of output: 14710


Script:

#!/bin/bash
# Let's examine the DefaultMessage class implementation to understand how these timestamps are used
ast-grep --pattern 'class DefaultMessage {
  $$$
}'

Length of output: 53


Script:

#!/bin/bash
# Let's try a different approach to find the DefaultMessage class implementation
rg "class DefaultMessage" -A 10

Length of output: 1304


Script:

#!/bin/bash
# Let's see the complete DefaultMessage class implementation
rg "class DefaultMessage implements Message" -A 20

Length of output: 1186

test/core/message-parser.test.ts (2)

84-95: LGTM: Proper validation of version field.

The test case correctly validates that messages without a version field are rejected.


156-157: LGTM: Updated assertions for action and operation fields.

The test now properly verifies the new message structure with action and operation fields.

test/core/message.test.ts (2)

Line range hint 176-220: LGTM: Comprehensive version comparison tests.

The test cases properly validate version comparison behavior and error handling. The error messages are clear and descriptive.


Line range hint 226-294: LGTM: Well-structured parametrized tests.

The test structure using describe.each provides good coverage of version comparison scenarios while maintaining code readability.

test/react/hooks/use-messages.test.tsx (2)

119-129: LGTM: Message object structure updated correctly.

The message object structure has been properly updated to include the new version-based properties (version, versionBefore, versionAfter, versionEqual) and metadata properties (deletedBy, updatedBy, deletedAt, updatedAt).


186-187: LGTM: Timestamp properties added correctly.

The message object now includes both createdAt and updatedAt timestamps using the same value, which is appropriate for a new message in the test.

demo/src/containers/Chat/Chat.tsx (1)

41-41: LGTM: Message version comparison updated correctly.

The message comparison logic has been properly updated to use versionBefore instead of actionBefore, aligning with the new version-based message update system.

test/react/hooks/use-messages.integration.test.tsx (1)

202-204: LGTM: Message update assertions updated correctly.

The test assertions have been properly updated to verify the new message structure:

  • Checking action property instead of latestAction
  • Verifying the operation object's properties
src/core/messages.ts (2)

514-533: LGTM! Well-structured message update implementation.

The changes properly implement message versioning and operation metadata handling. The debug logging will be helpful for troubleshooting.


541-561: LGTM! Robust message deletion implementation.

The changes properly implement message deletion with versioning and operation metadata. Using this._roomId instead of message.roomId is a good practice for reliability.

README.md (1)

307-317: LGTM! Clear and comprehensive documentation.

The documentation effectively explains the new message versioning system and provides clear examples for handling out-of-order updates.

test/core/messages.test.ts (1)

Line range hint 187-201: LGTM! Comprehensive test coverage.

The test changes properly verify:

  • Operation metadata handling
  • Message versioning
  • Client ID assertions

Also applies to: 267-289, 291-296

src/core/chat-api.ts Show resolved Hide resolved
src/core/message.ts Show resolved Hide resolved
test/core/messages.integration.test.ts Show resolved Hide resolved
test/core/chat.integration.test.ts Show resolved Hide resolved
src/core/messages.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@splindsay-92 splindsay-92 left a comment

Choose a reason for hiding this comment

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

Submitting what I have so far just to help speed things along, but I'm still reviewing :)

demo/src/containers/Chat/Chat.tsx Outdated Show resolved Hide resolved
src/core/action-metadata.ts Show resolved Hide resolved
src/core/index.ts Outdated Show resolved Hide resolved
src/core/message.ts Outdated Show resolved Hide resolved
src/core/message.ts Outdated Show resolved Hide resolved
src/core/message-parser.ts Outdated Show resolved Hide resolved
src/core/message-parser.ts Outdated Show resolved Hide resolved
src/core/message-parser.ts Show resolved Hide resolved
src/core/messages.ts Show resolved Hide resolved
src/core/messages.ts Outdated Show resolved Hide resolved
README.md Outdated Show resolved Hide resolved
@vladvelici vladvelici force-pushed the rename-fields-as-agreed branch from 91a7a1f to df76919 Compare December 4, 2024 15:15
@github-actions github-actions bot temporarily deployed to staging/pull/427/typedoc December 4, 2024 15:16 Inactive
@vladvelici vladvelici force-pushed the rename-fields-as-agreed branch from df76919 to b428369 Compare December 4, 2024 15:16
@github-actions github-actions bot temporarily deployed to staging/pull/427/typedoc December 4, 2024 15:18 Inactive
@splindsay-92 splindsay-92 self-requested a review December 4, 2024 15:48
@vladvelici vladvelici enabled auto-merge December 4, 2024 15:56
@vladvelici vladvelici merged commit 9de6a77 into main Dec 4, 2024
9 checks passed
@vladvelici vladvelici deleted the rename-fields-as-agreed branch December 4, 2024 15:58
lawrence-forooghian added a commit to ably/ably-chat-swift that referenced this pull request Dec 4, 2024
Upon our integration tests starting to fail, we noticed that Realtime
seems to have renamed the `latestAction` property to `action`. This
change has not yet been reflected in the spec, but has been in JS [1].

I’ve created an issue to get the spec updated [2] but since this test
failure is stopping us from merging anything else I am going to rename
this property until we get a more definitive answer.

Part of #169.

[1] ably/ably-chat-js#427
[2] ably/specification#254
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