MSP-8172 Add vendor

This commit is contained in:
Синельник Тимур Романович committed 2026-07-29 12:52:27 +03:00
1 parent 5175d87e08
commit eb066cb055
2619 files changed
+757077 -2

No files matched your search

@@ -0,0 +1,81 @@
# Package `sql_tracing`
Пакет `sql_tracing` предоставляет инструменты трассировки SQL-запросов для PostgreSQL-драйвера `pgx` с использованием OpenTelemetry. Поддерживает автоматическое создание span'ов, запись аргументов и SQL-выражений, а также метрики SQL-операций через `sql_metrics`.
## Types
### Tracer
Структура `Tracer` реализует интерфейс `pgx.QueryTracer` и обеспечивает создание и завершение span'ов при выполнении SQL-запросов. Позволяет гибко настраивать включение SQL-выражений и параметров в span'ы.
**Methods:**
#### `NewTracer(tracer trace.Tracer, config Config) Tracer`
Создаёт трейсер.
#### `(t Tracer) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context`
Создаёт span перед выполнением SQL-запроса. Возвращает новый `context.Context` с активным span.
#### `(t Tracer) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData)`
Завершает span после выполнения SQL-запроса. В случае ошибки (кроме `sql.ErrNoRows`) записывает её в span и устанавливает статус `Error`.
### Config
Структура `Config` содержит параметры конфигурации для трассировки SQL-запросов.
**Fields:**
#### `Provider tracing.TracerProvider`
Провайдер трассировки (по умолчанию `tracing.DefaultProvider`)
#### `EnableStatement bool`
Включает добавление SQL-выражения в атрибуты span'а
#### `EnableArgs bool`
Включает добавление аргументов запроса в атрибуты span'а
**Methods**
#### `NewConfig() Config`
Создаёт конфигурацию трассировки с провайдером по умолчанию.
#### `(c Config) QueryTracer() pgx.QueryTracer`
Возвращает либо полноценный трассировщик `Tracer`, либо `noop`, если провайдер трассировки является "заглушкой".
## Usage
### Подключение трассировки SQL-запросов
```go
import (
"github.com/txix-open/isp-kit/observability/tracing"
"github.com/txix-open/isp-kit/observability/sql_tracing"
"github.com/jackc/pgx/v5"
)
func setupTracer() pgx.QueryTracer {
cfg := sql_tracing.NewConfig()
cfg.EnableStatement = true
cfg.EnableArgs = true
return cfg.QueryTracer()
}
```
### Регистрация в `pgx` соединении
```go
connConfig := pgx.ConnConfig{ /* ваша конфигурация */ }
connConfig.Tracer = setupTracer()
```
Теперь каждый SQL-запрос будет автоматически трассироваться с учётом включённых опций (запрос, параметры, request ID и т.п.).
@@ -0,0 +1,38 @@
// Package sql_tracing provides pgx v5 query tracing for distributed tracing.
package sql_tracing
import (
"github.com/jackc/pgx/v5"
"github.com/txix-open/isp-kit/observability/tracing"
)
// tracerName identifies the tracer for SQL tracing.
const tracerName = "isp-kit/observability/tracing/sql"
// Config holds the configuration for SQL query tracing.
type Config struct {
// Provider is the tracer provider used to create tracers.
Provider tracing.TracerProvider
// EnableStatement determines whether to include SQL statements in spans.
EnableStatement bool
// EnableArgs determines whether to include query arguments in spans.
EnableArgs bool
}
// NewConfig creates a new Config with default values.
func NewConfig() Config {
return Config{
Provider: tracing.DefaultProvider,
}
}
// QueryTracer returns a pgx QueryTracer for instrumenting database queries.
// It returns a no-op tracer if the provider is a no-op.
func (c Config) QueryTracer() pgx.QueryTracer {
if tracing.IsNoop(c.Provider) {
return noop{}
}
tracer := c.Provider.Tracer(tracerName)
return NewTracer(tracer, c)
}
@@ -0,0 +1,19 @@
package sql_tracing
import (
"context"
"github.com/jackc/pgx/v5"
)
// noop is a no-op implementation of pgx.QueryTracer.
type noop struct{}
// TraceQueryStart returns the context unchanged without creating a span.
func (n noop) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
return ctx
}
// TraceQueryEnd performs no operation.
func (n noop) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) {
}
@@ -0,0 +1,101 @@
package sql_tracing
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/jackc/pgx/v5"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
"github.com/txix-open/isp-kit/observability/tracing"
"github.com/txix-open/isp-kit/requestid"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
"go.opentelemetry.io/otel/trace"
)
// QueryParametersKey is the attribute key for storing query arguments.
var QueryParametersKey = attribute.Key("pgx.query.parameters")
// contextKey is used for storing the span in the context.
type contextKey struct{}
// contextKeyValue is the global context key instance.
var contextKeyValue = contextKey{}
// Tracer implements pgx.QueryTracer for tracing SQL queries.
type Tracer struct {
tracer trace.Tracer
config Config
}
// NewTracer creates a new Tracer with the given tracer and configuration.
func NewTracer(tracer trace.Tracer, config Config) Tracer {
return Tracer{
tracer: tracer,
config: config,
}
}
// TraceQueryStart creates a span for the beginning of a database query.
// It extracts the operation label from context or from the SQL statement
// (for BEGIN/COMMIT). The span includes the SQL statement and arguments
// if configured. Returns the context with the span attached.
func (t Tracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
label := sql_metrics.OperationLabelFromContext(ctx)
if label == "" && strings.HasPrefix(data.SQL, "begin") {
label = "BEGIN"
}
if label == "" && strings.HasPrefix(data.SQL, "commit") {
label = "COMMIT"
}
if label == "" {
return ctx
}
attributes := []attribute.KeyValue{
tracing.RequestId.String(requestid.FromContext(ctx)),
}
if t.config.EnableStatement {
attributes = append(attributes, semconv.DBStatement(data.SQL))
}
if t.config.EnableArgs {
args := make([]string, 0, len(data.Args))
for _, arg := range data.Args {
args = append(args, fmt.Sprintf("%+v", arg))
}
attributes = append(attributes, QueryParametersKey.StringSlice(args))
}
opts := []trace.SpanStartOption{
trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(attributes...),
}
spanName := fmt.Sprintf("SQL query %s", label)
ctx, span := t.tracer.Start(ctx, spanName, opts...) //nolint:spancheck
return context.WithValue(ctx, contextKeyValue, span) //nolint:spancheck
}
// TraceQueryEnd ends the span for a database query and records any errors.
// It skips recording errors for sql.ErrNoRows.
func (t Tracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
span, _ := ctx.Value(contextKeyValue).(trace.Span)
if span == nil {
return
}
err := data.Err
if err != nil && !errors.Is(err, sql.ErrNoRows) {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
span.End()
}