3 Commits
8 changed files with 316 additions and 41 deletions
+35 -6
View File
@@ -4,6 +4,8 @@ import (
"context"
"errors"
"log"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
@@ -13,6 +15,7 @@ import (
"high-loud-apps-labs/internal/service"
"high-loud-apps-labs/internal/storage/postgres"
s3store "high-loud-apps-labs/internal/storage/s3"
"high-loud-apps-labs/internal/telemetry"
)
func main() {
@@ -26,8 +29,31 @@ func main() {
// return
// }
instanceID := os.Getenv("INSTANCE_ID")
if instanceID == "" {
instanceID, _ = os.Hostname()
}
tel, err := telemetry.Setup(context.Background(), telemetry.SetupConfig{
ServiceName: "messenger-reconciler",
ServiceVersion: "1.6.0",
InstanceID: instanceID,
Environment: "lab",
})
if err != nil {
log.Fatalf("reconciler: телеметрия: %v", err)
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := tel.Shutdown(ctx); err != nil {
log.Printf("reconciler: остановка телеметрии: %v", err)
}
}()
slog.SetDefault(tel.Logger)
if !cfg.S3Configured() {
log.Fatal("reconciler: S3 не настроен: задайте S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID_FILE/S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY_FILE/S3_SECRET_ACCESS_KEY")
slog.Error("reconciler: S3 не настроен: задайте S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID_FILE/S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY_FILE/S3_SECRET_ACCESS_KEY")
os.Exit(1)
}
ctx := context.Background()
@@ -41,7 +67,8 @@ func main() {
ConnectTimeout: 5 * time.Second,
})
if err != nil {
log.Fatalf("reconciler: БД: %v", err)
slog.Error("reconciler: ошибка БД", "error", err)
os.Exit(1)
}
defer pool.Close()
@@ -58,9 +85,11 @@ func main() {
if err != nil {
var unavailable *domain.UnavailableError
if errors.As(err, &unavailable) {
log.Fatalf("reconciler: s3: %v (reason: %s)", err, unavailable.Reason)
slog.Error("reconciler: ошибка s3", "error", err, "reason", unavailable.Reason)
} else {
slog.Error("reconciler: ошибка s3", "error", err)
}
log.Fatalf("reconciler: s3: %v", err)
os.Exit(1)
}
rec := service.NewReconciler(
@@ -74,7 +103,7 @@ func main() {
runCtx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
defer stop()
log.Printf("reconciler: запущен (interval=%s, grace=%s)", cfg.ReconcilerInterval, cfg.ReconcilerGracePeriod)
slog.Info("reconciler: запущен", "interval", cfg.ReconcilerInterval, "grace", cfg.ReconcilerGracePeriod)
rec.Run(runCtx, cfg.ReconcilerInterval)
log.Println("reconciler: остановлен")
slog.Info("reconciler: остановлен")
}
+43 -12
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"os/signal"
@@ -24,6 +25,7 @@ import (
"high-loud-apps-labs/internal/storage/postgres"
redisstore "high-loud-apps-labs/internal/storage/redis"
s3store "high-loud-apps-labs/internal/storage/s3"
"high-loud-apps-labs/internal/telemetry"
)
func main() {
@@ -39,6 +41,29 @@ func main() {
log.Fatalf("конфигурация: %v", err)
}
instanceID := os.Getenv("INSTANCE_ID")
if instanceID == "" {
instanceID, _ = os.Hostname()
}
tel, err := telemetry.Setup(context.Background(), telemetry.SetupConfig{
ServiceName: "messenger-api",
ServiceVersion: "1.6.0",
InstanceID: instanceID,
Environment: "lab",
})
if err != nil {
log.Fatalf("телеметрия: %v", err)
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := tel.Shutdown(ctx); err != nil {
log.Printf("остановка телеметрии: %v", err)
}
}()
// Делаем логгер глобальным для всего приложения
slog.SetDefault(tel.Logger)
addr := cfg.Host + ":" + cfg.Port
ctx := context.Background()
@@ -51,7 +76,8 @@ func main() {
ConnectTimeout: 5 * time.Second,
})
if err != nil {
log.Fatalf("БД: %v", err)
slog.Error("Ошибка подключения к БД", "error", err)
os.Exit(1)
}
defer pool.Close()
@@ -59,7 +85,8 @@ func main() {
rabbitPub, err := broker.NewRabbitPublisher(cfg.RabbitMQURL)
if err != nil {
log.Fatalf("rabbitmq: %v", err)
slog.Error("Ошибка подключения к RabbitMQ", "error", err)
os.Exit(1)
}
defer rabbitPub.Close()
@@ -79,7 +106,8 @@ func main() {
messageSvc := service.NewMessageService(store.Messages(), store.Chats(), cfg.IdempotencyTTL)
if !cfg.S3Configured() {
log.Fatal("S3 не настроен: задайте S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID_FILE/S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY_FILE/S3_SECRET_ACCESS_KEY")
slog.Error("S3 не настроен: задайте S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID_FILE/S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY_FILE/S3_SECRET_ACCESS_KEY")
os.Exit(1)
}
objectStorage, err := s3store.New(ctx, s3store.Config{
@@ -93,9 +121,11 @@ func main() {
if err != nil {
var unavailable *domain.UnavailableError
if errors.As(err, &unavailable) {
log.Fatalf("s3: %v (reason: %s)", err, unavailable.Reason)
slog.Error("Ошибка S3", "error", err, "reason", unavailable.Reason)
} else {
slog.Error("Ошибка S3", "error", err)
}
log.Fatalf("s3: %v", err)
os.Exit(1)
}
attachmentSvc := service.NewAttachmentService(
@@ -148,9 +178,10 @@ func main() {
// }
go func() {
log.Printf("Запускаем на %s (SESSION_STORE=%s, RECONCILER_ENABLED=%v)", addr, cfg.SessionStore)
slog.Info("Запускаем сервер", "addr", addr, "session_store", cfg.SessionStore)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("Ошибка запуска: %v", err)
slog.Error("Ошибка запуска сервера", "error", err)
os.Exit(1)
}
}()
@@ -158,26 +189,26 @@ func main() {
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Printf("Получен сигнал завершения; readiness выключен, drain %s", cfg.ShutdownDrain)
slog.Info("Получен сигнал завершения; readiness выключен", "drain", cfg.ShutdownDrain)
ready.Store(false)
outboxCancel()
// reconcilerCancel()
if cfg.ShutdownDrain > 0 {
time.Sleep(cfg.ShutdownDrain)
}
log.Println("Drain завершён, останавливаем HTTP-сервер...")
slog.Info("Drain завершён, останавливаем HTTP-сервер...")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Fatalf("Ошибка при остановке: %v", err)
slog.Error("Ошибка при остановке", "error", err)
}
log.Println("Сервер остановлен")
slog.Info("Сервер остановлен")
}
func runMigrate() error {
// Пока стандартный log, поменяем потом на slog
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("конфигурация: %w", err)
+33 -7
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"log"
"log/slog"
"os"
"os/signal"
"syscall"
@@ -15,6 +16,7 @@ import (
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/storage/postgres"
s3store "high-loud-apps-labs/internal/storage/s3"
"high-loud-apps-labs/internal/telemetry"
"high-loud-apps-labs/internal/worker"
)
@@ -24,10 +26,33 @@ func main() {
log.Fatalf("конфигурация: %v", err)
}
instanceID := os.Getenv("INSTANCE_ID")
if instanceID == "" {
instanceID, _ = os.Hostname()
}
tel, err := telemetry.Setup(context.Background(), telemetry.SetupConfig{
ServiceName: "messenger-worker",
ServiceVersion: "1.6.0",
InstanceID: instanceID,
Environment: "lab",
})
if err != nil {
log.Fatalf("телеметрия: %v", err)
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := tel.Shutdown(ctx); err != nil {
log.Printf("остановка телеметрии: %v", err)
}
}()
slog.SetDefault(tel.Logger)
ctx := context.Background()
pool, err := postgres.Connect(ctx, postgres.Config{URL: cfg.DatabaseURL})
if err != nil {
log.Fatalf("БД: %v", err)
slog.Error("Ошибка подключения к БД", "error", err)
os.Exit(1)
}
defer pool.Close()
@@ -41,7 +66,8 @@ func main() {
Region: cfg.S3Region,
})
if err != nil {
log.Fatalf("S3: %v", err)
slog.Error("Ошибка подключения к S3", "error", err)
os.Exit(1)
}
pipeline := worker.NewPipeline(store.Attachments(), objectStorage, store.Variants(), store.FailedJobs(), store.Outbox())
@@ -52,7 +78,7 @@ func main() {
if err == nil {
break // Нормальное завершение по сигналу
}
log.Printf("worker: ошибка соединения, перезапуск через 5 секунд: %v", err)
slog.Error("Ошибка соединения worker, перезапуск через 5 секунд", "error", err)
time.Sleep(5 * time.Second)
}
}
@@ -82,7 +108,7 @@ func runWorker(ctx context.Context, cfg *config.Config, pipeline *worker.Pipelin
return err
}
log.Println("worker: запущен и слушает очередь")
slog.Info("Worker запущен и слушает очередь")
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
@@ -90,7 +116,7 @@ func runWorker(ctx context.Context, cfg *config.Config, pipeline *worker.Pipelin
for {
select {
case <-quit:
log.Println("worker: получен сигнал завершения, останавливаемся...")
slog.Info("Worker получил сигнал завершения, останавливаемся...")
return nil
case d, ok := <-msgs:
if !ok {
@@ -98,12 +124,12 @@ func runWorker(ctx context.Context, cfg *config.Config, pipeline *worker.Pipelin
}
var msg domain.JobMessage
if err := json.Unmarshal(d.Body, &msg); err != nil {
log.Printf("worker: битое сообщение: %v", err)
slog.Error("Worker получил битое сообщение", "error", err)
_ = d.Nack(false, false)
continue
}
if err := pipeline.Process(ctx, msg.AttachmentID, msg.PipelineVersion); err != nil {
log.Printf("worker: ошибка %s: %v", msg.AttachmentID, err)
slog.Error("Ошибка обработки задачи", "attachment_id", msg.AttachmentID, "error", err)
_ = d.Nack(false, true)
} else {
_ = d.Ack(false)
+17 -16
View File
@@ -29,6 +29,7 @@ require (
github.com/go-logr/stdr v1.2.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.72.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
@@ -39,20 +40,20 @@ require (
)
require (
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/bytedance/gopkg v0.1.4 // indirect
github.com/bytedance/sonic v1.15.4 // indirect
github.com/bytedance/sonic/loader v0.5.2 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/cloudwego/base64x v0.1.7 // indirect
github.com/disintegration/imaging v1.6.2
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
github.com/gen2brain/webp v0.6.4
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/gin-contrib/sse v1.1.2 // indirect
github.com/go-playground/locales v0.14.2 // indirect
github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/go-playground/validator/v10 v10.30.5 // indirect
github.com/goccy/go-json v0.11.2 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
@@ -61,8 +62,8 @@ require (
github.com/klauspost/compress v1.19.2 // indirect
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/klauspost/crc32 v1.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/minio/crc64nvme v1.1.1 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
@@ -71,20 +72,20 @@ require (
github.com/pelletier/go-toml/v2 v2.4.3 // indirect
github.com/philhofer/fwd v1.2.0 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/quic-go/quic-go v0.63.0 // indirect
github.com/rabbitmq/amqp091-go v1.16.0
github.com/rs/xid v1.6.0 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/tinylib/msgp v1.6.4 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
github.com/ugorji/go/codec v1.3.2 // indirect
github.com/zeebo/xxh3 v1.1.0 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
go.mongodb.org/mongo-driver/v2 v2.9.1 // indirect
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/arch v0.31.0 // indirect
golang.org/x/net v0.60.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
+34
View File
@@ -4,16 +4,24 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM=
github.com/bytedance/gopkg v0.1.4/go.mod h1:v1zWfPm21Fb+OsyXN2VAHdL6TBb2L88anLQgdyje6R4=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic v1.15.4 h1:FgtV/4aBHpla9AxuMpuuzVUpa/Cf3izufkxNmnEzdI8=
github.com/bytedance/sonic v1.15.4/go.mod h1:8e51yTPdY8M6t+vvGL1c2Y1xL9i+frEeIAQAEl75NUc=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/bytedance/sonic/loader v0.5.2 h1:0QtP1gevc1OZ6/H8Lb9BRZiCXd1Ftjd3OKuj1T1lBIo=
github.com/bytedance/sonic/loader v0.5.2/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/cloudwego/base64x v0.1.7 h1:NppS+Fgzg5ovhn4NkUXaDT3x9jldgH5ToMCqzBSi2zI=
github.com/cloudwego/base64x v0.1.7/go.mod h1:Cu1PV9zfrSf7ET2tIbWbbEy7jO7HHJ13q4X2SQ8aWYg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -25,10 +33,14 @@ github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/gen2brain/webp v0.6.4 h1:SUDdmxADOAiPQ+5ylNmuHhuYf2dOi0KgKZHL5vpVCNU=
github.com/gen2brain/webp v0.6.4/go.mod h1:iGWMaCSw7t3I/Cv9llzEKmpnR36S8lS8VL/ZVjxU0JE=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-contrib/sse v1.1.2 h1:MU2fgl1RrdYTMcgJLtz2kJF+vPg3xrqaaKfUUU18tCo=
github.com/gin-contrib/sse v1.1.2/go.mod h1:QXzuVkA0YO7o/gun03UI1Q+FTI8ZV/n5t03kIQAI89s=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
@@ -40,12 +52,20 @@ github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lY
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4=
github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-json v0.11.2 h1:jdZv93Tt4ioR8yW1CoNsvSxrcZlCXAUU1aZXN7gpXUA=
github.com/goccy/go-json v0.11.2/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
@@ -80,8 +100,12 @@ github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI=
@@ -108,6 +132,8 @@ github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/quic-go/quic-go v0.63.0 h1:LIFGHI4PFUhhw2dDD1ARHdCff143ffMHwZtbnbuJ78A=
github.com/quic-go/quic-go v0.63.0/go.mod h1:RAro2j2yN9a9EiPACLHT9IB2NXCvGQmmo/alT0yYI0w=
github.com/rabbitmq/amqp091-go v1.16.0 h1:1O8oQqnj9hLACoo6CVMgn57z2pLWXvgemhh4GsquV+Y=
github.com/rabbitmq/amqp091-go v1.16.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/redis/go-redis/v9 v9.22.0 h1:laDvpYXTJtZLloinw1fA5Kqd6HAEH2XKxOkG/PDq2F0=
@@ -137,16 +163,22 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/ugorji/go/codec v1.3.2 h1:zkEASHHyEClGeURfgNT9PJZVfAbs9oEX9QXggwWNJbc=
github.com/ugorji/go/codec v1.3.2/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.mongodb.org/mongo-driver/v2 v2.9.1 h1:jewiFs2m1/VOQp8qhFshX6hWZ+EAXDhZHXExAUMcOgQ=
go.mongodb.org/mongo-driver/v2 v2.9.1/go.mod h1:SHKN0IWkKmEVGHLjXnni6s4wPKX4v86FTgOeJJFuXcA=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0 h1:/CdgE52i1OEPHhsGUqrggYNRaZy4v4YgVenGd52dRBI=
go.opentelemetry.io/contrib/bridges/otelslog v0.21.0/go.mod h1:9pBdbVbuehIDzxN4accnzzxEUPT8Nq7grbZMo+J1VN4=
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.72.0 h1:Vgm7vrC26vvecffpDcy2UINqBvASUg5qkfZle3Yrkug=
go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin v0.72.0/go.mod h1:zgCChxie/dA3qG7IgZGswax6voxkOR4+33msLT/RgNg=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.23.0 h1:5WVp40k2fJHuc5BtNTgKk+EugKFT8Eg3lywFfCPI/nE=
@@ -187,6 +219,8 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/arch v0.31.0 h1:22MlEb14/O/EPCYHFxsDdv5TuLD5dMjT5e2QeJw4ULk=
golang.org/x/arch v0.31.0/go.mod h1:KcJSod3cqT2dKcjBxqTyGfbumNikqU9p5tHJinPJnuY=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 h1:hVwzHzIUGRjiF7EcUjqNxk3NCfkPxbDKRdnNE1Rpg0U=
@@ -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"
}
+2
View File
@@ -24,6 +24,8 @@ func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
r.Use(gin.Recovery())
r.Use(middleware.RequestID())
r.Use(middleware.Instance())
r.Use(middleware.Metrics())
r.Use(middleware.OTel())
r.GET("/health/live", h.Health.Live)
r.GET("/health/ready", h.Health.Ready)