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

[SLT-141] feat(metrics): multiple exports #3099

Merged
merged 33 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
7ba8a43
initial
golangisfun123 Sep 3, 2024
9632578
done
golangisfun123 Sep 4, 2024
c762c4c
add lint
golangisfun123 Sep 4, 2024
3c15801
Merge branch 'master' into multiple-exports
trajan0x Sep 5, 2024
829812b
[goreleaser]
trajan0x Sep 5, 2024
e831fe9
different environment variables
golangisfun123 Sep 5, 2024
68def3c
rework logic, make primary/secondary optional, make code clearer, upd…
golangisfun123 Sep 5, 2024
51284b9
clearer code
golangisfun123 Sep 5, 2024
6bcd3ab
interfacify it better
golangisfun123 Sep 5, 2024
38e924b
lint
golangisfun123 Sep 5, 2024
f8a2048
[goreleaser]
golangisfun123 Sep 5, 2024
c163704
add test
trajan0x Sep 10, 2024
89e996b
cleanup
trajan0x Sep 10, 2024
780b4c5
actually suport multi exports
trajan0x Sep 10, 2024
1d82704
address https://github.com/synapsecns/sanguine/pull/3099/files#r17513…
trajan0x Sep 10, 2024
08fa2a4
fix function call [goreleaser]
golangisfun123 Sep 10, 2024
1c63c19
warnings and uneeded err check
golangisfun123 Sep 10, 2024
d08315e
more accurate comment
golangisfun123 Sep 10, 2024
1d670a0
[goreleaser]
golangisfun123 Sep 10, 2024
d6ee535
cleanup
trajan0x Sep 11, 2024
48f2afc
resolve merge conflicts
trajan0x Sep 11, 2024
4db816f
header bump [goreleaser]
trajan0x Sep 11, 2024
3923d42
Merge branch 'master' into multiple-exports
trajan0x Sep 11, 2024
bad4071
insecure mode [goreleaser]
trajan0x Sep 11, 2024
f8e240d
secure [goreleaser]
trajan0x Sep 11, 2024
a19300c
set default exporter to otlpgrpc again
trajan0x Sep 11, 2024
bfd1d7b
test
trajan0x Sep 11, 2024
d5e69f7
Revert "test"
trajan0x Sep 11, 2024
ceeddbc
cleanup
trajan0x Sep 11, 2024
4c6825a
cleanup [goreleaser]
trajan0x Sep 11, 2024
732f5fa
Merge branch 'multiple-exports' of https://github.com/synapsecns/sang…
trajan0x Sep 11, 2024
8a04f9e
paralellize exports [goreleaser]
trajan0x Sep 11, 2024
0e3a5ae
url
trajan0x Sep 11, 2024
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
2 changes: 1 addition & 1 deletion core/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ require (
go.uber.org/multierr v1.11.0
go.uber.org/zap v1.27.0
golang.org/x/sync v0.8.0
google.golang.org/grpc v1.64.0
gorm.io/driver/sqlite v1.5.6
gorm.io/gorm v1.25.10
k8s.io/apimachinery v0.29.3
Expand Down Expand Up @@ -189,7 +190,6 @@ require (
golang.org/x/tools v0.24.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240701130421-f6361c86f094 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240701130421-f6361c86f094 // indirect
google.golang.org/grpc v1.64.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
Expand Down
18 changes: 17 additions & 1 deletion core/metrics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,23 @@ There's also a `NAME_PREFIX` environment variable that will prefix all the metri

## OTLP

We do our best to support enviornment variables specified in the [Otel Spec](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/) and have added a few of our own. Key ones to note are:
We do our best to support enviornment variables specified in the [Otel Spec](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/) and the [OTLP Spec](https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/) and have added a few of our own. This was to allow for multiple exporter backends for traces, as otel clients only allow for one URL. The relevant multi exporter code is in `multiexporter.go`, and simply wraps multiple otel clients.

The additional environment variables to note are:
| Enviornment Variable | Description | Default |
|------------------------------------------|-------------------------------------------|---------|
| `OTEL_EXPORTER_OTLP_ENDPOINT` | The endpoint for the primary OTLP exporter | None |
| `OTEL_EXPORTER_OTLP_ENDPOINT_1` | The endpoint for the first additional OTLP exporter | None |
| `OTEL_EXPORTER_OTLP_ENDPOINT_2` | The endpoint for the second additional OTLP exporter | None |
| `OTEL_EXPORTER_OTLP_ENDPOINT_3` | The endpoint for the third additional OTLP exporter | None |
| ... | Additional endpoints can be added by incrementing the number | None |
| `OTEL_EXPORTER_OTLP_TRANSPORT` | The transport protocol for the primary OTLP exporter | `http` |
| `OTEL_EXPORTER_OTLP_TRANSPORT_1` | The transport protocol for the first additional OTLP exporter | `http` |
| `OTEL_EXPORTER_OTLP_TRANSPORT_2` | The transport protocol for the second additional OTLP exporter | `http` |
| `OTEL_EXPORTER_OTLP_TRANSPORT_3` | The transport protocol for the third additional OTLP exporter | `http` |
| ... | Additional transports can be specified by incrementing the number | `http` |

Note: The OTLP exporter endpoints and transports can be specified for multiple exporters by using incrementing numbers (1, 2, 3, etc.) in the environment variable names. This allows for configuration of multiple OTLP exporters. The primary exporter uses the base names without numbers.


## Jaeger
Expand Down
6 changes: 6 additions & 0 deletions core/metrics/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package metrics

// HeadersToMap converts a string of headers to a map.
func HeadersToMap(val string) map[string]string {
return headersToMap(val)
}
57 changes: 57 additions & 0 deletions core/metrics/multiexporter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package metrics

import (
"context"
"fmt"

"go.opentelemetry.io/otel/sdk/trace"

Check failure on line 7 in core/metrics/multiexporter.go

View workflow job for this annotation

GitHub Actions / Lint (core)

ST1019: package "go.opentelemetry.io/otel/sdk/trace" is being imported more than once (stylecheck)
tracesdk "go.opentelemetry.io/otel/sdk/trace"

Check failure on line 8 in core/metrics/multiexporter.go

View workflow job for this annotation

GitHub Actions / Lint (core)

ST1019(related information): other import of "go.opentelemetry.io/otel/sdk/trace" (stylecheck)
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the duplicate import of go.opentelemetry.io/otel/sdk/trace.

The go.opentelemetry.io/otel/sdk/trace package is being imported twice, once as trace and once as tracesdk. This is unnecessary and can cause confusion.

Apply this diff to remove the duplicate import:

 import (
 	"context"
 	"fmt"
 
-	"go.opentelemetry.io/otel/sdk/trace"
 	tracesdk "go.opentelemetry.io/otel/sdk/trace"
 )
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
"go.opentelemetry.io/otel/sdk/trace"
tracesdk "go.opentelemetry.io/otel/sdk/trace"
tracesdk "go.opentelemetry.io/otel/sdk/trace"
Tools
GitHub Check: Lint (core)

[failure] 7-7:
ST1019: package "go.opentelemetry.io/otel/sdk/trace" is being imported more than once (stylecheck)


[failure] 8-8:
ST1019(related information): other import of "go.opentelemetry.io/otel/sdk/trace" (stylecheck)

)

// MultiExporter is an interface that allows exporting spans to multiple OTLP trace exporters.
type MultiExporter interface {
Copy link
Contributor

Choose a reason for hiding this comment

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

should have a test

trace.SpanExporter
AddExporter(exporter trace.SpanExporter)
}

type multiExporter struct {
exporters []trace.SpanExporter
}

// NewMultiExporter creates a new multi exporter that forwards spans to multiple OTLP trace exporters.
// It takes in one or more trace.SpanExporter instances and ensures that spans are sent to all of them.
// This is useful when you need to send trace data to multiple backends or endpoints.
func NewMultiExporter(exporters ...trace.SpanExporter) MultiExporter {
return &multiExporter{
exporters: exporters,
}
}

// ExportSpans exports a batch of spans.
func (m *multiExporter) ExportSpans(ctx context.Context, ss []trace.ReadOnlySpan) error {
for _, exporter := range m.exporters {
err := exporter.ExportSpans(ctx, ss)
if err != nil {
return fmt.Errorf("could not export spans: %w", err)
}

Check warning on line 36 in core/metrics/multiexporter.go

View check run for this annotation

Codecov / codecov/patch

core/metrics/multiexporter.go#L32-L36

Added lines #L32 - L36 were not covered by tests
}
return nil

Check warning on line 38 in core/metrics/multiexporter.go

View check run for this annotation

Codecov / codecov/patch

core/metrics/multiexporter.go#L38

Added line #L38 was not covered by tests
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider collecting errors from all exporters before returning.

The current implementation of ExportSpans returns immediately if an error occurs while exporting to one of the exporters. This means that if one exporter fails, the remaining exporters will not receive the spans.

It would be better to collect errors from all exporters and return a combined error. This way, all exporters will have a chance to receive the spans, and the caller will be informed of all the errors that occurred.

Apply this diff to collect errors from all exporters:

 func (m *multiExporter) ExportSpans(ctx context.Context, ss []tracesdk.ReadOnlySpan) error {
+	var errs []error
 	for _, exporter := range m.exporters {
 		err := exporter.ExportSpans(ctx, ss)
 		if err != nil {
-			return fmt.Errorf("could not export spans: %w", err)
+			errs = append(errs, err)
 		}
 	}
+	if len(errs) > 0 {
+		return fmt.Errorf("could not export spans to some exporters: %v", errs)
+	}
 	return nil
 }
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
func (m *multiExporter) ExportSpans(ctx context.Context, ss []trace.ReadOnlySpan) error {
for _, exporter := range m.exporters {
err := exporter.ExportSpans(ctx, ss)
if err != nil {
return fmt.Errorf("could not export spans: %w", err)
}
}
return nil
func (m *multiExporter) ExportSpans(ctx context.Context, ss []trace.ReadOnlySpan) error {
var errs []error
for _, exporter := range m.exporters {
err := exporter.ExportSpans(ctx, ss)
if err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return fmt.Errorf("could not export spans to some exporters: %v", errs)
}
return nil
}
Tools
GitHub Check: codecov/patch

[warning] 32-36: core/metrics/multiexporter.go#L32-L36
Added lines #L32 - L36 were not covered by tests


[warning] 38-38: core/metrics/multiexporter.go#L38
Added line #L38 was not covered by tests

}

// Shutdown notifies the exporter of a pending halt to operations.
func (m *multiExporter) Shutdown(ctx context.Context) error {
for _, exporter := range m.exporters {
err := exporter.Shutdown(ctx)
if err != nil {
return fmt.Errorf("could not stop exporter: %w", err)
}

Check warning on line 47 in core/metrics/multiexporter.go

View check run for this annotation

Codecov / codecov/patch

core/metrics/multiexporter.go#L46-L47

Added lines #L46 - L47 were not covered by tests
}
return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Method Implementation Review: Shutdown

Similar to ExportSpans, the Shutdown method stops at the first error encountered. This could potentially leave some exporters running if one fails to shut down properly.

Consider implementing a similar error aggregation strategy as suggested for ExportSpans to ensure all exporters are attempted to be shut down before returning an error.

-		if err != nil {
-			return fmt.Errorf("could not stop exporter: %w", err)
-		}
+		if err != nil {
+			// Collect errors from all exporters
+			allErrors = append(allErrors, err)
+		}
+	}
+	if len(allErrors) > 0 {
+		return fmt.Errorf("could not stop some exporters: %v", allErrors)
+	}

Committable suggestion was skipped due to low confidence.

Tools
GitHub Check: codecov/patch

[warning] 46-47: core/metrics/multiexporter.go#L46-L47
Added lines #L46 - L47 were not covered by tests

Copy link
Contributor

Choose a reason for hiding this comment

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

Consider collecting errors from all exporters before returning.

Similar to the ExportSpans method, the current implementation of Shutdown returns immediately if an error occurs while shutting down one of the exporters. This means that if one exporter fails to shut down, the remaining exporters will not be shut down.

As suggested in the existing review comments, it would be better to collect errors from all exporters and return a combined error. This way, all exporters will be attempted to be shut down, and the caller will be informed of all the errors that occurred.

Apply this diff to collect errors from all exporters:

 func (m *multiExporter) Shutdown(ctx context.Context) error {
+	var errs []error
 	for _, exporter := range m.exporters {
 		err := exporter.Shutdown(ctx)
 		if err != nil {
-			return fmt.Errorf("could not stop exporter: %w", err)
+			errs = append(errs, err)
 		}
 	}
+	if len(errs) > 0 {
+		return fmt.Errorf("could not stop some exporters: %v", errs)
+	}
 	return nil
 }
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
func (m *multiExporter) Shutdown(ctx context.Context) error {
for _, exporter := range m.exporters {
err := exporter.Shutdown(ctx)
if err != nil {
return fmt.Errorf("could not stop exporter: %w", err)
}
}
return nil
}
func (m *multiExporter) Shutdown(ctx context.Context) error {
var errs []error
for _, exporter := range m.exporters {
err := exporter.Shutdown(ctx)
if err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return fmt.Errorf("could not stop some exporters: %v", errs)
}
return nil
}


// AddExporter adds an exporter to the multi exporter.
func (m *multiExporter) AddExporter(exporter trace.SpanExporter) {
m.exporters = append(m.exporters, exporter)
}

var _ tracesdk.SpanExporter = &multiExporter{}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure test coverage for multi-exporter logic.

The introduction of the multi-exporter logic is a significant enhancement. However, static analysis indicates that several lines in the ExportSpans and Shutdown methods are not covered by tests.

It's crucial to ensure that the multi-exporter functionality is covered by unit tests to verify its behavior under various scenarios, especially error handling.

Consider adding unit tests to cover these scenarios to ensure robust functionality verification.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

Tools
GitHub Check: codecov/patch

[warning] 32-36: core/metrics/multiexporter.go#L32-L36
Added lines #L32 - L36 were not covered by tests


[warning] 38-38: core/metrics/multiexporter.go#L38
Added line #L38 was not covered by tests


[warning] 46-47: core/metrics/multiexporter.go#L46-L47
Added lines #L46 - L47 were not covered by tests

45 changes: 45 additions & 0 deletions core/metrics/multiexporter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package metrics_test

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/synapsecns/sanguine/core/metrics"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
)

func TestMultiExporter(t *testing.T) {
// Create in-memory exporters
exporter1 := tracetest.NewInMemoryExporter()
exporter2 := tracetest.NewInMemoryExporter()

// Create multi-exporter
multiExporter := metrics.NewMultiExporter(exporter1, exporter2)

// Create test spans
spans := []sdktrace.ReadOnlySpan{
tracetest.SpanStub{}.Snapshot(),
tracetest.SpanStub{}.Snapshot(),
}

// Test ExportSpans
err := multiExporter.ExportSpans(context.Background(), spans)
require.NoError(t, err)

// Verify that spans were exported to both exporters
assert.Equal(t, 2, len(exporter1.GetSpans()))
assert.Equal(t, 2, len(exporter2.GetSpans()))

// Test Shutdown
err = multiExporter.Shutdown(context.Background())
require.NoError(t, err)

// Verify that both exporters were shut down
// Note: InMemoryExporter doesn't have a Stopped() method, so we can't check this directly
// Instead, we can try to export spans again and check for an error
err = multiExporter.ExportSpans(context.Background(), spans)
assert.NoError(t, err, "Expected no error after shutdown")
}
186 changes: 169 additions & 17 deletions core/metrics/otlp.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
import (
"context"
"fmt"
"google.golang.org/grpc/credentials"
"strings"
"time"

"github.com/synapsecns/sanguine/core"
"github.com/synapsecns/sanguine/core/config"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
tracesdk "go.opentelemetry.io/otel/sdk/trace"
"os"
"strings"
"time"
)

type otlpHandler struct {
Expand All @@ -28,23 +29,45 @@
}

func (n *otlpHandler) Start(ctx context.Context) (err error) {
var client otlptrace.Client
transport := transportFromString(core.GetEnv(otlpTransportEnv, otlpTransportGRPC.String()))
switch transport {
case otlpTransportHTTP:
client = otlptracehttp.NewClient()
case otlpTransportGRPC:
client = otlptracegrpc.NewClient()
default:
return fmt.Errorf("unknown transport type: %s", os.Getenv(otlpTransportEnv))
}
var exporters []tracesdk.SpanExporter

exporter, err := otlptrace.New(ctx, client)
primaryExporter, err := makeOTLPExporter(ctx, "")
if err != nil {
return fmt.Errorf("failed to create otlp exporter: %w", err)
return fmt.Errorf("could not create default client: %w", err)
}
exporters = append(exporters, primaryExporter)

// Loop to create additional exporters
for i := 1; ; i++ {
envSuffix := fmt.Sprintf("_%d", i)
// if this is empty we can assume no config exists at all.
endpointEnv := otelEndpointEnv + envSuffix

// no more transports to add.
if !core.HasEnv(endpointEnv) {
break
}

Check warning on line 49 in core/metrics/otlp.go

View check run for this annotation

Codecov / codecov/patch

core/metrics/otlp.go#L49

Added line #L49 was not covered by tests
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Add Tests for Error Handling in Multi-Exporter Logic

The current test TestMultiExporter verifies the successful operation of the multi-exporter logic but does not cover error handling scenarios such as exporter creation failure or breaking out of the loop when no exporters are configured. It is recommended to add unit tests to cover these scenarios to ensure robustness.

  • Consider adding tests for:
    • Breaking out of the loop when no more exporters are configured.
    • Error handling when exporter creation fails.
Analysis chain

Ensure test coverage for the multi-exporter logic and error handling scenarios.

Static analysis tools have reported that some lines in the Start method are not covered by tests:

  • Line 50: Breaking out of the loop when no more exporters are configured
  • Line 55: Error handling when exporter creation fails
  • Line 58: Appending the created exporter to the list of exporters

It's important to add unit tests to cover these scenarios and ensure the robustness of the multi-exporter logic and error handling.

Also applies to: 55-55, 58-58

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test coverage for the multi-exporter logic and error handling scenarios.

# Test: Search for tests covering the multi-exporter logic. Expect: At least one test.
rg --type go $'func Test.*MultiExporter'

# Test: Search for tests covering the error handling scenarios. Expect: At least one test.
rg --type go $'func Test.*ExporterCreationError'

Length of output: 165


Script:

#!/bin/bash
# Search for the implementation of the TestMultiExporter function to check its coverage.
rg --type go -A 20 'func TestMultiExporter' core/metrics/multiexporter_test.go

# Search for other test functions in the same file to see if they cover error handling.
rg --type go 'func Test' core/metrics/multiexporter_test.go

Length of output: 825

Tools
GitHub Check: codecov/patch

[warning] 50-50: core/metrics/otlp.go#L50
Added line #L50 was not covered by tests


exporter, err := makeOTLPExporter(ctx, envSuffix)
if err != nil {
return fmt.Errorf("could not create exporter %d: %v", i, err)

Check failure on line 53 in core/metrics/otlp.go

View workflow job for this annotation

GitHub Actions / Lint (core)

non-wrapping format verb for fmt.Errorf. Use `%w` to format errors (errorlint)
Copy link
Contributor

Choose a reason for hiding this comment

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

Address the non-wrapping format verb for fmt.Errorf.

Static analysis tools have reported the following issue:

non-wrapping format verb for fmt.Errorf. Use %w to format errors (errorlint)

Please use %w to format errors for better error handling and wrapping. Apply this diff to fix the issue:

-return fmt.Errorf("could not create exporter %d: %v", i, err)
+return fmt.Errorf("could not create exporter %d: %w", i, err)
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
return fmt.Errorf("could not create exporter %d: %v", i, err)
return fmt.Errorf("could not create exporter %d: %w", i, err)
Tools
GitHub Check: Lint (core)

[failure] 53-53:
non-wrapping format verb for fmt.Errorf. Use %w to format errors (errorlint)

}

Check warning on line 54 in core/metrics/otlp.go

View check run for this annotation

Codecov / codecov/patch

core/metrics/otlp.go#L54

Added line #L54 was not covered by tests

exporters = append(exporters, exporter)
}

n.baseHandler = newBaseHandler(n.buildInfo, tracesdk.WithBatcher(exporter, tracesdk.WithMaxQueueSize(1000000), tracesdk.WithMaxExportBatchSize(2000)), tracesdk.WithSampler(tracesdk.AlwaysSample()))
// create the multi-exporter with all the exporters
multiExporter := NewMultiExporter(exporters...)

n.baseHandler = newBaseHandler(
n.buildInfo,
tracesdk.WithBatcher(
multiExporter,
tracesdk.WithMaxQueueSize(defaultMaxQueueSize),
tracesdk.WithMaxExportBatchSize(defaultMaxExportBatch),
),
tracesdk.WithSampler(tracesdk.AlwaysSample()),
)

// start the new parent
err = n.baseHandler.Start(ctx)
Expand Down Expand Up @@ -90,7 +113,10 @@
}

const (
otlpTransportEnv = "OTEL_EXPORTER_OTLP_TRANSPORT"
otelEndpointEnv = "OTEL_EXPORTER_OTLP_ENDPOINT"
otelTransportEnv = "OTEL_EXPORTER_OTLP_TRANSPORT"
otelInsecureEvn = "INSECURE_MODE"
otelHeadersEnv = "OTEL_EXPORTER_OTLP_HEADERS"
)

//go:generate go run golang.org/x/tools/cmd/stringer -type=otlpTransportType -linecomment
Expand All @@ -101,6 +127,127 @@
otlpTransportGRPC // grpc
)

// getEnvSuffix returns the value of an environment variable with a suffix.
func getEnvSuffix(env, suffix, defaultRet string) string {
newEnv := env + suffix
return core.GetEnv(newEnv, defaultRet)
}

// makeOTLPTrace creates a new OTLP client based on the transport type and url.
func makeOTLPExporter(ctx context.Context, envSuffix string) (*otlptrace.Exporter, error) {
transport := transportFromString(getEnvSuffix(otelTransportEnv, envSuffix, otlpTransportHTTP.String()))
url := getEnvSuffix(otelEndpointEnv, envSuffix, "")
insecure := getEnvSuffix(otelInsecureEvn, envSuffix, "false")
headers := getEnvSuffix(otelHeadersEnv, envSuffix, "")

if url == "" {
return nil, fmt.Errorf("could not create exporter: url is empty")
}

oteltraceClient, err := buildClientFromTransport(
transport,
WithURL(url),
WithInsecure(insecure == "true"),
WithHeaders(headers),
)
if err != nil {
return nil, fmt.Errorf("could not create client from transport: %w", err)
}

exporter, err := otlptrace.New(ctx, oteltraceClient)
if err != nil {
return nil, fmt.Errorf("ocould not create client: %w", err)
}
return exporter, nil
}

// buildClientFromTransport creates a new OTLP client based on the transport type and url.
func buildClientFromTransport(transport otlpTransportType, options ...Option) (otlptrace.Client, error) {
to := transportOptions{}
for _, option := range options {
if err := option(&to); err != nil {
return nil, fmt.Errorf("could not apply option: %w", err)
}
}

// TODO: make sure url is validated

switch transport {
case otlpTransportHTTP:

Check warning on line 176 in core/metrics/otlp.go

View check run for this annotation

Codecov / codecov/patch

core/metrics/otlp.go#L176

Added line #L176 was not covered by tests
return otlptracehttp.NewClient(to.httpOptions...), nil
case otlpTransportGRPC:
return otlptracegrpc.NewClient(to.grpcOptions...), nil
default:
return nil, fmt.Errorf("unknown transport type: %s", transport.String())

Check warning on line 181 in core/metrics/otlp.go

View check run for this annotation

Codecov / codecov/patch

core/metrics/otlp.go#L180-L181

Added lines #L180 - L181 were not covered by tests
Comment on lines +194 to +195
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Add unit tests for error handling in buildClientFromTransport.

The error handling for unknown transport types in the buildClientFromTransport function is not currently covered by any tests. It is important to add unit tests to cover this scenario and ensure the robustness of the function.

  • Consider adding a test case that provides an invalid transport type and verifies that an error is returned.
Analysis chain

Improve error handling in the buildClientFromTransport function.

Static analysis tools have reported that the error handling for unknown transport types (lines 198-199) is not covered by tests.

It's important to add unit tests to cover this scenario and ensure the robustness of the function. Consider adding a test case that provides an invalid transport type and verifies that an error is returned.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test coverage for the error handling of unknown transport types.

# Test: Search for tests covering the error handling of unknown transport types. Expect: At least one test.
rg --type go $'func Test.*UnknownTransportType'

Length of output: 48


Script:

#!/bin/bash
# Description: Search for test cases involving the buildClientFromTransport function to check error handling coverage.

# Find the definition of the buildClientFromTransport function to understand its location and context.
ast-grep --lang go --pattern 'func buildClientFromTransport($_) $_ { $$$ }'

# Search for test functions that call buildClientFromTransport.
rg --type go 'buildClientFromTransport'

Length of output: 428


Script:

#!/bin/bash
# Description: Search for Go test files that might indirectly test the buildClientFromTransport function.

# List all Go test files in the repository.
fd --type f --extension go --exec basename {} \; | grep '_test.go'

# Search for any references to the buildClientFromTransport function in these test files.
rg --type go 'buildClientFromTransport' --glob '*_test.go'

Length of output: 5242

Tools
GitHub Check: codecov/patch

[warning] 198-199: core/metrics/otlp.go#L198-L199
Added lines #L198 - L199 were not covered by tests

}
}
Comment on lines +178 to +197
Copy link
Contributor

Choose a reason for hiding this comment

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

The new buildClientFromTransport function looks good!

Separating the client creation logic based on the transport type makes the code modular and extensible. The use of a switch statement makes it easy to add support for new transport types in the future, and applying the provided options allows for flexible configuration of the transport client.

However, static analysis tools have reported a lack of test coverage for certain lines in this function.

Please add unit tests to cover the following scenarios:

  • Creating an HTTP transport client (line 176)
  • Creating a gRPC transport client (line 178)
  • Handling an unknown transport type (lines 180-181)

This will ensure that all code paths in the function are properly tested.

Tools
GitHub Check: codecov/patch

[warning] 176-176: core/metrics/otlp.go#L176
Added line #L176 was not covered by tests


[warning] 180-181: core/metrics/otlp.go#L180-L181
Added lines #L180 - L181 were not covered by tests


type transportOptions struct {
// httpOptions are the options for the http transport.
httpOptions []otlptracehttp.Option
// grpcOptions are the options for the grpc transport.
grpcOptions []otlptracegrpc.Option
}

// Option Each option appends the correspond option for both http and grpc options.
// only one will be used in creating the actual client.
type Option func(*transportOptions) error

func WithURL(url string) Option {

Check failure on line 196 in core/metrics/otlp.go

View workflow job for this annotation

GitHub Actions / Lint (core)

exported: exported function WithURL should have comment or be unexported (revive)
return func(o *transportOptions) error {
o.httpOptions = append(o.httpOptions, otlptracehttp.WithEndpointURL(url))
o.grpcOptions = append(o.grpcOptions, otlptracegrpc.WithEndpointURL(url))

return nil
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The new option functions WithURL, WithInsecure, and WithHeaders look good!

Providing these option functions allows for clean and extensible configuration of the OTLP exporter. Exporting them enables flexibility in configuring the exporter from other packages.

The functions modify the transportOptions struct in a consistent way, appending the corresponding options for both HTTP and gRPC transports, which is a good practice for maintaining compatibility between the two transport types.

However, static analysis tools have reported that these functions should have comments or be unexported.

Please add comments for the exported functions to improve code documentation and maintainability. For example:

// WithURL sets the endpoint URL for the OTLP exporter.
func WithURL(url string) Option {
	// ...
}

// WithInsecure enables or disables secure connection for the OTLP exporter.
func WithInsecure(isInsecure bool) Option {
	// ...
}

// WithHeaders sets the headers for the OTLP exporter.
func WithHeaders(headers string) Option {
	// ...
}

Also applies to: 223-241, 243-250

Tools
GitHub Check: Lint (core)

[failure] 214-214:
exported: exported function WithURL should have comment or be unexported (revive)


func WithInsecure(isInsecure bool) Option {

Check failure on line 205 in core/metrics/otlp.go

View workflow job for this annotation

GitHub Actions / Lint (core)

exported: exported function WithInsecure should have comment or be unexported (revive)
return func(o *transportOptions) error {
if isInsecure {
o.httpOptions = append(o.httpOptions, otlptracehttp.WithInsecure())
o.grpcOptions = append(o.grpcOptions, otlptracegrpc.WithInsecure())
} else {
tlsCreds := credentials.NewClientTLSFromCert(nil, "")
// note: you do not need to specify the tls creds for http, this happens automatically when https:// is used as the protocol scheme.
o.grpcOptions = append(o.grpcOptions, otlptracegrpc.WithTLSCredentials(tlsCreds))
}

return nil
}
}

func WithHeaders(headers string) Option {

Check failure on line 220 in core/metrics/otlp.go

View workflow job for this annotation

GitHub Actions / Lint (core)

exported: exported function WithHeaders should have comment or be unexported (revive)
return func(o *transportOptions) error {
realHeaders := headersToMap(headers)
o.httpOptions = append(o.httpOptions, otlptracehttp.WithHeaders(realHeaders))
o.grpcOptions = append(o.grpcOptions, otlptracegrpc.WithHeaders(realHeaders))
return nil
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The new option functions WithURL, WithInsecure, and WithHeaders look good!

Providing these option functions allows for clean and extensible configuration of the OTLP exporter. Exporting them enables flexibility in configuring the exporter from other packages.

However, static analysis tools have reported that these functions should have comments or be unexported.

Please add comments for the exported functions to improve code documentation and maintainability. For example:

// WithURL sets the endpoint URL for the OTLP exporter.
func WithURL(url string) Option {
	// ...
}

// WithInsecure enables or disables secure connection for the OTLP exporter.
func WithInsecure(isInsecure bool) Option {
	// ...
}

// WithHeaders sets the headers for the OTLP exporter.
func WithHeaders(headers string) Option {
	// ...
}
Tools
GitHub Check: Lint (core)

[failure] 196-196:
exported: exported function WithURL should have comment or be unexported (revive)


[failure] 205-205:
exported: exported function WithInsecure should have comment or be unexported (revive)


[failure] 220-220:
exported: exported function WithHeaders should have comment or be unexported (revive)


func headersToMap(input string) map[string]string {
// Initialize the map
result := make(map[string]string)

// Split the input string by comma to get key=value pairs
pairs := strings.Split(input, ",")

// Iterate over each pair
for _, pair := range pairs {
// Split each pair by '=' to get the key and value
kv := strings.SplitN(pair, "=", 2)

Check failure on line 239 in core/metrics/otlp.go

View workflow job for this annotation

GitHub Actions / Lint (core)

Magic number: 2, in <argument> detected (mnd)
if len(kv) == 2 {

Check failure on line 240 in core/metrics/otlp.go

View workflow job for this annotation

GitHub Actions / Lint (core)

Magic number: 2, in <condition> detected (mnd)
key := kv[0]
value := kv[1]
// Add the key and value to the map
result[key] = value
}
}

return result
}

// transportFromString converts a string to a transport type.
// Defaults to http if the string is not recognized.
func transportFromString(transport string) otlpTransportType {
Expand All @@ -114,3 +261,8 @@
// (see uber's go stye guide for details)
return otlpTransportType(0)
}

const (
defaultMaxQueueSize = 1000000
defaultMaxExportBatch = 2000
)
Loading
Loading