chore: get files from lab6
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
)
|
||||
|
||||
func Auth(users domain.UserRepository) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader("X-User-Id")
|
||||
if id == "" {
|
||||
abortUnauthorized(c, "требуется X-User-Id")
|
||||
return
|
||||
}
|
||||
|
||||
u, err := users.GetByID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
abortUnauthorized(c, "неизвестный пользователь")
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(CurrentUserKey, u)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func abortUnauthorized(c *gin.Context, msg string) {
|
||||
reqID := GetRequestID(c)
|
||||
body := dto.ErrorFromDomain(
|
||||
&domain.UnauthorizedError{Reason: msg},
|
||||
reqID,
|
||||
)
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, body)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
"high-loud-apps-labs/internal/httpapi/dto"
|
||||
"high-loud-apps-labs/internal/service"
|
||||
)
|
||||
|
||||
const authTimeout = 3 * time.Second
|
||||
|
||||
// BearerAuth читает Authorization: Bearer <token>, проверяет сессию
|
||||
// через SessionService и кладёт пользователя и токен в контекст.
|
||||
func BearerAuth(sessions *service.SessionService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token, ok := parseBearerToken(c)
|
||||
if !ok {
|
||||
abortBearer(c, "требуется Bearer")
|
||||
return
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), authTimeout)
|
||||
defer cancel()
|
||||
|
||||
user, err := sessions.Resolve(ctx, token)
|
||||
if err != nil {
|
||||
abortBearerWithErr(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(CurrentUserKey, user)
|
||||
c.Set(CurrentTokenKey, token)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// parseBearerToken читает Authorization: Bearer <opaque-token>.
|
||||
func parseBearerToken(c *gin.Context) (string, bool) {
|
||||
const prefix = "Bearer "
|
||||
auth := c.GetHeader("Authorization")
|
||||
if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimSpace(auth[len(prefix):])
|
||||
if token == "" {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
func abortBearer(c *gin.Context, reason string) {
|
||||
abortBearerWithErr(c, &domain.UnauthorizedError{Reason: reason})
|
||||
}
|
||||
|
||||
// abortBearerWithErr формирует ответ на ошибку аутентификации.
|
||||
// Заголовок WWW-Authenticate: Bearer выставляется только на 401;
|
||||
// при 503 (недоступность БД/кэша) — обычный ответ ошибки без challenge.
|
||||
func abortBearerWithErr(c *gin.Context, err error) {
|
||||
reqID := GetRequestID(c)
|
||||
status := dto.StatusFromError(err)
|
||||
if status == 401 {
|
||||
c.Header("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
}
|
||||
c.AbortWithStatusJSON(status, dto.ErrorFromDomain(err, reqID))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
CurrentUserKey = "current_user"
|
||||
CurrentTokenKey = "current_token"
|
||||
)
|
||||
|
||||
func CurrentUser(c *gin.Context) *domain.User {
|
||||
if v, ok := c.Get(CurrentUserKey); ok {
|
||||
if u, ok := v.(*domain.User); ok {
|
||||
return u
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func CurrentToken(c *gin.Context) string {
|
||||
if v, ok := c.Get(CurrentTokenKey); ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const InstanceIDHeader = "X-Instance-Id"
|
||||
|
||||
var instanceID = resolveInstanceID()
|
||||
|
||||
func resolveInstanceID() string {
|
||||
if v := os.Getenv("INSTANCE_ID"); v != "" {
|
||||
return v
|
||||
}
|
||||
if v, err := os.Hostname(); err == nil && v != "" {
|
||||
return v
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
|
||||
func Instance() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set(InstanceIDHeader, instanceID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetInstanceID() string { return instanceID }
|
||||
@@ -0,0 +1,35 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Logging записывает результат запроса с шаблоном маршрута и контекстом серверного спана.
|
||||
func Logging() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
c.Next()
|
||||
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = "unknown"
|
||||
}
|
||||
status := c.Writer.Status()
|
||||
level := slog.LevelInfo
|
||||
if status >= 500 {
|
||||
level = slog.LevelError
|
||||
}
|
||||
slog.LogAttrs(c.Request.Context(), level, "HTTP-запрос завершён",
|
||||
slog.String("instance_id", GetInstanceID()),
|
||||
slog.String("event", "http.request.completed"),
|
||||
slog.String("request_id", GetRequestID(c)),
|
||||
slog.String("http.request.method", c.Request.Method),
|
||||
slog.String("http.route", route),
|
||||
slog.Int("http.response.status_code", status),
|
||||
slog.Float64("duration_seconds", time.Since(start).Seconds()),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type httpMetrics struct {
|
||||
requestsTotal metric.Int64Counter
|
||||
requestDuration metric.Float64Histogram
|
||||
}
|
||||
|
||||
func newHTTPMetrics() *httpMetrics {
|
||||
meter := telemetry.Meter("httpapi")
|
||||
m := &httpMetrics{}
|
||||
var err error
|
||||
|
||||
m.requestsTotal, err = meter.Int64Counter(
|
||||
"http_requests_total",
|
||||
metric.WithDescription("Общее количество HTTP-запросов"),
|
||||
)
|
||||
if err != nil {
|
||||
panic("метрика http_requests_total: " + err.Error())
|
||||
}
|
||||
|
||||
m.requestDuration, err = meter.Float64Histogram(
|
||||
"http_request_duration_seconds",
|
||||
metric.WithDescription("Длительность HTTP-запроса"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(
|
||||
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10,
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
panic("метрика http_request_duration_seconds: " + err.Error())
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func Metrics() gin.HandlerFunc {
|
||||
m := newHTTPMetrics()
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
|
||||
c.Next()
|
||||
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = "unknown"
|
||||
}
|
||||
status := c.Writer.Status()
|
||||
statusClass := "unknown"
|
||||
if status >= 100 {
|
||||
statusClass = strconv.Itoa(status/100) + "xx"
|
||||
}
|
||||
|
||||
attrs := metric.WithAttributes(
|
||||
attribute.String("http.request.method", c.Request.Method),
|
||||
attribute.String("http.route", route),
|
||||
attribute.String("http.response.status_class", statusClass),
|
||||
)
|
||||
|
||||
duration := time.Since(start).Seconds()
|
||||
m.requestsTotal.Add(c.Request.Context(), 1, attrs)
|
||||
m.requestDuration.Record(c.Request.Context(), duration, attrs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
// OTel создаёт серверный span для каждого HTTP-запроса.
|
||||
//
|
||||
// Имя span: "<METHOD> <route_template>", например "GET /api/v1/chats/:chat_id".
|
||||
// Родительский контекст извлекается из заголовков W3C traceparent чтобы связать внешний клиент (или LB) с внутренними спанами.
|
||||
|
||||
func OTel() gin.HandlerFunc {
|
||||
tracer := telemetry.Tracer("httpapi")
|
||||
return func(c *gin.Context) {
|
||||
// 1. Извлекаем родительский контекст из заголовков
|
||||
parentCtx := otel.GetTextMapPropagator().Extract(
|
||||
c.Request.Context(),
|
||||
propagation.HeaderCarrier(c.Request.Header),
|
||||
)
|
||||
|
||||
// 2. Стартуем span с временным именем (route ещё неизвестен)
|
||||
ctx, span := tracer.Start(parentCtx,
|
||||
c.Request.Method+" unknown",
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// 3. Кладём контекст в запрос, чтобы дочерние спаны (БД, S3, Redis) видели родителя
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
|
||||
// 4. Базовые атрибуты, известные до выполнения handler
|
||||
span.SetAttributes(
|
||||
attribute.String("http.request.method", c.Request.Method),
|
||||
attribute.String("url.path", c.Request.URL.Path),
|
||||
attribute.String("url.scheme", scheme(c)),
|
||||
attribute.String("server.address", c.Request.Host),
|
||||
attribute.String("client.address", c.ClientIP()),
|
||||
attribute.String("user_agent.original", c.Request.UserAgent()),
|
||||
)
|
||||
|
||||
// 5. Выполняем цепочку middleware и handler
|
||||
c.Next()
|
||||
|
||||
// 6. После выполнения знаем route template — обновляем имя span
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = "unknown"
|
||||
}
|
||||
span.SetName(c.Request.Method + " " + route)
|
||||
span.SetAttributes(attribute.String("http.route", route))
|
||||
|
||||
// 7. Статус ответа
|
||||
status := c.Writer.Status()
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", status))
|
||||
if status >= 500 {
|
||||
span.SetStatus(codes.Error, http.StatusText(status))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func scheme(c *gin.Context) string {
|
||||
if c.Request.TLS != nil {
|
||||
return "https"
|
||||
}
|
||||
if v := c.GetHeader("X-Forwarded-Proto"); v != "" {
|
||||
return v
|
||||
}
|
||||
return "http"
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
RequestIDKey = "request_id"
|
||||
RequestIDHeader = "X-Request-Id"
|
||||
)
|
||||
|
||||
func RequestID() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader(RequestIDHeader)
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
c.Set(RequestIDKey, id)
|
||||
c.Writer.Header().Set(RequestIDHeader, id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetRequestID(c *gin.Context) string {
|
||||
if v, ok := c.Get(RequestIDKey); ok {
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
Reference in New Issue
Block a user