forked from mtusi2026/mtusi2026lab6
100 lines
3.2 KiB
Go
100 lines
3.2 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/metric"
|
|
"go.opentelemetry.io/otel/trace"
|
|
|
|
"high-loud-apps-labs/internal/telemetry"
|
|
)
|
|
|
|
type poolTracer struct {
|
|
tracer trace.Tracer
|
|
duration metric.Float64Histogram
|
|
waiting metric.Int64UpDownCounter
|
|
}
|
|
|
|
func newPoolTracer() (*poolTracer, error) {
|
|
meter := telemetry.Meter("storage.postgres")
|
|
duration, err := meter.Float64Histogram("db_pool_acquire_duration_seconds",
|
|
metric.WithUnit("s"),
|
|
metric.WithExplicitBucketBoundaries(0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5),
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
waiting, err := meter.Int64UpDownCounter("db_pool_waiting",
|
|
metric.WithDescription("Число незавершённых вызовов Acquire"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &poolTracer{tracer: telemetry.Tracer("storage.postgres"), duration: duration, waiting: waiting}, nil
|
|
}
|
|
|
|
type acquireStartKey struct{}
|
|
|
|
func (t *poolTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
|
ctx, _ = t.tracer.Start(ctx, "postgresql.acquire")
|
|
t.waiting.Add(ctx, 1)
|
|
return context.WithValue(ctx, acquireStartKey{}, time.Now())
|
|
}
|
|
|
|
func (t *poolTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
|
|
t.waiting.Add(ctx, -1)
|
|
t.duration.Record(ctx, time.Since(ctx.Value(acquireStartKey{}).(time.Time)).Seconds())
|
|
endSpan(ctx, data.Err)
|
|
}
|
|
|
|
func (t *poolTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
|
// Передаём только известный SQL-глагол, без текста запроса и параметров.
|
|
op := "QUERY"
|
|
sql := strings.TrimSpace(data.SQL)
|
|
if i := strings.IndexAny(sql, " \r\n\t;("); i >= 0 {
|
|
sql = sql[:i]
|
|
}
|
|
switch verb := strings.ToUpper(sql); verb {
|
|
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK", "WITH":
|
|
op = verb
|
|
}
|
|
ctx, _ = t.tracer.Start(ctx, "postgresql."+op, trace.WithSpanKind(trace.SpanKindClient),
|
|
trace.WithAttributes(attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op)))
|
|
return ctx
|
|
}
|
|
|
|
func (t *poolTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
|
|
endSpan(ctx, data.Err)
|
|
}
|
|
|
|
func endSpan(ctx context.Context, err error) {
|
|
span := trace.SpanFromContext(ctx)
|
|
if err != nil {
|
|
span.SetStatus(codes.Error, "операция PostgreSQL не выполнена")
|
|
}
|
|
span.End()
|
|
}
|
|
|
|
func ObservePool(pool *pgxpool.Pool) (metric.Registration, error) {
|
|
meter := telemetry.Meter("storage.postgres")
|
|
connections, err := meter.Int64ObservableGauge("db_pool_connections")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return meter.RegisterCallback(func(_ context.Context, observer metric.Observer) error {
|
|
stat := pool.Stat()
|
|
observe := func(state string, count int32) {
|
|
observer.ObserveInt64(connections, int64(count), metric.WithAttributes(attribute.String("state", state)))
|
|
}
|
|
observe("used", stat.AcquiredConns())
|
|
observe("idle", stat.IdleConns())
|
|
observe("max", stat.MaxConns())
|
|
return nil
|
|
}, connections)
|
|
}
|