Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 35 additions & 14 deletions enterprise/reporting/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,37 @@ const (
)

const (
PathMetrics Path = "/metrics?version=v1"
PathRecordErrors Path = "/recordErrors"
PathTrackedUsers Path = "/trackedUser"
RouteMetrics Route = "/metrics?version=v1"
RouteRecordErrors Route = "/recordErrors"
RouteTrackedUsers Route = "/trackedUser"
)

type Path string
// Route contains the HTTP path and query string for the service.
type Route string

// URL returns the absolute URL for the route, given a base URL.
// * baseURL provides only the scheme, host, and port.
// * Route provides path and query parameters.
func (p Route) URL(baseURL string) (url.URL, error) {
u, err := url.Parse(baseURL)
if err != nil {
return url.URL{}, fmt.Errorf("parsing base URL: %w", err)
}

pathURL, err := url.Parse(string(p))
if err != nil {
return url.URL{}, fmt.Errorf("parsing service endpoint: %w", err)
}

u.Path = pathURL.Path
u.RawQuery = pathURL.RawQuery

return *u, nil
}

// Client handles sending metrics to the reporting service
type Client struct {
path Path
route Route
reportingServiceURL string

httpClient *http.Client
Expand Down Expand Up @@ -68,7 +89,7 @@ func backOffFromConfig(conf *config.Config) backoff.BackOff {
}

// New creates a new reporting client
func New(path Path, conf *config.Config, log logger.Logger, stats stats.Stats) *Client {
func New(path Route, conf *config.Config, log logger.Logger, stats stats.Stats) *Client {
reportingServiceURL := conf.GetString("REPORTING_URL", "https://reporting.dev.rudderlabs.com")
reportingServiceURL = strings.TrimSuffix(reportingServiceURL, "/")

Expand All @@ -78,7 +99,7 @@ func New(path Path, conf *config.Config, log logger.Logger, stats stats.Stats) *
},
reportingServiceURL: reportingServiceURL,
backoff: backOffFromConfig(conf),
path: path,
route: path,
instanceID: conf.GetString("INSTANCE_ID", "1"),
moduleName: conf.GetString("clientName", ""),
stats: stats,
Expand All @@ -92,15 +113,15 @@ func (c *Client) Send(ctx context.Context, payload any) error {
return err
}

u, err := url.JoinPath(c.reportingServiceURL, string(c.path))
u, err := c.route.URL(c.reportingServiceURL)
if err != nil {
return err
return fmt.Errorf("constructing URL for service endpoint (%q, %q): %w", c.route, c.reportingServiceURL, err)
}

o := func() error {
req, err := http.NewRequestWithContext(ctx, "POST", u, bytes.NewBuffer(payloadBytes))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewBuffer(payloadBytes))
if err != nil {
return err
return fmt.Errorf("constructing HTTP request: %w", err)
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
httpRequestStart := time.Now()
Expand All @@ -126,11 +147,11 @@ func (c *Client) Send(ctx context.Context, payload any) error {
defer func() { httputil.CloseResponse(resp) }()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading response body from reporting service: %q: %w", c.path, err)
return fmt.Errorf("reading response body: %q: %w", c.route, err)
}

if !c.isHTTPRequestSuccessful(resp.StatusCode) {
err = fmt.Errorf("received unexpected response from reporting service: %q: statusCode: %d body: %v", c.path, resp.StatusCode, string(respBody))
err = fmt.Errorf("received unexpected response: %q: statusCode: %d body: %v", c.route, resp.StatusCode, string(respBody))
}
return err
}
Expand All @@ -152,7 +173,7 @@ func (c *Client) getTags() stats.Tags {
"module": c.moduleName,
"instanceId": c.instanceID,
"endpoint": serverURL.Host,
"path": string(c.path),
"path": string(c.route),
}
}

Expand Down
165 changes: 156 additions & 9 deletions enterprise/reporting/client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ func TestClientSendMetric(t *testing.T) {
// Create a test server to mock the reporting service
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var err error

if r.URL.Path != "/metrics" {
w.WriteHeader(http.StatusNotFound)
t.Logf("received request with path: %s", r.URL.Path)
return
}

if r.URL.Query().Get("version") != "v1" {
w.WriteHeader(http.StatusBadRequest)
t.Logf("received request with version: %s", r.URL.Query().Get("version"))
return
}

receivedPayload, err = io.ReadAll(r.Body)
require.NoError(t, err)
payloadChan <- receivedPayload
Expand All @@ -53,9 +66,10 @@ func TestClientSendMetric(t *testing.T) {
conf.Set("INSTANCE_ID", "test-instance")
conf.Set("clientName", "test-client")
conf.Set("REPORTING_URL", server.URL)
conf.Set("Reporting.httpClient.backoff.maxRetries", 1)

// Create the client
c := client.New(client.PathMetrics, conf, logger.NOP, statsStore)
c := client.New(client.RouteMetrics, conf, logger.NOP, statsStore)

bucket, _ := reporting.GetAggregationBucketMinute(28017690, 10)

Expand Down Expand Up @@ -138,15 +152,15 @@ func TestClientSendMetric(t *testing.T) {
t.Run("ensure metrics are recorded", func(t *testing.T) {
// Expected tags for all metrics
expectedTags := stats.Tags{
"path": string(client.PathMetrics),
"path": string(client.RouteMetrics),
"module": "test-client",
"instanceId": instanceID,
"endpoint": serverURL.Host,
}

// Expected tags for HTTP metrics
expectedHttpTags := stats.Tags{
"path": string(client.PathMetrics),
"path": string(client.RouteMetrics),
"module": "test-client",
"instanceId": instanceID,
"endpoint": serverURL.Host,
Expand Down Expand Up @@ -196,7 +210,7 @@ func TestClientSendErrorMetric(t *testing.T) {
conf.Set("REPORTING_URL", server.URL)

// Create the client
c := client.New(client.PathMetrics, conf, logger.NOP, statsStore)
c := client.New(client.RouteMetrics, conf, logger.NOP, statsStore)

// Create sample event as json.RawMessage
sampleEvent := json.RawMessage(`{"event": "test_event", "properties": {"test": "value"}}`)
Expand Down Expand Up @@ -258,15 +272,15 @@ func TestClientSendErrorMetric(t *testing.T) {

// Expected tags for all metrics
expectedTags := stats.Tags{
"path": string(client.PathMetrics),
"path": string(client.RouteMetrics),
"module": "test-client",
"instanceId": "test-instance",
"endpoint": serverURL.Host,
}

// Expected tags for HTTP metrics
expectedHttpTags := stats.Tags{
"path": string(client.PathMetrics),
"path": string(client.RouteMetrics),
"module": "test-client",
"instanceId": "test-instance",
"endpoint": serverURL.Host,
Expand Down Expand Up @@ -327,19 +341,19 @@ func TestClient5xx(t *testing.T) {
conf.Set("REPORTING_URL", server.URL)
conf.Set("Reporting.httpClient.backoff.maxRetries", 1)

c := client.New(client.PathMetrics, conf, logger.NOP, statsStore)
c := client.New(client.RouteMetrics, conf, logger.NOP, statsStore)

// Send the metric and expect an error
err = c.Send(context.Background(), metric)
require.Error(t, err)
require.Contains(t, err.Error(), fmt.Sprintf("received unexpected response from reporting service: \"/metrics?version=v1\": statusCode: %d body: error with status %d", statusCode, statusCode))
require.Contains(t, err.Error(), fmt.Sprintf("received unexpected response: \"/metrics?version=v1\": statusCode: %d body: error with status %d", statusCode, statusCode))

// Get server hostname
serverURL, _ := url.Parse(server.URL)

// Expected tags for HTTP metrics
expectedHttpTags := stats.Tags{
"path": string(client.PathMetrics),
"path": string(client.RouteMetrics),
"module": "test-client",
"instanceId": "2",
"endpoint": serverURL.Host,
Expand All @@ -353,3 +367,136 @@ func TestClient5xx(t *testing.T) {
})
}
}

func TestRouteURL(t *testing.T) {
tests := []struct {
name string
route client.Route
baseURL string
wantURL string
wantErr bool
errContains string
}{
{
name: "valid metrics endpoint",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com",
wantURL: "https://reporting.dev.rudderlabs.com/metrics?version=v1",
wantErr: false,
},
{
name: "valid record errors endpoint",
route: client.RouteRecordErrors,
baseURL: "https://reporting.dev.rudderlabs.com",
wantURL: "https://reporting.dev.rudderlabs.com/recordErrors",
wantErr: false,
},
{
name: "valid tracked users endpoint",
route: client.RouteTrackedUsers,
baseURL: "https://reporting.dev.rudderlabs.com",
wantURL: "https://reporting.dev.rudderlabs.com/trackedUser",
wantErr: false,
},
{
name: "invalid base URL",
route: client.RouteMetrics,
baseURL: "://invalid-url",
wantErr: true,
errContains: "parsing base URL",
},
{
name: "invalid service endpoint",
route: client.Route("://invalid-endpoint"),
baseURL: "https://reporting.dev.rudderlabs.com",
wantErr: true,
errContains: "parsing service endpoint",
},
{
name: "base URL with trailing slash",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com/",
wantURL: "https://reporting.dev.rudderlabs.com/metrics?version=v1",
wantErr: false,
},
{
name: "base URL with trailing dot",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com./",
wantURL: "https://reporting.dev.rudderlabs.com./metrics?version=v1",
wantErr: false,
},

{
name: "base URL with existing path",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com/api",
wantURL: "https://reporting.dev.rudderlabs.com/metrics?version=v1",
wantErr: false,
},
{
name: "base URL with multiple trailing slashes",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com///",
wantURL: "https://reporting.dev.rudderlabs.com/metrics?version=v1",
wantErr: false,
},
{
name: "base URL with relative path up",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com/api/../",
wantURL: "https://reporting.dev.rudderlabs.com/metrics?version=v1",
wantErr: false,
},
{
name: "base URL with relative path current",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com/api/./",
wantURL: "https://reporting.dev.rudderlabs.com/metrics?version=v1",
wantErr: false,
},
{
name: "base URL with complex relative path",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com/api/v1/../v2/./v3/",
wantURL: "https://reporting.dev.rudderlabs.com/metrics?version=v1",
wantErr: false,
},
{
name: "base URL with encoded path",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com/api%2Fv1",
wantURL: "https://reporting.dev.rudderlabs.com/metrics?version=v1",
wantErr: false,
},
{
name: "base URL with query parameters",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com?param=value",
wantURL: "https://reporting.dev.rudderlabs.com/metrics?version=v1",
wantErr: false,
},
{
name: "base URL with port",
route: client.RouteMetrics,
baseURL: "https://reporting.dev.rudderlabs.com:8080",
wantURL: "https://reporting.dev.rudderlabs.com:8080/metrics?version=v1",
wantErr: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.route.URL(tt.baseURL)
if tt.wantErr {
require.Error(t, err)
if tt.errContains != "" {
require.Contains(t, err.Error(), tt.errContains)
}
return
}
require.NoError(t, err)
require.Equal(t, tt.wantURL, got.String())
})
}
}
2 changes: 1 addition & 1 deletion enterprise/reporting/error_reporting.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ func NewErrorDetailReporter(
config: conf,

useCommonClient: useCommonClient,
commonClient: client.New(client.PathRecordErrors, conf, log, stats),
commonClient: client.New(client.RouteRecordErrors, conf, log, stats),
}
}

Expand Down
2 changes: 1 addition & 1 deletion enterprise/reporting/flusher/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func CreateRunner(ctx context.Context, table string, log logger.Logger, stats st
return &NOPCronRunner{}, nil
}

commonClient := client.New(client.PathTrackedUsers, conf, log, stats)
commonClient := client.New(client.RouteTrackedUsers, conf, log, stats)

// DEPRECATED: Remove this after migration to commonClient.
reportingBaseURL := config.GetString("REPORTING_URL", "https://reporting.rudderstack.com/")
Expand Down
2 changes: 1 addition & 1 deletion enterprise/reporting/reporting.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func NewDefaultReporter(ctx context.Context, conf *config.Config, log logger.Log
eventSamplingDuration: eventSamplingDuration,
eventSampler: eventSampler,
useCommonClient: useCommonClient,
commonClient: client.New(client.PathMetrics, conf, log, stats),
commonClient: client.New(client.RouteMetrics, conf, log, stats),
}
}

Expand Down