Skip to content

feat: introduce common http client for reporting - #5669

Merged
lvrach merged 22 commits into
masterfrom
feat.reporting-client
Apr 15, 2025
Merged

lvrach merged 22 commits into
masterfrom
feat.reporting-client

Conversation

@lvrach

@lvrach lvrach commented Mar 31, 2025 •

Copy link
Copy Markdown
Member

Description

Motivation

To introduce a cost attribution metric for all reporting services. I've noticed coupling and discrepancies between different client implementations, making it hard to test the changes and requiring redundant effort.

First, I attempted a more aggressive refactor effort.

However, after discussing this with the PipeOps team, we decided to take a more cynical approach.

Plan

  • Introduce a common client for all communication with the reporting service
  • Support switching to the new common client via a single feature flag
  • Intention to remove old client/send method in the next release.

It was also decided

  • To break the backward compatibility with metrics exposed by old clients. This might break some dashboards, but no alert should be impacted.

Changes

Metric names

New metrics:

const (
	StatRequestTotalBytes     = "reporting_client_http_request_total_bytes"
	StatTotalDurationsSeconds = "reporting_client_http_total_durations_seconds"
	StatRequestLatency        = "reporting_client_http_request_latency"
	StatHttpRequest           = "reporting_client_http_request"
)

Deprecated metrics -- will no longer work after switching to the common client:

	f.reqLatency = f.stats.NewTaggedStat("reporting_flusher_http_request_duration_seconds", stats.TimerType, tags)
	f.reqCount = f.stats.NewTaggedStat("reporting_flusher_http_requests_total", stats.CountType, tags)
	f.sentBytes = f.stats.NewTaggedStat("reporting_flusher_sent_bytes", stats.HistogramType, tags)
	
        edr.stats.NewTaggedStat("error_detail_reporting_http_request", stats.CountType, httpStatTags).Increment()
	edr.edReportingRequestLatency = edr.stats.NewTaggedStat("error_detail_reporting_request_latency", stats.TimerType, tags)

Metric labels

Changes:

  • workspaceID -- REMOVED will no longer be captured by the client, as it is not relevant when multiple workspaces are batch to a single call
  • clientName -- RENAMED --> module
  • endpoint --> ADDED: reporting URL
  • path --> ADDED: reporting path/service

region query param

Region query parameter, used only by some reporting clients has been removed.

Based on team feedback this query param was used temporary for multi region transition and is no longer needed.

REPORTING_URL env var

REPORTING_URL now always defaults to "https://reporting.dev.rudderlabs.com"

Some of the existing clients defaulted to https://reporting.rudderstack.com/

To Be Discussed

  • Should we use a default value for REPORTING_URL, would we rather fail if REPORTING_URL is not configured ? It could be a privacy risk for EU customers if reporting us endpoint is configured accidentally.
  • Should we introduce .Ping() method and corresponding endpoint ?

Next steps

  1. Rollout useCommonClient flag in production
  2. Update Grafana dashboards as need
  3. Remove all deprecated code (most of it is marked with commends`
  4. Start the work for unifying reporting logic

Linear Ticket

Resolves PRI-168

https://linear.app/rudderstack/issue/PRI-168/introduce-reporting-client-metrics-in-rudder-server-for-cost

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

@lvrach
lvrach marked this pull request as ready for review April 1, 2025 14:41
Comment thread enterprise/reporting/reporting.go Resolved
Comment thread enterprise/reporting/reporting.go Resolved
Comment thread enterprise/reporting/flusher/flusher.go Resolved
Comment thread enterprise/reporting/flusher/flusher.go Resolved
Comment thread enterprise/reporting/flusher/flusher.go Resolved
Comment thread enterprise/reporting/error_reporting.go Resolved
Comment thread enterprise/reporting/client/client.go Resolved
@lvrach
lvrach requested a review from Copilot April 2, 2025 10:07

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull Request Overview

This PR introduces a common HTTP client for reporting, enabling a centralized mechanism for sending reporting metrics while deprecating older client implementations. Key changes include:

  • Exporting the aggregation bucket function (GetAggregationBucketMinute) for broader reuse.
  • Integrating the new common client behind a feature flag (useCommonClient) across various reporting modules.
  • Updating tests and factory methods to reflect these changes and adding deprecation notices for legacy code.

Reviewed Changes

Copilot reviewed 9 out of 11 changed files in this pull request and generated no comments.

Show a summary per file
File Description
enterprise/reporting/utils.go Renamed internal function to exported GetAggregationBucketMinute.
enterprise/reporting/util_test.go Updated tests to call GetAggregationBucketMinute instead of its internal name.
enterprise/reporting/reporting_test.go Updated tests to use GetAggregationBucketMinute.
enterprise/reporting/reporting.go Integrated useCommonClient flag and commonClient for metric reporting.
enterprise/reporting/flusher/flusher.go Updated to use commonClient and introduced deprecation warnings.
enterprise/reporting/flusher/factory.go Passed the new commonClient to the flusher during instantiation.
enterprise/reporting/error_reporting.go Integrated commonClient for error reporting with deprecation notes.
enterprise/reporting/client/client_test.go Added tests to validate common client behavior and metrics capture.
enterprise/reporting/client/client.go Introduced the new client implementation with backoff and metric recording.
Files not reviewed (2)
  • enterprise/reporting/client/testdata/send_error_metric.json: Language not supported
  • enterprise/reporting/client/testdata/send_metric.json: Language not supported
Comments suppressed due to low confidence (2)

enterprise/reporting/client/client.go:114

  • [nitpick] Consider adding a space after 'statusCode:' in the error message format to improve readability (e.g. 'statusCode: %d error: %v').
err = fmt.Errorf(`received response: statusCode:%d error:%v`, resp.StatusCode, string(respBody))

enterprise/reporting/utils.go:35

  • [nitpick] Since GetAggregationBucketMinute is now exported, consider adding a GoDoc comment to explain its purpose and usage.
func GetAggregationBucketMinute(timeMs, intervalMs int64) (int64, int64) {

@lvrach

lvrach commented Apr 2, 2025

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Apr 2, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change set introduces a new Go package for managing reporting via a dedicated client. The new client package provides a Client struct with methods for sending metrics using exponential backoff and detailed error handling. Updates in error reporting, flusher, and default reporting components integrate this new client, replacing the older URL-based approaches. Additionally, utility functions have been renamed to be publicly accessible, with tests updated accordingly.

Changes

File(s) Change Summary
.../client/client.go, .../client/client_test.go Introduced a new client package with a Client struct and associated methods (New, Send, getTags, isHTTPRequestSuccessful) to handle metric reporting. Added unit tests to verify correct payload construction, error handling, and retry logic.
.../error_reporting.go Updated ErrorDetailReporter by adding commonClient and useCommonClient fields. Modified the sendMetric method to conditionally use the new client instead of the previous HTTP client.
.../flusher/factory.go, .../flusher/flusher.go Refactored flusher instantiation to use a new commonClient instead of a URL. Updated the NewFlusher function signature and internal logic to support client-based reporting, including conditional usage between commonClient and the legacy HTTP client.
.../reporting.go, .../reporting_test.go Enhanced DefaultReporter by adding useCommonClient and commonClient fields. Modified sendMetric to remove the netClient parameter and use the new client for metric transmission. Adjusted aggregation function calls accordingly.
.../util_test.go, .../utils.go Renamed the function getAggregationBucketMinute to GetAggregationBucketMinute to make it exported. Updated all references in both tests and source files to use the new function name.
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 plan to trigger planning for file edits and PR creation.
  • @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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
enterprise/reporting/utils.go (1)

35-35: Function exported without documentation

The function GetAggregationBucketMinute has been exported (made public) but lacks Go doc comments. Since this function is now part of the public API, it should have comprehensive documentation explaining its purpose, parameters, return values, and any potential edge cases.

Consider adding proper documentation:

+// GetAggregationBucketMinute calculates the start and end of a time bucket based on the provided time and interval.
+// It ensures that the interval is a factor of 60 to maintain alignment with hourly buckets.
+// Parameters:
+//   - timeMs: The time in milliseconds to calculate the bucket for
+//   - intervalMs: The interval in milliseconds for the bucket size
+// Returns:
+//   - bucketStart: The start time of the bucket in milliseconds
+//   - bucketEnd: The end time of the bucket in milliseconds
 func GetAggregationBucketMinute(timeMs, intervalMs int64) (int64, int64) {
enterprise/reporting/client/client_test.go (2)

335-340: Inconsistent tag naming in TestClient5xx

In TestClient5xx, the HTTP metric tags use workspaceId and clientName, while other tests use module instead of clientName. This inconsistency could cause confusion and potentially affect metrics filtering.

Apply this diff to use consistent tag naming:

expectedHttpTags := stats.Tags{
-	"workspaceId": "test-workspace",
-	"clientName":  "test-client",
+	"path":       string(client.PathMetrics),
+	"module":     "test-client",
	"instanceId":  "test-instance",
	"endpoint":    serverURL.Host,
	"status":      "500",
}

30-168: Consider extracting repeated test setup code

The setup code (creating test server, stats store, config) is duplicated across test functions. This could be refactored into helper functions to improve maintainability.

Consider refactoring to something like:

func setupTestClient(t *testing.T, serverHandler http.HandlerFunc) (*httptest.Server, *client.Client, *memstats.Stats, *url.URL) {
    // Create a test server
    server := httptest.NewServer(serverHandler)
    
    // Create stats store
    statsStore, err := memstats.New()
    require.NoError(t, err)
    
    // Create a test config
    conf := config.New()
    conf.Set("INSTANCE_ID", "test-instance")
    conf.Set("clientName", "test-client")
    conf.Set("REPORTING_URL", server.URL)
    
    // Create the client
    c := client.New(client.PathMetrics, conf, logger.NOP, statsStore)
    
    // Parse server URL
    serverURL, _ := url.Parse(server.URL)
    
    return server, c, statsStore, serverURL
}
enterprise/reporting/flusher/factory.go (1)

60-60: Passing both reportingURL and commonClient
Even though you now pass commonClient, you still provide reportingURL. Confirm it's required during the transition or remove it if unneeded.

enterprise/reporting/client/client.go (1)

41-52: Consider providing a configurable transport or using the default transport.
A prior comment in an older commit mentioned removing or making the custom transport configurable. Currently, the code assigns a new http.Client{Timeout: ...} without allowing for any custom transport or configuration overrides. If advanced configurations, security features, timeouts, or choice of transport are desired, consider exposing these options.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ed7a11 and 6f8f4d9.

⛔ Files ignored due to path filters (2)
  • enterprise/reporting/client/testdata/send_error_metric.json is excluded by !**/*.json
  • enterprise/reporting/client/testdata/send_metric.json is excluded by !**/*.json
📒 Files selected for processing (9)
  • enterprise/reporting/client/client.go (1 hunks)
  • enterprise/reporting/client/client_test.go (1 hunks)
  • enterprise/reporting/error_reporting.go (6 hunks)
  • enterprise/reporting/flusher/factory.go (3 hunks)
  • enterprise/reporting/flusher/flusher.go (7 hunks)
  • enterprise/reporting/reporting.go (9 hunks)
  • enterprise/reporting/reporting_test.go (3 hunks)
  • enterprise/reporting/util_test.go (5 hunks)
  • enterprise/reporting/utils.go (2 hunks)
🧰 Additional context used
🧬 Code Definitions (5)
enterprise/reporting/reporting_test.go (1)
enterprise/reporting/utils.go (1)
  • GetAggregationBucketMinute (35-46)
enterprise/reporting/client/client_test.go (2)
enterprise/reporting/client/client.go (5)
  • New (55-68)
  • PathMetrics (34-34)
  • StatRequestTotalBytes (27-27)
  • StatTotalDurationsSeconds (28-28)
  • StatHttpRequest (30-30)
enterprise/reporting/utils.go (1)
  • GetAggregationBucketMinute (35-46)
enterprise/reporting/error_reporting.go (1)
enterprise/reporting/client/client.go (3)
  • Client (42-52)
  • New (55-68)
  • PathRecordErrors (35-35)
enterprise/reporting/util_test.go (1)
enterprise/reporting/utils.go (1)
  • GetAggregationBucketMinute (35-46)
enterprise/reporting/flusher/factory.go (2)
enterprise/reporting/client/client.go (1)
  • New (55-68)
enterprise/reporting/flusher/flusher.go (1)
  • NewFlusher (79-132)
🔇 Additional comments (40)
enterprise/reporting/utils.go (1)

66-66: Function call updated correctly

The function call has been properly updated to use the newly exported function name.

enterprise/reporting/client/client_test.go (2)

28-347: Well-structured test suite for the new HTTP client

The test file provides good coverage of the client functionality, including testing successful requests, error metrics, and server error handling. This aligns well with the PR objective of introducing a common HTTP client for reporting.


58-58: Good use of the exported function

The test correctly uses the newly exported GetAggregationBucketMinute function, which supports the refactoring goal of making this function available across packages.

enterprise/reporting/reporting_test.go (3)

188-188: Function call correctly updated

The function call has been properly updated to use the newly exported function name GetAggregationBucketMinute.


289-289: Function call correctly updated

The function call has been properly updated to use the newly exported function name GetAggregationBucketMinute.


369-369: Function call correctly updated

The function call has been properly updated to use the newly exported function name GetAggregationBucketMinute.

enterprise/reporting/util_test.go (5)

46-46: Function call correctly updated

The function call has been properly updated to use the newly exported function name GetAggregationBucketMinute.


106-106: Function call correctly updated

The function call has been properly updated to use the newly exported function name GetAggregationBucketMinute.


141-141: Function call correctly updated

The function call has been properly updated to use the newly exported function name GetAggregationBucketMinute.


181-181: Function call correctly updated

The function call has been properly updated to use the newly exported function name GetAggregationBucketMinute.


221-221: Function call correctly updated

The function call has been properly updated to use the newly exported function name GetAggregationBucketMinute.

enterprise/reporting/flusher/factory.go (3)

17-17: New import for client package
No issues adding this import. This aligns with the migration plan to the new client-based approach.


48-49: Initialize the commonClient
The instantiation looks correct. Ensure client.PathTrackedUsers is indeed the intended endpoint.

Would you like to verify usage references with a quick search script?


50-50: DEPRECATED comment
Having a clear deprecation note is helpful. Remember to remove reportingURL once migration is complete.

enterprise/reporting/error_reporting.go (8)

30-30: New import for client
Import aligns with the newly introduced common client usage.


99-100: Added fields useCommonClient and commonClient
This is consistent with the transition to the new client-based error reporting.


109-109: DEPRECATED comment
Good forward-planning. Be sure to remove the old logic once the feature flag usage is fully phased out.


111-112: Instantiation of netClient
No issues noted. This fallback is still needed as long as the old code path remains.


114-114: useCommonClient configuration
Loading the feature flag looks correct. Ensure the associated config key is documented.


168-169: Struct field assignments
Assigning both useCommonClient and commonClient is consistent with your migration approach.


757-757: DEPRECATED note for sendMetric
Clear comment. Remove the obsolete path when fully migrated to commonClient.


758-760: Conditional usage of commonClient
Switching to commonClient.Send is consistent with the new approach. Code looks good.

enterprise/reporting/reporting.go (6)

29-29: New import for client
No concerns. This import is part of the new reporting client setup.


85-86: Adding useCommonClient and commonClient to DefaultReporter
This pairs well with the existing config-based approach.


95-95: Loading useCommonClient from config
Straightforward feature flag usage. Consider ensuring default values are set in config documents.


529-529: bucketStart, bucketEnd usage
Using GetAggregationBucketMinute(reportedAt, aggregationIntervalMin) ensures consistent bucket boundaries.


601-601: DEPRECATED comment
Good approach to mark the old path for eventual removal. Keep an eye on timeline to avoid confusion later.


603-605: Conditional usage of commonClient
The fallback logic is clear. Good job ensuring an easy transition from the old client path.

enterprise/reporting/flusher/flusher.go (8)

23-23: New import for client
No issue. This is consistent with other migrations to the common client.


35-38: New fields in Flusher struct
Adding httpClient, useCommonClient, and commonClient supports the fallback approach.


75-76: DEPRECATED reportingURL field
Deprecation note is clear. Remember to remove once the feature-flag approach is stable.


79-79: Updated NewFlusher signature
Accepting both reportingURL and commonClient is fine for a phased migration.


95-96: Creating httpClient and loading useCommonClient
Fallback is properly initialized for the old path.


120-126: Setting struct fields in Flusher
Storing useCommonClient and commonClient along with the DEPRECATED reportingURL is consistent with your transitional plan.


389-391: Redirecting to commonClient
The code properly checks useCommonClient before calling f.commonClient.Send.


404-404: Fallback to f.httpClient
Retaining this logic preserves backward compatibility. No issues.

enterprise/reporting/client/client.go (4)

1-19: Looks good on the imports and package structure.
No immediate issues are detected here. The imports are appropriate, and the overall package layout seems coherent for introducing a centralized reporting client.


70-79: URL concatenation looks correct.
Your usage of url.JoinPath to construct the final endpoint is idiomatic and helps prevent path concatenation errors. This segment looks well-structured and maintainable.


81-126: Robust error handling with exponential backoff.
The exponential backoff usage is a strong approach to handling transient network issues. Logging warnings on retries and errors on failure is sufficiently informative. The metrics capture (request latency, total bytes, etc.) is also comprehensive. Great implementation!


140-146: Revisit handling of 4xx status codes as “successful.”
Currently, isHTTPRequestSuccessful returns true for status codes 400–499 (except 429). This means 400, 404, etc. will not cause retries nor surface as errors, which may mask problems in truly failed requests. Verify if you intentionally consider these codes “successful.” If not, consider handling them differently.

Do you want me to check other call sites to confirm that this is the intended behavior for 4xx responses (e.g., 404, 401) and see if we need to mark them as unsuccessful?

@lvrach
lvrach requested a review from Copilot April 2, 2025 11:09

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull Request Overview

This PR introduces a common HTTP client for all reporting services to centralize metric reporting, reduce duplication, and simplify the migration away from legacy implementations. Key changes include:

  • Renaming and exporting the aggregation bucket function (getAggregationBucketMinute → GetAggregationBucketMinute) and updating related tests.
  • Integrating a new common client behind a feature flag that routes HTTP requests for reporting.
  • Marking legacy code paths as deprecated and providing migration indicators throughout reporting, flusher, and error reporting files.

Reviewed Changes

Copilot reviewed 9 out of 11 changed files in this pull request and generated no comments.

Show a summary per file
File Description
enterprise/reporting/utils.go Exports the aggregation bucket function for broader usage.
enterprise/reporting/util_test.go Updates tests to reflect the new exported function name.
enterprise/reporting/reporting_test.go Updates function calls to use the new exported aggregation bucket function.
enterprise/reporting/reporting.go Integrates common client logic with feature flag checks and deprecation comments for legacy methods.
enterprise/reporting/flusher/flusher.go Refactors client usage by renaming variables and adding a commonClient field; deprecates reportingURL.
enterprise/reporting/flusher/factory.go Passes the new commonClient to the flusher.
enterprise/reporting/error_reporting.go Integrates commonClient support and marks legacy HTTP client usage as deprecated.
enterprise/reporting/client/client_test.go Introduces comprehensive tests for the new reporting client.
enterprise/reporting/client/client.go Implements the new common HTTP client with metrics reporting and backoff support.
Files not reviewed (2)
  • enterprise/reporting/client/testdata/send_error_metric.json: Language not supported
  • enterprise/reporting/client/testdata/send_metric.json: Language not supported
Comments suppressed due to low confidence (2)

enterprise/reporting/flusher/flusher.go:76

  • [nitpick] The deprecated field 'reportingURL' is still present alongside the new 'commonClient' and 'httpClient' fields, which may cause confusion. Consider consolidating or removing the deprecated field once the migration is complete.
reportingURL string

enterprise/reporting/client/client.go:159

  • [nitpick] Consider adding an inline comment inside 'isHTTPRequestSuccessful' to explain why status code 429 is treated as unsuccessful, improving clarity for future maintainers.
func (f *Client) isHTTPRequestSuccessful(status int) bool {

@lvrach
lvrach requested a review from atzoum April 2, 2025 11:10
@codecov

codecov Bot commented Apr 2, 2025 •

Copy link
Copy Markdown

Codecov Report

Attention: Patch coverage is 81.39535% with 24 lines in your changes missing coverage. Please review.

Project coverage is 77.08%. Comparing base (35fd4d2) to head (d1a1f1b).
Report is 6 commits behind head on master.

Files with missing lines Patch % Lines
enterprise/reporting/client/client.go 83.14% 10 Missing and 5 partials ⚠️
enterprise/reporting/error_reporting.go 66.66% 3 Missing ⚠️
enterprise/reporting/flusher/flusher.go 76.92% 2 Missing and 1 partial ⚠️
enterprise/reporting/reporting.go 75.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5669      +/-   ##
==========================================
+ Coverage   77.00%   77.08%   +0.07%     
==========================================
  Files         487      488       +1     
  Lines       66211    66328     +117     
==========================================
+ Hits        50988    51131     +143     
+ Misses      12448    12427      -21     
+ Partials     2775     2770       -5     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lvrach
lvrach requested a review from satishrudderstack April 3, 2025 08:07
@ktgowtham
ktgowtham requested a review from itsmihir April 3, 2025 11:36
Comment thread enterprise/reporting/client/client.go Resolved

@itsmihir itsmihir left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, please address the issue where 4xx status codes are being treated as successful

reportingServiceURL = strings.TrimSuffix(reportingServiceURL, "/")

return &Client{
httpClient: &http.Client{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

one reason why we would need to override the default transport is for tuning MaxIdleConnsPerHost which by default is 2. This client is going to open connections to a single host for multiple components, correct?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Here are the differences between: http.DefaultTransport (default) and &Transport{} (zero)

Property Default zero
Proxy useEnv no proxy
DialContext.Timeout 30s no timeout
DialContext.KeepAlive 30s 15s
ForceAttemptHTTP2 true false
MaxIdleConns 100 no limit
IdleConnTimeout 90s no timeout
TLSHandshakeTimeout 10s no timeout
ExpectContinueTimeout 10s no timeout

When it comes to MaxIdleConnsPerHost the both have the same behaviour, given the client only connected to a single host. MaxIdleConnsPerHost should effectively overrule MaxIdleConns when it comes to idle connections.

Examining the differences between them. I believe that using zero transport, is almost always a bad idea.

If we need to change some of the settings is better to do:

transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConnsPerHost = 10
&http.Client{Transport: transport}

It remains a question to me, what was the actual intention behind the following :

	tr := &http.Transport{}
	netClient := &http.Client{Transport: tr, Timeout: config.GetDuration("HttpClient.reporting.timeout", 60, time.Second)}

As nothing is override on Transport

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This client is going to open connections to a single host for multiple components, correct?

A single host is going to be used for all reporting-related communication.

Three instances ofreporting/client.Client going to be used. Depending on the component, a different number of concurrent requests is expected, up to Reporting.maxConcurrentRequests (32 by default)

Overall, it looks like many (30) connections are open, due to concurrency and then closed due to MaxIdleConnsPerHost.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One other option would be to create a transport of your own like here.
Unless you are pretty confident that the DefaultTransport remains unmodified and will always be of type http.Transport.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I find the change of http.DefaultTransport type.

Yes, we cannot exclude the probability of http.DefaultTransport changing. I trust the go dev team would be careful with the changes, most probably the change would be for better rather than worse.

For instance, the might introduce a method and add e sensible default value. You might missed it if you create your own every time.

I would be open to creating our default transport in rudder go kit and have our http client clone and use that.

@lvrach
lvrach merged commit 594bdce into master Apr 15, 2025
@lvrach
lvrach deleted the feat.reporting-client branch April 15, 2025 07:56
Sidddddarth pushed a commit that referenced this pull request Apr 29, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.48.0-rc.2](v1.47.0...v1.48.0-rc.2)
(2025-04-28)


### Features

* introduce common http client for reporting
([#5669](#5669))
([594bdce](594bdce))
* populate bytesPerTable for warehouse process API
([#5737](#5737))
([fd46379](fd46379))
* query load files using upload_id instead of staging_file_id
([#5700](#5700))
([3749ba9](3749ba9))
* support for creating upload v2 notifier jobs
([#5729](#5729))
([dbc830f](dbc830f))
* use header augmenter for router transformer client
([#5640](#5640))
([3749ba9](3749ba9))


### Bug Fixes

* httplb client doesn't respect connection limits
([#5773](#5773))
([ef0a15e](ef0a15e))
* jobsdb payload limit used compressed column sizes instead of actual
payload length
([#5723](#5723))
([c711b25](c711b25))
* race condition in table schema updates causing incorrect schema to be
saved ([#5756](#5756))
([f5ab51a](f5ab51a))
* use copy to load table in append mode for
redshift([#5743](#5743))
([877da25](877da25))
* use warehouse transformer event instead of using processor event
([#5764](#5764))
([f51e260](f51e260))
* version downgrade for databricks-sql-go to 1.6.1
([#5741](#5741))
([c711b25](c711b25))
* warehouse extracting messageId and receivedAt from event payload
([#5757](#5757))
([f5ab51a](f5ab51a))


### Miscellaneous

* add destination type in metrics
([#5727](#5727))
([fa38f34](fa38f34))
* **batchrouter:** limiter cleanup adjust stats and use harmonized
config
([#5783](#5783))
([96aba9d](96aba9d))
* change jobsdb payload column type default to text
([#5746](#5746))
([0f436e7](0f436e7))
* configure pubsub publish settings
([#5755](#5755))
([e481992](e481992))
* **deps:** bump google.golang.org/api from 0.228.0 to 0.229.0 in the
frequent group
([#5734](#5734))
([32854cc](32854cc))
* **deps:** bump the frequent group with 3 updates
([#5769](#5769))
([12b7d96](12b7d96))
* disable transformer compaction by default
([#5766](#5766))
([c504aa0](c504aa0))
* granular configuration for adaptive rate limiting
([#5739](#5739))
([c711b25](c711b25))
* improve BRT performance
([#5730](#5730))
([61642c8](61642c8))
* **jobsdb:** remove jobMinRowsMigrateThres configuration option
([#5763](#5763))
([5d2fae9](5d2fae9))
* processor UT mirroring
([#5710](#5710))
([f4f056c](f4f056c))
* remove payload logging
([#5447](#5447))
([8e08c11](8e08c11))
* trim down tracking plan validation payload
([#5749](#5749))
([e711579](e711579))
* use reloadable limiters
([#5744](#5744))
([d344d40](d344d40))
* use transformer compaction by default
([#5740](#5740))
([53792f2](53792f2))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
Sidddddarth pushed a commit that referenced this pull request Apr 29, 2025
🤖 I have created a release *beep* *boop*
---


##
[1.48.0](v1.47.0...v1.48.0)
(2025-04-28)


### Features

* introduce common http client for reporting
([#5669](#5669))
([594bdce](594bdce))
* populate bytesPerTable for warehouse process API
([#5737](#5737))
([fd46379](fd46379))
* query load files using upload_id instead of staging_file_id
([#5700](#5700))
([3749ba9](3749ba9))
* support for creating upload v2 notifier jobs
([#5729](#5729))
([dbc830f](dbc830f))
* use header augmenter for router transformer client
([#5640](#5640))
([3749ba9](3749ba9))


### Bug Fixes

* httplb client doesn't respect connection limits
([#5773](#5773))
([ef0a15e](ef0a15e))
* jobsdb payload limit used compressed column sizes instead of actual
payload length
([#5723](#5723))
([c711b25](c711b25))
* race condition in table schema updates causing incorrect schema to be
saved ([#5756](#5756))
([f5ab51a](f5ab51a))
* use copy to load table in append mode for
redshift([#5743](#5743))
([877da25](877da25))
* use warehouse transformer event instead of using processor event
([#5764](#5764))
([f51e260](f51e260))
* version downgrade for databricks-sql-go to 1.6.1
([#5741](#5741))
([c711b25](c711b25))
* warehouse extracting messageId and receivedAt from event payload
([#5757](#5757))
([f5ab51a](f5ab51a))


### Miscellaneous

* add destination type in metrics
([#5727](#5727))
([fa38f34](fa38f34))
* **batchrouter:** limiter cleanup adjust stats and use harmonized
config
([#5783](#5783))
([96aba9d](96aba9d))
* change jobsdb payload column type default to text
([#5746](#5746))
([0f436e7](0f436e7))
* configure pubsub publish settings
([#5755](#5755))
([e481992](e481992))
* **deps:** bump google.golang.org/api from 0.228.0 to 0.229.0 in the
frequent group
([#5734](#5734))
([32854cc](32854cc))
* **deps:** bump the frequent group with 3 updates
([#5769](#5769))
([12b7d96](12b7d96))
* disable transformer compaction by default
([#5766](#5766))
([c504aa0](c504aa0))
* granular configuration for adaptive rate limiting
([#5739](#5739))
([c711b25](c711b25))
* improve BRT performance
([#5730](#5730))
([61642c8](61642c8))
* **jobsdb:** remove jobMinRowsMigrateThres configuration option
([#5763](#5763))
([5d2fae9](5d2fae9))
* processor UT mirroring
([#5710](#5710))
([f4f056c](f4f056c))
* remove payload logging
([#5447](#5447))
([8e08c11](8e08c11))
* trim down tracking plan validation payload
([#5749](#5749))
([e711579](e711579))
* use reloadable limiters
([#5744](#5744))
([d344d40](d344d40))
* use transformer compaction by default
([#5740](#5740))
([53792f2](53792f2))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
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.

5 participants