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

feat(internal-plugin-mercury): add mercuryTimeOffset #4035

Open
wants to merge 1 commit into
base: next
Choose a base branch
from

Conversation

lialang-cisco
Copy link
Contributor

@lialang-cisco lialang-cisco commented Dec 18, 2024

COMPLETES CX-17334

This pull request addresses CX-17334

< DESCRIBE THE CONTEXT OF THE ISSUE >

by making the following changes we allow clients to know the difference between their system clock, and the time according to Mercury

< DESCRIBE YOUR CHANGES >

Each message and pong from mercury includes a fiend wsWriteTimestamp, the time (millis since epoch) at which the message was written to the websocket. The Webex App already uses this time to check whether the local system clock is correct (and compensate if it's not). This change exposes a value mercuryTimeOffset on mercury, which is the difference between this timestamp from mercury and Date.now(), updated each time we receive a message or pong; which will allow consumers of the SDK to do the same. This has already been successfully tested in the Webex contact center agent desktop client.

Change Type

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Tooling change
  • Internal code refactor

The following scenarios were tested

I certified that

  • I have read and followed contributing guidelines

  • I discussed changes with code owners prior to submitting this pull request

  • I have not skipped any automated checks

  • All existing and new tests passed

  • I have updated the documentation accordingly


Make sure to have followed the contributing guidelines before submitting.

Summary by CodeRabbit

  • New Features

    • Introduced mercuryTimeOffset property for improved time tracking in Mercury operations.
    • Added wsWriteTimestamp to enhance event data structure for better context in socket messages.
  • Bug Fixes

    • Improved error handling in the socket's send() method to prevent sending messages when not in an OPEN state.
  • Tests

    • Added new test suite for _setTimeOffset method in the Mercury plugin.
    • Updated tests for the Socket class to validate new properties and enhance message handling robustness.

@lialang-cisco lialang-cisco requested review from a team as code owners December 18, 2024 17:27
Copy link

coderabbitai bot commented Dec 18, 2024

Warning

Rate limit exceeded

@lialang-cisco has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 42 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 b7c2036 and 7f4f023.

📒 Files selected for processing (4)
  • packages/@webex/internal-plugin-mercury/src/mercury.js (4 hunks)
  • packages/@webex/internal-plugin-mercury/src/socket/socket-base.js (2 hunks)
  • packages/@webex/internal-plugin-mercury/test/unit/spec/mercury.js (1 hunks)
  • packages/@webex/internal-plugin-mercury/test/unit/spec/socket.js (2 hunks)

Walkthrough

This pull request introduces enhancements to the Mercury plugin's time tracking capabilities. The changes focus on adding a mercuryTimeOffset property to the Mercury class and modifying socket message handling to include a wsWriteTimestamp. The modifications allow for more precise time synchronization by capturing and calculating time offsets during WebSocket communications. The implementation spans multiple files in the @webex/internal-plugin-mercury package, including updates to the main Mercury class, socket base, and corresponding test suites.

Changes

File Change Summary
packages/@webex/internal-plugin-mercury/src/mercury.js - Added mercuryTimeOffset property to session object
- Implemented _setTimeOffset method to calculate time offsets
- Updated _onmessage and _attemptConnection methods to support time offset tracking
packages/@webex/internal-plugin-mercury/src/socket/socket-base.js - Added wsWriteTimestamp extraction from incoming messages
- Included wsWriteTimestamp in processed event data
packages/@webex/internal-plugin-mercury/test/unit/spec/mercury.js - Added test suite for _setTimeOffset method
- Verified mercuryTimeOffset calculation and setting
packages/@webex/internal-plugin-mercury/test/unit/spec/socket.js - Updated tests to include wsWriteTimestamp in message handling
- Enhanced socket message and closure testing

Sequence Diagram

sequenceDiagram
    participant Client
    participant Socket
    participant Mercury

    Client->>Socket: Send WebSocket Message
    Socket->>Socket: Extract wsWriteTimestamp
    Socket->>Mercury: Emit Message with Timestamp
    Mercury->>Mercury: Calculate mercuryTimeOffset
    Mercury-->>Client: Update Time Synchronization
Loading

Possibly related PRs

Suggested labels

validated

Suggested reviewers

  • marcin-bazyl
  • adhmenon

Poem

🕰️ Tick-tock goes the socket's beat,
A timestamp dance, oh so neat!
Mercury's offset, now precise,
Synchronization's rolling dice 🎲
Time syncs with rabbit-like grace! 🐰


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 (3)
packages/@webex/internal-plugin-mercury/src/mercury.js (1)

538-543: Consider adding time zone handling and documentation

While the implementation is correct, consider:

  1. Adding JSDoc to document the method's purpose and parameters
  2. Adding validation for extreme time differences that might indicate issues
  3. Considering time zone implications in the offset calculation
+/**
+ * Updates the Mercury time offset based on the websocket message timestamp
+ * @param {Object} event - The websocket event containing the write timestamp
+ * @private
+ */
 _setTimeOffset(event) {
   const {wsWriteTimestamp} = event;
-  if (typeof wsWriteTimestamp === 'number' && wsWriteTimestamp > 0) {
+  if (typeof wsWriteTimestamp === 'number' && wsWriteTimestamp > 0) {
+    const offset = Date.now() - wsWriteTimestamp;
+    // Validate that the offset is within reasonable bounds (e.g., ±24 hours)
+    if (Math.abs(offset) > 24 * 60 * 60 * 1000) {
+      this.logger.warn(`${this.namespace}: Unusually large time offset detected: ${offset}ms`);
+    }
+    this.mercuryTimeOffset = offset;
-    this.mercuryTimeOffset = Date.now() - wsWriteTimestamp;
   }
 }
packages/@webex/internal-plugin-mercury/test/unit/spec/socket.js (1)

Line range hint 753-803: Add test coverage for edge cases

While the basic functionality is well tested, consider adding test cases for:

  1. Invalid wsWriteTimestamp values (null, negative, non-numeric)
  2. Extreme time differences
  3. Time synchronization behavior over multiple pong messages

Example test cases to add:

it('handles invalid wsWriteTimestamp values', () => {
  const invalidTimestamps = [null, -1, 'invalid', undefined];
  invalidTimestamps.forEach(timestamp => {
    mockWebSocket.emit('message', {
      data: JSON.stringify({
        sequenceNumber: 3,
        id: 'mockid',
        wsWriteTimestamp: timestamp
      })
    });
    assert.isUndefined(socket.mercuryTimeOffset);
  });
});

it('updates time offset consistently across multiple pongs', () => {
  const timestamps = [1735689600000, 1735689601000, 1735689602000];
  const spy = sinon.spy();
  socket.on('pong', spy);
  
  timestamps.forEach(timestamp => {
    mockWebSocket.emit('message', {
      data: JSON.stringify({
        sequenceNumber: 3,
        id: 'mockid',
        type: 'pong',
        wsWriteTimestamp: timestamp
      })
    });
  });
  
  assert.equal(spy.callCount, timestamps.length);
  assert.isNumber(socket.mercuryTimeOffset);
});
packages/@webex/internal-plugin-mercury/test/unit/spec/mercury.js (1)

776-789: Add more test cases for comprehensive coverage.

While the current test case verifies basic functionality, consider adding these scenarios:

  • Test with different time offsets (positive and negative)
  • Test with missing or invalid wsWriteTimestamp
  • Test with edge cases (e.g., very large time differences)
 describe('#_setTimeOffset', () => {
   it('sets mercuryTimeOffset based on the difference between wsWriteTimestamp and now', () => {
     const event = {
       data: {
         wsWriteTimestamp: Date.now() - 1000,
       }          
     };
     assert.isUndefined(mercury.mercuryTimeOffset);
     mercury._setTimeOffset(event);
     assert.isDefined(mercury.mercuryTimeOffset);
     assert.true(mercury.mercuryTimeOffset > 0);
   });
+
+  it('handles missing wsWriteTimestamp gracefully', () => {
+    const event = { data: {} };
+    mercury._setTimeOffset(event);
+    assert.isUndefined(mercury.mercuryTimeOffset);
+  });
+
+  it('handles negative time offsets', () => {
+    const event = {
+      data: {
+        wsWriteTimestamp: Date.now() + 1000,
+      }
+    };
+    mercury._setTimeOffset(event);
+    assert.isDefined(mercury.mercuryTimeOffset);
+    assert.true(mercury.mercuryTimeOffset < 0);
+  });
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 42bd008 and b7c2036.

📒 Files selected for processing (4)
  • packages/@webex/internal-plugin-mercury/src/mercury.js (4 hunks)
  • packages/@webex/internal-plugin-mercury/src/socket/socket-base.js (2 hunks)
  • packages/@webex/internal-plugin-mercury/test/unit/spec/mercury.js (1 hunks)
  • packages/@webex/internal-plugin-mercury/test/unit/spec/socket.js (2 hunks)
🔇 Additional comments (3)
packages/@webex/internal-plugin-mercury/src/socket/socket-base.js (1)

Line range hint 298-312: LGTM: Clean implementation of wsWriteTimestamp handling

The addition of wsWriteTimestamp parsing and inclusion in the processedEvent object is implemented correctly. The parseInt ensures proper type conversion for the timestamp.

packages/@webex/internal-plugin-mercury/src/mercury.js (2)

44-47: LGTM: Well-defined mercuryTimeOffset property

The property is correctly defined with appropriate type and default value, following the existing pattern in the session object.


204-204: LGTM: Proper event handler for time offset updates

The pong event handler is correctly added to update the time offset, ensuring synchronization on each pong message.

Copy link

This pull request is automatically being deployed by Amplify Hosting (learn more).

Access this pull request here: https://pr-4035.d3m3l2kee0btzx.amplifyapp.com

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.

1 participant