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
@@ -0,0 +1,138 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/pkg/testutil"
|
||||
)
|
||||
|
||||
// Fixture values that must never reach a metric label.
|
||||
const (
|
||||
metricsFixtureEmail = "metrics.fixture@example.com"
|
||||
metricsFixtureID = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff"
|
||||
)
|
||||
|
||||
func newMetricsTestRouter(t *testing.T, apiHandler func(*v1.HealthHandler, *problem.Responder) api.Handler) (http.Handler, *metrics.Metrics) {
|
||||
t.Helper()
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
responder := problem.NewResponder(logger)
|
||||
collector := metrics.New()
|
||||
router, err := NewRouter(healthHandler, apiHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, collector, logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
return router, collector
|
||||
}
|
||||
|
||||
func scrapeMetrics(t *testing.T, collector *metrics.Metrics) string {
|
||||
t.Helper()
|
||||
response := httptest.NewRecorder()
|
||||
collector.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
||||
return response.Body.String()
|
||||
}
|
||||
|
||||
// Requests under the versioned prefix are labeled with the path template of
|
||||
// their operation, never the raw path, and error responses are counted by
|
||||
// their problem code.
|
||||
func TestRequestMetricsUseRouteTemplatesAndProblemCodes(t *testing.T) {
|
||||
router, collector := newMetricsTestRouter(t, func(health *v1.HealthHandler, responder *problem.Responder) api.Handler {
|
||||
return v1.NewHandler(health, responder)
|
||||
})
|
||||
for _, request := range []struct {
|
||||
method, target string
|
||||
status int
|
||||
}{
|
||||
{method: http.MethodGet, target: "/healthz", status: http.StatusOK},
|
||||
{method: http.MethodGet, target: "/api/v1/healthz", status: http.StatusOK},
|
||||
// DenyAllSecurity rejects the session before the operation runs.
|
||||
{method: http.MethodGet, target: "/api/v1/me/invitations/" + metricsFixtureID, status: http.StatusUnauthorized},
|
||||
{method: http.MethodGet, target: "/api/v1/me/assessment-attempts/" + metricsFixtureID + "?email=" + metricsFixtureEmail, status: http.StatusUnauthorized},
|
||||
{method: http.MethodGet, target: "/api/v1/users/" + metricsFixtureEmail, status: http.StatusNotFound},
|
||||
{method: http.MethodPost, target: "/api/v1/healthz", status: http.StatusMethodNotAllowed},
|
||||
{method: http.MethodGet, target: "/api/" + metricsFixtureEmail, status: http.StatusNotFound},
|
||||
{method: http.MethodGet, target: "/files/" + metricsFixtureID, status: http.StatusNotFound},
|
||||
} {
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(request.method, request.target, nil))
|
||||
if response.Code != request.status {
|
||||
t.Fatalf("%s %s = %d, want %d", request.method, request.target, response.Code, request.status)
|
||||
}
|
||||
}
|
||||
|
||||
body := scrapeMetrics(t, collector)
|
||||
for _, want := range []string{
|
||||
`lincodex_http_requests_total{method="GET",route="/healthz",status="200"} 1`,
|
||||
`lincodex_http_requests_total{method="GET",route="/api/v1/healthz",status="200"} 1`,
|
||||
`lincodex_http_requests_total{method="GET",route="/api/v1/me/invitations/{invitation_id}",status="401"} 1`,
|
||||
`lincodex_http_requests_total{method="GET",route="/api/v1/me/assessment-attempts/{attempt_id}",status="401"} 1`,
|
||||
`lincodex_http_requests_total{method="GET",route="/api/v1/*",status="404"} 1`,
|
||||
`lincodex_http_requests_total{method="POST",route="/api/v1/*",status="405"} 1`,
|
||||
`lincodex_http_requests_total{method="GET",route="/api/*",status="404"} 1`,
|
||||
`lincodex_http_requests_total{method="GET",route="unmatched",status="404"} 1`,
|
||||
`lincodex_http_request_duration_seconds_count{method="GET",route="/api/v1/healthz",status_class="2xx"} 1`,
|
||||
`lincodex_http_problems_total{code="unauthenticated",route="/api/v1/me/invitations/{invitation_id}"} 1`,
|
||||
`lincodex_http_problems_total{code="not_found",route="/api/v1/*"} 1`,
|
||||
`lincodex_http_problems_total{code="method_not_allowed",route="/api/v1/*"} 1`,
|
||||
`lincodex_http_problems_total{code="not_found",route="/api/*"} 1`,
|
||||
} {
|
||||
if !strings.Contains(body, want+"\n") {
|
||||
t.Fatalf("metrics output is missing %s:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
// A plain 404 outside /api is not a problem response.
|
||||
if strings.Contains(body, `lincodex_http_problems_total{code="not_found",route="unmatched"}`) {
|
||||
t.Fatalf("a non-problem 404 was counted as a problem:\n%s", body)
|
||||
}
|
||||
if found := testutil.FindPersonalIdentifiers(body); len(found) != 0 {
|
||||
t.Fatalf("request metrics expose identifiers %q:\n%s", found, body)
|
||||
}
|
||||
}
|
||||
|
||||
// An operation without an implementation is counted under its own route
|
||||
// with the not_implemented code.
|
||||
func TestRequestMetricsCountNotImplementedOperations(t *testing.T) {
|
||||
router, collector := newMetricsTestRouter(t, func(*v1.HealthHandler, *problem.Responder) api.Handler {
|
||||
return api.UnimplementedHandler{}
|
||||
})
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
|
||||
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
|
||||
|
||||
body := scrapeMetrics(t, collector)
|
||||
for _, want := range []string{
|
||||
`lincodex_http_requests_total{method="GET",route="/api/v1/healthz",status="501"} 1`,
|
||||
`lincodex_http_problems_total{code="not_implemented",route="/api/v1/healthz"} 1`,
|
||||
} {
|
||||
if !strings.Contains(body, want+"\n") {
|
||||
t.Fatalf("metrics output is missing %s:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The metrics adapter mirrors the contract's problem codes to bound its
|
||||
// label; a code missing from its list would be counted as "other".
|
||||
func TestEveryContractProblemCodeKeepsItsMetricLabel(t *testing.T) {
|
||||
collector := metrics.New()
|
||||
for _, code := range api.ProblemCode("").AllValues() {
|
||||
collector.ObserveProblem("/api/v1/*", string(code))
|
||||
}
|
||||
body := scrapeMetrics(t, collector)
|
||||
for _, code := range api.ProblemCode("").AllValues() {
|
||||
if want := `lincodex_http_problems_total{code="` + string(code) + `",route="/api/v1/*"} 1`; !strings.Contains(body, want+"\n") {
|
||||
t.Fatalf("metrics output is missing %s; add the code to the adapter list:\n%s", want, body)
|
||||
}
|
||||
}
|
||||
if strings.Contains(body, `code="other"`) {
|
||||
t.Fatalf("a contract problem code was counted as other:\n%s", body)
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Package observe carries per-request observations from the handlers that
|
||||
// make them to the logging and metrics middleware, through the request
|
||||
// context. It holds only bounded values, never request data.
|
||||
package observe
|
||||
|
||||
import "context"
|
||||
|
||||
// Request collects what handlers report about one request. The handler
|
||||
// chain of a request runs on one goroutine, so it needs no lock.
|
||||
type Request struct {
|
||||
problemCode string
|
||||
}
|
||||
|
||||
type requestKey struct{}
|
||||
|
||||
// Ensure returns ctx with a Request, reusing the one ctx already carries, so
|
||||
// every middleware of a request sees the same observations.
|
||||
func Ensure(ctx context.Context) (context.Context, *Request) {
|
||||
if current, ok := ctx.Value(requestKey{}).(*Request); ok {
|
||||
return ctx, current
|
||||
}
|
||||
current := &Request{}
|
||||
return context.WithValue(ctx, requestKey{}, current), current
|
||||
}
|
||||
|
||||
// RecordProblem notes the problem code of the response to the request of
|
||||
// ctx. The code must come from the closed problem catalogue. Without a
|
||||
// Request in ctx it does nothing.
|
||||
func RecordProblem(ctx context.Context, code string) {
|
||||
if current, ok := ctx.Value(requestKey{}).(*Request); ok {
|
||||
current.problemCode = code
|
||||
}
|
||||
}
|
||||
|
||||
// ProblemCode returns the recorded problem code, or empty when the handlers
|
||||
// recorded none.
|
||||
func (request *Request) ProblemCode() string {
|
||||
return request.problemCode
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package observe
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type testKey struct{}
|
||||
|
||||
func TestEnsureSharesOneRequestAndRecordsTheProblem(t *testing.T) {
|
||||
RecordProblem(context.Background(), "internal") // no Request: no effect, no panic
|
||||
|
||||
ctx, first := Ensure(context.Background())
|
||||
nested, second := Ensure(context.WithValue(ctx, testKey{}, "other value"))
|
||||
if first != second {
|
||||
t.Fatal("Ensure() created a second Request for the same request")
|
||||
}
|
||||
RecordProblem(nested, "not_found")
|
||||
if got := first.ProblemCode(); got != "not_found" {
|
||||
t.Fatalf("ProblemCode() = %q, want not_found", got)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/observe"
|
||||
)
|
||||
|
||||
// MediaType is the RFC 9457 media type of every public error response.
|
||||
@@ -132,12 +133,15 @@ var definitions = map[api.ProblemCode]definition{
|
||||
// New returns the problem response for code with its fixed status, title,
|
||||
// and detail, and the request ID of ctx as trace_id. An unknown code yields
|
||||
// the internal problem, so a caller cannot produce an undocumented status.
|
||||
// The code is also recorded for the request log and metrics; it comes from
|
||||
// the closed catalogue above, so the log field and metric label stay bounded.
|
||||
func New(ctx context.Context, code api.ProblemCode) *api.ProblemStatusCode {
|
||||
known, ok := definitions[code]
|
||||
if !ok {
|
||||
code = api.ProblemCodeInternal
|
||||
known = definitions[code]
|
||||
}
|
||||
observe.RecordProblem(ctx, string(code))
|
||||
response := api.Problem{
|
||||
Type: typePrefix + string(code),
|
||||
Title: known.title,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
|
||||
"lincodex/backend/pkg/testutil"
|
||||
)
|
||||
|
||||
var requestIDField = regexp.MustCompile(`"request_id":"[^"]*"`)
|
||||
|
||||
// The request log is collected into Loki, so an address or an identifier that
|
||||
// a client puts into a path or a query must not reach it.
|
||||
func TestRequestLogNamesTheRouteTemplateAndNoRequestData(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&logs, nil))
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
responder := problem.NewResponder(logger)
|
||||
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, metrics.New(), logger)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
for _, target := range []string{
|
||||
"/api/v1/healthz?email=" + metricsFixtureEmail,
|
||||
"/api/v1/users/" + metricsFixtureEmail,
|
||||
"/api/v1/me/invitations/" + metricsFixtureID + "?email=" + metricsFixtureEmail + "&id=" + metricsFixtureID,
|
||||
"/api/" + metricsFixtureEmail,
|
||||
"/files/" + metricsFixtureID,
|
||||
// The operational routes are not logged at all.
|
||||
"/healthz?email=" + metricsFixtureEmail,
|
||||
"/readyz",
|
||||
} {
|
||||
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, target, nil))
|
||||
}
|
||||
|
||||
// The request ID is a random UUID per request that links log lines; it
|
||||
// identifies no person, so it is left out of the scan.
|
||||
scanned := requestIDField.ReplaceAllString(logs.String(), `"request_id":""`)
|
||||
if found := testutil.FindPersonalIdentifiers(scanned); len(found) != 0 {
|
||||
t.Fatalf("request log exposes identifiers %q:\n%s", found, logs.String())
|
||||
}
|
||||
for _, marker := range []string{metricsFixtureEmail, metricsFixtureID, "@"} {
|
||||
if strings.Contains(logs.String(), marker) {
|
||||
t.Fatalf("request log exposes %q:\n%s", marker, logs.String())
|
||||
}
|
||||
}
|
||||
type line struct {
|
||||
Msg string `json:"msg"`
|
||||
Route string `json:"route"`
|
||||
Status int `json:"status"`
|
||||
StatusClass string `json:"status_class"`
|
||||
ProblemCode string `json:"problem_code"`
|
||||
QueryParams int `json:"query_params"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
var got []line
|
||||
scanner := bufio.NewScanner(&logs)
|
||||
for scanner.Scan() {
|
||||
var entry line
|
||||
if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {
|
||||
t.Fatalf("decode log line %s: %v", scanner.Text(), err)
|
||||
}
|
||||
if strings.HasPrefix(entry.Msg, "http request") {
|
||||
got = append(got, entry)
|
||||
}
|
||||
}
|
||||
want := []line{
|
||||
{Msg: "http request", Route: "/api/v1/healthz", Status: 200, StatusClass: "2xx", QueryParams: 1},
|
||||
{Msg: "http request error", Route: "/api/v1/*", Status: 404, StatusClass: "4xx", ProblemCode: "not_found"},
|
||||
{Msg: "http request error", Route: "/api/v1/me/invitations/{invitation_id}", Status: 401, StatusClass: "4xx", ProblemCode: "unauthenticated", QueryParams: 2},
|
||||
{Msg: "http request error", Route: "/api/*", Status: 404, StatusClass: "4xx", ProblemCode: "not_found"},
|
||||
{Msg: "http request error", Route: "unmatched", Status: 404, StatusClass: "4xx"},
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("logged %d request lines, want %d: %+v", len(got), len(want), got)
|
||||
}
|
||||
for index := range want {
|
||||
if got[index].RequestID == "" {
|
||||
t.Fatalf("line %d has no request ID", index)
|
||||
}
|
||||
got[index].RequestID = ""
|
||||
if got[index] != want[index] {
|
||||
t.Fatalf("line %d = %+v, want %+v", index, got[index], want[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,10 +51,12 @@ func NewRouter(
|
||||
router := chi.NewRouter()
|
||||
// Request ID, request logging, and metrics wrap every route, so both
|
||||
// recovery middlewares below run inside them: a recovered panic carries the
|
||||
// request ID and its 500 is logged and counted.
|
||||
// request ID and its 500 is logged and counted. The request log names the
|
||||
// same route template as the metrics, never the raw path or query.
|
||||
resolveRoute := operationRoute(apiServer)
|
||||
router.Use(kitmiddleware.RequestID())
|
||||
router.Use(kitmiddleware.Logger(logger, nil, kitmiddleware.WithSkipPaths(healthPath, readinessPath)))
|
||||
router.Use(httpmiddleware.CollectMetrics(collector))
|
||||
router.Use(httpmiddleware.RequestLog(logger, resolveRoute, healthPath, readinessPath))
|
||||
router.Use(httpmiddleware.CollectMetrics(collector, resolveRoute))
|
||||
router.Group(func(operational chi.Router) {
|
||||
operational.Use(kitmiddleware.Recoverer(logger))
|
||||
operational.Get(healthPath, health.Healthz)
|
||||
@@ -65,7 +67,7 @@ func NewRouter(
|
||||
// server aborts the response; the kit Recoverer would swallow that panic.
|
||||
router.Group(func(public chi.Router) {
|
||||
public.Use(problems.Recover)
|
||||
public.Handle(publicPrefix+"/*", apiServer)
|
||||
public.Handle(apiWildcard, apiServer)
|
||||
// Unknown /api paths outside the versioned prefix are also problems,
|
||||
// so every error under /api has the contract's format.
|
||||
public.Handle(apiRoot, http.HandlerFunc(problems.NotFound))
|
||||
@@ -73,3 +75,23 @@ func NewRouter(
|
||||
})
|
||||
return router, nil
|
||||
}
|
||||
|
||||
// apiWildcard is the chi pattern that mounts the generated server.
|
||||
const apiWildcard = publicPrefix + "/*"
|
||||
|
||||
// operationRoute names a request under the versioned prefix by the OpenAPI
|
||||
// path template of its operation, such as /api/v1/me/invitations/{invitation_id},
|
||||
// so the metrics tell operations apart without a path parameter in a label.
|
||||
// A path or method that matches no operation keeps the wildcard pattern.
|
||||
func operationRoute(server *apiadapter.Server) httpmiddleware.RouteResolver {
|
||||
return func(r *http.Request, pattern string) string {
|
||||
if pattern != apiWildcard {
|
||||
return pattern
|
||||
}
|
||||
operation, ok := server.FindPath(r.Method, r.URL)
|
||||
if !ok {
|
||||
return pattern
|
||||
}
|
||||
return operation.PathPattern()
|
||||
}
|
||||
}
|
||||
@@ -2044,7 +2044,7 @@ func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) {
|
||||
if strings.Contains(logs.String(), "jane@example.com") {
|
||||
t.Fatalf("panic value with personal data reached the logs: %s", logs.String())
|
||||
}
|
||||
want := []recordedRequest{{route: "/api/v1/*", status: http.StatusInternalServerError}}
|
||||
want := []recordedRequest{{route: "/api/v1/healthz", status: http.StatusInternalServerError}}
|
||||
if fmt.Sprint(recorder.requests) != fmt.Sprint(want) {
|
||||
t.Fatalf("metrics observed %v, want %v", recorder.requests, want)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user