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

🩹 Fix: sorting error in sortAcceptedTypes #3331

Merged
merged 4 commits into from
Mar 1, 2025

Conversation

ksw2000
Copy link
Member

@ksw2000 ksw2000 commented Feb 26, 2025

Description

The original implementation fails in the test below. The test is modified simply by moving {spec: "application/json", quality: 0.999, specificity: 3, order: 3} to the last element.

func Test_Utils_SortAcceptedTypes(t *testing.T) {
	t.Parallel()
	acceptedTypes := []acceptedType{
		{spec: "text/html", quality: 1, specificity: 3, order: 0},
		{spec: "text/*", quality: 0.5, specificity: 2, order: 1},
		{spec: "*/*", quality: 0.1, specificity: 1, order: 2},
		// {spec: "application/json", quality: 0.999, specificity: 3, order: 3}, <- move to the last
		{spec: "application/xml", quality: 1, specificity: 3, order: 4},
		{spec: "application/pdf", quality: 1, specificity: 3, order: 5},
		{spec: "image/png", quality: 1, specificity: 3, order: 6},
		{spec: "image/jpeg", quality: 1, specificity: 3, order: 7},
		{spec: "image/*", quality: 1, specificity: 2, order: 8},
		{spec: "image/gif", quality: 1, specificity: 3, order: 9},
		{spec: "text/plain", quality: 1, specificity: 3, order: 10},
		{spec: "application/json", quality: 0.999, specificity: 3, params: headerParams{"a": []byte("1")}, order: 11},
		{spec: "application/json", quality: 0.999, specificity: 3, order: 3}, // moved to here
	}
	sortAcceptedTypes(&acceptedTypes)
	require.Equal(t, []acceptedType{
		{spec: "text/html", quality: 1, specificity: 3, order: 0},
		{spec: "application/xml", quality: 1, specificity: 3, order: 4},
		{spec: "application/pdf", quality: 1, specificity: 3, order: 5},
		{spec: "image/png", quality: 1, specificity: 3, order: 6},
		{spec: "image/jpeg", quality: 1, specificity: 3, order: 7},
		{spec: "image/gif", quality: 1, specificity: 3, order: 9},
		{spec: "text/plain", quality: 1, specificity: 3, order: 10},
		{spec: "image/*", quality: 1, specificity: 2, order: 8},
		{spec: "application/json", quality: 0.999, specificity: 3, params: headerParams{"a": []byte("1")}, order: 11},
		{spec: "application/json", quality: 0.999, specificity: 3, order: 3},
		{spec: "text/*", quality: 0.5, specificity: 2, order: 1},
		{spec: "*/*", quality: 0.1, specificity: 1, order: 2},
	}, acceptedTypes)
}

In addition, the argument of sortAcceptedTypes can be a slice rather than a pointer to a slice.

Type of change

  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Copy link
Contributor

coderabbitai bot commented Feb 26, 2025

Walkthrough

The changes update the handling of the acceptedType slice by switching from pointer-based parameters to direct slice passing in both the sorting function and its tests. In helpers.go, the sortAcceptedTypes function signature is simplified, and the logic within has been adjusted accordingly, including a minor tweak to the sorting condition. In helpers_test.go, test cases and benchmark functions have been modified to align with the new function signature and to update the JSON entry order.

Changes

File(s) Change Summary
helpers.go Updated sortAcceptedTypes signature from pointer (*[]acceptedType) to slice ([]acceptedType); modified nil/length checks and refined comparison logic; updated its invocation within getOffer.
helpers_test.go, benchmark sections Adjusted tests to pass the slice directly; updated entries for application/json type and aligned benchmark function calls with the new signature.

Sequence Diagram(s)

sequenceDiagram
    participant Offer as getOffer
    participant Sort as sortAcceptedTypes
    Offer->>Sort: Call sortAcceptedTypes(acceptedTypes slice)
    Note right of Sort: Evaluate slice (length/checks) and perform sorting
    Sort-->>Offer: Return sorted slice

Suggested labels

☢️ Bug, v3

Suggested reviewers

  • gaby
  • sixcolors
  • ReneWerner87
  • efectn

Poem

I hopped through the code with cheer,
Tidying up logic far and near,
A swift change in slice, no pointer to fear,
Sorting dreams with each line I peer,
A rabbit’s delight in code so clear!
🐇💻


📜 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 a296b65 and 4d2eb87.

📒 Files selected for processing (1)
  • helpers.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • helpers.go
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: unit (1.23.x, macos-latest)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: Compare
  • GitHub Check: repeated
  • GitHub Check: Analyse

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.
  • @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

codecov bot commented Feb 26, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.27%. Comparing base (86cf806) to head (0635e2c).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3331      +/-   ##
==========================================
+ Coverage   84.21%   84.27%   +0.06%     
==========================================
  Files         116      116              
  Lines       11577    11572       -5     
==========================================
+ Hits         9749     9752       +3     
+ Misses       1397     1391       -6     
+ Partials      431      429       -2     
Flag Coverage Δ
unittests 84.27% <100.00%> (+0.06%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@ksw2000 ksw2000 marked this pull request as ready for review February 26, 2025 14:37
@ksw2000 ksw2000 requested a review from a team as a code owner February 26, 2025 14:37
@ksw2000 ksw2000 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team February 26, 2025 14:37
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bc4c920 and a296b65.

📒 Files selected for processing (2)
  • helpers.go (2 hunks)
  • helpers_test.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Analyse
  • GitHub Check: Compare
🔇 Additional comments (5)
helpers_test.go (3)

365-367: Approved change to fix the sorting order test case.

The change adds an application/json entry with order 3 at the end of the slice and modifies the function call to directly pass the slice instead of a pointer, aligning with the function signature change in the implementation file.


393-393: Properly updated benchmark call.

The benchmark function has been updated to correctly pass the slice directly instead of a pointer, consistent with the function signature change.


417-417: Properly updated unsorted benchmark call.

The unsorted benchmark function has also been updated to correctly pass the slice directly instead of a pointer, maintaining consistency with the function signature change.

helpers.go (2)

486-486: Updated function call to match new signature.

The call to sortAcceptedTypes now correctly passes the slice directly rather than its address, aligning with the updated function signature.


514-517: Improved function signature for better Go idioms.

The function now accepts a slice directly instead of a pointer to a slice, which is more idiomatic in Go. This improves readability and reduces unnecessary pointer operations.


for i := 1; i < len(at); i++ {
lo, hi := 0, i-1
for lo <= hi {
mid := (lo + hi) / 2
if at[i].quality < at[mid].quality ||
(at[i].quality == at[mid].quality && at[i].specificity < at[mid].specificity) ||
(at[i].quality == at[mid].quality && at[i].specificity < at[mid].specificity && len(at[i].params) < len(at[mid].params)) ||
(at[i].quality == at[mid].quality && at[i].specificity == at[mid].specificity && len(at[i].params) < len(at[mid].params)) ||
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fixed sorting condition for params comparison.

The comparison logic has been fixed to properly sort items when they have the same quality and specificity by checking if one has fewer parameters than the other. This precise change resolves the sorting error mentioned in the PR objectives.

Before this fix, the comparison logic likely didn't correctly handle the sorting of entries with different parameter counts, causing the element with order: 3 to be placed incorrectly.

@ReneWerner87
Copy link
Member

In addition, the argument of sortAcceptedTypes can be a slice rather than a pointer to a slice.

can you share benchmark results for this
the idea was that golang would not have to create a copy and the allocation savings would minimize the execution time

@ksw2000
Copy link
Member Author

ksw2000 commented Feb 26, 2025

In addition, the argument of sortAcceptedTypes can be a slice rather than a pointer to a slice.

can you share benchmark results for this the idea was that golang would not have to create a copy and the allocation savings would minimize the execution time

goos: linux
goarch: amd64
pkg: github.com/gofiber/fiber/v3
cpu: AMD EPYC 7763 64-Core Processor                
                                  │   old.txt   │              new.txt               │
                                  │   sec/op    │   sec/op     vs base               │
_Utils_SortAcceptedTypes_Sorted-4   11.48n ± 1%   10.56n ± 2%  -7.97% (p=0.000 n=20)

                                  │  old.txt   │            new.txt             │
                                  │    B/op    │    B/op     vs base            │
_Utils_SortAcceptedTypes_Sorted-4   0.000 ± 0%   0.000 ± 0%  ~ (p=1.000 n=20) ¹
¹ all samples are equal

                                  │  old.txt   │            new.txt             │
                                  │ allocs/op  │ allocs/op   vs base            │
_Utils_SortAcceptedTypes_Sorted-4   0.000 ± 0%   0.000 ± 0%  ~ (p=1.000 n=20) ¹
¹ all samples are equal

@ReneWerner87
Copy link
Member

@gaby
Copy link
Member

gaby commented Feb 27, 2025

CI is randomly failing but it's not related to this PR. Triggered "replay failed jobs"

Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

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

👍 LGTM

@ReneWerner87 ReneWerner87 merged commit 6afba95 into gofiber:main Mar 1, 2025
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

3 participants