MSP-8974 add download flow, server migration to http

This commit is contained in:
chashintv committed 2026-11-19 12:48:34 +03:00
1 parent 4e01670ceb
commit 9aeb791c53
46 files changed
+5102 -124

No files matched your search

@@ -0,0 +1,61 @@
# Package `server_tracing`
Пакет `server_tracing` предоставляет middleware для серверной части HTTP-приложения, обеспечивая автоматическое создание span'ов OpenTelemetry для обработки входящих HTTP-запросов.
## Types
### Config
Структура `Config` определяет настройки трассировки для входящих HTTP-запросов.
**Fields:**
#### `Provider tracing.TracerProvider`
Провайдер трассировки (по умолчанию `tracing.DefaultProvider`).
#### `Propagator tracing.Propagator`
Пропагатор контекста (по умолчанию `tracing.DefaultPropagator`).
**Methods:**
#### `NewConfig() Config`
Создаёт конфигурацию с провайдером и пропагатором по умолчанию:
#### `func (c Config) Middleware() http2.Middleware`
Возвращает middleware, который добавляет в контекст обработки запроса OpenTelemetry span с необходимыми атрибутами. При этом:
- Используется `Propagator` для извлечения контекста трассировки из входящего запроса.
- Определяется имя span'а на основе маршрута или метода + пути.
- В span записываются стандартные HTTP-атрибуты, request ID, а также (если используется `buffer.Buffer`) количество прочитанных и записанных байт.
- Ошибки логируются и, если уровень логирования `Error`, также записываются в span через `RecordError`.
## Usage
### Default usage flow
```go
package main
import (
"github.com/txix-open/isp-kit/observability/tracing/http/server_tracing"
"github.com/txix-open/isp-kit/http"
)
func main(){
...
tracingCfg := server_tracing.NewConfig()
mux := http.NewServeMux()
handler := http.WrapHandler(tracingCfg.Middleware())(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// обработка запроса
return nil
})
mux.Handle("/example", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = handler(r.Context(), w, r)
}))
...
}
```
@@ -0,0 +1,117 @@
// Package server_tracing provides HTTP server middleware for distributed tracing.
package server_tracing
import (
"context"
"fmt"
"net/http"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/log/logutil"
"github.com/txix-open/isp-kit/metrics/http_metrics"
"github.com/txix-open/isp-kit/observability/tracing"
"github.com/txix-open/isp-kit/observability/tracing/http/semconvutil"
"github.com/txix-open/isp-kit/requestid"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
"go.opentelemetry.io/otel/trace"
)
// ReadBytesKey is the attribute key for the total number of bytes read from the request body.
var ReadBytesKey = attribute.Key("http.read_bytes")
// WroteBytesKey is the attribute key for the total number of bytes written to the response.
var WroteBytesKey = attribute.Key("http.wrote_bytes")
// tracerName identifies the tracer for HTTP server tracing.
const tracerName = "isp-kit/observability/tracing/http"
// Config holds the configuration for the HTTP server tracing middleware.
type Config struct {
// Provider is the tracer provider used to create tracers.
Provider tracing.TracerProvider
// Propagator is the text map propagator for context propagation.
Propagator tracing.Propagator
}
// NewConfig creates a new Config with default values.
func NewConfig() Config {
return Config{
Provider: tracing.DefaultProvider,
Propagator: tracing.DefaultPropagator,
}
}
// Middleware returns an HTTP server middleware that creates spans for incoming requests.
// It extracts trace context from request headers, creates a server span, and sets
// appropriate attributes including status code and request details. If the provider
// is a no-op, it returns a pass-through middleware.
func (c Config) Middleware() http2.Middleware {
if tracing.IsNoop(c.Provider) {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return next(ctx, w, r)
}
}
}
tracer := c.Provider.Tracer(tracerName)
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
ctx = c.Propagator.Extract(ctx, propagation.HeaderCarrier(r.Header))
attributes := semconvutil.HTTPServerRequest("", r)
attributes = append(attributes, tracing.RequestId.String(requestid.FromContext(ctx)))
opts := []trace.SpanStartOption{
trace.WithSpanKind(trace.SpanKindServer),
}
var spanName string
serverEndpoint := http_metrics.ServerEndpoint(ctx)
if serverEndpoint != "" {
attributes = append(attributes, semconv.HTTPRouteKey.String(serverEndpoint))
spanName = serverEndpoint
} else {
spanName = fmt.Sprintf("%s %s", r.Method, r.URL.Path)
}
ctx, span := tracer.Start(ctx, spanName, opts...)
defer span.End()
var scSource scSource
buff, isBuffer := w.(*buffer.Buffer)
if isBuffer {
scSource = buff
} else {
scSource = &writerWrapper{ResponseWriter: w}
}
err := next(ctx, scSource, r)
if isBuffer {
attributes = append(
attributes,
ReadBytesKey.Int(len(buff.RequestBody())),
WroteBytesKey.Int(len(buff.ResponseBody())),
)
}
attributes = append(
attributes,
semconv.HTTPStatusCode(scSource.StatusCode()),
)
if err != nil {
logLevel := logutil.LogLevelForError(err)
if logLevel == log.ErrorLevel {
span.RecordError(err)
}
}
span.SetStatus(semconvutil.HTTPServerStatus(scSource.StatusCode()))
span.SetAttributes(attributes...)
return err
}
}
}
@@ -0,0 +1,48 @@
package server_tracing
import (
"bufio"
"net"
"net/http"
"github.com/txix-open/isp-kit/errors"
)
// scSource is an interface for HTTP response writers that provide status code access.
type scSource interface {
http.ResponseWriter
// StatusCode returns the HTTP status code.
StatusCode() int
}
// writerWrapper wraps an http.ResponseWriter to capture the status code.
type writerWrapper struct {
http.ResponseWriter
// statusCode holds the captured HTTP status code.
statusCode int
}
// Hijack implements the http.Hijacker interface by delegating to the upstream response writer.
// It returns an error if the upstream does not support hijacking.
func (w *writerWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
upstream, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("writerWrapper: upstream writer doesn't implement Hijack")
}
return upstream.Hijack()
}
// StatusCode returns the captured HTTP status code, or http.StatusOK if not yet set.
func (w *writerWrapper) StatusCode() int {
if w.statusCode == 0 {
return http.StatusOK
}
return w.statusCode
}
// WriteHeader captures the status code and delegates to the upstream response writer.
func (w *writerWrapper) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}