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 metric for request duration #747

Merged
merged 1 commit into from
Feb 11, 2025

Conversation

m-Peter
Copy link
Collaborator

@m-Peter m-Peter commented Feb 3, 2025

Closes: #739

Description

The HttpHandler middleware seemed to not be working properly for all cases, as can be seen in the linked issue above. So we remove it and move the request duration metric to the RPC server.


For contributor use:

  • Targeted PR against master branch
  • Linked to Github issue with discussion and accepted design OR link to spec that describes this work.
  • Code follows the standards mentioned here.
  • Updated relevant documentation
  • Re-reviewed Files changed in the Github PR explorer
  • Added appropriate labels

Summary by CodeRabbit

  • New Features
    • Enhanced request logging now captures detailed method and performance metrics.
  • Refactor
    • Streamlined request handling logic to improve efficiency.
  • Chores
    • Removed an outdated metrics tracking component.

Copy link
Contributor

coderabbitai bot commented Feb 3, 2025

Walkthrough

The changes update the HTTP request handling in the server by introducing a new variable to capture the JSON-RPC method from the request body. The conditional logic is streamlined to consolidate checks for a valid HTTP handler and path, while integrating request duration measurements tied to the extracted method. Additionally, the entire metrics middleware in metrics/handler.go has been removed, consolidating metrics collection into the updated server logic.

Changes

File(s) Change Summary
api/server.go Added requestMethod variable in ServeHTTP; consolidated condition for handler/path checks; added duration measurement with h.collector.MeasureRequestDuration(start, requestMethod).
metrics/handler.go Removed entire file including HttpHandler, NewMetricsHandler, ServeHTTP, and extractMethod—eliminating the previous HTTP middleware implementation for metrics collection.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant Collector
    Client->>Server: HTTP Request (with JSON body)
    Server->>Server: Extract JSON-RPC method (requestMethod)
    Server->>Collector: Measure request duration using requestMethod
    Server->>Client: Return HTTP Response
Loading

Assessment against linked issues

Objective Addressed Explanation
Investigate metrics error when extracting JSON-RPC method name [#739]

Possibly related PRs

Suggested labels

Technical Debt, Chore

Suggested reviewers

  • peterargue
  • zhangchiqing
  • janezpodhostnik

Poem

Hoppin' through the code so light,
I found new logs that shine so bright.
A fresh method captured every beat,
While old handlers hopped out of sight.
Cheers from a rabbit, coding with delight!


📜 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 5c8b24e and eb5b592.

📒 Files selected for processing (2)
  • api/server.go (2 hunks)
  • metrics/handler.go (0 hunks)
💤 Files with no reviewable changes (1)
  • metrics/handler.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/server.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test

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.

@m-Peter m-Peter changed the title Refactor metric for request duration and remove metrics HttpHandler middleware Refactor metric for request duration Feb 3, 2025
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: 0

🔭 Outside diff range comments (1)
api/server.go (1)

250-272: Add request body size limit to prevent memory issues.

The code reads the entire request body into memory without any size limits. This could lead to memory exhaustion if a malicious client sends a very large request.

Consider adding a size limit to the request body reader:

-	if b, err := io.ReadAll(r.Body); err == nil {
+	maxBodySize := int64(10 * 1024 * 1024) // 10MB limit
+	if b, err := io.ReadAll(io.LimitReader(r.Body, maxBodySize)); err == nil {
🧹 Nitpick comments (1)
api/server.go (1)

289-299: Improve error handling and context propagation.

The request duration measurement could be enhanced in several ways:

  1. Error handling for metric collection is missing
  2. Request context is not propagated to the metric collection

Consider these improvements:

 if h.httpHandler != nil && checkPath(r, "") {
 	start := time.Now()
+	ctx := r.Context()
 
 	h.httpHandler.ServeHTTP(logW, r)
 
 	if eth.IsValidMethod(requestMethod) {
-		h.collector.MeasureRequestDuration(start, requestMethod)
+		if err := h.collector.MeasureRequestDuration(ctx, start, requestMethod); err != nil {
+			h.logger.Error().Err(err).Msg("failed to measure request duration")
+		}
 	}
 
 	return
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0b5077a and 0c38346.

📒 Files selected for processing (2)
  • api/server.go (2 hunks)
  • metrics/handler.go (0 hunks)
💤 Files with no reviewable changes (1)
  • metrics/handler.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test
  • GitHub Check: Lint

@m-Peter m-Peter force-pushed the mpeter/refactor-request-duration-metric branch from 0c38346 to 5c8b24e Compare February 6, 2025 10:23
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 0c38346 and 5c8b24e.

📒 Files selected for processing (2)
  • api/server.go (2 hunks)
  • metrics/handler.go (0 hunks)
💤 Files with no reviewable changes (1)
  • metrics/handler.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test
🔇 Additional comments (2)
api/server.go (2)

251-251: LGTM!

The variable declaration is well-scoped and follows good initialization practices.


257-269: LGTM!

The method extraction and logging logic is robust with proper validation and type safety.

Comment on lines +289 to 299
if h.httpHandler != nil && checkPath(r, "") {
start := time.Now()

h.httpHandler.ServeHTTP(logW, r)

if eth.IsValidMethod(requestMethod) {
h.collector.MeasureRequestDuration(start, requestMethod)
}

return
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize request duration measurement.

The current implementation has a few areas for improvement:

  1. Request duration includes network latency as it's measured after ServeHTTP.
  2. The IsValidMethod check is redundant since requestMethod is only set for valid methods.
  3. Invalid method requests are not measured, which could skew metrics.

Consider this improved implementation:

 if h.httpHandler != nil && checkPath(r, "") {
   start := time.Now()
 
   h.httpHandler.ServeHTTP(logW, r)
 
-  if eth.IsValidMethod(requestMethod) {
-    h.collector.MeasureRequestDuration(start, requestMethod)
-  }
+  // Measure duration for all requests, using method if available
+  method := requestMethod
+  if method == "" {
+    method = "invalid_method"
+  }
+  h.collector.MeasureRequestDuration(start, method)
 
   return
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if h.httpHandler != nil && checkPath(r, "") {
start := time.Now()
h.httpHandler.ServeHTTP(logW, r)
if eth.IsValidMethod(requestMethod) {
h.collector.MeasureRequestDuration(start, requestMethod)
}
return
}
if h.httpHandler != nil && checkPath(r, "") {
start := time.Now()
h.httpHandler.ServeHTTP(logW, r)
// Measure duration for all requests, using method if available
method := requestMethod
if method == "" {
method = "invalid_method"
}
h.collector.MeasureRequestDuration(start, method)
return
}

@m-Peter m-Peter force-pushed the mpeter/refactor-request-duration-metric branch from 5c8b24e to eb5b592 Compare February 11, 2025 11:38
@m-Peter m-Peter merged commit 0e51508 into main Feb 11, 2025
2 checks passed
@m-Peter m-Peter deleted the mpeter/refactor-request-duration-metric branch February 11, 2025 11:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Investigate metrics error when extracting JSON-RPC method name
2 participants