Skip to content

optimize readPacket #1705

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

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

optimize readPacket #1705

wants to merge 1 commit into from

Conversation

methane
Copy link
Member

@methane methane commented Apr 23, 2025

Description

Avoid unnecessary allocation.

Checklist

  • Code compiles correctly
  • Created tests which fail without the change (if possible)
  • All tests passing
  • Extended the README / documentation, if necessary
  • Added myself / the copyright holder to the AUTHORS file

Summary by CodeRabbit

  • New Features

    • Added a method to retrieve the current length of the internal buffer.
  • Refactor

    • Simplified the process for reading data from the buffer and compressed streams, removing unnecessary parameters and streamlining the interface.
    • Centralized and clarified how data is read with timeout handling, improving code maintainability and consistency for end-users.

Copy link

coderabbitai bot commented Apr 23, 2025

Walkthrough

This change refactors the buffer and compressed IO reading logic by simplifying method signatures and internal data flow. The buffer type gains a new len() method, and its readNext method is simplified to remove error handling and external reader dependencies. Corresponding updates are made in the compressed IO (compIO) logic, eliminating the need to pass reader functions and streamlining packet reading. The mysqlConn type now encapsulates buffer reading and timeout logic within a new readNext method, further centralizing and simplifying byte reading throughout the codebase.

Changes

File(s) Change Summary
buffer.go Added len() method to buffer. Refactored readNext to remove error handling and dependency on readerFunc.
compress.go Updated compIO.readNext and readCompressedPacket to remove readerFunc parameter and streamline internal reads.
packets.go Added mysqlConn.readNext for encapsulated buffer reading with timeout. Updated readPacket to use new method.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant mysqlConn
  participant buffer

  Client->>mysqlConn: readPacket()
  mysqlConn->>mysqlConn: readNext(n)
  mysqlConn->>buffer: readNext(n)
  buffer-->>mysqlConn: []byte
  mysqlConn-->>Client: packet data
Loading

Possibly related PRs

  • stop double-buffering #1643: Refactored the buffer handling by removing double buffering and reworking the readNext method, which is directly built upon in this PR.

Suggested reviewers

  • shogo82148

Poem

In the warren of code, the buffers align,
No more error hops, just bytes in a line.
The packets now flow, with nibbles so neat,
Refactored and tidy, a developer's treat.
🐇✨


📜 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 f7d94ec and c630c5e.

📒 Files selected for processing (3)
  • buffer.go (2 hunks)
  • compress.go (2 hunks)
  • packets.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: test (windows-latest, 1.24, 8.4)
  • GitHub Check: test (ubuntu-latest, 1.24, mariadb-10.5)
  • GitHub Check: test (windows-latest, 1.24, mariadb-10.11)
  • GitHub Check: test (windows-latest, 1.24, mariadb-11.2)
  • GitHub Check: test (ubuntu-latest, 1.22, 9.0)
  • GitHub Check: test (windows-latest, 1.24, mariadb-11.1)
  • GitHub Check: test (windows-latest, 1.24, mariadb-11.4)
  • GitHub Check: test (macos-latest, 1.24, mariadb-10.5)
  • GitHub Check: test (windows-latest, 1.24, 9.0)
  • GitHub Check: test (windows-latest, 1.24, 8.0)
  • GitHub Check: test (macos-latest, 1.24, mariadb-10.6)
  • GitHub Check: test (macos-latest, 1.24, mariadb-11.1)
  • GitHub Check: test (ubuntu-latest, 1.24, mariadb-10.6)
  • GitHub Check: test (ubuntu-latest, 1.24, mariadb-10.11)
  • GitHub Check: test (macos-latest, 1.24, 5.7)
  • GitHub Check: test (macos-latest, 1.24, mariadb-11.4)
  • GitHub Check: test (ubuntu-latest, 1.24, mariadb-11.2)
  • GitHub Check: test (ubuntu-latest, 1.24, 5.7)
  • GitHub Check: test (ubuntu-latest, 1.24, 8.0)
  • GitHub Check: test (ubuntu-latest, 1.24, 8.4)
🔇 Additional comments (10)
buffer.go (2)

45-48: Good addition of len() method

This is a helpful accessor that simplifies code readability where buffer length needs to be checked.


94-98: Good simplification of readNext method

The method now has a single responsibility - slicing the buffer. The error handling and buffer filling logic is moved elsewhere, improving separation of concerns. The full slice expression (:need:need) prevents capacity leaks by limiting the capacity to exactly what's needed.

packets.go (4)

28-37: Well-designed readNext method

This new method centralizes the buffer filling and timeout handling logic, which was previously spread across different parts of the code. This encapsulation improves code structure and maintainability.


44-47: Good refactoring of packet reading logic

Using the new readNext variable to hold the appropriate reading function (either mc.readNext or mc.compIO.readNext) simplifies the code flow while maintaining the same functionality for both compressed and uncompressed connections.


51-52: Clean implementation of readNext

The code now uses the function reference approach which simplifies error handling while maintaining the same functionality.


99-100: Consistent use of readNext abstraction

This change maintains consistency with the new pattern established earlier in the function.

compress.go (4)

87-95: Good simplification of compIO.readNext

The method now follows the same pattern as other readNext implementations in the codebase. Removing the readerFunc parameter streamlines the code and makes it more consistent with the rest of the implementation.


97-99: Good refactoring of readCompressedPacket

The method now directly uses mc.readNext, which simplifies the code flow and aligns with the broader refactoring approach. This eliminates unnecessary parameter passing while maintaining the same functionality.


106-107: Minor optimization by removing type conversion

Using the byte directly instead of performing unnecessary type conversion is a small but good optimization.


123-126: Consistent use of mc.readNext

This change maintains consistency with the new pattern established earlier in the function, eliminating unnecessary parameter passing.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@methane methane mentioned this pull request Apr 23, 2025
5 tasks
Comment on lines -40 to +51
data, err := readNext(4, mc.readWithTimeout)
data, err := readNext(4)
Copy link
Member Author

Choose a reason for hiding this comment

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

go compiler allocated mc.readWithTimeout method trampoline object.

@@ -85,7 +96,7 @@ func (mc *mysqlConn) readPacket() ([]byte, error) {
}

// read packet body [pktLen bytes]
data, err = readNext(pktLen, mc.readWithTimeout)
data, err = readNext(pktLen)
Copy link
Member Author

Choose a reason for hiding this comment

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

ditto.

// read n bytes from mc.buf
func (mc *mysqlConn) readNext(n int) ([]byte, error) {
if mc.buf.len() < n {
err := mc.buf.fill(n, mc.readWithTimeout)
Copy link
Member Author

@methane methane Apr 23, 2025

Choose a reason for hiding this comment

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

Go compiler inlines mc.buff.fill. It doesn't allocate mc.readWithTimeout.

It may be possible to rewrite in cleaner code. But I minimise changes to backport this PR to 1.9 branch.

@coveralls
Copy link

Coverage Status

coverage: 82.758% (-0.08%) from 82.833%
when pulling c630c5e on methane:opt-read
into f7d94ec on go-sql-driver:master.

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