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

Restart closed websocket if still subscribed #1373

Merged
merged 2 commits into from
Jan 3, 2025
Merged

Conversation

paulfalgout
Copy link
Member

@paulfalgout paulfalgout commented Jan 3, 2025

Shortcut Story ID: [sc-58128]

This doesn't really account for lost connection.. ie: it won't retry until the connection is restored. but that's probably a pretty edgy-case where the connection is lost.. and regained without the user changing the context at any point

Summary by CodeRabbit

  • Bug Fixes

    • Improved WebSocket service connection handling to maintain subscriptions when resources are available after connection closure.
  • Tests

    • Enhanced WebSocket service test suite to more precisely track service start events and resource management.
  • New Features

    • Updated file handling logic to prevent duplicates in the file resource array.

@paulfalgout paulfalgout requested a review from nmajor25 January 3, 2025 06:05
Copy link

coderabbitai bot commented Jan 3, 2025

Walkthrough

The pull request introduces modifications to the WebSocket service implementation in both test and service files. The changes focus on improving event handling and subscription resilience. In the test file, the WebSocket service test suite is updated with more precise spy tracking and event monitoring. In the service implementation, a new mechanism is added to automatically re-establish subscriptions when resources exist after a connection closure.

Changes

File Change Summary
src/js/services/ws.cy.js - Updated startService command with enhanced event spying
- Modified test structure for socket restart scenario
- Added more granular assertions for service start events
src/js/services/ws.js - Enhanced onClose method to automatically re-subscribe when resources are present
src/js/entities-service/entities/actions.js - Modified _files update logic in addFile method to use union function for preventing duplicates

Sequence Diagram

sequenceDiagram
    participant WS as WebSocket Service
    participant Sub as Subscription Manager
    
    WS ->> WS: Connection Closed
    alt Resources Exist
        WS ->> Sub: Re-establish Subscription
        Sub -->> WS: Subscription Restored
    end
Loading

Possibly related PRs

Poem

🐰 Websockets dance, connections sway
Resilient code finds its way
Spies watch closely, events unfold
Resources bounce back, brave and bold
A rabbit's tale of network might! 🌐


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 18779c9 and 116503f.

📒 Files selected for processing (3)
  • src/js/entities-service/entities/actions.js (2 hunks)
  • src/js/services/ws.cy.js (2 hunks)
  • src/js/services/ws.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/js/services/ws.js
  • src/js/services/ws.cy.js
🔇 Additional comments (2)
src/js/entities-service/entities/actions.js (2)

253-253: Consider verifying the shape of _files.

If _files is expected to be an array of objects with { id, type }, confirm that _files is not empty or undefined before calling union. Also, ensure that union(...) is used consistently throughout the codebase for file attachments.


2-2: Validate object uniqueness when using _.union.

_.union uses strict equality checks for deduplication, which may not work as intended if _files contains different object references with the same { id, type }. If you want to ensure uniqueness by id, consider using a custom deduplication approach:

const currentFiles = this.get('_files');
const newFileRelation = [{ id: resource.id, type: 'files' }];

// Custom dedup approach using `_.uniq` on the `id` field
const dedupedFiles = _.uniq([...currentFiles, ...newFileRelation], false, file => file.id);
✅ Verification successful

Let me gather information about how _.union is being used in the codebase.


Let me search for more context about how files are handled.


Based on the code analysis, I can now provide the final response:

The _.union usage for files is safe in this context

The concern about object reference equality with _.union is not an issue in this implementation because:

  1. The file objects are consistently created with a simple structure { id: resource.id, type: 'files' } in the addFile method
  2. Files are uniquely identified by their id, and the removeFile method correctly filters based on id equality
  3. The file relationship objects are only created in controlled ways:
    • Through AttachmentAdded event handler which creates new file models
    • Through addFile method which always creates new relationship objects

The current implementation maintains consistency and there's no risk of duplicate entries with different object references.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for usage of _.union with files
rg "union.*files" -B 3 -A 3

Length of output: 573


Script:

#!/bin/bash
# Search for the specific file to see the full context
cat src/js/entities-service/entities/actions.js

Length of output: 8458


Script:

#!/bin/bash
# Look for any tests that might show how files are handled
fd "test|spec" --extension js --exec rg -l "union.*files"

Length of output: 59


Script:

#!/bin/bash
# Search for file-related models or types to understand the structure
ast-grep --pattern 'type: "files"' 

Length of output: 36


Script:

#!/bin/bash
# Search for file models and collections
rg "files:model|files:collection" -B 2 -A 2

Length of output: 1355


Script:

#!/bin/bash
# Look for file-related methods
rg "addFile|removeFile" -B 2 -A 2

Length of output: 2383


Script:

#!/bin/bash
# Search for _files property usage
rg "_files" -B 2 -A 2

Length of output: 1437


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)
src/js/services/ws.js (1)

96-96: Consider adding reconnection/backoff logic to avoid potential repeated subscription attempts upon network issues.

If the network is momentarily down, this line might trigger repeated subscription attempts. Consider implementing a retry strategy with exponential backoff or verifying the connection is available before re-subscribing.

src/js/services/ws.cy.js (2)

88-90: Naming consistency suggestion for clarity.

closedTest and addTest clearly represent the test data, but consider naming them in a more descriptive manner (e.g., closedResource / additionalResource) to align better with domain concepts.


121-124: Clarify or comment on the intended workflow around repeated socket closures.

Closing the socket again immediately after an add request may simulate frequent or abnormal disconnections. A short comment explaining this scenario would aid future readers.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 57f3cb4 and 18779c9.

📒 Files selected for processing (2)
  • src/js/services/ws.cy.js (2 hunks)
  • src/js/services/ws.js (1 hunks)
🔇 Additional comments (5)
src/js/services/ws.cy.js (5)

10-16: Good addition of a dedicated spy for verifying the 'start' event behavior.

Using .once('start', resolve) ensures the promise resolves only once on the first start event, preventing test flakiness if the service triggers multiple 'start' events.


91-100: Verify data shape consistency within the notification.

The notification.data.data object is deeply nested. If many layers are planned, confirm that the service's message handler can handle nested data structures. Otherwise, consider flattening to improve readability and reduce potential confusion.


107-107: Check whether repeated subscription calls might cause duplicate side effects.

Calling subscribe in the close event can re-trigger the subscription logic if the socket is repeatedly closed and reopened in quick succession. Confirm that this behavior is desired and doesn't generate extra messages on the server side.


115-120: Use additional assertions to ensure the correct argument shape during repeated calls.

Confirm that the second call's arguments not only match notification but also meet any internal invariants (e.g., valid resources, presence of required fields, etc.).


126-133: Excellent thoroughness in verifying repeated calls.

This sequence comprehensively tests the scenario of adding more resources and closing the socket again. It helps ensure that the service consistently re-issues the correct subscription requests.

Copy link

cypress bot commented Jan 3, 2025

RoundingWell Care Ops Frontend    Run #7126

Run Properties:  status check passed Passed #7126  •  git commit 116503f2c2: Remove destructuring merge
Project RoundingWell Care Ops Frontend
Branch Review websocket-close
Run status status check passed Passed #7126
Run duration 02m 54s
Commit git commit 116503f2c2: Remove destructuring merge
Committer Paul Falgout
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 1
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 313
View all changes introduced in this branch ↗︎

At least in tests sometimes `_files` isn’t iterable causing the test to fail.
@coveralls
Copy link

Pull Request Test Coverage Report for Build 38103d80-46ab-4f5e-8949-6af18b02836e

Details

  • 2 of 2 (100.0%) changed or added relevant lines in 2 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage remained the same at 99.987%

Totals Coverage Status
Change from base Build 4a48b152-7028-4688-abde-fd18386f6d12: 0.0%
Covered Lines: 6078
Relevant Lines: 6078

💛 - Coveralls

@paulfalgout paulfalgout requested a review from nmajor25 January 3, 2025 19:19
@paulfalgout paulfalgout merged commit 8bcb08f into develop Jan 3, 2025
6 checks passed
@paulfalgout paulfalgout deleted the websocket-close branch January 3, 2025 19:19
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.

3 participants