Skip to content
Open
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
114 changes: 103 additions & 11 deletions commenter.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"strings"

"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/propagation"
)

Expand All @@ -37,30 +38,85 @@ func (c *commentCarrier) Set(key, value string) {
}

func (c *commentCarrier) Marshal() string {
return strings.Join(*c, ",")
return " /*" + strings.Join(*c, ",") + "*/"
}

type commenter struct {
enabled bool
// Commenter an interface for that allows injecting comments into SQL statements.
type Commenter interface {
Query(ctx context.Context, query string) string
Exec(ctx context.Context, query string) string
Prepare(ctx context.Context, query string) string
}

type noopCommenter struct{}

var _ Commenter = noopCommenter{}

func (n noopCommenter) Query(_ context.Context, query string) string {
return query
}

func (n noopCommenter) Exec(_ context.Context, query string) string {
return query
}

func (n noopCommenter) Prepare(_ context.Context, query string) string {
return query
}

type propagationCommenter struct {
propagator propagation.TextMapPropagator
}

func newCommenter(enabled bool, propagator propagation.TextMapPropagator) *commenter {
var _ Commenter = (*propagationCommenter)(nil)

// NewPropagationCommenter returns a Commenter that will inject a comment into SQL statements using the propagator.
//
// e.g., a SQL query
//
// SELECT * from FOO
//
// will become
//
// SELECT * from FOO /*traceparent='00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',tracestate='congo%3Dt61rcWkgMzE%2Crojo%3D00f067aa0ba902b7'*/
//
// Notice: This option is EXPERIMENTAL and may be changed or removed in a
// later release.
// NewPropagationCommenter returns a Commenter that will inject a comment into SQL statements using the propagator.
//
// e.g., a SQL query
//
// SELECT * from FOO
//
// will become
//
// SELECT * from FOO /*traceparent='00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01',tracestate='congo%3Dt61rcWkgMzE%2Crojo%3D00f067aa0ba902b7'*/
//
// Notice: This option is EXPERIMENTAL and may be changed or removed in a
// later release.
func NewPropagationCommenter(propagator propagation.TextMapPropagator) Commenter {
if propagator == nil {
propagator = otel.GetTextMapPropagator()
}

return &commenter{
enabled: enabled,
return &propagationCommenter{
propagator: propagator,
}
}

func (c *commenter) withComment(ctx context.Context, query string) string {
if !c.enabled {
return query
}
func (c *propagationCommenter) Query(ctx context.Context, query string) string {
return c.withComment(ctx, query)
}

func (c *propagationCommenter) Exec(ctx context.Context, query string) string {
return c.withComment(ctx, query)
}

func (c *propagationCommenter) Prepare(ctx context.Context, query string) string {
return c.withComment(ctx, query)
}

func (c *propagationCommenter) withComment(ctx context.Context, query string) string {
var cc commentCarrier

c.propagator.Inject(ctx, &cc)
Expand All @@ -69,5 +125,41 @@ func (c *commenter) withComment(ctx context.Context, query string) string {
return query
}

return fmt.Sprintf("%s /*%s*/", query, cc.Marshal())
return query + cc.Marshal()
}

type fixedCommenter string

// NewFixedCommenter returns a Commenter that will inject the attributes as a comment into SQL statements.
//
// Notice: This option is EXPERIMENTAL and may be changed or removed in a
// later release.
func NewFixedCommenter(attributes attribute.Set) Commenter {
var cc commentCarrier

i := attributes.Iter()
for i.Next() {
attr := i.Attribute()
if attr.Valid() {
cc.Set(string(attr.Key), attr.Value.AsString())
}
}

if len(cc) == 0 {
return noopCommenter{}
}

return fixedCommenter(cc.Marshal())
}

func (f fixedCommenter) Query(_ context.Context, query string) string {
return query + string(f)
}

func (f fixedCommenter) Exec(_ context.Context, query string) string {
return query + string(f)
}

func (f fixedCommenter) Prepare(_ context.Context, query string) string {
return query + string(f)
}
86 changes: 72 additions & 14 deletions commenter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/baggage"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)

func TestCommenter_WithComment(t *testing.T) {
func TestPropagationCommenter(t *testing.T) {
query := "foo"

traceID, err := trace.TraceIDFromHex("a3d3b88cf7994e554c1afbdceec1620b")
Expand All @@ -52,35 +53,24 @@ func TestCommenter_WithComment(t *testing.T) {

testCases := []struct {
name string
enabled bool
ctx context.Context
propagator propagation.TextMapPropagator
expected string
}{
{
name: "empty context",
enabled: true,
ctx: context.Background(),
propagator: stdPropagator,
expected: query,
},
{
name: "context with disable",
enabled: false,
ctx: ctx,
propagator: stdPropagator,
expected: query,
},
{
name: "nil propagator",
enabled: true,
ctx: ctx,
propagator: nil,
expected: query,
},
{
name: "context and propagator",
enabled: true,
ctx: ctx,
propagator: stdPropagator,
expected: query + " /*tracestate='rojo%3D00f067aa0ba902b7%2Ccongo%3Dt61rcWkgMzE',traceparent='00-a3d3b88cf7994e554c1afbdceec1620b-683ec6a9a3a265fb-01',baggage='foo%3Dbar'*/",
Expand All @@ -89,9 +79,77 @@ func TestCommenter_WithComment(t *testing.T) {

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
c := newCommenter(tc.enabled, tc.propagator)
c := NewPropagationCommenter(tc.propagator)

result := c.Query(tc.ctx, query)
assert.Equal(t, tc.expected, result)

result = c.Exec(tc.ctx, query)
assert.Equal(t, tc.expected, result)

result = c.Prepare(tc.ctx, query)
assert.Equal(t, tc.expected, result)
})
}
}

func TestNewFixedCommenter(t *testing.T) {
query := "foo"

traceID, err := trace.TraceIDFromHex("a3d3b88cf7994e554c1afbdceec1620b")
require.NoError(t, err)
spanID, err := trace.SpanIDFromHex("683ec6a9a3a265fb")
require.NoError(t, err)

ctx := trace.ContextWithSpanContext(context.Background(), trace.NewSpanContext(trace.SpanContextConfig{
TraceID: traceID,
SpanID: spanID,
}))

testCases := []struct {
name string
ctx context.Context
attributes attribute.Set
expected string
}{
{
name: "empty context + empty attributes",
ctx: context.Background(),
attributes: attribute.Set{},
expected: query,
},
{
name: "ignores invalid attributes",
ctx: ctx,
attributes: attribute.NewSet(
attribute.KeyValue{
Key: "",
Value: attribute.StringValue("bar"),
}),
expected: query,
},
{
name: "attributes",
ctx: ctx,
attributes: attribute.NewSet(
attribute.String("service", "go test"),
attribute.String("tracestate", "rojo=00f067aa0ba902b7,congo=t61rcWkgMzE"),
),
expected: query + " /*service='go+test',tracestate='rojo%3D00f067aa0ba902b7%2Ccongo%3Dt61rcWkgMzE'*/",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
c := NewFixedCommenter(tc.attributes)

result := c.Query(tc.ctx, query)
assert.Equal(t, tc.expected, result)

result = c.Exec(tc.ctx, query)
assert.Equal(t, tc.expected, result)

result := c.withComment(tc.ctx, query)
result = c.Prepare(tc.ctx, query)
assert.Equal(t, tc.expected, result)
})
}
Expand Down
11 changes: 5 additions & 6 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
"go.opentelemetry.io/otel/trace"
)
Expand Down Expand Up @@ -73,16 +72,14 @@ type config struct {
// Default use method as span name
SpanNameFormatter SpanNameFormatter

// SQLCommenterEnabled enables context propagation for database
// SQLCommenter enables context propagation for database
// by injecting a comment into SQL statements.
//
// Experimental
//
// Notice: This config is EXPERIMENTAL and may be changed or removed in a
// later release.
SQLCommenterEnabled bool
SQLCommenter *commenter
TextMapPropagator propagation.TextMapPropagator
SQLCommenter Commenter

// AttributesGetter will be called to produce additional attributes while creating spans.
// Default returns nil
Expand Down Expand Up @@ -191,7 +188,9 @@ func newConfig(options ...Option) *config {
metric.WithInstrumentationVersion(Version()),
)

cfg.SQLCommenter = newCommenter(cfg.SQLCommenterEnabled, cfg.TextMapPropagator)
if cfg.SQLCommenter == nil {
cfg.SQLCommenter = noopCommenter{}
}

var err error
if cfg.Instruments, err = newInstruments(cfg.Meter); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func TestNewConfig(t *testing.T) {
Attributes: []attribute.KeyValue{
semconv.DBSystemNameMySQL,
},
SQLCommenter: newCommenter(false, otel.GetTextMapPropagator()),
SQLCommenter: noopCommenter{},
}, cfg)
assert.NotNil(t, cfg.Instruments)
}
Expand Down
6 changes: 3 additions & 3 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func (c *otConn) ExecContext(
defer span.End()
}

res, err = execer.ExecContext(ctx, c.cfg.SQLCommenter.withComment(ctx, query), args)
res, err = execer.ExecContext(ctx, c.cfg.SQLCommenter.Exec(ctx, query), args)
if err != nil {
recordSpanError(span, c.cfg, err)
return nil, err
Expand Down Expand Up @@ -143,7 +143,7 @@ func (c *otConn) QueryContext(
defer span.End()
}

rows, err = queryer.QueryContext(queryCtx, c.cfg.SQLCommenter.withComment(queryCtx, query), args)
rows, err = queryer.QueryContext(queryCtx, c.cfg.SQLCommenter.Query(queryCtx, query), args)
if err != nil {
recordSpanError(span, c.cfg, err)
return nil, err
Expand All @@ -165,7 +165,7 @@ func (c *otConn) PrepareContext(ctx context.Context, query string) (stmt driver.
defer recordSpanErrorDeferred(span, c.cfg, &err)
}

commentedQuery := c.cfg.SQLCommenter.withComment(ctx, query)
commentedQuery := c.cfg.SQLCommenter.Prepare(ctx, query)

if preparer, ok := c.Conn.(driver.ConnPrepareContext); ok {
if stmt, err = preparer.PrepareContext(ctx, commentedQuery); err != nil {
Expand Down
19 changes: 3 additions & 16 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ package otelsql
import (
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)

Expand Down Expand Up @@ -76,8 +75,7 @@ func WithMeterProvider(provider metric.MeterProvider) Option {
})
}

// WithSQLCommenter will enable or disable context propagation for database
// by injecting a comment into SQL statements.
// WithSQLCommenter will enable a commenter allowing injecting a comment into SQL statements.
//
// e.g., a SQL query
//
Expand All @@ -91,20 +89,9 @@ func WithMeterProvider(provider metric.MeterProvider) Option {
//
// Notice: This option is EXPERIMENTAL and may be changed or removed in a
// later release.
func WithSQLCommenter(enabled bool) Option {
func WithSQLCommenter(commenter Commenter) Option {
return OptionFunc(func(cfg *config) {
cfg.SQLCommenterEnabled = enabled
})
}

// WithTextMapPropagator specifies a text map propagator to used by the SQLCommenter
// option. If none is specified, the global text map propagator is used.
//
// Notice: This option is EXPERIMENTAL and may be changed or removed in a
// later release.
func WithTextMapPropagator(propagator propagation.TextMapPropagator) Option {
return OptionFunc(func(cfg *config) {
cfg.TextMapPropagator = propagator
cfg.SQLCommenter = commenter
})
}

Expand Down
Loading
Loading