Перенеси реализацию мессенджера из ЛР 6
Источник — проверенное рабочее дерево ЛР 6 поверх 18878d6, включая изменения после повторного ревью. SHA-256 списка исходных файлов: e45a3d85b41feff1da78dce3f20fd1f4af1c5ee629e6ed703218bc8e21ad58fe.
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"messenger/internal/platform/telemetry"
|
||||
)
|
||||
|
||||
func businessTelemetry() gin.HandlerFunc {
|
||||
m := otel.Meter("messenger.http")
|
||||
requests, _ := m.Int64Counter("messenger.http.requests")
|
||||
duration, _ := m.Float64Histogram("messenger.http.duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.001, .005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10))
|
||||
tracer := otel.Tracer("messenger.http")
|
||||
return func(c *gin.Context) {
|
||||
route := c.FullPath()
|
||||
if !strings.HasPrefix(route, "/api/v1/") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
method := c.Request.Method
|
||||
parent := otel.GetTextMapPropagator().Extract(c.Request.Context(), propagation.HeaderCarrier(c.Request.Header))
|
||||
ctx, span := tracer.Start(parent, method+" "+route, trace.WithSpanKind(trace.SpanKindServer))
|
||||
defer span.End()
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
start := time.Now()
|
||||
c.Next()
|
||||
status := c.Writer.Status()
|
||||
attrs := []attribute.KeyValue{attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", strconv.Itoa(status/100)+"xx")}
|
||||
opts := metric.WithAttributes(attrs...)
|
||||
requests.Add(ctx, 1, opts)
|
||||
duration.Record(ctx, time.Since(start).Seconds(), opts)
|
||||
attrs = append(attrs, attribute.String("request_id", RequestID(c)))
|
||||
span.SetAttributes(attrs...)
|
||||
if status >= 500 {
|
||||
span.SetStatus(codes.Error, "server_error")
|
||||
}
|
||||
telemetry.Event(ctx, "http.request", attrs...)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user