feat(observability): add product metrics for API, outbox and delivery
This commit is contained in:
1 parent
560724e2aa
commit
94488e2b57
51 files changed
+3655
-68
No files matched your search
@@ -6,18 +6,66 @@ import (
|
||||
|
||||
"github.com/felixge/httpsnoop"
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/observe"
|
||||
)
|
||||
|
||||
// unmatchedRoute names a request that matched no route.
|
||||
const unmatchedRoute = "unmatched"
|
||||
|
||||
// RequestMetrics records one finished request. route is a route template,
|
||||
// never the raw path.
|
||||
type RequestMetrics interface {
|
||||
ObserveRequest(method, route string, status int, duration time.Duration)
|
||||
}
|
||||
|
||||
func CollectMetrics(metrics RequestMetrics) func(http.Handler) http.Handler {
|
||||
// ProblemMetrics is the optional part of a RequestMetrics collector that also
|
||||
// counts error responses by the problem code they carry. A collector without
|
||||
// it still gets every request.
|
||||
type ProblemMetrics interface {
|
||||
ObserveProblem(route, problemCode string)
|
||||
}
|
||||
|
||||
// RouteResolver refines the chi route pattern of a request, for example into
|
||||
// the path template of a generated operation mounted under a wildcard. It
|
||||
// must return a template from a fixed set, never a value taken from the
|
||||
// request path. It returns pattern unchanged when it has nothing better.
|
||||
type RouteResolver func(r *http.Request, pattern string) string
|
||||
|
||||
// routeTemplate returns the bounded route of a finished request: the chi
|
||||
// pattern refined by resolve, or unmatchedRoute. chi keeps the route context
|
||||
// of the request as a pointer, so the pattern matched downstream is visible
|
||||
// through the request that entered the middleware.
|
||||
func routeTemplate(r *http.Request, resolve RouteResolver) string {
|
||||
var route string
|
||||
if routing := chi.RouteContext(r.Context()); routing != nil {
|
||||
route = routing.RoutePattern()
|
||||
}
|
||||
if resolve != nil {
|
||||
route = resolve(r, route)
|
||||
}
|
||||
if route == "" {
|
||||
return unmatchedRoute
|
||||
}
|
||||
return route
|
||||
}
|
||||
|
||||
// CollectMetrics observes every request with its route template, status,
|
||||
// and duration, and, when metrics implements ProblemMetrics, every error
|
||||
// response with the problem code it carries. resolve may be nil.
|
||||
func CollectMetrics(metrics RequestMetrics, resolve RouteResolver) func(http.Handler) http.Handler {
|
||||
problems, countsProblems := metrics.(ProblemMetrics)
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
captured := httpsnoop.CaptureMetrics(next, w, r)
|
||||
route := chi.RouteContext(r.Context()).RoutePattern()
|
||||
ctx, observed := observe.Ensure(r.Context())
|
||||
captured := httpsnoop.CaptureMetrics(next, w, r.WithContext(ctx))
|
||||
route := routeTemplate(r, resolve)
|
||||
metrics.ObserveRequest(r.Method, route, captured.Code, captured.Duration)
|
||||
// A problem built for a response that finally succeeded is not
|
||||
// an error of this request.
|
||||
if code := observed.ProblemCode(); countsProblems && captured.Code >= http.StatusBadRequest && code != "" {
|
||||
problems.ObserveProblem(route, code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/observe"
|
||||
)
|
||||
|
||||
type observedRequest struct {
|
||||
method, route, problem string
|
||||
status int
|
||||
}
|
||||
|
||||
type recordingCollector struct {
|
||||
requests []observedRequest
|
||||
}
|
||||
|
||||
func (collector *recordingCollector) ObserveRequest(method, route string, status int, _ time.Duration) {
|
||||
collector.requests = append(collector.requests, observedRequest{method: method, route: route, status: status})
|
||||
}
|
||||
|
||||
func (collector *recordingCollector) ObserveProblem(route, code string) {
|
||||
collector.requests = append(collector.requests, observedRequest{route: route, problem: code})
|
||||
}
|
||||
|
||||
// requestOnlyCollector has no ObserveProblem.
|
||||
type requestOnlyCollector struct {
|
||||
requests int
|
||||
}
|
||||
|
||||
func (collector *requestOnlyCollector) ObserveRequest(string, string, int, time.Duration) {
|
||||
collector.requests++
|
||||
}
|
||||
|
||||
func problemHandler(status int, code string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
observe.RecordProblem(r.Context(), code)
|
||||
w.WriteHeader(status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestLogAndMetricsShareTheRouteAndTheProblem(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
collector := &recordingCollector{}
|
||||
router := chi.NewRouter()
|
||||
router.Use(RequestLog(slog.New(slog.NewJSONHandler(&logs, nil)), nil, "/skipped"))
|
||||
router.Use(CollectMetrics(collector, nil))
|
||||
router.Get("/items/{id}", problemHandler(http.StatusInternalServerError, "internal"))
|
||||
router.Get("/skipped", problemHandler(http.StatusOK, ""))
|
||||
// A problem built for a response that finally succeeded is not counted.
|
||||
router.Get("/recovered", problemHandler(http.StatusOK, "not_found"))
|
||||
|
||||
for _, request := range []*http.Request{
|
||||
httptest.NewRequest(http.MethodGet, "/items/secret-value?token=x", nil),
|
||||
httptest.NewRequest(http.MethodGet, "/skipped", nil),
|
||||
httptest.NewRequest(http.MethodGet, "/recovered", nil),
|
||||
httptest.NewRequest("PROPFIND", "/dav", nil),
|
||||
} {
|
||||
router.ServeHTTP(httptest.NewRecorder(), request)
|
||||
}
|
||||
|
||||
want := []observedRequest{
|
||||
{method: http.MethodGet, route: "/items/{id}", status: 500},
|
||||
{route: "/items/{id}", problem: "internal"},
|
||||
{method: http.MethodGet, route: "/skipped", status: 200},
|
||||
{method: http.MethodGet, route: "/recovered", status: 200},
|
||||
// chi refuses a method it does not know before any route matches.
|
||||
{method: "PROPFIND", route: unmatchedRoute, status: 405},
|
||||
}
|
||||
if len(collector.requests) != len(want) {
|
||||
t.Fatalf("observed %+v, want %+v", collector.requests, want)
|
||||
}
|
||||
for index := range want {
|
||||
if collector.requests[index] != want[index] {
|
||||
t.Fatalf("observation %d = %+v, want %+v", index, collector.requests[index], want[index])
|
||||
}
|
||||
}
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(logs.String()), "\n")
|
||||
if len(lines) != 3 {
|
||||
t.Fatalf("logged %d lines, want 3 without the skipped path:\n%s", len(lines), logs.String())
|
||||
}
|
||||
if strings.Contains(logs.String(), "secret-value") || strings.Contains(logs.String(), "token") {
|
||||
t.Fatalf("request log carries the raw path or query:\n%s", logs.String())
|
||||
}
|
||||
var failed map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[0]), &failed); err != nil {
|
||||
t.Fatalf("decode %s: %v", lines[0], err)
|
||||
}
|
||||
if failed["level"] != "ERROR" || failed["route"] != "/items/{id}" || failed["problem_code"] != "internal" || failed["query_params"] != 1.0 {
|
||||
t.Fatalf("5xx line = %s", lines[0])
|
||||
}
|
||||
if strings.Contains(lines[1], "problem_code") {
|
||||
t.Fatalf("a successful response was logged with a problem code: %s", lines[1])
|
||||
}
|
||||
if !strings.Contains(lines[2], `"method":"OTHER"`) {
|
||||
t.Fatalf("an unknown method was logged verbatim: %s", lines[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectMetricsWithoutProblemMetricsAndOutsideChi(t *testing.T) {
|
||||
collector := &requestOnlyCollector{}
|
||||
handler := CollectMetrics(collector, nil)(problemHandler(http.StatusNotFound, "not_found"))
|
||||
handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/anything", nil))
|
||||
if collector.requests != 1 {
|
||||
t.Fatalf("observed %d requests, want 1", collector.requests)
|
||||
}
|
||||
|
||||
recording := &recordingCollector{}
|
||||
CollectMetrics(recording, nil)(problemHandler(http.StatusNotFound, "")).
|
||||
ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/anything", nil))
|
||||
if want := (observedRequest{method: http.MethodGet, route: unmatchedRoute, status: 404}); len(recording.requests) != 1 || recording.requests[0] != want {
|
||||
t.Fatalf("observed %+v, want only %+v", recording.requests, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
|
||||
"github.com/felixge/httpsnoop"
|
||||
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/observe"
|
||||
)
|
||||
|
||||
// otherMethod replaces a method outside the standard set in logs and
|
||||
// metrics, so a client cannot write arbitrary text through it.
|
||||
const otherMethod = "OTHER"
|
||||
|
||||
var knownMethods = []string{
|
||||
http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch,
|
||||
http.MethodDelete, http.MethodHead, http.MethodOptions,
|
||||
}
|
||||
|
||||
// RequestLog logs every finished request except the paths in skip, which are
|
||||
// matched exactly. A line carries the request ID, the method, the bounded
|
||||
// route template (the same as in the metrics), the status and its class, the
|
||||
// problem code when the response is a problem, the latency, the response
|
||||
// size, and the number of query parameters.
|
||||
//
|
||||
// It never logs the raw path, a query key or value, a header, the client
|
||||
// address, or the user agent: a path or a query can carry an address, a
|
||||
// token, or another identifier that a client put there, and the access logs
|
||||
// have no purpose that needs the client address. The request ID links a line
|
||||
// to the handler logs of the same request.
|
||||
func RequestLog(logger *slog.Logger, resolve RouteResolver, skip ...string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if slices.Contains(skip, r.URL.Path) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
ctx, observed := observe.Ensure(r.Context())
|
||||
captured := httpsnoop.CaptureMetrics(next, w, r.WithContext(ctx))
|
||||
attributes := []slog.Attr{
|
||||
slog.String("request_id", kitmiddleware.GetRequestID(ctx)),
|
||||
slog.String("method", boundedMethod(r.Method)),
|
||||
slog.String("route", routeTemplate(r, resolve)),
|
||||
slog.Int("status", captured.Code),
|
||||
slog.String("status_class", statusClass(captured.Code)),
|
||||
slog.Int64("latency_ms", captured.Duration.Milliseconds()),
|
||||
slog.Int64("bytes", captured.Written),
|
||||
slog.Int("query_params", len(r.URL.Query())),
|
||||
}
|
||||
if code := observed.ProblemCode(); code != "" && captured.Code >= http.StatusBadRequest {
|
||||
attributes = append(attributes, slog.String("problem_code", code))
|
||||
}
|
||||
level, message := slog.LevelInfo, "http request"
|
||||
switch {
|
||||
case captured.Code >= http.StatusInternalServerError:
|
||||
level, message = slog.LevelError, "http request failed"
|
||||
case captured.Code >= http.StatusBadRequest:
|
||||
level, message = slog.LevelWarn, "http request error"
|
||||
}
|
||||
logger.LogAttrs(ctx, level, message, attributes...)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func boundedMethod(method string) string {
|
||||
if slices.Contains(knownMethods, method) {
|
||||
return method
|
||||
}
|
||||
return otherMethod
|
||||
}
|
||||
|
||||
// statusClass maps a status code to 1xx-5xx, or "other" outside them.
|
||||
func statusClass(status int) string {
|
||||
if status < 100 || status > 599 {
|
||||
return "other"
|
||||
}
|
||||
return strconv.Itoa(status/100) + "xx"
|
||||
}
|
||||
Reference in new issue
Block a user