feat(observability): add product metrics for API, outbox and delivery

This commit is contained in:
shira committed 2026-10-06 19:48:15 +03:00
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)
}
@@ -0,0 +1,59 @@
package postgres
import (
"context"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// DeliveryStatisticsStore reads the delivery aggregate behind the metrics on
// a pool connection, with GetDeliveryStatistics.
type DeliveryStatisticsStore struct {
queries *sqlc.Queries
}
func NewDeliveryStatisticsStore(pool *pgxpool.Pool) *DeliveryStatisticsStore {
return &DeliveryStatisticsStore{queries: sqlc.New(standaloneDB{pool: pool})}
}
var _ outbound.DeliveryStatisticsReader = (*DeliveryStatisticsStore)(nil)
func (store *DeliveryStatisticsStore) DeliveryStatistics(ctx context.Context) (outbound.DeliveryStatistics, error) {
rows, err := store.queries.GetDeliveryStatistics(ctx)
if err != nil {
return outbound.DeliveryStatistics{}, fmt.Errorf("DeliveryStatisticsStore.DeliveryStatistics - read: %w", sanitizedDatabaseError(err))
}
statistics := outbound.DeliveryStatistics{Counts: make([]outbound.DeliveryStatusCount, 0, len(rows))}
for _, row := range rows {
count, err := deliveryStatusCount(row.Kind, row.Status, row.Deliveries)
if err != nil {
return outbound.DeliveryStatistics{}, fmt.Errorf("DeliveryStatisticsStore.DeliveryStatistics - read row: %w", err)
}
statistics.Counts = append(statistics.Counts, count)
earliest := row.EarliestPendingAttemptAt
if earliest.Valid && (statistics.EarliestPendingAttemptAt.IsZero() || earliest.Time.Before(statistics.EarliestPendingAttemptAt)) {
statistics.EarliestPendingAttemptAt = earliest.Time
}
}
return statistics, nil
}
// deliveryStatusCount parses the stored kind and status, which the table
// constraints already restrict, so a metric label never carries a value
// outside the domain sets.
func deliveryStatusCount(kind, status string, deliveries int64) (outbound.DeliveryStatusCount, error) {
parsedKind, err := domain.ParseMailKind(kind)
if err != nil {
return outbound.DeliveryStatusCount{}, fmt.Errorf("postgres.deliveryStatusCount - parse kind: %w", err)
}
parsedStatus, err := domain.ParseDeliveryStatus(status)
if err != nil {
return outbound.DeliveryStatusCount{}, fmt.Errorf("postgres.deliveryStatusCount - parse status: %w", err)
}
return outbound.DeliveryStatusCount{Kind: parsedKind, Status: parsedStatus, Deliveries: deliveries}, nil
}
@@ -80,6 +80,55 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery
return i, err
}
const getDeliveryStatistics = `-- name: GetDeliveryStatistics :many
SELECT
kind,
status,
count(*) AS deliveries,
min(next_attempt_at) FILTER (
WHERE status = 'pending'
)::timestamptz AS earliest_pending_attempt_at
FROM deliveries
GROUP BY kind, status
`
type GetDeliveryStatisticsRow struct {
Kind string
Status string
Deliveries int64
EarliestPendingAttemptAt pgtype.Timestamptz
}
// Aggregates the deliveries by kind and status for the metrics, at most once
// per metrics interval. It reads only kind, status, and next_attempt_at,
// never an address, a body, or an ID. No index covers status, so it scans
// the table; add an index on (status) or keep per-status counters before
// the table holds millions of rows.
func (q *Queries) GetDeliveryStatistics(ctx context.Context) ([]GetDeliveryStatisticsRow, error) {
rows, err := q.db.Query(ctx, getDeliveryStatistics)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetDeliveryStatisticsRow
for rows.Next() {
var i GetDeliveryStatisticsRow
if err := rows.Scan(
&i.Kind,
&i.Status,
&i.Deliveries,
&i.EarliestPendingAttemptAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getLatestDeliveryStatus = `-- name: GetLatestDeliveryStatus :one
SELECT
id,
@@ -99,6 +99,12 @@ type Querier interface {
// after it.
GetCurrentConsentText(ctx context.Context, arg GetCurrentConsentTextParams) (ConsentText, error)
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
// Aggregates the deliveries by kind and status for the metrics, at most once
// per metrics interval. It reads only kind, status, and next_attempt_at,
// never an address, a body, or an ID. No index covers status, so it scans
// the table; add an index on (status) or keep per-status counters before
// the table holds millions of rows.
GetDeliveryStatistics(ctx context.Context) ([]GetDeliveryStatisticsRow, error)
// Among the versions of a family already effective at a time, the newest
// publication wins. A version scheduled for later therefore never undoes a
// version published after it. The unique (policy_key, version) index serves
@@ -0,0 +1,62 @@
package prometheus
import (
"slices"
client "github.com/prometheus/client_golang/prometheus"
)
// otherLabelValue replaces a label value outside its closed set, so a caller
// mistake cannot create unbounded series.
const otherLabelValue = "other"
// assessmentMetrics count the saving of assessment answers, which PRD 6.6
// names as a product signal next to API errors and queues. The answer
// command (SubmitMyAssessmentAnswer) is not implemented yet, so nothing
// calls the hook and no series exists; its HTTP latency and errors are
// already counted per route template by the request metrics.
type assessmentMetrics struct {
answerSaves *client.CounterVec
}
var (
// answerFormats mirror the answer formats of the public contract.
answerFormats = []string{"choice", "number", "string", "order", "find_error", "configuration", "practice"}
// answerSaveOutcomes: stored (a new answer was stored), unchanged (the
// same answer was already stored; nothing changed), rejected (a stale
// version, a state conflict, or an invalid answer), or failed (an
// internal error; nothing was stored).
answerSaveOutcomes = []string{"stored", "unchanged", "rejected", "failed"}
)
func newAssessmentMetrics() assessmentMetrics {
return assessmentMetrics{
answerSaves: client.NewCounterVec(client.CounterOpts{
Name: "lincodex_assessment_answer_saves_total",
Help: "Assessment answer save commands by answer format and outcome: stored, unchanged, rejected, or failed.",
}, []string{"format", "outcome"}),
}
}
func (assessment assessmentMetrics) collectors() []client.Collector {
return []client.Collector{assessment.answerSaves}
}
// ObserveAssessmentAnswerSave counts one answer save command. It is the hook
// for the assessment usecase: call it once per command after its transaction
// ended, with the format of the answer and one of the outcomes above. A
// value outside these sets is counted as "other". Never pass an attempt,
// item, or candidate identifier.
func (metrics *Metrics) ObserveAssessmentAnswerSave(format, outcome string) {
metrics.assessment.answerSaves.WithLabelValues(
boundedLabel(format, answerFormats),
boundedLabel(outcome, answerSaveOutcomes),
).Inc()
}
func boundedLabel(value string, allowed []string) string {
if slices.Contains(allowed, value) {
return value
}
return otherLabelValue
}
@@ -0,0 +1,148 @@
package prometheus
import (
"time"
client "github.com/prometheus/client_golang/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// mailMetrics describe the stored mail deliveries and the quota of the
// configured provider account. Their labels come from closed sets: the
// delivery kind and status from the domain, the transport name from
// configuration, and the quota window. A recipient, address, user or
// delivery ID, subject, and the provider account label never become labels;
// the account label is free text an operator chooses, and one process
// reports only its own configured account.
type mailMetrics struct {
// deliveries and oldestDuePendingAge are database-wide values at the
// last statistics read. Every backend instance reports the same values,
// so dashboards aggregate them with max. Both are vectors so that no
// series exists before the first successful read: an age of 0 then would
// claim that nothing is late.
deliveries *client.GaugeVec
oldestDuePendingAge *client.GaugeVec
// lastSuccess is the Unix time of the last read in which every
// aggregate was read; 0 from the sampler start until the first one.
lastSuccess *client.GaugeVec
// quotaUsed, quotaLimit, and quotaProviderExhausted describe the current
// UTC day and month windows of the configured provider account.
quotaUsed *client.GaugeVec
quotaLimit *client.GaugeVec
quotaProviderExhausted *client.GaugeVec
}
// deliveryKinds and deliveryStatuses list the series that always exist, so a
// status that empties drops to zero instead of keeping its last value.
var (
deliveryKinds = []domain.MailKind{
domain.MailKindVerification,
domain.MailKindPasswordReset,
domain.MailKindNotification,
}
deliveryStatuses = []domain.DeliveryStatus{
domain.DeliveryStatusPending,
domain.DeliveryStatusWaitingQuota,
domain.DeliveryStatusUnknown,
domain.DeliveryStatusAccepted,
domain.DeliveryStatusRejected,
}
)
func newMailMetrics() mailMetrics {
return mailMetrics{
deliveries: client.NewGaugeVec(client.GaugeOpts{
Name: "lincodex_mail_deliveries",
Help: "Stored mail deliveries by kind and status at the last statistics read: pending, waiting_quota, unknown, accepted, or rejected.",
}, []string{"kind", "status"}),
oldestDuePendingAge: client.NewGaugeVec(client.GaugeOpts{
Name: "lincodex_mail_delivery_oldest_due_pending_age_seconds",
Help: "How long the earliest pending delivery has been due for its next attempt, by the application clock, at the last statistics read; 0 without due pending deliveries, absent before the first read.",
}, nil),
lastSuccess: client.NewGaugeVec(client.GaugeOpts{
Name: "lincodex_mail_metrics_last_success_timestamp_seconds",
Help: "Unix time of the last read of the delivery and quota aggregates in which every read succeeded; 0 from the sampler start until the first one.",
}, nil),
quotaUsed: client.NewGaugeVec(client.GaugeOpts{
Name: "lincodex_mail_quota_used_recipients",
Help: "Recipients counted against the current UTC window of the configured provider account, by provider and window: day or month.",
}, []string{"provider", "window"}),
quotaLimit: client.NewGaugeVec(client.GaugeOpts{
Name: "lincodex_mail_quota_limit_recipients",
Help: "Configured recipient limit of the current UTC window, by provider and window: day or month.",
}, []string{"provider", "window"}),
quotaProviderExhausted: client.NewGaugeVec(client.GaugeOpts{
Name: "lincodex_mail_quota_provider_exhausted",
Help: "1 when the provider itself reported the quota of the current UTC window used up, 0 otherwise, by provider and window.",
}, []string{"provider", "window"}),
}
}
func (mail mailMetrics) collectors() []client.Collector {
return []client.Collector{
mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess,
mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted,
}
}
type deliveryState struct {
kind domain.MailKind
status domain.DeliveryStatus
}
// ObserveDeliveryStates records the latest delivery statistics read. Every
// known kind and status pair is set, to zero when counts has none.
func (metrics *Metrics) ObserveDeliveryStates(counts []outbound.DeliveryStatusCount, oldestDuePending time.Duration) {
values := make(map[deliveryState]int64, len(deliveryKinds)*len(deliveryStatuses))
for _, kind := range deliveryKinds {
for _, status := range deliveryStatuses {
values[deliveryState{kind: kind, status: status}] = 0
}
}
// The store parses kind and status into domain values, so a value the
// lists above do not know yet is still bounded.
for _, count := range counts {
values[deliveryState{kind: count.Kind, status: count.Status}] += count.Deliveries
}
for state, value := range values {
metrics.mail.deliveries.WithLabelValues(string(state.kind), string(state.status)).Set(float64(value))
}
metrics.mail.oldestDuePendingAge.WithLabelValues().Set(oldestDuePending.Seconds())
}
// PrepareMailMetricsReads exposes the last success time at 0 when the
// sampler starts, so an alert sees a sampler that never reads successfully.
func (metrics *Metrics) PrepareMailMetricsReads() {
metrics.mail.lastSuccess.WithLabelValues().Set(0)
}
// ObserveMailMetricsReadSuccess records a read in which every aggregate was
// read.
func (metrics *Metrics) ObserveMailMetricsReadSuccess(at time.Time) {
metrics.mail.lastSuccess.WithLabelValues().Set(float64(at.UnixNano()) / float64(time.Second))
}
// ObserveMailQuota records the usage of the current windows of the
// configured account of provider, a transport name from configuration.
func (metrics *Metrics) ObserveMailQuota(provider string, usage outbound.MailQuotaUsage, limits domain.MailQuotaLimits) {
windows := []struct {
period domain.MailQuotaPeriod
used int64
exhausted time.Time
}{
{period: domain.MailQuotaPeriodDay, used: usage.DayUsed, exhausted: usage.DayProviderExhaustedAt},
{period: domain.MailQuotaPeriodMonth, used: usage.MonthUsed, exhausted: usage.MonthProviderExhaustedAt},
}
for _, window := range windows {
labels := []string{provider, string(window.period)}
metrics.mail.quotaUsed.WithLabelValues(labels...).Set(float64(window.used))
metrics.mail.quotaLimit.WithLabelValues(labels...).Set(float64(limits.Of(window.period)))
exhausted := 0.0
if !window.exhausted.IsZero() {
exhausted = 1
}
metrics.mail.quotaProviderExhausted.WithLabelValues(labels...).Set(exhausted)
}
}
@@ -15,7 +15,11 @@ import (
type Metrics struct {
registry *client.Registry
requests *client.CounterVec
latency *client.HistogramVec
// latency carries the status class, so a fast stream of rejected
// requests does not hide slow successful ones.
latency *client.HistogramVec
// problems counts error responses by the problem code they carry.
problems *client.CounterVec
// relayEvents counts outbox events by relay outcome: published or
// failed. A failed event stays pending and is counted again on every
// retry.
@@ -40,6 +44,9 @@ type Metrics struct {
scheduledJobsDue client.Gauge
scheduledJobsOldestDueAge client.Gauge
scheduledJobsDead client.Gauge
mail mailMetrics
assessment assessmentMetrics
}
// Outbox relay outcome label values.
@@ -65,9 +72,13 @@ func New() *Metrics {
}, []string{"method", "route", "status"})
latency := client.NewHistogramVec(client.HistogramOpts{
Name: "lincodex_http_request_duration_seconds",
Help: "HTTP request duration in seconds.",
Help: "HTTP request duration in seconds, by method, route template, and status class.",
Buckets: client.DefBuckets,
}, []string{"method", "route"})
}, []string{"method", "route", "status_class"})
problems := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_http_problems_total",
Help: "Public API error responses by route template and the code of the RFC 9457 problem they carry.",
}, []string{"route", "code"})
relayEvents := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_outbox_relay_events_total",
Help: "Outbox events handled by the relay, by outcome; failed events stay pending and are retried.",
@@ -104,13 +115,17 @@ func New() *Metrics {
Name: "lincodex_scheduled_jobs_dead",
Help: "Dead scheduled jobs, which need an operator, at the last backlog read.",
})
mail := newMailMetrics()
assessment := newAssessmentMetrics()
registry.MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
requests, latency, relayEvents, relayPending, relayOldestAge,
requests, latency, problems, relayEvents, relayPending, relayOldestAge,
consumerRecords, consumerFailures,
scheduledJobs, scheduledJobsDue, scheduledJobsOldestDueAge, scheduledJobsDead,
)
registry.MustRegister(mail.collectors()...)
registry.MustRegister(assessment.collectors()...)
// Expose both series from the start so rate queries see zero, not absence.
relayEvents.WithLabelValues(relayOutcomePublished)
relayEvents.WithLabelValues(relayOutcomeFailed)
@@ -118,6 +133,7 @@ func New() *Metrics {
registry: registry,
requests: requests,
latency: latency,
problems: problems,
relayEvents: relayEvents,
relayPending: relayPending,
relayOldestAge: relayOldestAge,
@@ -129,6 +145,9 @@ func New() *Metrics {
scheduledJobsDue: scheduledJobsDue,
scheduledJobsOldestDueAge: scheduledJobsOldestDueAge,
scheduledJobsDead: scheduledJobsDead,
mail: mail,
assessment: assessment,
}
}
@@ -201,7 +220,36 @@ func (metrics *Metrics) ObserveRequest(method, route string, status int, duratio
method = "OTHER"
}
metrics.requests.WithLabelValues(method, route, strconv.Itoa(status)).Inc()
metrics.latency.WithLabelValues(method, route).Observe(duration.Seconds())
metrics.latency.WithLabelValues(method, route, statusClass(status)).Observe(duration.Seconds())
}
// problemCodes mirror the problem codes of the public contract, which this
// adapter does not import; a test in the HTTP adapter checks that every
// contract code is listed.
var problemCodes = []string{
"validation_failed", "verification_token_invalid", "verification_token_expired",
"unauthenticated", "invalid_credentials", "forbidden", "email_not_verified",
"csrf_check_failed", "not_found", "method_not_allowed", "idempotency_in_progress",
"state_conflict", "version_conflict", "payload_too_large", "unsupported_media_type",
"idempotency_key_reused", "precondition_required", "rate_limited", "internal",
"not_implemented",
}
// ObserveProblem counts one error response. A code outside the contract
// catalogue is counted as "other"; an empty route is the unmatched one.
func (metrics *Metrics) ObserveProblem(route, code string) {
if route == "" {
route = "unmatched"
}
metrics.problems.WithLabelValues(route, boundedLabel(code, problemCodes)).Inc()
}
// 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"
}
func (metrics *Metrics) Handler() http.Handler {
@@ -19,7 +19,7 @@ func TestMetricsHandlerExposesBoundedRequestLabels(t *testing.T) {
if !strings.Contains(body, `lincodex_http_requests_total{method="OTHER",route="unmatched",status="599"} 1`) {
t.Fatalf("metrics output is missing bounded request labels:\n%s", body)
}
if !strings.Contains(body, `lincodex_http_request_duration_seconds_bucket{method="OTHER",route="unmatched",le="0.05"} 1`) {
if !strings.Contains(body, `lincodex_http_request_duration_seconds_bucket{method="OTHER",route="unmatched",status_class="5xx",le="0.05"} 1`) {
t.Fatalf("metrics output is missing request duration:\n%s", body)
}
}
@@ -0,0 +1,174 @@
package prometheus
import (
"net/http/httptest"
"strings"
"testing"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/pkg/testutil"
)
func scrape(t *testing.T, metrics *Metrics) string {
t.Helper()
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
return response.Body.String()
}
func requireSeries(t *testing.T, body string, want ...string) {
t.Helper()
for _, series := range want {
if !strings.Contains(body, series+"\n") {
t.Fatalf("metrics output is missing %s:\n%s", series, body)
}
}
}
func TestMetricsHandlerExposesProblemsAndLatencyByStatusClass(t *testing.T) {
metrics := New()
metrics.ObserveRequest("GET", "/api/v1/healthz", 200, 3*time.Millisecond)
metrics.ObserveRequest("GET", "/api/v1/*", 404, time.Millisecond)
metrics.ObserveProblem("/api/v1/*", "not_found")
metrics.ObserveProblem("", "internal")
requireSeries(t, scrape(t, metrics),
`lincodex_http_request_duration_seconds_count{method="GET",route="/api/v1/healthz",status_class="2xx"} 1`,
`lincodex_http_request_duration_seconds_count{method="GET",route="/api/v1/*",status_class="4xx"} 1`,
`lincodex_http_problems_total{code="not_found",route="/api/v1/*"} 1`,
`lincodex_http_problems_total{code="internal",route="unmatched"} 1`,
)
}
func TestMetricsHandlerExposesEveryDeliveryState(t *testing.T) {
metrics := New()
// Before the first read nothing claims that no delivery is late.
if body := scrape(t, metrics); strings.Contains(body, "lincodex_mail_delivery_oldest_due_pending_age_seconds ") ||
strings.Contains(body, "lincodex_mail_deliveries{") {
t.Fatalf("delivery series exist before the first read:\n%s", body)
}
metrics.ObserveDeliveryStates([]outbound.DeliveryStatusCount{
{Kind: domain.MailKindVerification, Status: domain.DeliveryStatusPending, Deliveries: 3},
{Kind: domain.MailKindNotification, Status: domain.DeliveryStatusUnknown, Deliveries: 1},
}, 90*time.Second)
requireSeries(t, scrape(t, metrics),
`lincodex_mail_deliveries{kind="verification",status="pending"} 3`,
`lincodex_mail_deliveries{kind="notification",status="unknown"} 1`,
// Every known pair exists at zero.
`lincodex_mail_deliveries{kind="password_reset",status="waiting_quota"} 0`,
`lincodex_mail_deliveries{kind="verification",status="accepted"} 0`,
`lincodex_mail_deliveries{kind="notification",status="rejected"} 0`,
"lincodex_mail_delivery_oldest_due_pending_age_seconds 90",
)
// A status that emptied drops to zero instead of keeping its value.
metrics.ObserveDeliveryStates(nil, 0)
requireSeries(t, scrape(t, metrics),
`lincodex_mail_deliveries{kind="verification",status="pending"} 0`,
`lincodex_mail_deliveries{kind="notification",status="unknown"} 0`,
"lincodex_mail_delivery_oldest_due_pending_age_seconds 0",
)
}
func TestMetricsHandlerExposesMailQuotaWithoutTheAccount(t *testing.T) {
limits, err := domain.NewMailQuotaLimits(100, 3000)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
metrics := New()
metrics.ObserveMailQuota("resend", outbound.MailQuotaUsage{
DayUsed: 100,
MonthUsed: 1250,
DayProviderExhaustedAt: time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC),
}, limits)
body := scrape(t, metrics)
requireSeries(t, body,
`lincodex_mail_quota_used_recipients{provider="resend",window="day"} 100`,
`lincodex_mail_quota_used_recipients{provider="resend",window="month"} 1250`,
`lincodex_mail_quota_limit_recipients{provider="resend",window="day"} 100`,
`lincodex_mail_quota_limit_recipients{provider="resend",window="month"} 3000`,
`lincodex_mail_quota_provider_exhausted{provider="resend",window="day"} 1`,
`lincodex_mail_quota_provider_exhausted{provider="resend",window="month"} 0`,
)
if strings.Contains(body, "account=") {
t.Fatalf("quota metrics carry an account label:\n%s", body)
}
}
func TestAssessmentAnswerSaveHookBoundsItsLabels(t *testing.T) {
metrics := New()
if body := scrape(t, metrics); strings.Contains(body, "lincodex_assessment_answer_saves_total{") {
t.Fatalf("answer save series exist before the hook was called:\n%s", body)
}
metrics.ObserveAssessmentAnswerSave("choice", "stored")
metrics.ObserveAssessmentAnswerSave("practice", "unchanged")
// A caller mistake must not create a series per value.
metrics.ObserveAssessmentAnswerSave("0199b4f2-7c1e-7d3a-9f00-aabbccddeeff", "jane@example.com")
requireSeries(t, scrape(t, metrics),
`lincodex_assessment_answer_saves_total{format="choice",outcome="stored"} 1`,
`lincodex_assessment_answer_saves_total{format="practice",outcome="unchanged"} 1`,
`lincodex_assessment_answer_saves_total{format="other",outcome="other"} 1`,
)
}
// TestRegisteredMetricsCarryNoPersonalIdentifiers exercises every hook of the
// adapter, including values that look like the identifiers a careless caller
// could pass, and scans the whole exposition, label names and values
// included, for an email address or a UUID.
func TestRegisteredMetricsCarryNoPersonalIdentifiers(t *testing.T) {
const (
fixtureEmail = "metrics.fixture@example.com"
fixtureID = "0199b4f2-7c1e-7d3a-9f00-aabbccddeeff"
)
limits, err := domain.NewMailQuotaLimits(100, 3000)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
metrics := New()
metrics.ObserveRequest("GET", "/api/v1/me/invitations/{invitationId}", 401, time.Millisecond)
metrics.ObserveProblem("/api/v1/me/invitations/{invitationId}", "unauthenticated")
metrics.ObserveOutboxRelayPass(2, 1)
metrics.ObserveOutboxBacklog(outbound.OutboxBacklog{Pending: 1, OldestAge: time.Second})
metrics.PrepareEventConsumer("mail_delivery")
metrics.ObserveConsumedRecord("mail_delivery", "applied")
metrics.ObserveConsumerFailure("mail_delivery", "handler")
metrics.PrepareScheduledJobKind("invitation.response_deadline")
metrics.ObserveScheduledJob("invitation.response_deadline", "done")
metrics.ObserveScheduledJobBacklog(outbound.JobBacklog{Due: 1})
metrics.ObserveDeliveryStates([]outbound.DeliveryStatusCount{
{Kind: domain.MailKindVerification, Status: domain.DeliveryStatusAccepted, Deliveries: 1},
}, time.Minute)
metrics.ObserveMailQuota("resend", outbound.MailQuotaUsage{DayUsed: 1, MonthUsed: 1}, limits)
metrics.PrepareMailMetricsReads()
metrics.ObserveMailMetricsReadSuccess(time.Now())
metrics.ObserveAssessmentAnswerSave(fixtureEmail, fixtureID)
body := scrape(t, metrics)
if found := testutil.FindPersonalIdentifiers(body); len(found) != 0 {
t.Fatalf("metrics expose identifiers %q:\n%s", found, body)
}
for _, marker := range []string{fixtureEmail, fixtureID, "@"} {
if strings.Contains(body, marker) {
t.Fatalf("metrics expose %q:\n%s", marker, body)
}
}
}
func TestMetricsHandlerExposesTheLastSuccessfulMailMetricsRead(t *testing.T) {
metrics := New()
if body := scrape(t, metrics); strings.Contains(body, "lincodex_mail_metrics_last_success_timestamp_seconds ") {
t.Fatalf("the last success time exists without a sampler:\n%s", body)
}
metrics.PrepareMailMetricsReads()
requireSeries(t, scrape(t, metrics), "lincodex_mail_metrics_last_success_timestamp_seconds 0")
metrics.ObserveMailMetricsReadSuccess(time.Unix(1791290638, 500_000_000))
requireSeries(t, scrape(t, metrics), "lincodex_mail_metrics_last_success_timestamp_seconds 1.7912906385e+09")
}
func TestProblemCodesOutsideTheCatalogueAreBounded(t *testing.T) {
metrics := New()
metrics.ObserveProblem("/api/v1/*", "jane@example.com")
requireSeries(t, scrape(t, metrics), `lincodex_http_problems_total{code="other",route="/api/v1/*"} 1`)
}
+21 -12
View File
@@ -18,6 +18,7 @@ import (
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/deliverymetrics"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/outboxrelay"
)
@@ -45,6 +46,9 @@ type Application struct {
// is nil when the worker is disabled, no job kind is registered, or the
// database is not configured.
jobs *jobrunner.Worker
// deliveryMetrics reads the delivery and quota gauges while the servers
// run. It is nil when the database is not configured.
deliveryMetrics *deliverymetrics.Sampler
}
func NewApplication(
@@ -56,16 +60,18 @@ func NewApplication(
relay *outboxrelay.Relay,
consumers eventConsumers,
jobs *jobrunner.Worker,
deliveryMetrics *deliverymetrics.Sampler,
) *Application {
return &Application{
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
config: config,
apiHandler: apiHandler,
metrics: metrics,
logger: logger,
mailSender: mailSender,
relay: relay,
consumers: consumers,
jobs: jobs,
deliveryMetrics: deliveryMetrics,
}
}
@@ -191,10 +197,10 @@ func (application *Application) run(ctx context.Context) error {
return err
}
// startWorkers runs the relay, every consumer, and the scheduled job worker
// until ctx ends and returns a channel that closes when all of them have
// stopped. The workers stop together with the servers; none of them
// depends on another.
// startWorkers runs the relay, every consumer, the scheduled job worker, and
// the delivery metrics sampler until ctx ends and returns a channel that
// closes when all of them have stopped. The workers stop together with the
// servers; none of them depends on another.
func (application *Application) startWorkers(ctx context.Context) <-chan struct{} {
var workers sync.WaitGroup
if application.relay != nil {
@@ -206,6 +212,9 @@ func (application *Application) startWorkers(ctx context.Context) <-chan struct{
if application.jobs != nil {
workers.Go(func() { application.jobs.Run(ctx) })
}
if application.deliveryMetrics != nil {
workers.Go(func() { application.deliveryMetrics.Run(ctx) })
}
stopped := make(chan struct{})
go func() {
defer close(stopped)
+1 -1
View File
@@ -191,7 +191,7 @@ func TestApplicationRunsConsumersWhileServingAndWaitsForThem(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil)
}, http.NotFoundHandler(), metrics, logger, nil, nil, eventConsumers{consumer}, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
@@ -0,0 +1,80 @@
package bootstrap
import (
"context"
"fmt"
"log/slog"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/worker/deliverymetrics"
)
const (
// deliveryMetricsPoolMaxConns covers the reads of one sample, which run
// one after another.
deliveryMetricsPoolMaxConns = 1
// deliveryMetricsInterval matches the usual Prometheus scrape interval.
// The delivery read scans the deliveries table, so it is not repeated
// more often than a scrape can show it.
deliveryMetricsInterval = 30 * time.Second
)
var _ deliverymetrics.Metrics = (*prometheus.Metrics)(nil)
// newDeliveryMetrics builds the delivery metrics sampler and the PostgreSQL
// pool it owns. Nothing connects here; an unavailable database leaves the
// gauges stale and logs a warning per sample. It returns no sampler when
// DATABASE_URL is unset. The quota part runs only for an active transport.
func newDeliveryMetrics(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
metrics *prometheus.Metrics,
) (*deliverymetrics.Sampler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("delivery metrics sampler skipped because DATABASE_URL is not set")
return nil, func() {}, nil
}
quota, err := deliveryMetricsQuota(settings)
if err != nil {
return nil, nil, err
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, deliveryMetricsPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newDeliveryMetrics - create pool: %w", err)
}
if quota != nil {
quota.Reader = postgres.NewMailQuotaStore(pool).MailQuotas()
}
sampler := deliverymetrics.New(
postgres.NewDeliveryStatisticsStore(pool),
quota,
metrics,
logger.With(slog.String("component", "delivery_metrics")),
deliveryMetricsInterval,
time.Now,
)
// The application stops the sampler before this cleanup runs.
return sampler, pool.Close, nil
}
// deliveryMetricsQuota returns the configured account and limits without a
// reader, or nil for EMAIL_PROVIDER=disabled, which has no quota.
func deliveryMetricsQuota(settings config.Config) (*deliverymetrics.Quota, error) {
if settings.EmailProvider == config.EmailProviderDisabled {
return nil, nil
}
account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount)
if err != nil {
return nil, fmt.Errorf("bootstrap.deliveryMetricsQuota - provider account: %w", err)
}
limits, err := domain.NewMailQuotaLimits(int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly))
if err != nil {
return nil, fmt.Errorf("bootstrap.deliveryMetricsQuota - limits: %w", err)
}
return &deliverymetrics.Quota{Account: account, Limits: limits}, nil
}
@@ -0,0 +1,81 @@
package bootstrap
import (
"context"
"log/slog"
"net/http"
"testing"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/prometheus"
)
func TestNewDeliveryMetricsSkipsWithoutADatabase(t *testing.T) {
sampler, cleanup, err := newDeliveryMetrics(t.Context(), config.Config{EmailProvider: config.EmailProviderDisabled},
slog.New(slog.DiscardHandler), prometheus.New())
if err != nil {
t.Fatalf("newDeliveryMetrics() error = %v", err)
}
cleanup()
if sampler != nil {
t.Fatal("newDeliveryMetrics() built a sampler without DATABASE_URL")
}
}
func TestDeliveryMetricsQuotaFollowsTheTransport(t *testing.T) {
quota, err := deliveryMetricsQuota(config.Config{EmailProvider: config.EmailProviderDisabled})
if err != nil || quota != nil {
t.Fatalf("deliveryMetricsQuota(disabled) = %v, %v; want no quota", quota, err)
}
quota, err = deliveryMetricsQuota(config.Config{
EmailProvider: config.EmailProviderResend,
EmailAccount: "primary",
EmailQuotaDaily: 100,
EmailQuotaMonthly: 3000,
})
if err != nil {
t.Fatalf("deliveryMetricsQuota(resend) error = %v", err)
}
if quota.Account.Provider() != "resend" || quota.Account.Account() != "primary" || quota.Limits.Daily() != 100 || quota.Limits.Monthly() != 3000 {
t.Fatalf("deliveryMetricsQuota(resend) = %+v", quota)
}
if _, err := deliveryMetricsQuota(config.Config{EmailProvider: config.EmailProviderSMTP, EmailAccount: "Not A Label", EmailQuotaDaily: 1, EmailQuotaMonthly: 1}); err == nil {
t.Fatal("deliveryMetricsQuota() accepted an invalid account label")
}
}
// TestApplicationRunsAndStopsTheDeliveryMetricsSampler starts the sampler
// against a database that does not answer: it logs stale gauges, and the
// application still stops within its shutdown budget.
func TestApplicationRunsAndStopsTheDeliveryMetricsSampler(t *testing.T) {
settings := consumerTestConfig(t)
settings.HTTPAddr = "127.0.0.1:0"
settings.MetricsAddr = "127.0.0.1:0"
settings.ShutdownTimeout = time.Second
metrics := prometheus.New()
logger := slog.New(slog.DiscardHandler)
sampler, cleanup, err := newDeliveryMetrics(t.Context(), settings, logger, metrics)
if err != nil {
t.Fatalf("newDeliveryMetrics() error = %v", err)
}
defer cleanup()
if sampler == nil {
t.Fatal("newDeliveryMetrics() built no sampler with DATABASE_URL set")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, nil, sampler)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
go func() { finished <- application.run(ctx) }()
time.Sleep(50 * time.Millisecond)
cancel()
select {
case err := <-finished:
if err != nil {
t.Fatalf("run() error = %v", err)
}
case <-time.After(relayLifecycleTimeout):
t.Fatal("run() did not return after cancellation")
}
}
+1 -1
View File
@@ -87,7 +87,7 @@ func TestApplicationRunsAndStopsTheJobWorker(t *testing.T) {
if worker == nil {
t.Fatal("buildJobWorker() built no worker for a registered kind")
}
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker)
application := NewApplication(settings, http.NotFoundHandler(), metrics, logger, nil, nil, nil, worker, nil)
ctx, cancel := context.WithCancel(t.Context())
finished := make(chan error, 1)
+1 -1
View File
@@ -76,7 +76,7 @@ func TestApplicationRunsTheRelayWhileServing(t *testing.T) {
HTTPAddr: "127.0.0.1:0",
MetricsAddr: "127.0.0.1:0",
ShutdownTimeout: time.Second,
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil)
}, http.NotFoundHandler(), metrics, logger, nil, relay, nil, nil, nil)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
+1
View File
@@ -50,6 +50,7 @@ func initialize(
newOutboxRelay,
newEventConsumers,
newJobWorker,
newDeliveryMetrics,
NewApplication,
),
)
+12 -1
View File
@@ -79,8 +79,19 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker)
sampler, cleanup7, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, sampler)
return application, func() {
cleanup7()
cleanup6()
cleanup5()
cleanup4()
@@ -0,0 +1,32 @@
package outbound
import (
"context"
"time"
"lincodex/backend/internal/domain"
)
// DeliveryStatusCount is the number of stored deliveries of one kind in one
// status.
type DeliveryStatusCount struct {
Kind domain.MailKind
Status domain.DeliveryStatus
Deliveries int64
}
// DeliveryStatistics aggregates all stored deliveries for operators and
// metrics. It holds no recipient, address, content, or delivery ID.
type DeliveryStatistics struct {
// Counts has one entry per kind and status that has deliveries.
Counts []DeliveryStatusCount
// EarliestPendingAttemptAt is the earliest NextAttemptAt of a pending
// delivery, by the application clock that wrote it; zero without
// pending deliveries.
EarliestPendingAttemptAt time.Time
}
// DeliveryStatisticsReader reads the delivery aggregate without locking.
type DeliveryStatisticsReader interface {
DeliveryStatistics(ctx context.Context) (DeliveryStatistics, error)
}
@@ -0,0 +1,117 @@
// Package deliverymetrics periodically reads the delivery and mail quota
// aggregates from the database into the metrics. The database stores no
// metrics, so the gauges come from cheap periodic reads instead of a query
// per scrape.
package deliverymetrics
import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/retry"
)
// Metrics records the aggregates without per-delivery or per-account labels.
type Metrics interface {
ObserveDeliveryStates(counts []outbound.DeliveryStatusCount, oldestDuePending time.Duration)
ObserveMailQuota(provider string, usage outbound.MailQuotaUsage, limits domain.MailQuotaLimits)
PrepareMailMetricsReads()
ObserveMailMetricsReadSuccess(at time.Time)
}
// Quota names the configured provider account whose current windows the
// sampler reports, with its configured limits.
type Quota struct {
Reader outbound.MailQuotaUsageReader
Account domain.MailProviderAccount
Limits domain.MailQuotaLimits
}
// Sampler reads the aggregates once per interval. Every backend instance
// reports the same database-wide values.
type Sampler struct {
deliveries outbound.DeliveryStatisticsReader
// quota is nil when no transport is configured, for example with
// EMAIL_PROVIDER=disabled.
quota *Quota
metrics Metrics
logger *slog.Logger
interval time.Duration
now func() time.Time
}
// New builds a sampler. interval is the time between two reads and also
// bounds one read; now is the application clock that wrote the delivery
// times.
func New(
deliveries outbound.DeliveryStatisticsReader,
quota *Quota,
metrics Metrics,
logger *slog.Logger,
interval time.Duration,
now func() time.Time,
) *Sampler {
return &Sampler{deliveries: deliveries, quota: quota, metrics: metrics, logger: logger, interval: interval, now: now}
}
// Run samples at once and then every interval until ctx ends. A failed read
// is logged and the gauges keep their previous values until the next read
// succeeds.
func (sampler *Sampler) Run(ctx context.Context) {
sampler.metrics.PrepareMailMetricsReads()
sampler.logger.Info("delivery metrics sampler started", slog.Duration("interval", sampler.interval))
defer sampler.logger.Info("delivery metrics sampler stopped")
for {
if err := sampler.Sample(ctx); err != nil && ctx.Err() == nil {
sampler.logger.Warn("delivery metrics could not be read; the gauges are stale", slog.Any("error", err))
}
if !retry.Wait(ctx, sampler.interval) {
return
}
}
}
// Sample reads both aggregates once. A failure of one read does not skip the
// other; only a sample in which every read succeeded advances the last
// success time.
func (sampler *Sampler) Sample(ctx context.Context) error {
readCtx, cancel := context.WithTimeout(ctx, sampler.interval)
defer cancel()
if err := errors.Join(sampler.sampleDeliveries(readCtx), sampler.sampleQuota(readCtx)); err != nil {
return err
}
sampler.metrics.ObserveMailMetricsReadSuccess(sampler.now())
return nil
}
func (sampler *Sampler) sampleDeliveries(ctx context.Context) error {
statistics, err := sampler.deliveries.DeliveryStatistics(ctx)
if err != nil {
return fmt.Errorf("Sampler.sampleDeliveries - read delivery statistics: %w", err)
}
var oldestDuePending time.Duration
if !statistics.EarliestPendingAttemptAt.IsZero() {
// A pending delivery that is not due yet is not late.
oldestDuePending = max(sampler.now().Sub(statistics.EarliestPendingAttemptAt), 0)
}
sampler.metrics.ObserveDeliveryStates(statistics.Counts, oldestDuePending)
return nil
}
func (sampler *Sampler) sampleQuota(ctx context.Context) error {
if sampler.quota == nil {
return nil
}
windows := domain.MailQuotaWindowsAt(sampler.now())
usage, err := sampler.quota.Reader.Usage(ctx, sampler.quota.Account, windows)
if err != nil {
return fmt.Errorf("Sampler.sampleQuota - read quota usage: %w", err)
}
sampler.metrics.ObserveMailQuota(sampler.quota.Account.Provider(), usage, sampler.quota.Limits)
return nil
}
@@ -0,0 +1,208 @@
package deliverymetrics
import (
"context"
"errors"
"log/slog"
"sync"
"testing"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/pkg/testutil"
)
const testInterval = time.Second
var errDatabaseDown = errors.New("database down")
type fakeStatistics struct {
statistics outbound.DeliveryStatistics
err error
}
func (reader fakeStatistics) DeliveryStatistics(context.Context) (outbound.DeliveryStatistics, error) {
return reader.statistics, reader.err
}
type fakeUsage struct {
usage outbound.MailQuotaUsage
err error
windows domain.MailQuotaWindows
}
func (reader *fakeUsage) Usage(_ context.Context, _ domain.MailProviderAccount, windows domain.MailQuotaWindows) (outbound.MailQuotaUsage, error) {
reader.windows = windows
return reader.usage, reader.err
}
func (*fakeUsage) OtherAccountsWithUsage(context.Context, domain.MailProviderAccount, time.Time) ([]string, error) {
return nil, nil
}
type recordingMetrics struct {
mu sync.Mutex
states int
counts []outbound.DeliveryStatusCount
oldest time.Duration
quotas int
provider string
usage outbound.MailQuotaUsage
dailyLimit int64
prepared int
successes []time.Time
}
func (metrics *recordingMetrics) PrepareMailMetricsReads() {
metrics.mu.Lock()
defer metrics.mu.Unlock()
metrics.prepared++
}
func (metrics *recordingMetrics) ObserveMailMetricsReadSuccess(at time.Time) {
metrics.mu.Lock()
defer metrics.mu.Unlock()
metrics.successes = append(metrics.successes, at)
}
func (metrics *recordingMetrics) preparations() int {
metrics.mu.Lock()
defer metrics.mu.Unlock()
return metrics.prepared
}
func (metrics *recordingMetrics) ObserveDeliveryStates(counts []outbound.DeliveryStatusCount, oldest time.Duration) {
metrics.mu.Lock()
defer metrics.mu.Unlock()
metrics.states++
metrics.counts, metrics.oldest = counts, oldest
}
func (metrics *recordingMetrics) ObserveMailQuota(provider string, usage outbound.MailQuotaUsage, limits domain.MailQuotaLimits) {
metrics.mu.Lock()
defer metrics.mu.Unlock()
metrics.quotas++
metrics.provider, metrics.usage, metrics.dailyLimit = provider, usage, limits.Daily()
}
func (metrics *recordingMetrics) samples() int {
metrics.mu.Lock()
defer metrics.mu.Unlock()
return metrics.states
}
func testQuota(t *testing.T, reader outbound.MailQuotaUsageReader) *Quota {
t.Helper()
account, err := domain.NewMailProviderAccount("resend", "default")
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
limits, err := domain.NewMailQuotaLimits(100, 3000)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
return &Quota{Reader: reader, Account: account, Limits: limits}
}
func TestSampleReportsStatesTheOldestDuePendingAgeAndTheQuota(t *testing.T) {
now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
counts := []outbound.DeliveryStatusCount{
{Kind: domain.MailKindVerification, Status: domain.DeliveryStatusPending, Deliveries: 2},
{Kind: domain.MailKindNotification, Status: domain.DeliveryStatusAccepted, Deliveries: 5},
}
usage := &fakeUsage{usage: outbound.MailQuotaUsage{DayUsed: 7, MonthUsed: 40}}
metrics := &recordingMetrics{}
sampler := New(
fakeStatistics{statistics: outbound.DeliveryStatistics{Counts: counts, EarliestPendingAttemptAt: now.Add(-90 * time.Second)}},
testQuota(t, usage), metrics, slog.New(slog.DiscardHandler), testInterval, testutil.NewFakeClock(now).Now,
)
if err := sampler.Sample(t.Context()); err != nil {
t.Fatalf("Sample() error = %v", err)
}
if len(metrics.counts) != len(counts) || metrics.oldest != 90*time.Second {
t.Fatalf("observed %v and %s, want %v and 90s", metrics.counts, metrics.oldest, counts)
}
if metrics.provider != "resend" || metrics.usage != usage.usage || metrics.dailyLimit != 100 {
t.Fatalf("observed quota %q %+v %d", metrics.provider, metrics.usage, metrics.dailyLimit)
}
if want := domain.MailQuotaWindowsAt(now); usage.windows != want {
t.Fatalf("read windows %+v, want the current %+v", usage.windows, want)
}
if len(metrics.successes) != 1 || !metrics.successes[0].Equal(now) {
t.Fatalf("recorded successes %v, want one at %s", metrics.successes, now)
}
}
func TestSampleTreatsAPendingDeliveryThatIsNotDueAsNotLate(t *testing.T) {
now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
metrics := &recordingMetrics{oldest: time.Hour}
sampler := New(
fakeStatistics{statistics: outbound.DeliveryStatistics{EarliestPendingAttemptAt: now.Add(time.Minute)}},
nil, metrics, slog.New(slog.DiscardHandler), testInterval, testutil.NewFakeClock(now).Now,
)
if err := sampler.Sample(t.Context()); err != nil {
t.Fatalf("Sample() error = %v", err)
}
if metrics.oldest != 0 || metrics.quotas != 0 {
t.Fatalf("observed age %s and %d quota reads, want 0 and none without a transport", metrics.oldest, metrics.quotas)
}
}
// One failed read leaves its gauges stale but does not skip the other.
func TestSampleReadsTheQuotaWhenTheDeliveryReadFails(t *testing.T) {
metrics := &recordingMetrics{}
sampler := New(
fakeStatistics{err: errDatabaseDown}, testQuota(t, &fakeUsage{}), metrics,
slog.New(slog.DiscardHandler), testInterval, time.Now,
)
err := sampler.Sample(t.Context())
if !errors.Is(err, errDatabaseDown) {
t.Fatalf("Sample() error = %v, want the read failure", err)
}
if metrics.states != 0 || metrics.quotas != 1 || len(metrics.successes) != 0 {
t.Fatalf("observed %d state and %d quota samples and %d successes, want 0, 1, and none", metrics.states, metrics.quotas, len(metrics.successes))
}
metrics = &recordingMetrics{}
sampler = New(
fakeStatistics{}, testQuota(t, &fakeUsage{err: errDatabaseDown}), metrics,
slog.New(slog.DiscardHandler), testInterval, time.Now,
)
if err := sampler.Sample(t.Context()); !errors.Is(err, errDatabaseDown) {
t.Fatalf("Sample() error = %v, want the read failure", err)
}
if metrics.states != 1 || metrics.quotas != 0 || len(metrics.successes) != 0 {
t.Fatalf("observed %d state and %d quota samples and %d successes, want 1, 0, and none", metrics.states, metrics.quotas, len(metrics.successes))
}
}
func TestRunSamplesAtOnceAndStopsWithItsContext(t *testing.T) {
metrics := &recordingMetrics{}
sampler := New(fakeStatistics{}, nil, metrics, slog.New(slog.DiscardHandler), time.Hour, time.Now)
ctx, cancel := context.WithCancel(t.Context())
stopped := make(chan struct{})
go func() {
defer close(stopped)
sampler.Run(ctx)
}()
deadline := time.Now().Add(5 * time.Second)
for metrics.samples() == 0 {
if time.Now().After(deadline) {
t.Fatal("Run() did not sample at start")
}
time.Sleep(time.Millisecond)
}
cancel()
select {
case <-stopped:
case <-time.After(5 * time.Second):
t.Fatal("Run() did not stop after cancellation")
}
if samples := metrics.samples(); samples != 1 {
t.Fatalf("Run() sampled %d times within one interval, want 1", samples)
}
if prepared := metrics.preparations(); prepared != 1 {
t.Fatalf("Run() prepared the last success time %d times, want once", prepared)
}
}