Skip to content

fix: ensure udp messages are sent on close #946

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

Merged
merged 3 commits into from
Apr 8, 2025
Merged

fix: ensure udp messages are sent on close #946

merged 3 commits into from
Apr 8, 2025

Conversation

dnlup
Copy link
Contributor

@dnlup dnlup commented Mar 31, 2025

🚨 Proposed changes

Please review the guidelines for contributing to this repository.

[[Describe the big picture of your changes here to communicate to the maintainers why we should accept this pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue.]]

⚙️ Types of changes

What types of changes does your code introduce? Put an x in the boxes that apply

  • New feature (non-breaking change which adds functionality)
  • Bugfix (non-breaking change which fixes an issue)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation Update (if none of the other choices apply)
  • Refactor

Summary by CodeRabbit

  • New Features

    • Enhanced message handling now ensures all communications finish processing before disconnecting, providing a more reliable experience.
    • Added new properties to track pending messages and idle state in the socket classes.
  • Tests

    • Introduced new testing scenarios to confirm that queued messages are correctly handled before a disconnection.
    • Added tests to verify the behavior of SocketTcp during the closing process, ensuring proper management of message queue and idle state.

Copy link

coderabbitai bot commented Mar 31, 2025

Walkthrough

The pull request modifies the core socket functionality by updating the Socket class to extend EventEmitter and enhancing the SocketTcp and SocketUdp classes with a pending messages counter. The send method now manipulates this counter by incrementing when a message is sent and decrementing it upon completion, emitting an idle event when the count reaches zero. The close method is updated to wait asynchronously for pending messages to clear. Additionally, new getter methods for the pending messages count and idle state have been added, along with new tests to verify that queued messages are handled correctly during the close operation.

Changes

File Change Summary
src/socket.ts - Modified Socket to extend EventEmitter by calling super() in the constructor.
- Updated SocketTcp and SocketUdp by adding a private _pendingMessages counter.
- Enhanced send method to increment/decrement the counter and emit an 'idle' event when messages are completed.
- Made close() asynchronous to wait for pending messages.
- Added pendingMessages and idle getters.
test/index.spec.ts - Added a new test case "close with queued messages should wait" to verify that the socket waits for queued messages to clear before closing, ensuring the pending messages count is properly managed during the closing operation.
test/tcp.spec.ts - Added a new test case "TCP close should wait" to verify that the pendingMessages count reflects the number of messages sent before closing, and checks that idle state is true after closing. Updated existing tests to include assertions for pendingMessages and idle state.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client/Caller
    participant S as SocketTcp (EventEmitter)
    
    C->>S: send(message)
    S-->>S: Increment _pendingMessages
    alt send successful
        S-->>S: Decrement _pendingMessages
    else send error
        S-->>S: onError called\nDecrement _pendingMessages
    end
    alt _pendingMessages equals 0
        S->>S: Emit 'idle' event
    end
    C->>S: close()
    alt _pendingMessages > 0
        S->>S: Wait for 'idle' event
    end
    S-->>C: Socket closed
Loading

Poem

I'm a bunny through the code,
Hopping paths where messages goad.
Pending counts now jump and play,
Emitting 'idle' when they're away.
With tests that pass, I dance with glee—
CodeRabbit sings in harmony! 🐰


📜 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 0e2cde7 and cfe1529.

📒 Files selected for processing (1)
  • src/socket.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/socket.ts

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@dnlup dnlup changed the base branch from main to next March 31, 2025 09:44
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 (1)
src/socket.ts (1)

194-209: Remove the return statement to align with the void return type.
Static analysis warns that returning a value from a function declared as void can be misleading. Since the returned value is never consumed, you can safely remove it:

-        return this.socket.send(data, this.port, this.hostname, (err) => {
+        this.socket.send(data, this.port, this.hostname, (err) => {
🧰 Tools
🪛 Biome (1.9.4)

[error] 195-209: The function should not return a value because its return type is void.

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.

(lint/correctness/noVoidTypeReturn)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 38a59cd and dbe88c6.

📒 Files selected for processing (2)
  • src/socket.ts (6 hunks)
  • test/index.spec.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/socket.ts

[error] 195-209: The function should not return a value because its return type is void.

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.

(lint/correctness/noVoidTypeReturn)

🔇 Additional comments (4)
test/index.spec.ts (1)

401-422: Consider awaiting the client.connect() call for clarity and potential race avoidance.
By not awaiting the connect() call, there may be sporadic race conditions if the test attempts to verify pendingMessages before the client finishes connection procedures. If this is intentional (e.g., verifying message queuing during connection), then it’s fine; otherwise, consider:

-    client.connect();
+    await client.connect();

Do you want me to open a follow-up PR with this adjustment?

src/socket.ts (3)

6-7: Nice extension of the Socket class from EventEmitter.
This improvement allows emitting and listening to custom events (e.g., 'idle') more flexibly.

Also applies to: 19-19


132-132: Good introduction of _pendingMessages tracking and the idle accessor.
This approach neatly encapsulates the queue tracking logic and clarifies when the socket is free.

Also applies to: 153-153, 173-178


212-221: Well-implemented async close method.
Waiting for the 'idle' event ensures that no messages are lost, aligning nicely with reliability requirements.

@dnlup dnlup changed the base branch from next to main March 31, 2025 12:19
@dnlup
Copy link
Contributor Author

dnlup commented Mar 31, 2025

@coderabbitai review

Copy link

coderabbitai bot commented Mar 31, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (3)
test/tcp.spec.ts (1)

116-134: Excellent test case for the new message waiting functionality!

This test effectively verifies that:

  1. The socket correctly tracks pending messages (counter increments to 4)
  2. The idle state reflects when messages are being processed
  3. The close method properly waits for all messages to complete
  4. The 'idle' event is correctly emitted once

One minor improvement opportunity:

Consider adding a test assertion to verify that sending a message after close doesn't increment the pending messages counter (line 130). While you're implicitly testing this with the next assertion, an explicit check would make the test more comprehensive:

    await socket.close();
    socket.send('something');
+   t.is(socket.pendingMessages, 0, 'Sending after close should not increment pending messages');
    t.is(socket.pendingMessages, 0);
    t.is(socket.idle, true);
    t.true(emit.calledOnceWith('idle'));
src/socket.ts (2)

116-131: Message tracking implementation looks good, with a minor defensive coding opportunity.

The implementation properly tracks pending messages and emits the 'idle' event when appropriate.

Consider adding a defensive check to ensure the counter doesn't go negative, which could happen in edge cases:

    this.socket.write(data + '\n', (err) => {
        if (this._pendingMessages) {
            this._pendingMessages -= 1;
        }
+       // Ensure counter never goes below zero as a safeguard
+       if (this._pendingMessages < 0) {
+           this._pendingMessages = 0;
+       }
        if (err) {
            try {
                this.onError(err);

229-236: Good async implementation of UDP close.

The implementation correctly waits for pending messages to complete before closing the socket.

For consistency with the TCP implementation, consider moving the this.connected = false line inside the promise callback:

    await new Promise((res) => {
        this.socket.close(res as () => void);
-       this.connected = false;
+       this.connected = false;
    });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dbe88c6 and 0e2cde7.

📒 Files selected for processing (3)
  • src/socket.ts (4 hunks)
  • test/index.spec.ts (1 hunks)
  • test/tcp.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/index.spec.ts
🧰 Additional context used
🪛 Biome (1.9.4)
src/socket.ts

[error] 212-226: The function should not return a value because its return type is void.

The function is here:

'void' signals the absence of value. The returned value is likely to be ignored by the caller.

(lint/correctness/noVoidTypeReturn)

🔇 Additional comments (7)
test/tcp.spec.ts (1)

112-114: Good addition of pending message checks!

These assertions validate that the socket correctly reports its state after a send attempt on a closed connection.

src/socket.ts (6)

6-7: Good choice extending EventEmitter!

Using EventEmitter provides a clean way to signal when all pending messages have been processed.


13-13: Well-designed tracking of pending messages.

Adding this protected property allows both TCP and UDP implementations to track messages consistently.


20-20: Required super() call for EventEmitter.

Correctly initializes the EventEmitter parent class.


28-28: Proper initialization of the counter.

Good practice to initialize the counter in the constructor.


40-45: Clean accessor implementation for state inspection.

These getters provide a nice, consistent interface for checking the message state without exposing the internal counter directly.


134-138: Good implementation of async close with waiting.

Making the close method async and using the 'once' utility to wait for the 'idle' event is an elegant solution.

@dnlup
Copy link
Contributor Author

dnlup commented Apr 1, 2025

@coderabbitai review

Copy link

coderabbitai bot commented Apr 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@dnlup dnlup changed the base branch from main to next April 8, 2025 10:45
@dnlup dnlup merged commit aeee314 into next Apr 8, 2025
7 checks passed
@simonecorsi
Copy link
Collaborator

🎉 This PR is included in version 5.1.1-next.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

@coderabbitai coderabbitai bot mentioned this pull request Apr 8, 2025
5 tasks
@simonecorsi
Copy link
Collaborator

🎉 This PR is included in version 5.1.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants