forked from mtusi2026/mtusi2026lab6
lab6
This commit is contained in:
@@ -9,7 +9,6 @@ import (
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -25,6 +24,7 @@ import (
|
||||
"mtusi2026/internal/jobs"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
"mtusi2026/internal/telemetry"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -162,7 +162,7 @@ func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u m
|
||||
err = a.blobs.Put(putCtx, stagingKey, io.NewSectionReader(tmp, 0, n), n, mt)
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Printf("s3 put failed: %v", err)
|
||||
telemetry.Error(r.Context(), "attachment.staging.write_failed")
|
||||
delCtx, delCancel := context.WithTimeout(baseCtx, 5*time.Second)
|
||||
_ = a.blobs.Delete(delCtx, stagingKey)
|
||||
delCancel()
|
||||
@@ -177,7 +177,7 @@ func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u m
|
||||
SizeBytes: n, SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key, StagingKey: stagingKey,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("attachment metadata commit uncertain, staging retained: %v", err)
|
||||
telemetry.Error(r.Context(), "attachment.accept_failed")
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
@@ -252,10 +252,10 @@ func (a *api) handleDownloadAttachment(w http.ResponseWriter, r *http.Request, u
|
||||
t.Stop()
|
||||
if err != nil {
|
||||
if errors.Is(err, blobstore.ErrNotFound) {
|
||||
log.Printf("INCONSISTENCY: metadata without object id=%s key=%s", att.ID, att.ObjectKey)
|
||||
telemetry.Error(r.Context(), "attachment.object_missing")
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
} else {
|
||||
log.Printf("s3 get failed: %v", err)
|
||||
telemetry.Error(r.Context(), "attachment.object_read_failed")
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
}
|
||||
return
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/model"
|
||||
@@ -46,7 +48,9 @@ func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u mode
|
||||
return
|
||||
}
|
||||
|
||||
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text, ids)
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Second)
|
||||
defer cancel()
|
||||
m, err := a.store.CreateMessage(ctx, chatID, u.ID, key, req.Text, ids)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrChatNotFound), errors.Is(err, store.ErrAttachmentNotFound):
|
||||
|
||||
@@ -1,30 +1,66 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/felixge/httpsnoop"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
otellog "go.opentelemetry.io/otel/log"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi2026/internal/store"
|
||||
"mtusi2026/internal/telemetry"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
var (
|
||||
httpRequests, _ = telemetry.Meter.Int64Counter("messenger.http.requests")
|
||||
httpDuration, _ = telemetry.Meter.Float64Histogram("messenger.http.request.duration",
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(.001, .0025, .005, .01, .025, .05, .1, .25, .5, 1, 2, 4, 8, 15, 30, 60))
|
||||
)
|
||||
|
||||
func (r *statusRecorder) WriteHeader(status int) {
|
||||
r.status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
func observeRequests(root, apiMux *http.ServeMux) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
log.Printf("method=%s path=%s status=%d duration=%s",
|
||||
r.Method, r.URL.Path, rec.status, time.Since(start))
|
||||
_, pattern := root.Handler(r)
|
||||
if pattern == "GET /health/live" || pattern == "GET /health/ready" {
|
||||
root.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
_, pattern = apiMux.Handler(r)
|
||||
registeredMethod, route, matched := strings.Cut(pattern, " ")
|
||||
if !matched || (registeredMethod != r.Method && !(r.Method == http.MethodHead && registeredMethod == http.MethodGet)) {
|
||||
route = "<unmatched>"
|
||||
}
|
||||
method := r.Method
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch,
|
||||
http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace:
|
||||
default:
|
||||
method = "_OTHER"
|
||||
}
|
||||
ctx := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
ctx, span := telemetry.Tracer.Start(ctx, method+" "+route, trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(attribute.String("http.request.method", method), attribute.String("http.route", route)))
|
||||
defer span.End()
|
||||
result := httpsnoop.CaptureMetrics(root, w, r.WithContext(ctx))
|
||||
statusClass := strconv.Itoa(result.Code/100) + "xx"
|
||||
attrs := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route),
|
||||
attribute.String("status_class", statusClass))
|
||||
httpRequests.Add(ctx, 1, attrs)
|
||||
httpDuration.Record(ctx, result.Duration.Seconds(), attrs)
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", result.Code))
|
||||
severity := otellog.SeverityInfo
|
||||
if result.Code >= 500 {
|
||||
severity = otellog.SeverityError
|
||||
telemetry.SetError(span, statusClass)
|
||||
}
|
||||
telemetry.Event(ctx, severity, "http.request",
|
||||
otellog.String("method", method), otellog.String("route", route), otellog.Int("http.status_code", result.Code),
|
||||
otellog.Float64("duration_s", result.Duration.Seconds()), otellog.String("request_id", w.Header().Get("X-Request-Id")))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -82,10 +82,7 @@ func NewRouterWithCache(
|
||||
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Blobs, o.Draining))
|
||||
root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux))
|
||||
|
||||
var h http.Handler = root
|
||||
h = loggingMiddleware(h)
|
||||
h = instanceMiddleware(o.InstanceID, h)
|
||||
return h
|
||||
return instanceMiddleware(o.InstanceID, observeRequests(root, apiMux))
|
||||
}
|
||||
|
||||
func instanceMiddleware(id string, next http.Handler) http.Handler {
|
||||
|
||||
Reference in New Issue
Block a user