forked from mtusi2026/mtusi2026lab6
feat: add OpenTelemetry instrumentation
This commit is contained in:
@@ -13,16 +13,21 @@ import (
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry"
|
||||
)
|
||||
|
||||
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
started := time.Now()
|
||||
result := "client_error"
|
||||
defer func() {
|
||||
s.metrics.attachmentUploads.WithLabelValues(result).Inc()
|
||||
s.metrics.attachmentDuration.Observe(time.Since(started).Seconds())
|
||||
attributes := metric.WithAttributes(attribute.String("result", result))
|
||||
s.metrics.attachmentUploads.Add(r.Context(), 1, attributes)
|
||||
s.metrics.attachmentDuration.Record(r.Context(), time.Since(started).Seconds(), attributes)
|
||||
}()
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
@@ -47,7 +52,7 @@ func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiEr
|
||||
uploaded, err := s.attachments.Upload(r.Context(), attachment.Upload{
|
||||
ChatID: chatID, OwnerID: user.ID, Filename: filename,
|
||||
ContentType: r.Header.Get("Content-Type"), ContentLength: r.ContentLength, Body: r.Body,
|
||||
Traceparent: traceparent(r.Header.Get("traceparent")), Tracestate: tracestate(r.Header.Get("tracestate")),
|
||||
TraceContext: telemetry.ContextCarrier(r.Context()),
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, model.ErrCapacity) {
|
||||
@@ -59,7 +64,7 @@ func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiEr
|
||||
return attachmentError(err)
|
||||
}
|
||||
result = "success"
|
||||
s.metrics.attachmentBytes.Add(float64(uploaded.SizeBytes))
|
||||
s.metrics.attachmentBytes.Add(r.Context(), uploaded.SizeBytes)
|
||||
writeJSON(w, http.StatusAccepted, uploaded)
|
||||
return nil
|
||||
}
|
||||
@@ -128,7 +133,7 @@ func (s *Server) attachmentContent(w http.ResponseWriter, r *http.Request) *apiE
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": content.Attachment.Filename}))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, content.Body); err != nil {
|
||||
s.logger.Warn("attachment download interrupted", "attachment_id", content.Attachment.ID, "error", err)
|
||||
s.logger.WarnContext(r.Context(), "attachment download interrupted", "event", "attachment_download_interrupted", "attachment_id", content.Attachment.ID, "error", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
)
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
@@ -229,7 +229,7 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
return unavailable()
|
||||
}
|
||||
if replay {
|
||||
s.metrics.replays.Inc()
|
||||
s.metrics.replays.Add(r.Context(), 1)
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
return nil
|
||||
|
||||
@@ -4,8 +4,8 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -17,80 +18,50 @@ var (
|
||||
)
|
||||
|
||||
type metrics struct {
|
||||
requests *prometheus.CounterVec
|
||||
duration *prometheus.HistogramVec
|
||||
inFlight prometheus.Gauge
|
||||
replays prometheus.Counter
|
||||
attachmentUploads *prometheus.CounterVec
|
||||
attachmentDuration prometheus.Histogram
|
||||
attachmentBytes prometheus.Counter
|
||||
requests metric.Int64Counter
|
||||
duration metric.Float64Histogram
|
||||
inFlight metric.Int64UpDownCounter
|
||||
replays metric.Int64Counter
|
||||
attachmentUploads metric.Int64Counter
|
||||
attachmentDuration metric.Float64Histogram
|
||||
attachmentBytes metric.Int64Counter
|
||||
handler http.Handler
|
||||
}
|
||||
|
||||
func newMetrics() *metrics {
|
||||
registry := prometheus.NewRegistry()
|
||||
result := &metrics{
|
||||
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "requests_total",
|
||||
Help: "Completed HTTP requests.",
|
||||
}, []string{"method", "route", "status_class"}),
|
||||
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "request_duration_seconds",
|
||||
Help: "HTTP request duration in seconds.",
|
||||
Buckets: requestDurationBuckets,
|
||||
}, []string{"method", "route"}),
|
||||
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "requests_in_flight",
|
||||
Help: "HTTP requests currently being served.",
|
||||
}),
|
||||
replays: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "idempotency_replays_total",
|
||||
Help: "Message requests served from an idempotency record.",
|
||||
}),
|
||||
attachmentUploads: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Name: "attachment_uploads_total",
|
||||
Help: "Completed attachment uploads by result.",
|
||||
}, []string{"result"}),
|
||||
attachmentDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: "messenger",
|
||||
Name: "attachment_upload_duration_seconds",
|
||||
Help: "Attachment upload duration in seconds.",
|
||||
Buckets: uploadDurationBuckets,
|
||||
}),
|
||||
attachmentBytes: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Name: "attachment_upload_bytes_total",
|
||||
Help: "Bytes accepted by successful attachment uploads.",
|
||||
}),
|
||||
func newMetrics(meter metric.Meter, handler http.Handler) *metrics {
|
||||
if meter == nil {
|
||||
meter = otel.Meter("messenger-api")
|
||||
}
|
||||
registry.MustRegister(
|
||||
result.requests,
|
||||
result.duration,
|
||||
result.inFlight,
|
||||
result.replays,
|
||||
result.attachmentUploads,
|
||||
result.attachmentDuration,
|
||||
result.attachmentBytes,
|
||||
collectors.NewGoCollector(),
|
||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
if handler == nil {
|
||||
handler = http.NotFoundHandler()
|
||||
}
|
||||
requests, _ := meter.Int64Counter("messenger_http_requests", metric.WithDescription("Completed HTTP requests."))
|
||||
duration, _ := meter.Float64Histogram("messenger_http_request_duration",
|
||||
metric.WithDescription("HTTP request duration."), metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(requestDurationBuckets...),
|
||||
)
|
||||
result.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
|
||||
return result
|
||||
inFlight, _ := meter.Int64UpDownCounter("messenger_http_requests_in_flight", metric.WithDescription("HTTP requests currently being served."))
|
||||
replays, _ := meter.Int64Counter("messenger_http_idempotency_replays", metric.WithDescription("Message requests served from an idempotency record."))
|
||||
attachmentUploads, _ := meter.Int64Counter("messenger_attachment_uploads", metric.WithDescription("Completed attachment uploads by result."))
|
||||
attachmentDuration, _ := meter.Float64Histogram("messenger_attachment_upload_duration",
|
||||
metric.WithDescription("Attachment upload duration."), metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(uploadDurationBuckets...),
|
||||
)
|
||||
attachmentBytes, _ := meter.Int64Counter("messenger_attachment_upload_bytes", metric.WithDescription("Bytes accepted by successful attachment uploads."), metric.WithUnit("By"))
|
||||
return &metrics{
|
||||
requests: requests, duration: duration, inFlight: inFlight, replays: replays,
|
||||
attachmentUploads: attachmentUploads, attachmentDuration: attachmentDuration,
|
||||
attachmentBytes: attachmentBytes, handler: handler,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *metrics) observe(r *http.Request, status int, started time.Time) {
|
||||
route := routeTemplate(r.URL.Path)
|
||||
m.requests.WithLabelValues(r.Method, route, strconv.Itoa(status/100)+"xx").Inc()
|
||||
m.duration.WithLabelValues(r.Method, route).Observe(time.Since(started).Seconds())
|
||||
func (m *metrics) observe(ctx context.Context, r *http.Request, status int, started time.Time) {
|
||||
attributes := metric.WithAttributes(
|
||||
attribute.String("method", r.Method), attribute.String("route", routeTemplate(r.URL.Path)),
|
||||
attribute.String("status_class", strconv.Itoa(status/100)+"xx"),
|
||||
)
|
||||
m.requests.Add(ctx, 1, attributes)
|
||||
m.duration.Record(ctx, time.Since(started).Seconds(), attributes)
|
||||
}
|
||||
|
||||
func routeTemplate(path string) string {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
|
||||
@@ -6,6 +6,16 @@ import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.34.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/telemetry"
|
||||
)
|
||||
|
||||
type Dependencies struct {
|
||||
@@ -17,6 +27,8 @@ type Dependencies struct {
|
||||
Passwords PasswordService
|
||||
Database HealthChecker
|
||||
Objects HealthChecker
|
||||
Meter metric.Meter
|
||||
Metrics http.Handler
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
@@ -67,7 +79,8 @@ func NewServer(
|
||||
attachments: dependencies.Attachments, sessions: dependencies.Sessions,
|
||||
passwords: dependencies.Passwords, database: dependencies.Database, objects: dependencies.Objects,
|
||||
sessionTTL: config.SessionTTL, idempotencyTTL: config.IdempotencyTTL, requestTTL: config.RequestTTL,
|
||||
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort, metrics: newMetrics(),
|
||||
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort,
|
||||
metrics: newMetrics(dependencies.Meter, dependencies.Metrics),
|
||||
}
|
||||
s.ready.Store(true)
|
||||
return s
|
||||
@@ -82,27 +95,39 @@ func (s *Server) Handler() http.Handler {
|
||||
}
|
||||
|
||||
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
|
||||
requestContext := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
tracer := otel.Tracer("messenger-api/http")
|
||||
route := routeTemplate(r.URL.Path)
|
||||
requestContext, span := tracer.Start(requestContext, r.Method+" "+route, trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(semconv.HTTPRequestMethodKey.String(r.Method), semconv.HTTPRoute(route)))
|
||||
defer span.End()
|
||||
r = r.WithContext(requestContext)
|
||||
w.Header().Set("X-Instance-Id", s.instanceID)
|
||||
requestID, err := newID()
|
||||
if err != nil {
|
||||
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
span.SetAttributes(attribute.String("request.id", requestID))
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
started := time.Now()
|
||||
s.metrics.inFlight.Inc()
|
||||
s.metrics.inFlight.Add(r.Context(), 1)
|
||||
defer func() {
|
||||
s.metrics.inFlight.Dec()
|
||||
s.metrics.inFlight.Add(r.Context(), -1)
|
||||
if recovered := recover(); recovered != nil {
|
||||
s.logger.Error("request panic", "request_id", requestID, "method", r.Method, "path", r.URL.Path)
|
||||
s.logger.ErrorContext(r.Context(), "request panic", "event", "http_request_panic", "request_id", requestID, "method", r.Method, "route", route)
|
||||
if wrapped.status == http.StatusOK {
|
||||
writeError(wrapped, requestID, internalError())
|
||||
}
|
||||
}
|
||||
s.metrics.observe(r, wrapped.status, started)
|
||||
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
|
||||
s.metrics.observe(r.Context(), r, wrapped.status, started)
|
||||
span.SetAttributes(semconv.HTTPResponseStatusCode(wrapped.status))
|
||||
if wrapped.status >= http.StatusInternalServerError {
|
||||
span.SetStatus(codes.Error, http.StatusText(wrapped.status))
|
||||
}
|
||||
s.logger.InfoContext(r.Context(), "request", "event", "http_request_completed", "request_id", requestID, "method", r.Method, "route", route, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
|
||||
}()
|
||||
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
|
||||
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
|
||||
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab6/internal/model"
|
||||
)
|
||||
|
||||
var errDependency = errors.New("dependency unavailable")
|
||||
|
||||
Reference in New Issue
Block a user