Files
mtusi2026lab7/internal/platform/postgres/tracer.go
T
kudesn1k 8054913ef9
Application / e2e (pull_request) Blocked by required conditions
Application / unit (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Перенеси реализацию мессенджера из ЛР 6
Источник — проверенное рабочее дерево ЛР 6 поверх 18878d6, включая изменения после повторного ревью. SHA-256 списка исходных файлов: e45a3d85b41feff1da78dce3f20fd1f4af1c5ee629e6ed703218bc8e21ad58fe.
2026-11-30 10:54:41 +03:00

73 lines
2.0 KiB
Go

package postgres
import (
"context"
"errors"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"messenger/internal/platform/telemetry"
)
type queryTracer struct{}
func (queryTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
if !trace.SpanFromContext(ctx).IsRecording() {
return ctx
}
op, _, _ := strings.Cut(strings.TrimSpace(data.SQL), " ")
op = strings.ToUpper(op)
switch op {
case "SELECT", "INSERT", "UPDATE", "DELETE", "WITH", "BEGIN", "COMMIT", "ROLLBACK":
default:
op = "QUERY"
}
ctx, _ = otel.Tracer("messenger.postgres").Start(ctx, "postgres "+op, trace.WithSpanKind(trace.SpanKindClient))
return ctx
}
func (queryTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
endDatabaseSpan(ctx, data.Err)
}
func (queryTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
if !trace.SpanFromContext(ctx).IsRecording() {
return ctx
}
ctx, _ = otel.Tracer("messenger.postgres").Start(ctx, "postgres acquire", trace.WithSpanKind(trace.SpanKindClient))
return ctx
}
func (queryTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
endDatabaseSpan(ctx, data.Err)
}
func endDatabaseSpan(ctx context.Context, err error) {
s := trace.SpanFromContext(ctx)
if !s.IsRecording() {
return
}
defer s.End()
if err == nil || errors.Is(err, pgx.ErrNoRows) {
return
}
code := "query_error"
if unreachable(err) {
code = "unavailable"
} else if e, ok := errors.AsType[*pgconn.PgError](err); ok {
code = "postgres_error"
if e.Code == codeUniqueViolation {
code = "unique_violation"
}
}
s.SetStatus(codes.Error, code)
telemetry.Event(ctx, "db.error", attribute.String("error_code", code))
}