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

(DAL) Possible fix for memory leak #1921

Closed
wants to merge 6 commits into from

Conversation

nick-bisonai
Copy link
Collaborator

Description

CloseHandler

        closeHandler := conn.CloseHandler()
	conn.SetCloseHandler(func(code int, text string) error {
		log.Info().Str("Player", "controller").Int("code", code).Str("text", text).Msg("close handler")
		c.unregister <- conn
		return closeHandler(code, text)
	})

Custom closeHandler which overwrites default closeHandler so that it can automatically signal unregister on disconnection.

Refactoring

  • Separated file websocketcontroller from controller
  • Separated func handleMessage from handleWebsocket function
  • Encapsulated internal logics inside Controller.Start method for readability

Minor update

  • InsertWebsocketSubscriptions for bulk insertion of subscription stats
  • k6 script for stress testing and memory leak reproduction
  • websockethelper isAlive func to be later used in test codes so that it can check conn live from client side

Type of change

Please delete options that are not relevant.

  • 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 not work as expected)
  • This change requires a documentation update

Checklist before requesting a review

  • I have performed a self-review of my code.
  • If it is a core feature, I have added thorough tests.

Deployment

  • Should publish npm package
  • Should publish Docker image

@nick-bisonai nick-bisonai self-assigned this Jul 27, 2024
@nick-bisonai nick-bisonai requested a review from a team as a code owner July 27, 2024 04:23
Copy link
Contributor

coderabbitai bot commented Jul 27, 2024

Warning

Rate limit exceeded

@nick-bisonai has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 18 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

Files that changed from the base of the PR and between 749f8f5 and dcfe780.

Walkthrough

Walkthrough

The recent changes enhance the WebSocket functionality in the application. Key improvements include better logging for traceability, refactoring connection handling for clarity, and introducing batch processing for subscriptions. A new WebSocket controller facilitates real-time communication, while a performance testing script supports efficient testing with k6. Overall, these updates improve maintainability, performance, and error handling across the WebSocket-related codebase.

Changes

Files Change Summary
node/pkg/dal/api/controller.go, node/pkg/dal/api/websocketcontroller.go Enhanced logging, refactored connection handling, introduced methods for broadcasting and handling connections.
node/pkg/dal/k6/script.js Added a performance testing script for WebSocket interactions, including subscription handling and connection management.
node/pkg/dal/tests/api_test.go Restructured the test logic for improved readability without changing functional behavior.
node/pkg/dal/utils/stats/stats.go Introduced InsertWebsocketSubscriptions for bulk inserting subscription entries.
node/pkg/wss/utils.go Added IsAlive method to check WebSocket connection status.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant WebSocketController
    participant Controller
    participant Stats

    Client->>WebSocketController: Connect
    WebSocketController->>Controller: Retrieve instance
    WebSocketController-->>Client: Connection established
    Client->>WebSocketController: Send subscription request
    WebSocketController->>Controller: Handle connection
    Controller->>Stats: Insert subscription
    Stats-->>Controller: Confirmation
    Controller-->>WebSocketController: Subscription successful
    WebSocketController-->>Client: Confirmation message
Loading

🐰 "In the meadow where bunnies hop,
With logs and webs, we just can't stop!
Connections dance in a joyful stream,
Performance testing, our dream team!
With every change, we leap with glee,
Hopping forward, as happy as can be!" 🌼


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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
Contributor

@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: 7

Outside diff range, codebase verification and nitpick comments (1)
node/pkg/dal/k6/script.js (1)

4-4: Ensure proper error handling for the ws import.

The ws module is used in node/pkg/dal/k6/script.js without any error handling mechanisms. It is important to add error handling around the ws.connect call and within the event handlers to manage potential issues during WebSocket communication.

  • node/pkg/dal/k6/script.js: Add try-catch blocks or other error handling mechanisms around the ws.connect call and within the event handlers.
Analysis chain

Ensure proper error handling for the ws import.

The imported module should be checked for availability and proper error handling.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the availability of the ws module.

# Test: Search for the module usage. Expect: Only occurrences of the correct import.
rg --type js -A 5 $'import ws from "k6/ws"'

Length of output: 2654


Script:

#!/bin/bash
# Description: Check for error handling around the usage of the ws module in script.js.

# Search for the usage of the ws module in script.js and include context lines to identify error handling mechanisms.
rg --type js 'ws' -A 10 -B 10 node/pkg/dal/k6/script.js

Length of output: 4777

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d77d8f0 and 749f8f5.

Files selected for processing (6)
  • node/pkg/dal/api/controller.go (5 hunks)
  • node/pkg/dal/api/websocketcontroller.go (1 hunks)
  • node/pkg/dal/k6/script.js (1 hunks)
  • node/pkg/dal/tests/api_test.go (1 hunks)
  • node/pkg/dal/utils/stats/stats.go (1 hunks)
  • node/pkg/wss/utils.go (1 hunks)
Additional context used
Learnings (2)
node/pkg/dal/api/websocketcontroller.go (2)
Learnt from: nick-bisonai
PR: Bisonai/orakl#1791
File: node/pkg/dal/api/controller.go:0-0
Timestamp: 2024-07-12T02:42:57.258Z
Learning: In the `node/pkg/dal/api/controller.go`, the `handleWebsocket` function no longer requires explicit validation for the `X-Api-Key` header, as this is handled by the `gofiber keyauth` middleware in `initializer.go`.
Learnt from: nick-bisonai
PR: Bisonai/orakl#1791
File: node/pkg/dal/api/controller.go:109-113
Timestamp: 2024-07-12T01:57:43.211Z
Learning: In the `node/pkg/dal/api/controller.go`, the `handleWebsocket` function includes logic to extract and validate the `X-Api-Key` header.
node/pkg/wss/utils.go (1)
Learnt from: nick-bisonai
PR: Bisonai/orakl#1524
File: node/pkg/wss/utils.go:0-0
Timestamp: 2024-05-28T05:35:40.840Z
Learning: The `Run` method in `WebsocketHelper` now includes a context-based mechanism to exit the loop and a flag (`IsRunning`) to prevent multiple instances from running simultaneously.
Additional comments not posted (15)
node/pkg/dal/api/websocketcontroller.go (2)

19-24: LGTM! Ensure the custom close handler is thoroughly tested.

The custom close handler correctly unregisters the connection and logs the event.


68-93: LGTM! Ensure subscription handling is thoroughly tested.

The subscription handling logic appears correct, with proper locking and insertion of subscription statistics.

node/pkg/dal/utils/stats/stats.go (1)

74-80: LGTM! Ensure bulk insertion is thoroughly tested.

The bulk insertion logic appears correct and should improve performance for multiple subscriptions.

node/pkg/dal/k6/script.js (2)

64-81: LGTM! Ensure WebSocket stress test is thoroughly tested.

The WebSocket stress test logic appears correct and should help identify memory leaks.


1-3: Ensure proper error handling for the randomIntBetween import.

The imported function should be checked for availability and proper error handling.

Verification successful

The randomIntBetween function is imported and used correctly.

The function is imported from a reliable external library and used appropriately in the script.

  • The import statement is correct.
  • The function is used to set the sessionDuration variable.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the availability of the randomIntBetween function.

# Test: Search for the function usage. Expect: Only occurrences of the correct import.
rg --type js -A 5 $'randomIntBetween'

Length of output: 2871

node/pkg/dal/tests/api_test.go (1)

166-220: Improved Readability and Organization

The restructuring of the TestApiWebsocket function into a sub-test "test subscription" enhances readability and organization. This change makes the test's intent clearer and the sequence of operations more understandable.

node/pkg/dal/api/controller.go (8)

22-22: Enhanced Logging for Config Retrieval

The logging statement adds context by including the "Player" field, which improves traceability.


32-32: Enhanced Logging for Collector Creation

The logging statement adds context by including the "Player" field, which improves traceability.


56-58: Enhanced Logging for Collector and Connection Handler Start

The logging statements add context by including the "Player" field, which improves traceability.


62-86: Refactored Connection Handling

The refactored handleConnection method improves readability and maintainability. The use of sync.RWMutex ensures safe concurrent access to the clients map.


88-98: New Method for Broadcasting Data

The startBroadCast method improves the clarity of the broadcast setup process by encapsulating the logic in a dedicated method.


117-125: Simplified Function Signature

The castSubmissionData method now accepts a string for the symbol instead of a pointer. This change simplifies the function signature and eliminates unnecessary pointer dereferencing, improving performance.


49-49: Removal of Unused Code

The removal of commented-out sections related to websocket connection handling streamlines the file and focuses on the essential logic.


Line range hint 105-111: Correct Mapping of Configuration ID to Symbol

The configIdToSymbol method correctly maps a configuration ID to a symbol, ensuring the correct symbol is used for broadcasting data.

node/pkg/wss/utils.go (1)

284-296: New Method for Checking WebSocket Connection Status

The IsAlive method enhances the functionality by checking the status of the WebSocket connection. It correctly handles the connection status and logs errors if the ping fails.

node/pkg/dal/api/websocketcontroller.go Outdated Show resolved Hide resolved
node/pkg/dal/api/websocketcontroller.go Outdated Show resolved Hide resolved
node/pkg/dal/api/websocketcontroller.go Show resolved Hide resolved
node/pkg/dal/api/websocketcontroller.go Show resolved Hide resolved
node/pkg/dal/api/websocketcontroller.go Outdated Show resolved Hide resolved
node/pkg/dal/api/websocketcontroller.go Outdated Show resolved Hide resolved
node/pkg/dal/k6/script.js Show resolved Hide resolved
@nick-bisonai nick-bisonai marked this pull request as draft July 27, 2024 12:19
@nick-bisonai nick-bisonai deleted the feat/possible-fix-for-memory-leak branch August 3, 2024 03:08
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