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

Add websocket session support #24

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open

Add websocket session support #24

wants to merge 8 commits into from

Conversation

esterlus
Copy link
Member

@esterlus esterlus commented Oct 24, 2024

Summary by CodeRabbit

  • New Features

    • Introduced TCP server capabilities to enhance server functionality.
    • Added functions for managing server connections and responding to clients.
  • Bug Fixes

    • Improved error handling during server setup and response processes.
  • Version Updates

    • Application version updated to 4.0.0-a.1.
    • Dependency on @hoprnet/uhttp-lib updated to a beta version.

@esterlus esterlus requested a review from mjadach-iv October 24, 2024 22:35
Copy link

coderabbitai bot commented Oct 24, 2024

📝 Walkthrough

Walkthrough

The pull request introduces significant updates to the package.json and src/index.ts files. The package.json file reflects a major version increment to 4.0.0-a.1 and updates the @hoprnet/uhttp-lib dependency to a beta version. In src/index.ts, new functionalities are added to support TCP server capabilities, including enhanced error handling and response management. Key new functions for server setup and connection handling are introduced, and existing types are updated to accommodate these changes.

Changes

File Change Summary
package.json - Version updated from 3.4.0 to 4.0.0-a.1
- Dependency @hoprnet/uhttp-lib updated from ^3.8.0 to ^3.9.0-beta.1
src/index.ts - Added import for Node.js Net module
- Updated State type to include server property
- Updated Ops type to include tcpPort
- Added setupServer, onConnection, and respond functions
- Modified start function to integrate TCP server setup
- Enhanced error handling in setup function and updated sendResponse function for detailed logging

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant TCPServer

    Client->>Server: Send request
    Server->>TCPServer: Setup TCP server
    TCPServer-->>Server: Server ready
    Server->>TCPServer: Accept connection
    TCPServer->>Server: Connection established
    Server->>TCPServer: Process incoming data
    TCPServer->>Server: Data received
    Server->>Client: Send response
Loading

Warning

Rate limit exceeded

@esterlus has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 2 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 dc98c67 and 55ccdc9.


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

🧹 Outside diff range and nitpick comments (4)
src/index.ts (4)

177-192: Ensure Proper Error Handling and Resource Management in TCP Server

The setupServer function initializes the TCP server and sets up event listeners for 'error' and 'close' events. Currently, on a server error, the error is logged, but no further action is taken. Consider whether the server should attempt to restart or shut down gracefully upon encountering an error to maintain service availability and prevent resource leaks.


217-219: Adjust Log Level for 'end' Event in Socket Connection

In the conn.on('end', ...) event handler, the unexpected end of an incoming socket connection is logged as an error. If the 'end' event is a normal occurrence in the socket lifecycle, consider logging it as a warning or informational message instead of an error.


703-711: Remove Deprecated or Commented-Out Code

There is a block of commented-out code related to reporting to the discovery platform within the respond function. Removing commented-out code can improve code readability and maintainability. If this code is no longer needed, consider deleting it.

Apply this diff to remove the commented-out code:

-//     if (ops.discoveryPlatform) {
-//         reportToDiscoveryPlatform({
-//             ops,
-//             cacheEntry,
-//             reqPayload,
-//             segments,
-//         });
-//     }

180-182: Handle Server Errors to Enhance Reliability

In the server.on('error', ...) event handler, the error is logged, but the server is not closed or restarted. Depending on the application's requirements, consider implementing logic to gracefully handle server errors, such as shutting down the server or attempting a restart, to improve reliability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dc98c67 and 55ccdc9.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (2)
  • package.json (2 hunks)
  • src/index.ts (8 hunks)
🔇 Additional comments (3)
package.json (2)

34-34: Consider the risks of using a beta dependency

Moving from a stable version (^3.8.0) to a beta version (^3.9.0-beta.1) of @hoprnet/uhttp-lib in production code carries risks:

  • Beta versions may contain bugs or incomplete features
  • Breaking changes might be introduced before the final release
  • Future updates might be less predictable

Please ensure that:

  1. This beta version has been thoroughly tested
  2. There's a compelling reason to use the beta version instead of waiting for a stable release

3-3: Verify breaking changes documentation for v4.0.0

The major version bump (3.x.x → 4.0.0-a.1) correctly indicates breaking changes, which aligns with the new TCP server capabilities being added. However, ensure that all breaking changes are properly documented.

src/index.ts (1)

915-915: ⚠️ Potential issue

Use Validated 'tcpPort' in Server Configuration

After adding validation for the TCP port, ensure that the validated tcpPort variable is used in the server configuration to prevent potential issues with invalid port numbers.

Apply this diff to use the validated tcpPort:

 start({
     privateKey: process.env.UHTTP_EA_PRIVATE_KEY,
     publicKey: process.env.UHTTP_EA_PUBLIC_KEY,
     apiEndpoint: new URL(process.env.UHTTP_EA_HOPRD_ENDPOINT),
     accessToken: process.env.UHTTP_EA_HOPRD_ACCESS_TOKEN,
     discoveryPlatform,
     dbFile: process.env.UHTTP_EA_DATABASE_FILE,
     pinnedFetch: globalThis.fetch.bind(globalThis),
-    tcpPort: parseInt(process.env.UHTTP_EA_TCPPORT),
+    tcpPort,
 });

Likely invalid or redundant comment.

Comment on lines +890 to +891
throw new Error("Missing 'UHTTP_EA_TCPPORT' env var.");
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate 'UHTTP_EA_TCPPORT' Environment Variable

When reading the UHTTP_EA_TCPPORT environment variable, ensure that it is not only present but also a valid integer within the acceptable TCP port range (1-65535). Invalid port numbers could cause the server to fail unexpectedly.

Apply this diff to add validation:

 if (!process.env.UHTTP_EA_TCPPORT) {
     throw new Error("Missing 'UHTTP_EA_TCPPORT' env var.");
 }
+const tcpPort = parseInt(process.env.UHTTP_EA_TCPPORT, 10);
+if (isNaN(tcpPort) || tcpPort < 1 || tcpPort > 65535) {
+    throw new Error("Invalid 'UHTTP_EA_TCPPORT' env var. It must be a valid port number (1-65535).");
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
throw new Error("Missing 'UHTTP_EA_TCPPORT' env var.");
}
if (!process.env.UHTTP_EA_TCPPORT) {
throw new Error("Missing 'UHTTP_EA_TCPPORT' env var.");
}
const tcpPort = parseInt(process.env.UHTTP_EA_TCPPORT, 10);
if (isNaN(tcpPort) || tcpPort < 1 || tcpPort > 65535) {
throw new Error("Invalid 'UHTTP_EA_TCPPORT' env var. It must be a valid port number (1-65535).");
}

@Teebor-Choka Teebor-Choka changed the title session support Add websocket session support Nov 22, 2024
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