Skip to content

feat(): add possibility to define custom OnShed handler;#1314

Merged
ReneWerner87 merged 9 commits into
gofiber:mainfrom
nsakharenko:feat/loadhed-add-custom-onshed-handler
Jun 26, 2025
Merged

feat(): add possibility to define custom OnShed handler;#1314
ReneWerner87 merged 9 commits into
gofiber:mainfrom
nsakharenko:feat/loadhed-add-custom-onshed-handler

Conversation

@nsakharenko
Copy link
Copy Markdown

@nsakharenko nsakharenko commented Jun 19, 2025

Purpose of this PR to add possibility to define a custom OnShed handler.
This will allow to control (add metrics, log messages etc.), and customize response code/message for a declined requests.

Summary by CodeRabbit

  • New Features
    • Added support for a customizable callback to handle requests declined due to load shedding, allowing tailored responses instead of the default error.
  • Tests
    • Introduced comprehensive test cases to verify the behavior and flexibility of the new customizable load shedding handler under various scenarios.
  • Documentation
    • Updated usage examples and configuration details to include the new customizable load shedding handler, with improved formatting and explanations.

@nsakharenko nsakharenko requested a review from a team as a code owner June 19, 2025 13:18
@nsakharenko nsakharenko requested review from ReneWerner87, efectn, gaby and sixcolors and removed request for a team June 19, 2025 13:18
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 19, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • go.work is excluded by !**/*.work, !**/*.work

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

A new optional OnShed callback was added to the load shedding middleware configuration, enabling custom handling when requests are declined due to high load. The middleware now invokes this callback if set, instead of returning a default 503 error. Comprehensive tests were introduced to verify various OnShed behaviors and responses. The README was updated with usage examples and documentation for the new callback.

Changes

File(s) Change Summary
loadshed/loadshed.go Added OnShed callback to Config struct; middleware now calls OnShed for custom shed handling.
loadshed/loadshed_test.go Added multiple tests covering OnShed callback scenarios and their effects on HTTP responses.
loadshed/README.md Added usage examples and documentation for OnShed callback; improved formatting and updated defaults.

Poem

In the warren of code, a new path is laid,
For when the server’s tired and requests are waylaid.
OnShed hops in, a custom friend,
To shape the answer we wish to send.
With tests that nibble every case,
The middleware’s now a safer place!
🐇✨

✨ Finishing Touches
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 auto-generate unit tests to generate unit tests 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 or @coderabbitai title 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.

@github-actions github-actions Bot added the ✏️ Feature New feature or request label Jun 19, 2025
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @nsakharenko, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a significant enhancement to the load shedding middleware by providing a mechanism for users to define a custom handler for requests that are declined due to high load. This allows for greater control over the response, enabling custom logging, metrics, and tailored error messages or status codes, moving beyond the default 503 Service Unavailable response.

Highlights

  • Configuration Extension: I've extended the Config struct in loadshed/loadshed.go by adding a new OnShed field. This field is a function func(c *fiber.Ctx) error, allowing users to define a custom handler that will be executed when a request is declined due to load shedding.
  • Custom Handler Integration: The core load shedding middleware in loadshed/loadshed.go has been updated. Now, if a request is determined to be shed (cfg.Criteria.ShouldShed(metric) returns true) and a custom OnShed handler is provided in the configuration, that custom handler will be invoked instead of the default fiber.NewError(fiber.StatusServiceUnavailable).
  • Comprehensive Test Coverage: I've added a suite of new test cases in loadshed/loadshed_test.go to thoroughly validate the behavior of the new OnShed handler. These tests cover various scenarios, including custom status codes, custom responses, handling nil returns, custom errors, and JSON responses, ensuring the flexibility and robustness of the new feature.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a custom OnShed handler in the load shedding middleware. The implementation is clean, and the tests are thorough. The suggestions focus on clarifying the behavior of the OnShed handler in specific edge cases and ensuring test comments are accurate.

Comment thread loadshed/loadshed_test.go
Comment thread loadshed/loadshed_test.go Outdated
Copy link
Copy Markdown
Member

@ReneWerner87 ReneWerner87 left a comment

Choose a reason for hiding this comment

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

thx looks good
@nsakharenko can you add more documentation for this new feature

@ReneWerner87
Copy link
Copy Markdown
Member

@nsakharenko feature is looking good, just the documentation is missing

Copy link
Copy Markdown
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

🔭 Outside diff range comments (1)
loadshed/README.md (1)

70-73: Duplicate missing import in the second example

Same issue as above – add time to the import list.

 import (
   "github.com/gofiber/fiber/v2"
   loadshed "github.com/gofiber/contrib/loadshed"
+  "time"
 )
🧹 Nitpick comments (2)
loadshed/README.md (2)

148-154: Fix list indentation (markdownlint MD007)

The bullet list under “Proportional Rejection Probability” is indented with four spaces instead of two, tripping common linters and breaking GitHub’s renderer in some themes.

-    - **Below `LowerThreshold`**: No requests are rejected, as the system is considered under acceptable load.
-    - **Between `LowerThreshold` and `UpperThreshold`**: The probability of rejecting a request increases as the CPU
-      usage approaches the `UpperThreshold`. This is calculated using the formula:
+  - **Below `LowerThreshold`**: No requests are rejected, as the system is considered under acceptable load.
+  - **Between `LowerThreshold` and `UpperThreshold`**: The probability of rejecting a request increases as the CPU
+    usage approaches the `UpperThreshold`. This is calculated using the formula:

137-137: Hyphenate “decision-making”

Small grammar nit:

-... CPU usage is averaged for decision making.
+... CPU usage is averaged for decision-making.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d432624 and 5618426.

📒 Files selected for processing (2)
  • loadshed/README.md (3 hunks)
  • loadshed/loadshed.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • loadshed/loadshed.go
🧰 Additional context used
🪛 LanguageTool
loadshed/README.md

[uncategorized] ~137-~137: The noun “decision-making” (= the process of deciding something) is spelled with a hyphen.
Context: ...ver which the CPU usage is averaged for decision making. ...

(DECISION_MAKING)

🪛 markdownlint-cli2 (0.17.2)
loadshed/README.md

148-148: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


149-149: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


154-154: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

Comment thread loadshed/README.md
Copy link
Copy Markdown
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: 0

♻️ Duplicate comments (2)
loadshed/README.md (2)

39-42: time import still missing – example will not compile

This has been pointed out previously but is still unresolved.
Add the standard-library time package to the import block so that 10 * time.Second type-checks.

 import (
   "github.com/gofiber/fiber/v2"
   loadshed "github.com/gofiber/contrib/loadshed"
+  "time"
 )

70-73: Second snippet repeats the missing time import

Same issue as above in the “custom rejection handler” example – copy-pasting will fail to build without:

 import (
   "github.com/gofiber/fiber/v2"
   loadshed "github.com/gofiber/contrib/loadshed"
+  "time"
 )
🧹 Nitpick comments (1)
loadshed/README.md (1)

136-136: Hyphenate “decision-making” for correctness

-... averaged for decision making.
+... averaged for decision-making.
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5618426 and dcc3cab.

📒 Files selected for processing (1)
  • loadshed/README.md (5 hunks)
🧰 Additional context used
🪛 LanguageTool
loadshed/README.md

[uncategorized] ~136-~136: The noun “decision-making” (= the process of deciding something) is spelled with a hyphen.
Context: ...ver which the CPU usage is averaged for decision making. ...

(DECISION_MAKING)

@nsakharenko nsakharenko requested a review from ReneWerner87 June 24, 2025 09:42
@nsakharenko
Copy link
Copy Markdown
Author

@ReneWerner87 documentation updated, let me know if there is anything else that i can improve.

@ReneWerner87 ReneWerner87 merged commit 54da7bb into gofiber:main Jun 26, 2025
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✏️ Feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants