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

refactor(server): improve logging and handle shutdown signals with ease #39

Merged
merged 2 commits into from
Dec 29, 2024

Conversation

mertssmnoglu
Copy link
Collaborator

@mertssmnoglu mertssmnoglu commented Dec 20, 2024

PR #11 missing task will be done with these changes.

  • Made error messages meaningful
  • The server can exit early if there is no request
  • Still handling graceful shutdown with 5 second context timeout

@mertssmnoglu mertssmnoglu added this to the v1.0 milestone Dec 20, 2024
@mertssmnoglu mertssmnoglu self-assigned this Dec 20, 2024
Copy link

coderabbitai bot commented Dec 20, 2024

Walkthrough

The pull request modifies the cmd/capture/main.go file, enhancing the server's shutdown handling and logging. A new function, gracefulShutdown, is introduced to manage the shutdown logic, which listens for termination signals and logs them. The previous inline shutdown logic is replaced with this function, improving code organization. Log messages during the shutdown process are updated for clarity, providing more context for server shutdown and listening errors, while the overall control flow remains intact.

Changes

File Change Summary
cmd/capture/main.go - Added function gracefulShutdown(srv *http.Server, timeout time.Duration) error
- Replaced inline shutdown logic with gracefulShutdown
- Updated shutdown log messages for clarity
- Improved error message context for server shutdown and listening errors

Poem

🐰 A Rabbit's Ode to Graceful Exits 🚪

With signals swift and logs so bright,
Our server dances through the night
Shutting down with gentle care,
No panic, just a message fair
A clean goodbye, both swift and light! 🌟

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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. (Beta)
  • @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

@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)
cmd/capture/main.go (1)

Server timeouts need configuration flexibility

The timeouts are currently hardcoded:

  • ReadHeaderTimeout: 5 seconds
  • Shutdown timeout: 5 seconds

These should be configurable via environment variables since:

  • The application already uses environment-based configuration (PORT, API_SECRET)
  • The Config struct in internal/config/config.go can be extended
  • Fixed timeout values may not suit all deployment scenarios

Recommendations:

  • Add timeout configuration to the Config struct
  • Use environment variables like READ_HEADER_TIMEOUT and SHUTDOWN_TIMEOUT
  • Provide sensible defaults (current 5-second values) when env vars are not set
🔗 Analysis chain

Line range hint 41-43: Verify timeout values for security implications

The implementation uses two different timeouts:

  1. ReadHeaderTimeout: 5 seconds for incoming requests
  2. Shutdown context timeout: 5 seconds for graceful shutdown

These values might need adjustment based on:

  • Production load characteristics
  • Average request processing time
  • Connection pool cleanup requirements

Also applies to: 61-62


Let me search for any configuration handling or environment variables that might be used for these timeouts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other timeout configurations in the codebase for consistency
rg -i 'timeout|duration' --type go

# Look for any existing configuration handling of these timeouts
ast-grep --pattern 'time.Second' 

Length of output: 278


Script:

#!/bin/bash
# Search for environment variables or configuration related to timeouts
rg -i "env|config.*timeout" --type go -A 3

# Look for any configuration structs or types
ast-grep --pattern 'type $_ struct {
  $$$
}'

Length of output: 3831

🧹 Nitpick comments (2)
cmd/capture/main.go (2)

58-58: LGTM! But will need adjustment

The improved log message is more descriptive and clearer. However, this line should be removed if you implement the suggested force shutdown changes, as the logging will be handled in the signal handling goroutine.


64-64: Consider enhancing error messages further

While the error messages have been improved, they could be even more informative:

-    log.Fatal("server shutdown error:", err)
+    log.Fatal("server shutdown error (timeout after 5s):", err)

-    log.Println("server has been shutdown.")
+    log.Println("server has been successfully shutdown.")

-    log.Fatalf("listen error: %s\n", srvErr)
+    log.Fatalf("failed to start server on port %s: %s\n", appConfig.Port, srvErr)

Also applies to: 69-69, 75-75

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 861c26c and 8f33ab3.

📒 Files selected for processing (1)
  • cmd/capture/main.go (1 hunks)

cmd/capture/main.go Outdated Show resolved Hide resolved
…ction

- When received a signal early exit if there is no request
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 (2)
cmd/capture/main.go (2)

54-54: Enhance error message with more context

While the error message is improved, consider adding more context about the server's address to help with debugging.

-log.Fatalf("listen error: %s\n", srvErr)
+log.Fatalf("failed to start server on %s: %v\n", srv.Addr, srvErr)

46-46: Consider making shutdown timeout configurable

The shutdown timeout is currently hardcoded to 5 seconds. Consider making this configurable through the application config to allow adjustment based on deployment requirements.

Suggested approach:

  1. Add ShutdownTimeout to the config structure
  2. Allow override via environment variable
  3. Provide a reasonable default value

Example:

 // in config/config.go
 type Config struct {
     Port       string
     APISecret  string
+    ShutdownTimeout time.Duration
 }

 func NewConfig(port, apiSecret string) *Config {
+    shutdownTimeout := 5 * time.Second
+    if timeout := os.Getenv("SHUTDOWN_TIMEOUT"); timeout != "" {
+        if d, err := time.ParseDuration(timeout); err == nil {
+            shutdownTimeout = d
+        }
+    }
     return &Config{
         Port:       port,
         APISecret:  apiSecret,
+        ShutdownTimeout: shutdownTimeout,
     }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f33ab3 and 94871a4.

📒 Files selected for processing (1)
  • cmd/capture/main.go (1 hunks)
🔇 Additional comments (1)
cmd/capture/main.go (1)

46-47: ⚠️ Potential issue

Force shutdown functionality is missing

While the graceful shutdown implementation is good, it doesn't fulfill the PR objective of handling force shutdown (repeated termination signals). The current implementation will not forcefully close the application on repeated signals.

Consider implementing the force shutdown logic as previously suggested:

 func main() {
     server := &http.Server{...}
     go serve(server)
-    if err := gracefulShutdown(server, 5*time.Second); err != nil {
-        log.Fatalln("graceful shutdown error", err)
+    if err := gracefulShutdown(server, 5*time.Second, true); err != nil {
+        log.Fatalln("shutdown error:", err)
     }
 }

-func gracefulShutdown(srv *http.Server, timeout time.Duration) error {
+func gracefulShutdown(srv *http.Server, timeout time.Duration, enableForceShutdown bool) error {
     quit := make(chan os.Signal, 1)
+    forceQuit := make(chan struct{})
+    shutdownCount := 0
     signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

+    if enableForceShutdown {
+        go func() {
+            for range quit {
+                shutdownCount++
+                if shutdownCount == 1 {
+                    log.Println("received exit signal, gracefully shutting down")
+                } else {
+                    log.Println("received second exit signal, forcing shutdown!")
+                    close(forceQuit)
+                    os.Exit(0)
+                }
+            }
+        }()
+    }

-    sig := <-quit
-    log.Printf("signal received: %v", sig)
+    select {
+    case sig := <-quit:
+        log.Printf("signal received: %v", sig)
+    case <-forceQuit:
+        return nil
+    }

Likely invalid or redundant comment.

cmd/capture/main.go Show resolved Hide resolved
@mertssmnoglu mertssmnoglu changed the title fix(server): improve shutdown logging and handle force shutdown refactor(server): improve logging and handle shutdown signals with ease Dec 22, 2024
@mertssmnoglu
Copy link
Collaborator Author

Tested it in various scenarios and it works as expected.

@mertssmnoglu mertssmnoglu merged commit 2f8f3f9 into develop Dec 29, 2024
2 checks passed
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.

1 participant