feat: add OpenTelemetry instrumentation

This commit is contained in:
2026-11-01 17:06:32 +03:00
parent cea50c2cd6
commit 934dfefee7
49 changed files with 1113 additions and 286 deletions
+12 -7
View File
@@ -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
}