Лаб6 - оценка 4

This commit is contained in:
Rakshasa2
2026-11-19 18:40:32 +03:00
parent 470d9d6f1e
commit dbce1eb574
62 changed files with 6087 additions and 15 deletions
+283
View File
@@ -0,0 +1,283 @@
package main
import (
"context"
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"mtusi2026lab6-fork/src/internal/handler"
"mtusi2026lab6-fork/src/internal/session"
"mtusi2026lab6-fork/src/internal/storage"
"mtusi2026lab6-fork/src/internal/store"
"mtusi2026lab6-fork/src/internal/telemetry"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/metric"
)
var instanceID = func() string {
if v := os.Getenv("INSTANCE_ID"); v != "" {
return v
}
if h, err := os.Hostname(); err == nil && h != "" {
return h
}
return "unknown"
}()
type streamPublisher struct {
rdb *redis.Client
stream string
}
func (p *streamPublisher) PublishJob(ctx context.Context, jobID string, traceparent string) error {
values := map[string]interface{}{
"job_id": jobID,
}
if traceparent != "" {
values["traceparent"] = traceparent
}
return p.rdb.XAdd(ctx, &redis.XAddArgs{
Stream: p.stream,
Values: values,
}).Err()
}
func RequestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rid := uuid.New().String()
w.Header().Set("X-Request-Id", rid)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), handler.RequestIDKey, rid)))
})
}
func InstanceIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Instance-Id", instanceID)
next.ServeHTTP(w, r)
})
}
func main() {
serviceName := os.Getenv("OTEL_SERVICE_NAME")
if serviceName == "" {
serviceName = "messenger-api"
}
providers, err := telemetry.Init(context.Background(), serviceName)
if err != nil {
slog.Warn("telemetry init failed, running with fallback", "error", err)
}
logger := slog.New(telemetry.NewTraceContextHandler(providers.Logger.Handler()))
slog.SetDefault(logger)
logger.Info("worker starting", "instance", instanceID)
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
dbURL = "postgres://lab4:lab4@postgres:5432/lab4?sslmode=disable&timezone=UTC"
}
logger.Info("connecting to PostgreSQL", "instance", instanceID)
pgStore, err := store.NewPostgres(dbURL)
if err != nil {
logger.Error("failed to connect to database", "error", err)
os.Exit(1)
}
if providers != nil && providers.Meter != nil {
m := providers.Meter
acq, _ := m.Int64ObservableGauge("db_pool_acquired_conns")
idle, _ := m.Int64ObservableGauge("db_pool_idle_conns")
mx, _ := m.Int64ObservableGauge("db_pool_max_conns")
_, _ = m.RegisterCallback(func(_ context.Context, o metric.Observer) error {
st := pgStore.PoolStats()
o.ObserveInt64(acq, int64(st.AcquiredConns))
o.ObserveInt64(idle, int64(st.IdleConns))
o.ObserveInt64(mx, int64(st.MaxConns))
return nil
}, acq, idle, mx)
}
defer pgStore.Close()
redisURL := os.Getenv("REDIS_URL")
if redisURL == "" {
redisURL = "redis://redis:6379/0"
}
sessionTTL := 24 * time.Hour
if s := os.Getenv("SESSION_TTL_SECONDS"); s != "" {
if secs, err := strconv.Atoi(s); err == nil && secs > 0 {
sessionTTL = time.Duration(secs) * time.Second
}
}
redisStore, err := session.NewRedisStore(redisURL, sessionTTL)
if err != nil {
logger.Error("failed to connect to Redis", "error", err)
os.Exit(1)
}
defer redisStore.Close()
s3Cfg := storage.ConfigFromEnv()
s3Client, err := storage.NewClient(s3Cfg)
if err != nil {
logger.Error("failed to connect to S3", "error", err)
os.Exit(1)
}
brokerURL := os.Getenv("BROKER_URL")
if brokerURL == "" {
brokerURL = "redis://broker:6379/1"
}
brokerOpt, err := redis.ParseURL(brokerURL)
if err != nil {
logger.Error("broker url parse failed", "error", err)
os.Exit(1)
}
brokerRdb := redis.NewClient(brokerOpt)
defer brokerRdb.Close()
logger.Info("broker connected", "instance", instanceID)
publisher := &streamPublisher{rdb: brokerRdb, stream: "attachment_jobs"}
// --- Handler ---
h := handler.New(pgStore, redisStore, s3Client, publisher, sessionTTL)
reconcilerCtx, reconcilerCancel := context.WithCancel(context.Background())
defer reconcilerCancel()
go runAttachmentReconciler(reconcilerCtx, pgStore, s3Client, s3Cfg.Grace)
// --- Router ---
r := chi.NewRouter()
r.Use(InstanceIDMiddleware)
r.Use(RequestIDMiddleware)
r.Use(middleware.RealIP)
r.Use(middleware.Recoverer)
// OTel HTTP middleware: автоматические spans + метрики http.server.*
r.Use(otelhttp.NewMiddleware("messenger-api",
otelhttp.WithTracerProvider(otel.GetTracerProvider()),
otelhttp.WithMeterProvider(otel.GetMeterProvider()),
))
// Логирование запросов через slog с trace_id из контекста.
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
rid, _ := r.Context().Value(handler.RequestIDKey).(string)
slog.InfoContext(r.Context(), "http request",
"method", r.Method,
"path", r.URL.Path,
"duration_ms", time.Since(start).Milliseconds(),
"request_id", rid,
"instance", instanceID,
)
})
})
r.Get("/health/live", h.HealthLive)
r.Get("/health/ready", h.HealthReady)
r.Route("/api/v1", func(r chi.Router) {
r.Post("/users", h.CreateUser)
r.Post("/auth/sessions", h.CreateSession)
r.Group(func(r chi.Router) {
r.Use(h.BearerAuthMiddleware)
r.Delete("/auth/sessions/current", h.DeleteSession)
r.Get("/users/me", h.GetMe)
r.Get("/chats", h.ListChats)
r.Post("/chats", h.CreateChat)
r.Get("/chats/{chat_id}", h.GetChat)
r.Post("/chats/{chat_id}/messages", h.SendMessage)
r.Get("/chats/{chat_id}/messages", h.GetMessages)
r.Post("/chats/{chat_id}/attachments", h.UploadAttachment)
r.Get("/attachments/{attachment_id}", h.GetAttachment)
r.Get("/attachments/{attachment_id}/content", h.DownloadAttachment)
})
})
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
rid, _ := r.Context().Value(handler.RequestIDKey).(string)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":{"code":"not_found","message":"Not Found","request_id":"` + rid + `"}}`))
})
// --- HTTP server ---
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
srv := &http.Server{
Addr: "0.0.0.0:" + port,
Handler: r,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 120 * time.Second,
}
go func() {
logger.Info("server starting", "port", port, "instance", instanceID)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Error("server failed", "error", err)
os.Exit(1)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
logger.Info("shutting down", "instance", instanceID)
reconcilerCancel()
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
srv.SetKeepAlivesEnabled(false)
if err := srv.Shutdown(ctx); err != nil {
logger.Error("forced shutdown", "error", err)
}
// Graceful shutdown telemetry: flush buffers в Collector.
if providers != nil {
if err := providers.Shutdown(ctx); err != nil {
logger.Error("telemetry shutdown failed", "error", err)
}
}
logger.Info("exited properly", "instance", instanceID)
}
func runAttachmentReconciler(ctx context.Context, st store.Store, cl *storage.Client, grace time.Duration) {
t := time.NewTicker(30 * time.Second)
defer t.Stop()
slog.Info("attachment reconciler started", "grace", grace, "instance", instanceID)
for {
select {
case <-ctx.Done():
slog.Info("attachment reconciler stopped", "instance", instanceID)
return
case <-t.C:
items, err := st.ClaimStaleQueued(ctx, time.Now().Add(-grace))
if err != nil {
slog.Error("reconciler claim", "error", err, "instance", instanceID)
continue
}
for _, a := range items {
if err := cl.DeleteObject(ctx, a.ObjectKey); err != nil {
slog.Error("reconciler delete object", "error", err, "object_key", a.ObjectKey, "instance", instanceID)
continue
}
if err := st.DeleteFailedStaleAttachment(ctx, a.ID); err != nil {
slog.Error("reconciler delete row", "error", err, "attachment_id", a.ID, "instance", instanceID)
continue
}
slog.Info("reconciler cleaned stale attachment", "attachment_id", a.ID, "instance", instanceID)
}
}
}
}
+704
View File
@@ -0,0 +1,704 @@
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"io"
"log/slog"
"math/rand"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"mtusi2026lab6-fork/src/internal/model"
"mtusi2026lab6-fork/src/internal/storage"
"mtusi2026lab6-fork/src/internal/store"
"mtusi2026lab6-fork/src/internal/telemetry"
"github.com/HugoSmits86/nativewebp"
"github.com/disintegration/imaging"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
var instanceID = func() string {
if h, err := os.Hostname(); err == nil && h != "" {
return h
}
return "worker-unknown"
}()
type cfg struct {
stream, group, consumer, dlq string
concurrency int
lease, jobTimeout time.Duration
pollEvery, stagingRetention time.Duration
reclaimIdle time.Duration
maxBytes, maxPixels int64
}
func envInt(k string, d int) int {
if v := os.Getenv(k); v != "" {
if n, e := strconv.Atoi(v); e == nil && n > 0 {
return n
}
}
return d
}
func loadCfg() cfg {
return cfg{
stream: "attachment_jobs",
group: "worker_group",
consumer: instanceID,
dlq: "attachment_jobs_dlq",
concurrency: envInt("JOB_CONCURRENCY", 2),
lease: time.Duration(envInt("JOB_LEASE_SECONDS", 90)) * time.Second,
jobTimeout: time.Duration(envInt("JOB_TIMEOUT_SECONDS", 60)) * time.Second,
pollEvery: time.Duration(envInt("JOB_POLL_SECONDS", 5)) * time.Second,
stagingRetention: time.Duration(envInt("STAGING_RETENTION_SECONDS", 300)) * time.Second,
reclaimIdle: time.Duration(envInt("JOB_RECLAIM_IDLE_SECONDS", 15)) * time.Second,
maxBytes: int64(envInt("MAX_UPLOAD_BYTES", 10485760)),
maxPixels: int64(envInt("MAX_IMAGE_PIXELS", 40000000)),
}
}
type app struct {
pg store.Store
s3 *storage.Client
rdb *redis.Client
c cfg
tracer trace.Tracer
logger *slog.Logger
jobsProcessed metric.Int64Counter
jobDuration metric.Float64Histogram
depth atomic.Int64
oldestAge atomic.Int64
inFlight atomic.Int64
}
func faultMarker(name string) string { return "/tmp/.lab6_fault_" + name }
func faultExit(point string) {
if os.Getenv("FAULT_EXIT_AT") != point {
return
}
m := faultMarker("exit_" + point)
if _, err := os.Stat(m); err == nil {
return
}
_ = os.WriteFile(m, []byte(time.Now().Format(time.RFC3339Nano)), 0o600)
slog.Info("FAULT deliberate exit", "point", point, "instance", instanceID)
os.Exit(70)
}
func faultFailure() *procErr {
mode := os.Getenv("FAULT_FAIL_MODE")
if mode != "transient" && mode != "permanent" {
return nil
}
limit := envInt("FAULT_FAIL_TIMES", 1000000)
m := faultMarker("fail_" + mode)
n := 0
if b, err := os.ReadFile(m); err == nil {
n, _ = strconv.Atoi(strings.TrimSpace(string(b)))
}
if n >= limit {
return nil
}
_ = os.WriteFile(m, []byte(strconv.Itoa(n+1)), 0o600)
if mode == "permanent" {
return pe("invalid_image_format", fmt.Errorf("injected permanent failure #%d", n+1))
}
return te("s3_download_failed", fmt.Errorf("injected transient failure #%d", n+1))
}
func main() {
ctx := context.Background()
serviceName := os.Getenv("OTEL_SERVICE_NAME")
if serviceName == "" {
serviceName = "messenger-worker"
}
providers, err := telemetry.Init(ctx, serviceName)
if err != nil {
slog.Warn("telemetry init failed, running with fallback", "error", err)
}
logger := slog.New(telemetry.NewTraceContextHandler(providers.Logger.Handler()))
slog.SetDefault(logger)
logger.Info("worker starting", "instance", instanceID)
c := loadCfg()
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
dbURL = "postgres://lab4:lab4@postgres:5432/lab4?sslmode=disable&timezone=UTC"
}
pg, err := store.NewPostgres(dbURL)
if err != nil {
logger.Error("postgres connect failed", "error", err)
os.Exit(1)
}
defer pg.Close()
brokerURL := os.Getenv("REDIS_URL")
if brokerURL == "" {
brokerURL = "redis://broker:6379/1"
}
opt, err := redis.ParseURL(brokerURL)
if err != nil {
logger.Error("broker url parse failed", "error", err)
os.Exit(1)
}
rdb := redis.NewClient(opt)
defer rdb.Close()
s3c, err := storage.NewClient(storage.ConfigFromEnv())
if err != nil {
logger.Error("s3 connect failed", "error", err)
os.Exit(1)
}
a := &app{pg: pg, s3: s3c, rdb: rdb, c: c, tracer: providers.Tracer, logger: logger}
initMetrics(a, providers)
if err := rdb.XGroupCreateMkStream(ctx, c.stream, c.group, "0").Err(); err != nil &&
!strings.Contains(err.Error(), "BUSYGROUP") {
logger.Error("create group failed", "error", err)
os.Exit(1)
}
runCtx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
q := make(chan os.Signal, 1)
signal.Notify(q, syscall.SIGINT, syscall.SIGTERM)
<-q
logger.Info("shutting down", "instance", instanceID)
cancel()
}()
logger.Info("worker config",
"concurrency", c.concurrency, "lease", c.lease, "timeout", c.jobTimeout,
"reclaimIdle", c.reclaimIdle, "maxBytes", c.maxBytes, "maxPixels", c.maxPixels)
var wg sync.WaitGroup
wg.Add(4)
go func() { defer wg.Done(); a.consume(runCtx) }()
go func() { defer wg.Done(); a.recover(runCtx) }()
go func() { defer wg.Done(); a.janitor(runCtx) }()
go func() { defer wg.Done(); a.reclaim(runCtx) }()
<-runCtx.Done()
wg.Wait()
shCtx, shCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer shCancel()
_ = providers.Shutdown(shCtx)
logger.Info("worker stopped gracefully", "instance", instanceID)
}
func initMetrics(a *app, p *telemetry.Providers) {
if p == nil || p.Meter == nil {
return
}
m := p.Meter
a.jobsProcessed, _ = m.Int64Counter("worker_jobs_processed_total",
metric.WithDescription("Jobs processed by terminal status"))
a.jobDuration, _ = m.Float64Histogram("worker_job_duration_seconds",
metric.WithUnit("s"), metric.WithDescription("End-to-end job processing duration"))
qd, _ := m.Int64ObservableGauge("attachment_jobs_queue_depth",
metric.WithDescription("pending+published+processing jobs"))
oa, _ := m.Int64ObservableGauge("attachment_jobs_oldest_age_seconds",
metric.WithUnit("s"), metric.WithDescription("Age of the oldest unfinished job (queue lag)"))
fl, _ := m.Int64ObservableGauge("worker_in_flight_jobs",
metric.WithDescription("Jobs currently being processed (saturation)"))
cap, _ := m.Int64ObservableGauge("worker_concurrency_limit",
metric.WithDescription("Configured max concurrent jobs"))
acq, _ := m.Int64ObservableGauge("db_pool_acquired_conns")
idle, _ := m.Int64ObservableGauge("db_pool_idle_conns")
mx, _ := m.Int64ObservableGauge("db_pool_max_conns")
_, _ = m.RegisterCallback(func(_ context.Context, o metric.Observer) error {
o.ObserveInt64(qd, a.depth.Load())
o.ObserveInt64(oa, a.oldestAge.Load())
o.ObserveInt64(fl, a.inFlight.Load())
o.ObserveInt64(cap, int64(a.c.concurrency))
st := a.pg.PoolStats()
o.ObserveInt64(acq, int64(st.AcquiredConns))
o.ObserveInt64(idle, int64(st.IdleConns))
o.ObserveInt64(mx, int64(st.MaxConns))
return nil
}, qd, oa, fl, cap, acq, idle, mx)
}
// extractParent восстанавливает W3C trace context из полей сообщения брокера.
func extractParent(values map[string]interface{}) context.Context {
carrier := propagation.MapCarrier{}
for k, v := range values {
if s, ok := v.(string); ok {
carrier[k] = s
}
}
return otel.GetTextMapPropagator().Extract(context.Background(), carrier)
}
func (a *app) consume(ctx context.Context) {
sem := make(chan struct{}, a.c.concurrency)
for {
if ctx.Err() != nil {
return
}
res, err := a.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: a.c.group,
Consumer: a.c.consumer,
Streams: []string{a.c.stream, ">"},
Count: int64(a.c.concurrency),
Block: 3 * time.Second,
}).Result()
if err != nil && !errors.Is(err, redis.Nil) {
if ctx.Err() != nil {
return
}
a.logger.ErrorContext(ctx, "XReadGroup error", "error", err)
time.Sleep(time.Second)
continue
}
for _, st := range res {
for _, m := range st.Messages {
jobID, _ := m.Values["job_id"].(string)
if jobID == "" {
a.ack(ctx, m.ID)
continue
}
parent := extractParent(m.Values)
sem <- struct{}{}
go func(msgID, jid string, pctx context.Context) {
defer func() { <-sem }()
a.handle(pctx, msgID, jid)
}(m.ID, jobID, parent)
}
}
}
}
func (a *app) recover(ctx context.Context) {
t := time.NewTicker(a.c.pollEvery)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if n, err := a.pg.RequeueExpiredLeases(ctx); err != nil {
a.logger.ErrorContext(ctx, "requeue leases", "error", err)
} else if n > 0 {
a.logger.WarnContext(ctx, "requeued expired-lease jobs", "count", n)
}
if n, err := a.pg.QueueDepth(ctx); err == nil {
a.depth.Store(n)
}
if age, err := a.pg.OldestJobAgeSeconds(ctx); err == nil {
a.oldestAge.Store(int64(age))
}
jobs, err := a.pg.GetPendingJobs(ctx, 20)
if err != nil {
a.logger.ErrorContext(ctx, "pending jobs", "error", err)
continue
}
for _, j := range jobs {
if err := a.publish(ctx, j.ID); err != nil {
a.logger.WarnContext(ctx, "republish failed", "job_id", j.ID, "error", err)
continue
}
_ = a.pg.UpdateJobStatus(ctx, j.ID, "published", j.Attempts, "")
a.logger.InfoContext(ctx, "republished job", "job_id", j.ID, "attempt", j.Attempts)
}
}
}
}
func (a *app) reclaim(ctx context.Context) {
t := time.NewTicker(a.c.pollEvery)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
pend, err := a.rdb.XPendingExt(ctx, &redis.XPendingExtArgs{
Stream: a.c.stream, Group: a.c.group,
Start: "-", End: "+", Count: 20, Idle: a.c.reclaimIdle,
}).Result()
if err != nil && !errors.Is(err, redis.Nil) {
a.logger.ErrorContext(ctx, "XPendingExt", "error", err)
continue
}
for _, p := range pend {
msgs, err := a.rdb.XClaim(ctx, &redis.XClaimArgs{
Stream: a.c.stream, Group: a.c.group, Consumer: a.c.consumer,
MinIdle: a.c.reclaimIdle, Messages: []string{p.ID},
}).Result()
if err != nil {
continue
}
for _, m := range msgs {
jobID, _ := m.Values["job_id"].(string)
if jobID == "" {
a.ack(ctx, m.ID)
continue
}
a.logger.InfoContext(ctx, "reclaimed message",
"msg_id", m.ID, "job_id", jobID, "idle", p.Idle)
a.handle(extractParent(m.Values), m.ID, jobID)
}
}
}
}
}
func (a *app) janitor(ctx context.Context) {
t := time.NewTicker(60 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
refs, err := a.pg.ListCompletedStaging(ctx, time.Now().Add(-a.c.stagingRetention))
if err != nil {
a.logger.ErrorContext(ctx, "list staging", "error", err)
continue
}
for _, r := range refs {
if err := a.s3.DeleteObject(ctx, r.StagingKey); err != nil {
continue
}
_ = a.pg.ClearStagingKey(ctx, r.ID)
a.logger.InfoContext(ctx, "janitor removed staging", "key", r.StagingKey)
}
}
}
}
func (a *app) publish(ctx context.Context, jobID string) error {
values := map[string]interface{}{"job_id": jobID}
carrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, carrier)
for k, v := range carrier {
values[k] = v
}
return a.rdb.XAdd(ctx, &redis.XAddArgs{Stream: a.c.stream, Values: values}).Err()
}
func (a *app) ack(ctx context.Context, msgID string) {
_ = a.rdb.XAck(ctx, a.c.stream, a.c.group, msgID).Err()
}
func (a *app) handle(parent context.Context, msgID, jobID string) {
ctx, span := a.tracer.Start(parent, "process_job",
trace.WithSpanKind(trace.SpanKindConsumer))
defer span.End()
span.SetAttributes(
attribute.String("messaging.system", "redis_streams"),
attribute.String("messaging.operation", "process"),
attribute.String("job.id", jobID),
)
a.inFlight.Add(1)
defer a.inFlight.Add(-1)
start := time.Now()
job, err := a.pg.ClaimJob(ctx, jobID, a.c.consumer, a.c.lease)
if err != nil {
if errors.Is(err, store.ErrConflict) {
if cur, e := a.pg.GetJobByID(ctx, jobID); e == nil {
a.logger.InfoContext(ctx, "job not claimable, ack", "job_id", jobID, "status", cur.Status)
}
a.ack(ctx, msgID)
return
}
a.logger.ErrorContext(ctx, "claim job", "job_id", jobID, "error", err)
return
}
span.SetAttributes(attribute.Int("job.attempt", job.Attempts))
faultExit("after_claim")
att, err := a.pg.GetAttachmentByID(ctx, job.AttachmentID)
if err != nil {
a.observe(ctx, start, "failed")
a.fail(ctx, msgID, job, job.AttachmentID, "attachment_not_found", err, false)
return
}
if att.Status == "ready" {
a.logger.InfoContext(ctx, "job already complete, no-op ack", "job_id", jobID)
_ = a.pg.CompleteAttachment(ctx, att.ID, jobID, att.ObjectKey, nil)
a.observe(ctx, start, "done")
a.ack(ctx, msgID)
return
}
if job.Attempts > job.MaxAttempts {
a.observe(ctx, start, "failed")
a.fail(ctx, msgID, job, att.ID, "retry_exhausted",
fmt.Errorf("attempts=%d max=%d", job.Attempts, job.MaxAttempts), false)
return
}
jctx, cancel := context.WithTimeout(ctx, a.c.jobTimeout)
defer cancel()
variants, finalKey, perr := a.build(jctx, att)
if perr != nil {
span.RecordError(perr.err)
a.observe(ctx, start, "failed")
a.fail(jctx, msgID, job, att.ID, perr.code, perr.err, !perr.permanent)
return
}
faultExit("after_s3_before_commit")
_, dbSpan := a.tracer.Start(jctx, "db.complete_attachment")
err = a.pg.CompleteAttachment(jctx, att.ID, jobID, finalKey, variants)
dbSpan.End()
if err != nil {
a.observe(ctx, start, "failed")
a.fail(ctx, msgID, job, att.ID, "db_commit_failed", err, true)
return
}
faultExit("after_commit_before_ack")
if att.ObjectKey != finalKey {
if err := a.s3.DeleteObject(ctx, att.ObjectKey); err == nil {
_ = a.pg.ClearStagingKey(ctx, att.ID)
}
}
a.observe(ctx, start, "done")
a.ack(ctx, msgID)
a.logger.InfoContext(ctx, "job done",
"job_id", jobID, "attempt", job.Attempts, "variants", len(variants),
"duration_ms", time.Since(start).Milliseconds())
}
func (a *app) observe(ctx context.Context, start time.Time, status string) {
if a.jobsProcessed == nil {
return
}
attrs := metric.WithAttributes(attribute.String("status", status))
a.jobsProcessed.Add(ctx, 1, attrs)
a.jobDuration.Record(ctx, time.Since(start).Seconds(), attrs)
}
type procErr struct {
code string
err error
permanent bool
}
func pe(code string, err error) *procErr { return &procErr{code, err, true} }
func te(code string, err error) *procErr { return &procErr{code, err, false} }
func (a *app) build(ctx context.Context, att *model.Attachment) ([]model.Variant, string, *procErr) {
if fe := faultFailure(); fe != nil {
return nil, "", fe
}
_, s3Span := a.tracer.Start(ctx, "s3.get_staging")
obj, err := a.s3.GetObject(ctx, att.ObjectKey)
s3Span.End()
if err != nil {
return nil, "", te("s3_download_failed", err)
}
raw, err := io.ReadAll(io.LimitReader(obj.Body, a.c.maxBytes+1))
obj.Body.Close()
if err != nil {
return nil, "", te("s3_read_failed", err)
}
if int64(len(raw)) > a.c.maxBytes {
return nil, "", pe("image_too_large", fmt.Errorf("bytes=%d", len(raw)))
}
_, decSpan := a.tracer.Start(ctx, "image.decode")
dcfg, _, err := image.DecodeConfig(bytes.NewReader(raw))
if err != nil {
decSpan.End()
return nil, "", pe("invalid_image_format", err)
}
if int64(dcfg.Width)*int64(dcfg.Height) > a.c.maxPixels {
decSpan.End()
return nil, "", pe("image_too_many_pixels", fmt.Errorf("%dx%d", dcfg.Width, dcfg.Height))
}
img, err := imaging.Decode(bytes.NewReader(raw), imaging.AutoOrientation(true))
decSpan.End()
if err != nil {
return nil, "", pe("invalid_image_format", err)
}
ext := ".png"
if att.ContentType == "image/jpeg" {
ext = ".jpg"
}
finalKey := "original/" + att.ID + ext
thumbKey := "variants/" + att.ID + "/thumbnail.jpg"
cropKey := "variants/" + att.ID + "/crop.jpg"
optKey := "variants/" + att.ID + "/optimized.webp"
if err := a.s3.PutObject(ctx, finalKey, raw, att.ContentType); err != nil {
return nil, "", te("s3_upload_original_failed", err)
}
_, encSpan := a.tracer.Start(ctx, "image.encode_variants")
thumb := imaging.Fit(img, 256, 256, imaging.Lanczos)
tb, err := encodeJPEG(thumb, 85)
if err != nil {
encSpan.End()
return nil, "", pe("jpeg_encode_failed", err)
}
crop := imaging.Fill(img, 128, 128, imaging.Center, imaging.Lanczos)
cb, err := encodeJPEG(crop, 90)
if err != nil {
encSpan.End()
return nil, "", pe("jpeg_encode_failed", err)
}
src := img
if img.Bounds().Dx() > 1280 || img.Bounds().Dy() > 1280 {
src = imaging.Fit(img, 1280, 1280, imaging.Lanczos)
}
ob, err := encodeWebP(src)
encSpan.End()
if err != nil {
return nil, "", pe("webp_encode_failed", err)
}
_, putSpan := a.tracer.Start(ctx, "s3.put_variants")
for _, o := range []struct {
key, ct string
data []byte
}{
{thumbKey, "image/jpeg", tb},
{cropKey, "image/jpeg", cb},
{optKey, "image/webp", ob},
} {
if err := a.s3.PutObject(ctx, o.key, o.data, o.ct); err != nil {
putSpan.End()
return nil, "", te("s3_upload_variant_failed", err)
}
}
putSpan.End()
mk := func(name, key, ct string, b []byte, im image.Image) model.Variant {
return model.Variant{
Name: name, ObjectKey: key, ContentType: ct,
SizeBytes: int64(len(b)), Width: im.Bounds().Dx(), Height: im.Bounds().Dy(),
SHA256: sha256Hex(b),
}
}
return []model.Variant{
mk("thumbnail", thumbKey, "image/jpeg", tb, thumb),
mk("crop", cropKey, "image/jpeg", cb, crop),
mk("optimized", optKey, "image/webp", ob, src),
}, finalKey, nil
}
func flatten(src image.Image) *image.RGBA {
b := src.Bounds()
dst := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.RGBA{255, 255, 255, 255}), image.Point{}, draw.Src)
draw.Draw(dst, dst.Bounds(), src, b.Min, draw.Over)
return dst
}
func encodeJPEG(src image.Image, q int) ([]byte, error) {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, flatten(src), &jpeg.Options{Quality: q}); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func encodeWebP(src image.Image) ([]byte, error) {
var buf bytes.Buffer
if err := nativewebp.Encode(&buf, src, nil); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func (a *app) fail(ctx context.Context, msgID string, job *model.Job, attID, code string, cause error, transient bool) {
a.logger.ErrorContext(ctx, "job failed",
"job_id", job.ID, "code", code, "error", cause,
"attempt", job.Attempts, "max", job.MaxAttempts)
if transient && job.Attempts < job.MaxAttempts {
delay := backoff(job.Attempts)
if err := a.pg.RetryJob(ctx, job.ID, attID, code, cause.Error(), delay); err != nil {
a.logger.ErrorContext(ctx, "retry job", "error", err)
return
}
a.logger.WarnContext(ctx, "job retry scheduled", "job_id", job.ID, "delay", delay)
a.ack(ctx, msgID)
return
}
if err := a.pg.FailJob(ctx, job.ID, attID, code, cause.Error()); err != nil {
a.logger.ErrorContext(ctx, "fail job", "error", err)
return
}
_ = a.rdb.XAdd(ctx, &redis.XAddArgs{
Stream: a.c.dlq,
Values: map[string]interface{}{
"job_id": job.ID, "attachment_id": attID,
"error_code": code, "attempts": job.Attempts,
},
}).Err()
a.ack(ctx, msgID)
}
func backoff(attempt int) time.Duration {
if attempt < 1 {
attempt = 1
}
d := float64(5*time.Second) * float64(int(1)<<min(attempt-1, 4))
if d > float64(60*time.Second) {
d = float64(60 * time.Second)
}
return time.Duration(d * (0.75 + rand.Float64()*0.5))
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func sha256Hex(b []byte) string {
s := sha256.Sum256(b)
return hex.EncodeToString(s[:])
}
+46
View File
@@ -0,0 +1,46 @@
package auth
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"time"
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(hash), nil
}
func CheckPassword(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func GenerateToken() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b), nil
}
func HashToken(token string) string {
h := sha256.Sum256([]byte(token))
return hex.EncodeToString(h[:])
}
func SecureCompare(a, b string) bool {
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}
func IsSessionExpired(expiresAt time.Time) bool {
return time.Now().After(expiresAt)
}
+905
View File
@@ -0,0 +1,905 @@
package handler
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"log/slog"
"mtusi2026lab6-fork/src/internal/telemetry"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"mtusi2026lab6-fork/src/internal/auth"
"mtusi2026lab6-fork/src/internal/model"
"mtusi2026lab6-fork/src/internal/storage"
"mtusi2026lab6-fork/src/internal/store"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"go.opentelemetry.io/otel/trace"
)
type CtxKey string
const RequestIDKey CtxKey = "request_id"
const UserIDKey CtxKey = "user_id"
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
var pngSignature = []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}
var (
errUnsupportedImage = errors.New("unsupported_image")
errCorruptImage = errors.New("corrupt_image")
)
type SessionStore interface {
Get(ctx context.Context, tokenHash string) (string, error)
Set(ctx context.Context, userID, tokenHash string, ttl time.Duration) error
Delete(ctx context.Context, tokenHash string) error
}
type JobPublisher interface {
PublishJob(ctx context.Context, jobID string, traceparent string) error
}
type Handler struct {
store store.Store
sessionStore SessionStore
s3 *storage.Client
publisher JobPublisher
sessionTTL time.Duration
}
func New(s store.Store, ss SessionStore, s3 *storage.Client, pub JobPublisher, ttl time.Duration) *Handler {
return &Handler{
store: s,
sessionStore: ss,
s3: s3,
publisher: pub,
sessionTTL: ttl,
}
}
func isValidUUID(s string) bool {
_, err := uuid.Parse(s)
return err == nil
}
func userToMap(u *model.User) map[string]interface{} {
return map[string]interface{}{
"id": u.ID,
"username": u.Username,
"display_name": u.DisplayName,
"created_at": u.CreatedAt.UTC().Format(time.RFC3339Nano),
}
}
func chatToMap(c *model.Chat) map[string]interface{} {
ids := c.MemberIDs
if ids == nil {
ids = []string{}
}
return map[string]interface{}{
"id": c.ID,
"title": c.Title,
"member_ids": ids,
"created_at": c.CreatedAt.UTC().Format(time.RFC3339Nano),
}
}
func messageToMap(m *model.Message) map[string]interface{} {
ids := m.AttachmentIDs
if ids == nil {
ids = []string{}
}
return map[string]interface{}{
"id": m.ID,
"chat_id": m.ChatID,
"sender_id": m.SenderID,
"text": m.Text,
"attachment_ids": ids,
"created_at": m.CreatedAt.UTC().Format(time.RFC3339Nano),
}
}
func attachmentToMap(a *model.Attachment) map[string]interface{} {
variants := []any{}
if a.Variants != nil {
variants = a.Variants
}
var errorCode interface{} = nil
if a.ErrorCode != nil {
errorCode = *a.ErrorCode
}
return map[string]interface{}{
"id": a.ID,
"chat_id": a.ChatID,
"owner_id": a.OwnerID,
"filename": a.Filename,
"content_type": a.ContentType,
"size_bytes": a.SizeBytes,
"sha256": a.SHA256,
"status": a.Status,
"variants": variants,
"error_code": errorCode,
"created_at": a.CreatedAt.UTC().Format(time.RFC3339Nano),
"updated_at": a.UpdatedAt.UTC().Format(time.RFC3339Nano),
}
}
func respondError(w http.ResponseWriter, r *http.Request, code int, errorCode string) {
requestID, _ := r.Context().Value(RequestIDKey).(string)
slog.ErrorContext(r.Context(), "http error",
"status", code,
"error_code", errorCode,
"request_id", requestID,
)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(map[string]interface{}{
"error": map[string]string{
"code": errorCode,
"message": http.StatusText(code),
"request_id": requestID,
},
})
}
func respondJSON(w http.ResponseWriter, code int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(data)
}
func checkContentType(r *http.Request) bool {
ct := r.Header.Get("Content-Type")
return ct == "application/json" || strings.HasPrefix(ct, "application/json;")
}
func validateFilename(name string) bool {
if name == "" || utf8.RuneCountInString(name) > 255 {
return false
}
for _, ch := range name {
if ch == '/' || ch == '\\' || ch == 0 || unicode.IsControl(ch) {
return false
}
}
return true
}
func detectImage(data []byte) (string, image.Config, error) {
if len(data) == 0 {
return "", image.Config{}, errUnsupportedImage
}
if bytes.HasPrefix(data, pngSignature) {
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width <= 0 || cfg.Height <= 0 {
return "", image.Config{}, errCorruptImage
}
return "image/png", cfg, nil
}
if len(data) >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF {
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width <= 0 || cfg.Height <= 0 {
return "", image.Config{}, errCorruptImage
}
return "image/jpeg", cfg, nil
}
return "", image.Config{}, errUnsupportedImage
}
func verifyImageIntegrity(data []byte) error {
_, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return errCorruptImage
}
return nil
}
func sha256Hex(b []byte) string {
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])
}
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
if !checkContentType(r) {
respondError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type")
return
}
var req struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&req); err != nil {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
if !usernamePattern.MatchString(req.Username) ||
utf8.RuneCountInString(req.Password) < 12 ||
utf8.RuneCountInString(req.Password) > 128 {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
pwHash, err := auth.HashPassword(req.Password)
if err != nil {
slog.ErrorContext(r.Context(), "hash password error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
return
}
user, err := h.store.CreateUser(r.Context(), req.Username, req.DisplayName, pwHash)
if err != nil {
if errors.Is(err, store.ErrConflict) {
respondError(w, r, http.StatusConflict, "conflict")
} else {
respondError(w, r, http.StatusBadRequest, "invalid_request")
}
return
}
respondJSON(w, http.StatusCreated, userToMap(user))
}
func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Basic ") {
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
payload, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authHeader, "Basic "))
if err != nil {
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
parts := strings.SplitN(string(payload), ":", 2)
if len(parts) != 2 {
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
username, password := parts[0], parts[1]
user, err := h.store.GetUserByUsername(r.Context(), username)
if err != nil || !auth.CheckPassword(password, user.PasswordHash) {
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
token, err := auth.GenerateToken()
if err != nil {
slog.ErrorContext(r.Context(), "generate token error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
return
}
tokenHash := auth.HashToken(token)
expiresAt := time.Now().Add(h.sessionTTL)
if _, err := h.store.CreateSession(r.Context(), user.ID, tokenHash, expiresAt); err != nil {
slog.ErrorContext(r.Context(), "create postgres session error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
return
}
if err := h.sessionStore.Set(r.Context(), user.ID, tokenHash, h.sessionTTL); err != nil {
_ = h.store.DeleteSession(r.Context(), tokenHash)
slog.ErrorContext(r.Context(), "create redis session error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
return
}
respondJSON(w, http.StatusCreated, map[string]interface{}{
"token": token,
"token_type": "Bearer",
"expires_at": expiresAt.UTC().Format(time.RFC3339Nano),
"user": userToMap(user),
})
}
func (h *Handler) DeleteSession(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
token := strings.TrimPrefix(authHeader, "Bearer ")
tokenHash := auth.HashToken(token)
if err := h.store.DeleteSession(r.Context(), tokenHash); err != nil {
slog.ErrorContext(r.Context(), "delete postgres session error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
return
}
if err := h.sessionStore.Delete(r.Context(), tokenHash); err != nil {
slog.WarnContext(r.Context(), "delete redis session error", "error", err, "request_id", r.Context().Value(RequestIDKey))
}
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) BearerAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
token := strings.TrimPrefix(authHeader, "Bearer ")
tokenHash := auth.HashToken(token)
userID, err := h.sessionStore.Get(r.Context(), tokenHash)
if err != nil {
sess, errPg := h.store.GetSession(r.Context(), tokenHash)
if errPg != nil {
if errors.Is(errPg, store.ErrNotFound) {
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
slog.ErrorContext(r.Context(), "postgres session lookup error", "error", errPg, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
return
}
if auth.IsSessionExpired(sess.ExpiresAt) {
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
userID = sess.UserID
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), UserIDKey, userID)))
})
}
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
userID, ok := r.Context().Value(UserIDKey).(string)
if !ok || !isValidUUID(userID) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
user, err := h.store.GetUserByID(r.Context(), userID)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
slog.ErrorContext(r.Context(), "get user by id error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
return
}
respondJSON(w, http.StatusOK, userToMap(user))
}
func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
if !checkContentType(r) {
respondError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type")
return
}
userID, ok := r.Context().Value(UserIDKey).(string)
if !ok || !isValidUUID(userID) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
var req struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&req); err != nil {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
if len(req.MemberIDs) == 0 {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
seen := make(map[string]struct{}, len(req.MemberIDs))
isMember := false
for _, id := range req.MemberIDs {
if !isValidUUID(id) {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
if _, exists := seen[id]; exists {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
seen[id] = struct{}{}
if id == userID {
isMember = true
}
if _, err := h.store.GetUserByID(r.Context(), id); err != nil {
if errors.Is(err, store.ErrNotFound) {
respondError(w, r, http.StatusNotFound, "not_found")
return
}
slog.ErrorContext(r.Context(), "validate chat member error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
return
}
}
if !isMember {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
chat, err := h.store.CreateChat(r.Context(), req.Title, req.MemberIDs)
if err != nil {
switch {
case errors.Is(err, store.ErrInvalidRequest), errors.Is(err, store.ErrNotFound):
respondError(w, r, http.StatusBadRequest, "invalid_request")
case errors.Is(err, store.ErrConflict):
respondError(w, r, http.StatusConflict, "conflict")
default:
slog.ErrorContext(r.Context(), "create chat error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
}
return
}
respondJSON(w, http.StatusCreated, chatToMap(chat))
}
func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
userID, ok := r.Context().Value(UserIDKey).(string)
if !ok || !isValidUUID(userID) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
limit := 50
if ls := r.URL.Query().Get("limit"); ls != "" {
p, err := strconv.Atoi(ls)
if err != nil || p < 1 || p > 100 {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
limit = p
}
chats, nextCursor, err := h.store.ListChats(r.Context(), userID, limit, r.URL.Query().Get("cursor"))
if err != nil {
switch {
case errors.Is(err, store.ErrInvalidRequest):
respondError(w, r, http.StatusBadRequest, "invalid_request")
case errors.Is(err, store.ErrNotFound):
respondError(w, r, http.StatusNotFound, "not_found")
default:
slog.ErrorContext(r.Context(), "list chats error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
}
return
}
items := make([]map[string]interface{}, 0, len(chats))
for _, c := range chats {
items = append(items, chatToMap(c))
}
respondJSON(w, http.StatusOK, map[string]interface{}{
"items": items,
"next_cursor": nextCursor,
})
}
func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
userID, ok := r.Context().Value(UserIDKey).(string)
if !ok || !isValidUUID(userID) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
chatID := chi.URLParam(r, "chat_id")
if !isValidUUID(chatID) {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
chat, err := h.store.GetChat(r.Context(), chatID, userID)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
respondError(w, r, http.StatusNotFound, "not_found")
return
}
slog.ErrorContext(r.Context(), "get chat error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
return
}
respondJSON(w, http.StatusOK, chatToMap(chat))
}
func (h *Handler) SendMessage(w http.ResponseWriter, r *http.Request) {
if !checkContentType(r) {
respondError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type")
return
}
userID, ok := r.Context().Value(UserIDKey).(string)
if !ok || !isValidUUID(userID) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
chatID := chi.URLParam(r, "chat_id")
if !isValidUUID(chatID) {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
idemKey := r.Header.Get("Idempotency-Key")
if !idempotencyKeyPattern.MatchString(idemKey) {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
var req struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&req); err != nil {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
if req.AttachmentIDs == nil {
req.AttachmentIDs = []string{}
}
if utf8.RuneCountInString(req.Text) > 4000 || len(req.AttachmentIDs) > 10 {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
if strings.TrimSpace(req.Text) == "" && len(req.AttachmentIDs) == 0 {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
seen := make(map[string]struct{}, len(req.AttachmentIDs))
normalized := make([]string, 0, len(req.AttachmentIDs))
for _, rawID := range req.AttachmentIDs {
parsed, err := uuid.Parse(rawID)
if err != nil {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
id := parsed.String()
if _, exists := seen[id]; exists {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
seen[id] = struct{}{}
normalized = append(normalized, id)
}
req.AttachmentIDs = normalized
canonicalBody, err := json.Marshal(struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}{
Text: req.Text,
AttachmentIDs: req.AttachmentIDs,
})
if err != nil {
slog.ErrorContext(r.Context(), "marshal canonical message error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
return
}
requestHash := sha256Hex(canonicalBody)
path := "/api/v1/chats/" + chatID + "/messages"
msg, err := h.store.SendMessageIdempotent(
r.Context(), chatID, userID,
req.Text, req.AttachmentIDs,
idemKey, path, requestHash,
)
if err != nil {
switch {
case errors.Is(err, store.ErrInvalidRequest):
respondError(w, r, http.StatusBadRequest, "invalid_request")
case errors.Is(err, store.ErrNotFound):
respondError(w, r, http.StatusNotFound, "not_found")
case errors.Is(err, store.ErrConflict):
respondError(w, r, http.StatusConflict, "conflict")
default:
slog.ErrorContext(r.Context(), "send message error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
}
return
}
if msg.AttachmentIDs == nil {
msg.AttachmentIDs = []string{}
}
respondJSON(w, http.StatusCreated, messageToMap(msg))
}
func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) {
userID, ok := r.Context().Value(UserIDKey).(string)
if !ok || !isValidUUID(userID) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
chatID := chi.URLParam(r, "chat_id")
if !isValidUUID(chatID) {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
limit := 50
if ls := r.URL.Query().Get("limit"); ls != "" {
p, err := strconv.Atoi(ls)
if err != nil || p < 1 || p > 100 {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
limit = p
}
messages, nextCursor, err := h.store.GetMessages(r.Context(), chatID, userID, r.URL.Query().Get("cursor"), limit)
if err != nil {
switch {
case errors.Is(err, store.ErrInvalidRequest):
respondError(w, r, http.StatusBadRequest, "invalid_request")
case errors.Is(err, store.ErrNotFound):
respondError(w, r, http.StatusNotFound, "not_found")
default:
slog.ErrorContext(r.Context(), "get messages error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
}
return
}
items := make([]map[string]interface{}, 0, len(messages))
for _, m := range messages {
if m.AttachmentIDs == nil {
m.AttachmentIDs = []string{}
}
items = append(items, messageToMap(m))
}
respondJSON(w, http.StatusOK, map[string]interface{}{
"items": items,
"next_cursor": nextCursor,
})
}
func (h *Handler) UploadAttachment(w http.ResponseWriter, r *http.Request) {
userID, ok := r.Context().Value(UserIDKey).(string)
if !ok || !isValidUUID(userID) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
if h.s3 == nil {
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
return
}
chatID := chi.URLParam(r, "chat_id")
if !isValidUUID(chatID) {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
filename := r.URL.Query().Get("filename")
if !validateFilename(filename) {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
if _, err := h.store.GetChat(r.Context(), chatID, userID); err != nil {
if errors.Is(err, store.ErrNotFound) {
respondError(w, r, http.StatusNotFound, "not_found")
return
}
slog.ErrorContext(r.Context(), "chat membership for upload error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
return
}
cfg := h.s3.Config()
data, err := io.ReadAll(io.LimitReader(r.Body, cfg.MaxUpload+1))
if err != nil {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
if int64(len(data)) > cfg.MaxUpload {
respondError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large")
return
}
contentType, imgCfg, err := detectImage(data)
if err != nil {
respondError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type")
return
}
if ct := r.Header.Get("Content-Type"); ct != "" && !strings.HasPrefix(ct, contentType) {
respondError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type")
return
}
if int64(imgCfg.Width)*int64(imgCfg.Height) > cfg.MaxPixels {
respondError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large")
return
}
if err := verifyImageIntegrity(data); err != nil {
respondError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type")
return
}
sha := sha256Hex(data)
if existing, _ := h.store.GetAttachmentBySHA256InChat(r.Context(), chatID, sha); existing != nil {
if full, err := h.store.GetAttachmentForMetadata(r.Context(), existing.ID, userID); err == nil {
slog.InfoContext(r.Context(), "dedup hit same chat",
"sha256_prefix", sha[:16],
"request_id", r.Context().Value(RequestIDKey),
)
respondJSON(w, http.StatusAccepted, attachmentToMap(full))
return
}
}
ext := ".png"
if contentType == "image/jpeg" {
ext = ".jpg"
}
stagingKey := "staging/" + uuid.NewString() + ext
if err := h.s3.PutObject(r.Context(), stagingKey, data, contentType); err != nil {
slog.ErrorContext(r.Context(), "s3 put staging error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
return
}
att, job, err := h.store.CreateAttachmentAndJob(
r.Context(), chatID, userID, filename,
stagingKey, contentType, int64(len(data)), sha,
)
if err != nil {
_ = h.s3.DeleteObject(r.Context(), stagingKey)
slog.ErrorContext(r.Context(), "create attachment and job error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
return
}
// === ПУБЛИКАЦИЯ В ПОТОК С TRACE CONTEXT ===
if h.publisher != nil {
traceparent := ""
if sc := trace.SpanContextFromContext(r.Context()); sc.IsValid() {
traceparent = fmt.Sprintf("00-%s-%s-%02s",
sc.TraceID().String(),
sc.SpanID().String(),
sc.TraceFlags().String())
}
if err := h.publisher.PublishJob(r.Context(), job.ID, traceparent); err != nil {
slog.WarnContext(r.Context(), "publish job failed",
"job_id", job.ID,
"error", err,
"trace_id", telemetry.TraceIDFromContext(r.Context()),
)
} else {
slog.InfoContext(r.Context(), "job published to stream",
"job_id", job.ID,
"trace_id", telemetry.TraceIDFromContext(r.Context()),
)
}
}
respondJSON(w, http.StatusAccepted, attachmentToMap(att))
}
func (h *Handler) GetAttachment(w http.ResponseWriter, r *http.Request) {
userID, ok := r.Context().Value(UserIDKey).(string)
if !ok || !isValidUUID(userID) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
attachmentID := chi.URLParam(r, "attachment_id")
if !isValidUUID(attachmentID) {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
att, err := h.store.GetAttachmentForMetadata(r.Context(), attachmentID, userID)
if err != nil {
switch {
case errors.Is(err, store.ErrNotFound):
respondError(w, r, http.StatusNotFound, "not_found")
case errors.Is(err, store.ErrInvalidRequest):
respondError(w, r, http.StatusBadRequest, "invalid_request")
default:
slog.ErrorContext(r.Context(), "get attachment error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
}
return
}
respondJSON(w, http.StatusOK, attachmentToMap(att))
}
func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
userID, ok := r.Context().Value(UserIDKey).(string)
if !ok || !isValidUUID(userID) {
respondError(w, r, http.StatusUnauthorized, "unauthorized")
return
}
if h.s3 == nil {
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
return
}
attachmentID := chi.URLParam(r, "attachment_id")
if !isValidUUID(attachmentID) {
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
variantName := r.URL.Query().Get("variant")
switch variantName {
case "", "thumbnail", "crop", "optimized":
default:
respondError(w, r, http.StatusBadRequest, "invalid_request")
return
}
var objectKey, contentType string
var sizeBytes int64
if variantName == "" {
att, err := h.store.GetAttachmentForDownload(r.Context(), attachmentID, userID)
if err != nil {
h.respondAttachmentReadError(w, r, attachmentID, userID, err)
return
}
objectKey, contentType, sizeBytes = att.ObjectKey, att.ContentType, att.SizeBytes
} else {
v, err := h.store.GetAttachmentVariant(r.Context(), attachmentID, userID, variantName)
if err != nil {
h.respondAttachmentReadError(w, r, attachmentID, userID, err)
return
}
objectKey, contentType, sizeBytes = v.ObjectKey, v.ContentType, v.SizeBytes
}
obj, err := h.s3.GetObject(r.Context(), objectKey)
if err != nil {
switch {
case errors.Is(err, storage.ErrObjectNotFound):
respondError(w, r, http.StatusNotFound, "not_found")
case errors.Is(err, storage.ErrDependencyUnavailable):
respondError(w, r, http.StatusServiceUnavailable, "unavailable")
default:
slog.ErrorContext(r.Context(), "s3 get object error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
}
return
}
defer obj.Body.Close()
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.FormatInt(sizeBytes, 10))
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, obj.Body); err != nil {
slog.ErrorContext(r.Context(), "copy attachment body error", "error", err, "request_id", r.Context().Value(RequestIDKey))
}
}
func (h *Handler) respondAttachmentReadError(w http.ResponseWriter, r *http.Request, attachmentID, userID string, err error) {
switch {
case errors.Is(err, store.ErrNotFound):
meta, metaErr := h.store.GetAttachmentForMetadata(r.Context(), attachmentID, userID)
if metaErr == nil && meta != nil && meta.Status != "ready" {
respondError(w, r, http.StatusConflict, "conflict")
return
}
respondError(w, r, http.StatusNotFound, "not_found")
case errors.Is(err, store.ErrInvalidRequest):
respondError(w, r, http.StatusBadRequest, "invalid_request")
default:
slog.ErrorContext(r.Context(), "read attachment error", "error", err, "request_id", r.Context().Value(RequestIDKey))
respondError(w, r, http.StatusInternalServerError, "internal_error")
}
}
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
respondJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
respondJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
+79
View File
@@ -0,0 +1,79 @@
package model
import "time"
type User struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
PasswordHash string `json:"-"`
CreatedAt time.Time `json:"created_at"`
}
type Chat struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt time.Time `json:"created_at"`
}
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
CreatedAt time.Time `json:"created_at"`
}
type Session struct {
ID string `json:"-"`
UserID string `json:"-"`
TokenHash string `json:"-"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
}
type Attachment struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ObjectKey string `json:"-"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []any `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type Job struct {
ID string
AttachmentID string
Status string
Attempts int
MaxAttempts int
NextRunAt time.Time
LastError *string
CreatedAt time.Time
LeaseUntil *time.Time
LeasedBy *string
PipelineVersion int
}
type StagingRef struct {
ID string
StagingKey string
}
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
ObjectKey string `json:"-"`
}
+47
View File
@@ -0,0 +1,47 @@
package session
import (
"context"
"time"
"github.com/redis/go-redis/v9"
)
type RedisStore struct {
client *redis.Client
ttl time.Duration
}
func NewRedisStore(url string, ttl time.Duration) (*RedisStore, error) {
opt, err := redis.ParseURL(url)
if err != nil {
return nil, err
}
client := redis.NewClient(opt)
if err := client.Ping(context.Background()).Err(); err != nil {
return nil, err
}
return &RedisStore{
client: client,
ttl: ttl,
}, nil
}
func (s *RedisStore) Get(ctx context.Context, tokenHash string) (string, error) {
return s.client.Get(ctx, "session:"+tokenHash).Result()
}
func (s *RedisStore) Set(ctx context.Context, userID, tokenHash string, ttl time.Duration) error {
return s.client.Set(ctx, "session:"+tokenHash, userID, ttl).Err()
}
func (s *RedisStore) Delete(ctx context.Context, tokenHash string) error {
return s.client.Del(ctx, "session:"+tokenHash).Err()
}
func (s *RedisStore) Close() error {
return s.client.Close()
}
+230
View File
@@ -0,0 +1,230 @@
package storage
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
var (
ErrDependencyUnavailable = errors.New("s3_unavailable")
ErrObjectNotFound = errors.New("object_not_found")
)
type Config struct {
Endpoint string
Region string
Bucket string
AccessKey string
SecretKey string
UseSSL bool
MaxUpload int64
MaxPixels int64
Grace time.Duration
}
type Client struct {
client *minio.Client
bucket string
cfg Config
}
func ConfigFromEnv() Config {
endpoint := getenv("S3_ENDPOINT", "http://s3:9000")
region := getenv("S3_REGION", "us-east-1")
bucket := getenv("S3_BUCKET", "messenger-attachments")
access := getenv("S3_ACCESS_KEY_ID", "")
secret := getenv("S3_SECRET_ACCESS_KEY", "")
useSSL := false
if v := getenv("S3_USE_SSL", "false"); v != "" {
parsed, err := strconv.ParseBool(v)
if err == nil {
useSSL = parsed
}
}
if strings.HasPrefix(endpoint, "http://") || strings.HasPrefix(endpoint, "https://") {
u, err := url.Parse(endpoint)
if err == nil {
endpoint = u.Host
if u.Scheme == "https" {
useSSL = true
}
}
}
maxUpload := getInt64("MAX_UPLOAD_BYTES", 10*1024*1024)
maxPixels := getInt64("MAX_IMAGE_PIXELS", 40_000_000)
grace := time.Duration(getInt64("ATTACHMENT_GRACE_SECONDS", 600)) * time.Second
return Config{
Endpoint: endpoint,
Region: region,
Bucket: bucket,
AccessKey: access,
SecretKey: secret,
UseSSL: useSSL,
MaxUpload: maxUpload,
MaxPixels: maxPixels,
Grace: grace,
}
}
func NewClient(cfg Config) (*Client, error) {
if cfg.Endpoint == "" {
return nil, errors.New("S3_ENDPOINT is required")
}
if cfg.Bucket == "" {
return nil, errors.New("S3_BUCKET is required")
}
if cfg.AccessKey == "" || cfg.SecretKey == "" {
return nil, errors.New("S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY are required")
}
client, err := minio.New(cfg.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: cfg.UseSSL,
Region: cfg.Region,
BucketLookup: minio.BucketLookupPath,
})
if err != nil {
return nil, fmt.Errorf("create minio client: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
exists, err := client.BucketExists(ctx, cfg.Bucket)
if err != nil {
return nil, fmt.Errorf("check bucket exists: %w", err)
}
if !exists {
err = client.MakeBucket(ctx, cfg.Bucket, minio.MakeBucketOptions{Region: cfg.Region})
if err != nil {
return nil, fmt.Errorf("create bucket %s: %w", cfg.Bucket, err)
}
log.Printf("INFO: Successfully created bucket '%s'", cfg.Bucket)
}
return &Client{
client: client,
bucket: cfg.Bucket,
cfg: cfg,
}, nil
}
func (c *Client) Config() Config {
return c.cfg
}
func (c *Client) PutObject(ctx context.Context, key string, data []byte, contentType string) error {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
_, err := c.client.PutObject(
ctx,
c.bucket,
key,
bytes.NewReader(data),
int64(len(data)),
minio.PutObjectOptions{
ContentType: contentType,
},
)
if err != nil {
return fmt.Errorf("%w: put object: %v", ErrDependencyUnavailable, err)
}
return nil
}
type Object struct {
Body io.ReadCloser
Size int64
ContentType string
}
func (c *Client) GetObject(ctx context.Context, key string) (*Object, error) {
// ВАЖНО: не создаём новый контекст с таймаутом и не делаем defer cancel().
// Контекст HTTP-запроса должен жить, пока клиент читает поток (io.Copy).
// Он будет отменён автоматически при отключении клиента.
info, err := c.client.StatObject(ctx, c.bucket, key, minio.StatObjectOptions{})
if err != nil {
errResp := minio.ToErrorResponse(err)
if errResp.StatusCode == 404 || errResp.Code == "NoSuchKey" || errResp.Code == "NotFound" {
return nil, ErrObjectNotFound
}
return nil, fmt.Errorf("%w: stat object: %v", ErrDependencyUnavailable, err)
}
obj, err := c.client.GetObject(ctx, c.bucket, key, minio.GetObjectOptions{})
if err != nil {
return nil, fmt.Errorf("%w: get object: %v", ErrDependencyUnavailable, err)
}
contentType := info.ContentType
if contentType == "" {
contentType = "application/octet-stream"
}
return &Object{
Body: obj,
Size: info.Size,
ContentType: contentType,
}, nil
}
func (c *Client) DeleteObject(ctx context.Context, key string) error {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
err := c.client.RemoveObject(ctx, c.bucket, key, minio.RemoveObjectOptions{})
if err != nil {
errResp := minio.ToErrorResponse(err)
if errResp.StatusCode == 404 ||
errResp.Code == "NoSuchKey" ||
errResp.Code == "NotFound" {
return nil
}
return fmt.Errorf("%w: delete object: %v", ErrDependencyUnavailable, err)
}
return nil
}
func getenv(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
func getInt64(key string, fallback int64) int64 {
v := os.Getenv(key)
if v == "" {
return fallback
}
parsed, err := strconv.ParseInt(v, 10, 64)
if err != nil || parsed <= 0 {
return fallback
}
return parsed
}
@@ -0,0 +1,47 @@
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username VARCHAR(32) NOT NULL UNIQUE,
display_name VARCHAR(100) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT username_format CHECK (username ~ '^[a-z0-9_]{3,32}$')
);
CREATE INDEX idx_users_username ON users(username);
CREATE TABLE chats (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE chat_members (
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX idx_chat_members_user ON chat_members(user_id);
CREATE TABLE messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
text TEXT NOT NULL CHECK (length(text) >= 1 AND length(text) <= 4000),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_messages_chat_created ON messages(chat_id, created_at, id);
CREATE TABLE sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(64) NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_sessions_token ON sessions(token_hash);
CREATE INDEX idx_sessions_user ON sessions(user_id);
CREATE INDEX idx_sessions_expires ON sessions(expires_at);
@@ -0,0 +1,19 @@
CREATE TABLE IF NOT EXISTS idempotency_keys (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
method TEXT NOT NULL,
path TEXT NOT NULL,
key TEXT NOT NULL,
request_hash TEXT NOT NULL, -- SHA-256 hex canonical JSON body
response_code INT NOT NULL,
response_body JSONB NOT NULL, -- сохранённый Message для реплея
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + INTERVAL '24 hours',
UNIQUE (user_id, method, path, key)
);
CREATE INDEX IF NOT EXISTS idx_idem_expires ON idempotency_keys (expires_at);
-- Сообщения связываем с ключом, чтобы при реплее вернуть тот же объект
ALTER TABLE messages
ADD COLUMN IF NOT EXISTS idempotency_key_id UUID REFERENCES idempotency_keys(id) ON DELETE SET NULL;
@@ -0,0 +1,27 @@
CREATE TABLE IF NOT EXISTS attachments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
filename TEXT NOT NULL,
object_key TEXT NOT NULL UNIQUE,
content_type TEXT NOT NULL,
size_bytes BIGINT NOT NULL,
sha256 CHAR(64) NOT NULL,
status TEXT NOT NULL DEFAULT 'ready'
CHECK (status IN ('uploading', 'ready', 'failed')),
error_code TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_attachments_chat_id ON attachments (chat_id);
CREATE INDEX IF NOT EXISTS idx_attachments_status_created_at ON attachments (status, created_at);
CREATE TABLE IF NOT EXISTS message_attachments (
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
position INT NOT NULL,
PRIMARY KEY (message_id, attachment_id)
);
CREATE INDEX IF NOT EXISTS idx_message_attachments_message_id ON message_attachments (message_id, position);
@@ -0,0 +1,3 @@
-- Лабораторная 4: разрешаем пустой текст, если есть вложения.
-- Валидация "непустой текст ИЛИ непустой attachment_ids" выполняется на уровне приложения (handler.go).
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_check;
@@ -0,0 +1,14 @@
CREATE TABLE IF NOT EXISTS attachment_jobs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'published', 'processing', 'done', 'failed')),
attempts INT NOT NULL DEFAULT 0,
max_attempts INT NOT NULL DEFAULT 5,
next_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_attachment_jobs_status_next_run
ON attachment_jobs (status, next_run_at);
@@ -0,0 +1,43 @@
-- Лабораторная 5: асинхронная обработка вложений
-- 1. Расширяем статусы вложений: добавляем 'deleting' для промежуточного состояния при очистке
ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_status_check;
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check
CHECK (status IN ('queued', 'processing', 'ready', 'failed', 'deleting'));
-- 2. Таблица заданий на обработку (обратная связь между БД и брокером)
CREATE TABLE IF NOT EXISTS attachment_jobs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'published', 'processing', 'done', 'failed')),
attempts INT NOT NULL DEFAULT 0,
max_attempts INT NOT NULL DEFAULT 5,
next_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_attachment_jobs_pending
ON attachment_jobs (status, next_run_at)
WHERE status IN ('pending', 'published');
-- 3. Таблица вариантов вложения (оригинал, 256×256, 128×128, WebP optimized)
-- Используется в уровне 4 лабы 5 и далее
CREATE TABLE IF NOT EXISTS attachment_variants (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
kind TEXT NOT NULL
CHECK (kind IN ('original', 'thumbnail_256', 'crop_128', 'optimized_webp')),
object_key TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes BIGINT NOT NULL,
width INT NOT NULL,
height INT NOT NULL,
sha256 CHAR(64) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (attachment_id, kind)
);
CREATE INDEX IF NOT EXISTS idx_attachment_variants_attachment
ON attachment_variants (attachment_id);
@@ -0,0 +1,19 @@
CREATE TABLE IF NOT EXISTS attachment_jobs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'published', 'processing', 'done', 'failed')),
attempts INT NOT NULL DEFAULT 0,
max_attempts INT NOT NULL DEFAULT 5,
next_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
last_error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_attachment_jobs_status_next_run
ON attachment_jobs (status, next_run_at)
WHERE status IN ('pending', 'published');
CREATE INDEX IF NOT EXISTS idx_attachment_jobs_attachment_id
ON attachment_jobs (attachment_id);
@@ -0,0 +1,18 @@
-- Лабораторная 5: хранение вариантов вложения (оригинал + 256×256)
CREATE TABLE IF NOT EXISTS attachment_variants (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
kind TEXT NOT NULL
CHECK (kind IN ('original', 'thumbnail_256', 'crop_128', 'optimized_webp')),
object_key TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes BIGINT NOT NULL,
width INT NOT NULL,
height INT NOT NULL,
sha256 CHAR(64) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (attachment_id, kind)
);
CREATE INDEX IF NOT EXISTS idx_attachment_variants_attachment
ON attachment_variants (attachment_id);
@@ -0,0 +1,10 @@
DELETE FROM attachment_variants
WHERE kind = 'original' OR width < 1 OR height < 1 OR size_bytes < 1;
ALTER TABLE attachment_variants DROP CONSTRAINT IF EXISTS attachment_variants_kind_check;
ALTER TABLE attachment_variants ADD CONSTRAINT attachment_variants_kind_check
CHECK (kind IN ('thumbnail_256', 'crop_128', 'optimized_webp'));
ALTER TABLE attachment_variants DROP CONSTRAINT IF EXISTS attachment_variants_dims_check;
ALTER TABLE attachment_variants ADD CONSTRAINT attachment_variants_dims_check
CHECK (width >= 1 AND height >= 1 AND size_bytes >= 1);
@@ -0,0 +1,27 @@
-- Lease и версия pipeline
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS lease_until TIMESTAMPTZ;
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS leased_by TEXT;
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS pipeline_version INT NOT NULL DEFAULT 1;
CREATE INDEX IF NOT EXISTS idx_attachment_jobs_lease
ON attachment_jobs (lease_until) WHERE status = 'processing';
-- staging хранится отдельно от финального ключа
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS staging_key TEXT;
UPDATE attachments SET staging_key = object_key
WHERE staging_key IS NULL AND status <> 'ready';
-- варианты: только контрактные имена, размеры >= 1
DELETE FROM attachment_variants
WHERE kind NOT IN ('thumbnail_256','crop_128','optimized_webp')
OR width < 1 OR height < 1 OR size_bytes < 1;
ALTER TABLE attachment_variants DROP CONSTRAINT IF EXISTS attachment_variants_kind_check;
ALTER TABLE attachment_variants ADD CONSTRAINT attachment_variants_kind_check
CHECK (kind IN ('thumbnail_256','crop_128','optimized_webp'));
ALTER TABLE attachment_variants DROP CONSTRAINT IF EXISTS attachment_variants_dims_check;
ALTER TABLE attachment_variants ADD CONSTRAINT attachment_variants_dims_check
CHECK (width >= 1 AND height >= 1 AND size_bytes >= 1);
ALTER TABLE attachment_variants ADD COLUMN IF NOT EXISTS pipeline_version INT NOT NULL DEFAULT 1;
@@ -0,0 +1,59 @@
-- Восстановление схемы attachment_jobs.
-- Причина: дубль номера миграции 005 → часть DDL не применилась,
-- а CREATE TABLE IF NOT EXISTS в 007 не добавляет колонки к существующей таблице.
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS attachment_id UUID REFERENCES attachments(id) ON DELETE CASCADE;
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'pending';
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS attempts INT NOT NULL DEFAULT 0;
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS max_attempts INT NOT NULL DEFAULT 5;
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS next_run_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS last_error TEXT;
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS lease_until TIMESTAMPTZ;
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS leased_by TEXT;
ALTER TABLE attachment_jobs ADD COLUMN IF NOT EXISTS pipeline_version INT NOT NULL DEFAULT 1;
ALTER TABLE attachment_jobs DROP CONSTRAINT IF EXISTS attachment_jobs_status_check;
ALTER TABLE attachment_jobs ADD CONSTRAINT attachment_jobs_status_check
CHECK (status IN ('pending','published','processing','done','failed'));
CREATE INDEX IF NOT EXISTS idx_attachment_jobs_pending
ON attachment_jobs (status, next_run_at)
WHERE status IN ('pending','published');
CREATE INDEX IF NOT EXISTS idx_attachment_jobs_lease
ON attachment_jobs (lease_until) WHERE status = 'processing';
CREATE INDEX IF NOT EXISTS idx_attachment_jobs_attachment
ON attachment_jobs (attachment_id);
-- staging-ключ и финальный ключ живут раздельно
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS staging_key TEXT;
UPDATE attachments SET staging_key = object_key
WHERE staging_key IS NULL AND status <> 'ready';
-- варианты: полный набор колонок + уникальность ключа эффекта
ALTER TABLE attachment_variants ADD COLUMN IF NOT EXISTS object_key TEXT;
ALTER TABLE attachment_variants ADD COLUMN IF NOT EXISTS content_type TEXT;
ALTER TABLE attachment_variants ADD COLUMN IF NOT EXISTS size_bytes BIGINT;
ALTER TABLE attachment_variants ADD COLUMN IF NOT EXISTS width INT;
ALTER TABLE attachment_variants ADD COLUMN IF NOT EXISTS height INT;
ALTER TABLE attachment_variants ADD COLUMN IF NOT EXISTS sha256 CHAR(64);
ALTER TABLE attachment_variants ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW();
ALTER TABLE attachment_variants ADD COLUMN IF NOT EXISTS pipeline_version INT NOT NULL DEFAULT 1;
DELETE FROM attachment_variants
WHERE kind NOT IN ('thumbnail_256','crop_128','optimized_webp')
OR width IS NULL OR width < 1
OR height IS NULL OR height < 1
OR size_bytes IS NULL OR size_bytes < 1
OR object_key IS NULL;
-- UNIQUE нужен для ON CONFLICT (attachment_id, kind) — ключ идемпотентности эффекта
CREATE UNIQUE INDEX IF NOT EXISTS uq_attachment_variants_attachment_kind
ON attachment_variants (attachment_id, kind);
-- индекс дедупликации, который потерялся вместе с пропущенным 005
CREATE INDEX IF NOT EXISTS idx_attachments_sha256_status
ON attachments (sha256, status) WHERE status = 'ready';
@@ -0,0 +1,5 @@
-- Ускоряет поиск существующих файлов с тем же содержимым.
CREATE INDEX IF NOT EXISTS idx_attachments_sha256_status
ON attachments (sha256, status)
WHERE status = 'ready';
File diff suppressed because it is too large Load Diff
+61
View File
@@ -0,0 +1,61 @@
package telemetry
import (
"context"
"log/slog"
"os"
)
type TraceContextHandler struct {
slog.Handler
}
func NewTraceContextHandler(h slog.Handler) *TraceContextHandler {
return &TraceContextHandler{Handler: h}
}
type multiHandler struct{ hs []slog.Handler }
func NewStdoutAndOTelHandler(otelHandler slog.Handler) slog.Handler {
return &multiHandler{hs: []slog.Handler{
slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}),
otelHandler,
}}
}
func (m *multiHandler) Enabled(ctx context.Context, l slog.Level) bool {
for _, h := range m.hs {
if h.Enabled(ctx, l) {
return true
}
}
return false
}
func (m *multiHandler) Handle(ctx context.Context, r slog.Record) error {
var firstErr error
for _, h := range m.hs {
if h.Enabled(ctx, r.Level) {
if err := h.Handle(ctx, r.Clone()); err != nil && firstErr == nil {
firstErr = err
}
}
}
return firstErr
}
func (m *multiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
out := make([]slog.Handler, len(m.hs))
for i, h := range m.hs {
out[i] = h.WithAttrs(attrs)
}
return &multiHandler{hs: out}
}
func (m *multiHandler) WithGroup(name string) slog.Handler {
out := make([]slog.Handler, len(m.hs))
for i, h := range m.hs {
out[i] = h.WithGroup(name)
}
return &multiHandler{hs: out}
}
+211
View File
@@ -0,0 +1,211 @@
package telemetry
import (
"context"
"fmt"
"log/slog"
"os"
"strings"
"time"
"go.opentelemetry.io/contrib/bridges/otelslog"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
"go.opentelemetry.io/otel/log/global"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
sdklog "go.opentelemetry.io/otel/sdk/log"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
"go.opentelemetry.io/otel/trace"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type Providers struct {
Tracer trace.Tracer
Meter metric.Meter
Logger *slog.Logger
shutdown func(ctx context.Context) error
}
func otlpTarget() string {
ep := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
if ep == "" {
ep = "otelcol:4317"
}
ep = strings.TrimPrefix(ep, "http://")
ep = strings.TrimPrefix(ep, "https://")
ep = strings.TrimPrefix(ep, "dns:///")
ep = strings.TrimSuffix(ep, "/")
return ep
}
func fallbackProviders(serviceName string) *Providers {
return &Providers{
Tracer: otel.Tracer(serviceName),
Meter: otel.Meter(serviceName),
Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)),
shutdown: func(context.Context) error { return nil },
}
}
func Init(ctx context.Context, serviceName string) (*Providers, error) {
fb := fallbackProviders(serviceName)
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(err error) {
slog.Warn("otel export error", "error", err)
}))
host, _ := os.Hostname()
res, err := resource.New(ctx,
resource.WithAttributes(
semconv.ServiceName(serviceName),
semconv.ServiceInstanceID(host), // ← различает api-1 и api-2
semconv.ServiceVersion("lab6"),
semconv.DeploymentEnvironment("dev"),
),
)
if err != nil {
return fb, fmt.Errorf("resource: %w", err)
}
target := otlpTarget()
slog.Info("otel dialing collector", "target", target, "service", serviceName)
conn, err := grpc.NewClient(target,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
return fb, fmt.Errorf("grpc client: %w", err)
}
tp, err := newTracerProvider(ctx, res, conn)
if err != nil {
return fb, err
}
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
propagation.TraceContext{},
propagation.Baggage{},
))
mp, err := newMeterProvider(ctx, res, conn)
if err != nil {
return fb, err
}
otel.SetMeterProvider(mp)
lp, err := newLoggerProvider(ctx, res, conn)
if err != nil {
return fb, err
}
global.SetLoggerProvider(lp)
return &Providers{
Tracer: tp.Tracer(serviceName),
Meter: mp.Meter(serviceName),
Logger: slog.New(otelslog.NewHandler(serviceName)),
shutdown: func(ctx context.Context) error {
err1 := lp.Shutdown(ctx)
err2 := mp.Shutdown(ctx)
err3 := tp.Shutdown(ctx)
_ = conn.Close()
if err1 != nil {
return err1
}
if err2 != nil {
return err2
}
return err3
},
}, nil
}
func newTracerProvider(ctx context.Context, res *resource.Resource, conn *grpc.ClientConn) (*sdktrace.TracerProvider, error) {
exp, err := otlptracegrpc.New(ctx, otlptracegrpc.WithGRPCConn(conn))
if err != nil {
return nil, fmt.Errorf("trace exporter: %w", err)
}
return sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp,
sdktrace.WithBatchTimeout(5*time.Second),
sdktrace.WithMaxExportBatchSize(512),
sdktrace.WithMaxQueueSize(2048),
),
sdktrace.WithResource(res),
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())),
), nil
}
func newMeterProvider(ctx context.Context, res *resource.Resource, conn *grpc.ClientConn) (*sdkmetric.MeterProvider, error) {
exp, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithGRPCConn(conn))
if err != nil {
return nil, fmt.Errorf("metric exporter: %w", err)
}
return sdkmetric.NewMeterProvider(
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(exp,
sdkmetric.WithInterval(10*time.Second),
)),
sdkmetric.WithResource(res),
), nil
}
func newLoggerProvider(ctx context.Context, res *resource.Resource, conn *grpc.ClientConn) (*sdklog.LoggerProvider, error) {
exp, err := otlploggrpc.New(ctx, otlploggrpc.WithGRPCConn(conn))
if err != nil {
return nil, fmt.Errorf("log exporter: %w", err)
}
return sdklog.NewLoggerProvider(
sdklog.WithProcessor(sdklog.NewBatchProcessor(exp,
sdklog.WithExportTimeout(5*time.Second),
sdklog.WithExportMaxBatchSize(512),
)),
sdklog.WithResource(res),
), nil
}
func (p *Providers) Shutdown(ctx context.Context) error {
if p == nil || p.shutdown == nil {
return nil
}
return p.shutdown(ctx)
}
func TraceIDFromContext(ctx context.Context) string {
sc := trace.SpanContextFromContext(ctx)
if sc.HasTraceID() {
return sc.TraceID().String()
}
return ""
}
func (h *TraceContextHandler) Handle(ctx context.Context, r slog.Record) error {
if tid := TraceIDFromContext(ctx); tid != "" {
r.AddAttrs(slog.String("trace_id", tid))
}
if sid := SpanIDFromContext(ctx); sid != "" {
r.AddAttrs(slog.String("span_id", sid))
}
return h.Handler.Handle(ctx, r)
}
func (h *TraceContextHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &TraceContextHandler{Handler: h.Handler.WithAttrs(attrs)}
}
func (h *TraceContextHandler) WithGroup(name string) slog.Handler {
return &TraceContextHandler{Handler: h.Handler.WithGroup(name)}
}
func SpanIDFromContext(ctx context.Context) string {
sc := trace.SpanContextFromContext(ctx)
if sc.HasSpanID() {
return sc.SpanID().String()
}
return ""
}