📒 docs: Improve Timeout middleware documentation#3675
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughThe documentation for the Fiber timeout middleware was rewritten for clarity and completeness. It now details middleware behavior, usage constraints, and proper handler wrapping. A new, runnable example demonstrates timeout handling and context cancellation. Headings, formatting, and code samples were updated, and cautionary notes about correct usage were added. Changes
Sequence Diagram(s)Not applicable: Only documentation and example code changes were made. Estimated code review effort🎯 2 (Simple) | ⏱️ ~7 minutes Assessment against linked issues
Assessment against linked issues: Out-of-scope changesNo out-of-scope changes were found. Suggested reviewers
Poem
Note 🔌 MCP (Model Context Protocol) integration is now available in Early Access!Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context. ✨ Finishing Touches🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Summary of Changes
Hello @gaby, 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!
I'm enhancing the documentation for the timeout middleware. This PR clarifies its purpose, provides a comprehensive runnable example with curl instructions, removes outdated information, and adds a crucial warning about its improper usage with app.Use.
Highlights
- Clarified Timeout Middleware Purpose: I've updated the introductory text to clearly explain what the timeout middleware does and how it uses context.WithTimeout.
- Added Comprehensive Example: I've included a full, runnable Go example demonstrating the timeout middleware, complete with curl commands for testing both successful and timed-out requests.
- Removed Outdated Information: I've removed notes referring to previous or distinct implementations of the timeout middleware, streamlining the guide.
- Added Usage Warning: I've added a prominent caution against using timeout.New with app.Use and explained the potential panic if c.Next() is called inside the wrapped handler.
- Improved Example Structure: I've reformatted existing examples (custom error, DB call) to be consistent subheadings.
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 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 or fill out our survey 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
-
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. ↩
There was a problem hiding this comment.
Code Review
This pull request significantly improves the documentation for the timeout middleware. The explanation of the middleware's purpose is now clearer, and it includes a crucial warning about its correct usage. The old, fragmented example has been replaced with a complete, runnable Go program, including curl commands for testing, which is a great enhancement for users. I've found one minor issue in the new example where an error is ignored, which could be improved to demonstrate better error handling practices.
There was a problem hiding this comment.
Pull Request Overview
This PR improves the timeout middleware documentation to make it clearer and more user-friendly. It addresses confusion about how the middleware works and provides better guidance on proper usage.
Key changes:
- Replaced vague explanations with clear description of timeout behavior and context cancellation
- Added comprehensive runnable example with curl test instructions
- Added warning about incorrect usage with
app.Use()that causes panics
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
docs/middleware/timeout.md (1)
129-141: Improve DB example: error handling and transaction rollback
- Check and handle errors from gorm.Open/Begin.
- Roll back on any failure to avoid leaving open transactions.
- Keep the context usage as-is.
- handler := func(ctx fiber.Ctx) error { - tran := db.WithContext(ctx.Context()).Begin() - - if tran = tran.Exec("SELECT pg_sleep(50)"); tran.Error != nil { - return tran.Error - } - - if tran = tran.Commit(); tran.Error != nil { - return tran.Error - } - - return nil - } + handler := func(ctx fiber.Ctx) error { + tx := db.WithContext(ctx.Context()).Begin() + if tx.Error != nil { + return tx.Error + } + if err := tx.Exec("SELECT pg_sleep(50)").Error; err != nil { + _ = tx.Rollback().Error + return err + } + if err := tx.Commit().Error; err != nil { + _ = tx.Rollback().Error + return err + } + return nil + }
♻️ Duplicate comments (2)
docs/middleware/timeout.md (2)
97-101: Handle parse errors consistentlyMirror the basic example: validate sleepTime and return 400 on bad input.
- sleepTime, _ := time.ParseDuration(c.Params("sleepTime") + "ms") + sleepStr := c.Params("sleepTime") + sleepTime, err := time.ParseDuration(sleepStr + "ms") + if err != nil { + return fiber.NewError(fiber.StatusBadRequest, "invalid sleepTime") + }
57-63: Handle parse errors and flip error-wrapping order
- Return 400 on invalid delay instead of ignoring the error.
- Prefer “context: %w” ordering for error wrapping.
- handler := func(c fiber.Ctx) error { - delay, _ := time.ParseDuration(c.Params("delay") + "ms") - if err := sleepWithContext(c.Context(), delay); err != nil { - return fmt.Errorf("%w: execution error", err) - } - return c.SendString("finished") - } + handler := func(c fiber.Ctx) error { + delayStr := c.Params("delay") + delay, err := time.ParseDuration(delayStr + "ms") + if err != nil { + return fiber.NewError(fiber.StatusBadRequest, "invalid delay") + } + if err := sleepWithContext(c.Context(), delay); err != nil { + return fmt.Errorf("execution error: %w", err) + } + return c.SendString("finished") + }
🧹 Nitpick comments (5)
docs/middleware/timeout.md (5)
7-10: Clarify cancellation requirement for handlersAdd an explicit note that handlers must actively observe c.Context().Done() and stop work, otherwise the goroutine may continue running even after the 408 is sent.
12-16: Strengthen “Do/Don’t” with explicit examplesConsider adding a small “Do vs Don’t” snippet to make misuse obvious.
// Don't: global use (will panic) app.Use(timeout.New(h)) // Do: wrap the final handler per route app.Get("/foo", timeout.New(h, timeout.Config{Timeout: 2 * time.Second}))
33-52: Avoid potential timer leak; prefer time.NewTimer with stop/drainUsing time.After prevents canceling the timer if the context fires first. Suggest using time.NewTimer and stopping/draining it on cancellation.
-func sleepWithContext(ctx context.Context, d time.Duration) error { - select { - case <-time.After(d): - return nil - case <-ctx.Done(): - return ctx.Err() - } -} +func sleepWithContext(ctx context.Context, d time.Duration) error { + timer := time.NewTimer(d) + defer func() { + if !timer.Stop() { + <-timer.C + } + }() + select { + case <-timer.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } +}
73-78: Optional: show explicit timeout behavior in curlConsider adding examples with timing to make the difference visible:
time curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/sleep/1000 time curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/sleep/3000
125-128: Optional: acknowledge omitted imports for partial snippetConsider a brief note that imports/DSN handling are omitted for brevity, consistent with other Fiber docs.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
docs/middleware/timeout.md(4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
docs/**
📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)
Review and update the contents of the
docsfolder if necessary when modifying code
Files:
docs/middleware/timeout.md
🧠 Learnings (2)
📓 Common learnings
Learnt from: sixcolors
PR: gofiber/fiber#3446
File: docs/middleware/logger.md:44-44
Timestamp: 2025-05-13T00:19:16.407Z
Learning: In documentation files for the Fiber framework, code examples are often partial and don't repeat import statements that were shown in earlier examples, focusing instead on demonstrating specific usage patterns.
📚 Learning: 2024-11-10T23:44:13.704Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
Applied to files:
docs/middleware/timeout.md
🔇 Additional comments (5)
docs/middleware/timeout.md (5)
26-31: LGTM: clear intro for the basic example
65-67: LGTM: per-route wrapping with explicit timeout
89-89: LGTM: clearer heading
108-119: LGTM: robust timer handling patternGood use of time.NewTimer with proper stop/drain.
122-122: LGTM: heading capitalization is consistent
Summary
app.Use, which will panicFixes #3674