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
@@ -219,3 +219,19 @@ WHERE
|
||||
AND kind = sqlc.arg(kind)
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- 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.
|
||||
-- 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;
|
||||
@@ -0,0 +1,129 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
deliveryStatisticsTestTimeout = 3 * time.Minute
|
||||
deliveryStatisticsAddress = "metrics.fixture@example.com"
|
||||
)
|
||||
|
||||
// TestDeliveryStatistics checks the GetDeliveryStatistics aggregate behind the
|
||||
// delivery metrics against the real deliveries table and its constraints.
|
||||
func TestDeliveryStatistics(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), deliveryStatisticsTestTimeout)
|
||||
defer cancel()
|
||||
pool := env.newPool(ctx, t)
|
||||
store := postgresadapter.NewDeliveryStatisticsStore(pool)
|
||||
|
||||
empty, err := store.DeliveryStatistics(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("DeliveryStatistics() on an empty table error = %v", err)
|
||||
}
|
||||
if len(empty.Counts) != 0 || !empty.EarliestPendingAttemptAt.IsZero() {
|
||||
t.Fatalf("DeliveryStatistics() on an empty table = %+v, want nothing", empty)
|
||||
}
|
||||
|
||||
start := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
|
||||
recipient := createStatisticsRecipient(ctx, t, postgresadapter.NewIdentityStore(pool).Users(), start)
|
||||
deliveries := postgresadapter.NewDeliveryStore(pool).Deliveries()
|
||||
account := mustProviderAccount(t, "resend")
|
||||
create := func(kind domain.MailKind, createdAt time.Time) uuid.UUID {
|
||||
t.Helper()
|
||||
content, err := domain.NewMailContent(kind, string(kind)+".v1", "Subject", "Body\n", "")
|
||||
if err != nil {
|
||||
t.Fatalf("NewMailContent() error = %v", err)
|
||||
}
|
||||
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
|
||||
ID: uuid.Must(uuid.NewV7()),
|
||||
RecipientUserID: recipient.ID,
|
||||
Recipient: recipient.Email,
|
||||
Content: content,
|
||||
ProviderAccount: account,
|
||||
CreatedAt: createdAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewDelivery() error = %v", err)
|
||||
}
|
||||
if created, err := deliveries.Create(ctx, delivery); err != nil || !created {
|
||||
t.Fatalf("Create() = %t, %v; want the delivery stored", created, err)
|
||||
}
|
||||
return delivery.ID()
|
||||
}
|
||||
// New deliveries are pending and due at creation.
|
||||
create(domain.MailKindVerification, start.Add(2*time.Minute))
|
||||
create(domain.MailKindVerification, start.Add(time.Minute))
|
||||
create(domain.MailKindNotification, start.Add(3*time.Minute))
|
||||
// The status updates below satisfy the table constraints for each
|
||||
// status, the way the sending worker will leave them.
|
||||
setStatus := func(id uuid.UUID, statement string) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(ctx, "UPDATE deliveries SET "+statement+" WHERE id = $1", id); err != nil {
|
||||
t.Fatalf("set the delivery status: %v", err)
|
||||
}
|
||||
}
|
||||
// The earliest pending delivery stops being pending, so the earliest
|
||||
// due time comes from the remaining pending ones only.
|
||||
setStatus(create(domain.MailKindVerification, start), "status = 'unknown'")
|
||||
setStatus(create(domain.MailKindPasswordReset, start), "status = 'waiting_quota', next_attempt_at = NULL")
|
||||
setStatus(create(domain.MailKindNotification, start), "status = 'accepted', next_attempt_at = NULL, provider_message_id = 'msg-1'")
|
||||
setStatus(create(domain.MailKindNotification, start), "status = 'rejected', next_attempt_at = NULL")
|
||||
|
||||
statistics, err := store.DeliveryStatistics(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("DeliveryStatistics() error = %v", err)
|
||||
}
|
||||
got := slices.Clone(statistics.Counts)
|
||||
slices.SortFunc(got, func(a, b outbound.DeliveryStatusCount) int {
|
||||
return strings.Compare(string(a.Kind)+"/"+string(a.Status), string(b.Kind)+"/"+string(b.Status))
|
||||
})
|
||||
want := []outbound.DeliveryStatusCount{
|
||||
{Kind: domain.MailKindNotification, Status: domain.DeliveryStatusAccepted, Deliveries: 1},
|
||||
{Kind: domain.MailKindNotification, Status: domain.DeliveryStatusPending, Deliveries: 1},
|
||||
{Kind: domain.MailKindNotification, Status: domain.DeliveryStatusRejected, Deliveries: 1},
|
||||
{Kind: domain.MailKindPasswordReset, Status: domain.DeliveryStatusWaitingQuota, Deliveries: 1},
|
||||
{Kind: domain.MailKindVerification, Status: domain.DeliveryStatusPending, Deliveries: 2},
|
||||
{Kind: domain.MailKindVerification, Status: domain.DeliveryStatusUnknown, Deliveries: 1},
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("Counts = %+v, want %+v", got, want)
|
||||
}
|
||||
if !statistics.EarliestPendingAttemptAt.Equal(start.Add(time.Minute)) {
|
||||
t.Fatalf("EarliestPendingAttemptAt = %s, want %s", statistics.EarliestPendingAttemptAt, start.Add(time.Minute))
|
||||
}
|
||||
}
|
||||
|
||||
func createStatisticsRecipient(ctx context.Context, t *testing.T, users outbound.UserRepository, now time.Time) domain.User {
|
||||
t.Helper()
|
||||
hash, err := domain.NewPasswordHash(identityTestPasswordHash)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPasswordHash() error = %v", err)
|
||||
}
|
||||
user, err := domain.NewUser(domain.Registration{
|
||||
Email: mustEmail(t, deliveryStatisticsAddress),
|
||||
PasswordHash: hash,
|
||||
Scenario: domain.ScenarioCandidate,
|
||||
RegisteredAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewUser() error = %v", err)
|
||||
}
|
||||
if err := users.Create(ctx, user); err != nil {
|
||||
t.Fatalf("create the recipient account: %v", err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
@@ -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`)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -50,6 +50,7 @@ func initialize(
|
||||
newOutboxRelay,
|
||||
newEventConsumers,
|
||||
newJobWorker,
|
||||
newDeliveryMetrics,
|
||||
NewApplication,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package testutil
|
||||
|
||||
import "regexp"
|
||||
|
||||
var (
|
||||
// emailLike matches an address anywhere in a text, for example inside a
|
||||
// metric label value or a log line.
|
||||
emailLike = regexp.MustCompile(`[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`)
|
||||
// uuidLike matches the canonical text form of a UUID, the form of user,
|
||||
// delivery, attempt, and document IDs.
|
||||
uuidLike = regexp.MustCompile(`[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}`)
|
||||
)
|
||||
|
||||
// FindPersonalIdentifiers returns every email-like and UUID-like substring of
|
||||
// text. Tests use it on a metrics exposition or a log to prove that no
|
||||
// address or entity ID leaked into labels or messages.
|
||||
func FindPersonalIdentifiers(text string) []string {
|
||||
return append(emailLike.FindAllString(text, -1), uuidLike.FindAllString(text, -1)...)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package testutil
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFindPersonalIdentifiers(t *testing.T) {
|
||||
text := `a{route="/x",user="Jane.Doe+tag@mail.example.org"} 1` + "\n" +
|
||||
`b{id="0199b4f2-7c1e-7d3a-9f00-AABBCCDDEEFF"} 1` + "\n" +
|
||||
`c{route="/api/v1/me/invitations/{invitationId}",status="404"} 1`
|
||||
got := FindPersonalIdentifiers(text)
|
||||
want := []string{"Jane.Doe+tag@mail.example.org", "0199b4f2-7c1e-7d3a-9f00-AABBCCDDEEFF"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("FindPersonalIdentifiers() = %q, want %q", got, want)
|
||||
}
|
||||
if found := FindPersonalIdentifiers(`go_info{version="go1.26.8"} 1`); len(found) != 0 {
|
||||
t.Fatalf("FindPersonalIdentifiers() reported %q in a clean text", found)
|
||||
}
|
||||
}
|
||||
@@ -205,6 +205,7 @@ services:
|
||||
- "12347"
|
||||
networks:
|
||||
observability: {}
|
||||
docker-api: {}
|
||||
app:
|
||||
aliases:
|
||||
- faro-receiver
|
||||
@@ -234,11 +235,17 @@ services:
|
||||
EVENTS: "1"
|
||||
IMAGES: "0"
|
||||
INFO: "0"
|
||||
NETWORKS: "0"
|
||||
# Alloy discovery.docker reads the networks of each container to
|
||||
# build its labels; without read access discovery fails with 403 and
|
||||
# no log reaches Loki.
|
||||
NETWORKS: "1"
|
||||
PING: "1"
|
||||
POST: "0"
|
||||
VERSION: "1"
|
||||
volumes:
|
||||
# read_only only stops writes to the socket file inode; every Docker
|
||||
# API call still goes through it. The HAProxy rules above are the only
|
||||
# API restriction.
|
||||
- type: bind
|
||||
source: ${DOCKER_SOCKET_PATH:-/var/run/docker.sock}
|
||||
target: /var/run/docker.sock
|
||||
@@ -247,8 +254,10 @@ services:
|
||||
create_host_path: false
|
||||
expose:
|
||||
- "2375"
|
||||
# Only Alloy shares this network, so no other monitoring service can
|
||||
# reach the Docker API through the proxy.
|
||||
networks:
|
||||
- observability
|
||||
- docker-api
|
||||
# The image entrypoint renders HAProxy configuration before starting.
|
||||
tmpfs:
|
||||
- /tmp
|
||||
@@ -303,6 +312,9 @@ networks:
|
||||
external: true
|
||||
observability:
|
||||
internal: true
|
||||
# The Docker API proxy and its only client, Alloy.
|
||||
docker-api:
|
||||
internal: true
|
||||
|
||||
volumes:
|
||||
alloy_data:
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:alpine
|
||||
# Terse error logging leaves out DETAIL, HINT, QUERY, and CONTEXT. The
|
||||
# DETAIL of a unique or foreign key violation quotes the key value, such
|
||||
# as an email address, and the container logs go to Loki.
|
||||
command: ["postgres", "-c", "log_error_verbosity=terse"]
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:?Set POSTGRES_DB in the root .env file}
|
||||
POSTGRES_USER: ${POSTGRES_USER:?Set POSTGRES_USER in the root .env file}
|
||||
|
||||
+19
-10
@@ -228,7 +228,7 @@ Every `rejected` or `unknown` answer with a known error name sets `ProviderCode`
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
Implemented (TASK-015): the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented with TASK-018; see [Mail quotas](#mail-quotas). Planned: the worker that claims due deliveries, passes them through the quota gate, and calls `MailSender` (TASK-016), retries and the unknown outcome policy (TASK-017), delivery metrics (TASK-022), and the permission check before a send (TASK-462). No product flow calls `MailRequester` yet, and nothing sends a stored delivery.
|
||||
Implemented (TASK-015): the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented with TASK-018; see [Mail quotas](#mail-quotas). Planned: the worker that claims due deliveries, passes them through the quota gate, and calls `MailSender` (TASK-016), retries and the unknown outcome policy (TASK-017), and the permission check before a send (TASK-462). The delivery state gauges are implemented with TASK-022; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and nothing sends a stored delivery.
|
||||
|
||||
A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds:
|
||||
|
||||
@@ -257,7 +257,7 @@ Personal data at rest. A delivery row holds the recipient address and the bodies
|
||||
- Queries for operations select metadata columns (ID, kind, status, attempts, times, provider) and never the bodies, the request text, or the address; see [DEPLOY.md](DEPLOY.md#mail-deliveries).
|
||||
- Deleting an account deletes its mail requests, deliveries, and their attempts by cascade. The unverified account cleanup locks them with `FOR UPDATE SKIP LOCKED` like tokens and sessions, so it never waits for the delivery consumer or a worker that holds a row.
|
||||
- A retention rule that deletes or clears terminal deliveries after a bounded period is not implemented yet; until it exists, rows stay. Encryption of the bodies at rest is not implemented either.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText`, and `EmailAddress` redact themselves in `fmt` and `slog` output: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. There is no delivery metric yet; TASK-022 adds them with labels limited to kind, status, and provider, never the address, account ID, or subject.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText`, and `EmailAddress` redact themselves in `fmt` and `slog` output: a delivery logs its ID, kind, status, and provider. Handler errors name the broken rule and never quote the payload, and the adapter replaces PostgreSQL error text with its SQLSTATE and constraint. The delivery metrics (TASK-022) carry only the kind, status, provider, and quota window labels, never the address, a user or delivery ID, the provider account label, or the subject.
|
||||
|
||||
Statuses. The values follow the `MailSender` outcomes:
|
||||
|
||||
@@ -293,7 +293,7 @@ The store already provides `Get`, `ListAttempts`, the version-checked `RecordAtt
|
||||
|
||||
### Mail quotas
|
||||
|
||||
Implemented (TASK-018): quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). Planned: the sending worker that calls the gate around `MailSender.Send` and builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP (TASK-016), quota metrics (TASK-022), and the API or identity flow that shows the status reader's result. Nothing sends yet, so the current build counts nothing.
|
||||
Implemented (TASK-018): quota windows and limits in `backend/internal/domain/mail_quota.go`; the `outbound.MailQuotaRepository` port (`port/outbound/mail_quota.go`), whose writes go through `UnitOfWork.MailQuotas()` and whose reads also go through `postgres.MailQuotaStore`; migration `00007_create_mail_quota_usage.sql` with the `mail_quota_usage` and `mail_quota_reservations` tables; the queries in `backend/db/queries/mail_quota.sql`; in `backend/internal/usecase/notification/`, `QuotaGate` with `PrepareSend` and `SettleSend` (`quota.go`), the startup report `ReportQuotaUsage`, and the user status reader `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` in the mail port, filled by the Resend adapter; and the startup report in bootstrap (`bootstrap/mail_quota.go`). Planned: the sending worker that calls the gate around `MailSender.Send` and builds it from configuration with `resend.IdempotencyWindow` or zero for SMTP (TASK-016) and the API or identity flow that shows the status reader's result. Nothing sends yet, so the current build counts nothing.
|
||||
|
||||
Limits. `EMAIL_QUOTA_DAILY` and `EMAIL_QUOTA_MONTHLY` limit the recipients sent through the configured provider account (`EMAIL_PROVIDER` and `EMAIL_ACCOUNT`) per UTC day, from 00:00 to 00:00 UTC, and per UTC calendar month. Every recipient counts, as Resend counts them; a delivery has one recipient. The defaults are the Resend Free limits checked on 2026-10-05, 100 and 3000; they apply to `resend` and to `disabled`, which sends nothing. `smtp` has no default and does not start without both values, because a relay's limits are not Resend's. Values range from 1 to 1000000000, and the daily limit must not exceed the monthly one. No value turns the quota off, so no provider runs without the gate. Limits are configuration, not domain constants, and are not stored: a changed limit applies from the next reservation, and a limit lowered below the current usage defers every new send until the window resets.
|
||||
|
||||
@@ -333,7 +333,7 @@ What the user sees. `notification.DeliveryStatusReader.LatestForUser(ctx, userID
|
||||
| `accepted` | Your email was sent. It means that the provider accepted it, not that it reached the inbox |
|
||||
| `rejected` | Your email could not be sent |
|
||||
|
||||
Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. There is no quota metric yet; `MailQuotaRepository.Usage` is the read that TASK-022 can expose with the labels provider and period.
|
||||
Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quotas). The gate logs `mail quota is used up; the delivery waits for the reset` at info level and `the mail provider reported its quota used up; local sending stops until the reset` at warn level, with only the delivery ID, provider, period, and reset time. The quota gauges (TASK-022) come from `MailQuotaUsageReader.Usage` for the configured account, with the labels provider and window only; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts).
|
||||
|
||||
### Product policy versions
|
||||
|
||||
@@ -428,7 +428,8 @@ backend/
|
||||
port/outbound/ readiness, cache, object storage, transaction, outbox, outbox relay, event publishing, event consumption, identity, consent ledger, organization and membership, policy, password hashing, and mail boundaries
|
||||
adapter/primary/http/
|
||||
api/ generated ogen handler
|
||||
middleware/ request metrics
|
||||
middleware/ request log and request metrics by route template
|
||||
observe/ request-scoped observations, such as the problem code
|
||||
problem/ RFC 9457 error responses
|
||||
v1/ handwritten health endpoint
|
||||
router.go chi composition
|
||||
@@ -442,15 +443,16 @@ backend/
|
||||
postgres/sqlc/ generated SQL adapter
|
||||
redis/ cache adapter and Redis check
|
||||
seaweedfs/ S3 adapter and bucket check
|
||||
prometheus/ bounded Go/process and request metrics
|
||||
prometheus/ bounded Go/process, request, problem, outbox, consumer, job, delivery, quota, and answer save metrics
|
||||
worker/outboxrelay/ outbox relay loop: claim, publish, mark, backoff, and shutdown
|
||||
worker/eventconsumer/ event consumer runtime: dedup transaction, retries, dead letters, offset commits, and shutdown
|
||||
worker/jobrunner/ scheduled job runtime: claim under a lease, run with the completion, retries, release, and shutdown
|
||||
worker/retry/ backoff with jitter and a context-aware wait shared by the workers
|
||||
worker/deliverymetrics/ periodic read of the delivery and mail quota aggregates into the metrics
|
||||
bootstrap/ configuration, wiring, lifecycle, shutdown
|
||||
db/ embedded migrations and SQL queries; outbox, identity, policy, event consumer, delivery, mail quota, scheduled job, consent ledger, and organization tables
|
||||
codegen/ ogen and sqlc configs
|
||||
pkg/testutil/ fake application clock shared by tests
|
||||
pkg/testutil/ fake application clock and identifier scan shared by tests
|
||||
```
|
||||
|
||||
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The consent ledger types live in `consent.go`. The organization, verification, and membership types live in `organization.go` and `membership.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
|
||||
@@ -459,7 +461,7 @@ Product domain types and usecase modules, the SMTP and FSP adapters, and product
|
||||
|
||||
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, product job kinds, file workflows, mail delivery, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
|
||||
|
||||
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; the identity usecases (verification and password reset) are expected to call it when they create their deliveries, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
|
||||
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; the identity usecases (verification and password reset) are expected to call it when they create their deliveries, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
|
||||
|
||||
`api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown.
|
||||
|
||||
@@ -698,13 +700,20 @@ Contract rules: UUID identifiers, UTC date-time, explicit enums, integer RUB amo
|
||||
|
||||
## Metrics, telemetry, and alerts
|
||||
|
||||
The current Go service exports standard Go/process metrics, `lincodex_http_requests_total` with bounded `method`, route-template `route`, and `status` labels, and `lincodex_http_request_duration_seconds`. Do not use user, candidate, request IDs, full URLs, addresses, or resume content as labels. `/metrics` uses an internal listener outside `/api/v1`. Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux dashboard JSON files are maintained project sources, not imported dashboard IDs. The scheduled job counters and backlog gauges are described in [Scheduled jobs](#scheduled-jobs). Inference and product-event metrics are not implemented in the current scaffold.
|
||||
The Go service exports standard Go/process metrics and the product metrics of TASK-022 on an internal `/metrics` listener outside `/api/v1`:
|
||||
|
||||
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}`, and `lincodex_http_problems_total{route,code}`. `route` is the chi route template of an operational route and, under `/api/v1`, the OpenAPI path template of the matched operation, such as `/api/v1/me/invitations/{invitation_id}`, which the router resolves with the generated server's `FindPath`; a path or method without an operation keeps the mount pattern `/api/v1/*` or `/api/*`, and a path outside every route is `unmatched`. `status_class` is `1xx` to `5xx`. `code` is the RFC 9457 problem code: `problem.New` records it from the closed catalogue through the request-scoped `observe` package (`adapter/primary/http/observe/`), the middleware counts it only for a 4xx or 5xx response, and the adapter counts a code outside its mirrored list as `other`. An error without a problem body, such as `/readyz` 503, is counted by status only. The request log (`middleware.RequestLog`, which replaces the go-httpkit logger) uses the same route template and logs the request ID, method, status and class, problem code, latency, response size, and the number of query parameters, never the raw path, a query key or value, a header, the client address, or the user agent; `/healthz` and `/readyz` are not logged.
|
||||
- Outbox and events: the relay, consumer, and scheduled job metrics in [Outbox relay](#outbox-relay), [Event consumers](#event-consumers), and [Scheduled jobs](#scheduled-jobs). Outbox lag is `lincodex_outbox_relay_oldest_pending_age_seconds`.
|
||||
- Mail: `lincodex_mail_deliveries{kind,status}` for every kind and the statuses `pending`, `waiting_quota`, `unknown`, `accepted`, and `rejected`, zero included; `lincodex_mail_delivery_oldest_due_pending_age_seconds`; and, for an active transport, `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted`, each with `provider` and `window` (`day` or `month`). The sampler in `backend/internal/worker/deliverymetrics/` reads them every 30 seconds on its own one-connection pool: `postgres.DeliveryStatisticsStore` aggregates `deliveries` by kind and status, and `MailQuotaUsageReader.Usage` reads the current windows of the configured account. The delivery aggregate is the sqlc query `GetDeliveryStatistics` in `db/queries/delivery.sql`. It scans the table, which suits the current volume; add an index or per-status counters before the table holds millions of rows. `EMAIL_ACCOUNT` is not a label: it is free operator text that can name a person, and each process reports only its own account. Every instance reports the same database-wide values; aggregate them with `max`. A failed read keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` shows the last read in which every aggregate was read (0 from the sampler start until the first one), and the age gauge exists only after the first successful read. There is no attempt outcome counter yet, because the sending worker (TASK-016) does not exist.
|
||||
- Assessment answers: `lincodex_assessment_answer_saves_total{format,outcome}` with the outcomes `stored`, `unchanged`, `rejected`, and `failed`. PRD 6.6 asks to observe the saving of answers; this is read as the assessment answer command `SubmitMyAssessmentAnswer`. The command is not implemented, so only the hook `Metrics.ObserveAssessmentAnswerSave` exists, and no series appears until the usecase calls it once per command. A value outside the closed sets becomes `other`. The HTTP latency and errors of the command already appear under the route `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
|
||||
|
||||
Do not use user, candidate, delivery, or request IDs, full URLs or query strings, addresses, or resume content as labels. Unit tests drive the real router and every metric hook with email and UUID fixtures and fail when the exposition contains an email-like or UUID-like value. Go runtime, PostgreSQL, Redis, SeaweedFS, Linux, and Lincodex product dashboard JSON files are maintained project sources, not imported dashboard IDs. Inference metrics are not implemented in the current scaffold.
|
||||
|
||||
Planned observability work includes bounded measurements for queued jobs, oldest ready age, wait and run duration, retries, and terminal failures; pgxpool state should use bounded nonblocking reads inside Go. Nginx `stub_status` does not provide latency by HTTP status; access logs can provide `request_time` and `upstream_response_time`. cAdvisor is optional if the selected runtime supports it. Redis exporter is included in the separate monitoring Compose project; Prometheus scrapes its internal port 9121. SeaweedFS metrics are scraped directly on internal port 9327, retaining only selected aggregate series without object paths. DCGM exporter is only needed with a local NVIDIA model.
|
||||
|
||||
The planned browser path is Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. The React SDK is not connected yet. Collect cleaned Web Vitals, JavaScript errors, release, and normalized route; exclude console logs, form content, resume text, and session replay. Remove query strings, fragments, and identifiers from URLs. Limit receiver size, rate, and origin. Request/trace IDs remain log fields, not labels; complete span storage needs a separate backend such as Tempo and is not currently supported.
|
||||
|
||||
Future alerts cover unavailable targets, elevated 5xx rate with enough requests, latency budget breaches, old or terminally failed jobs, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
|
||||
Alert rules in `observability/prometheus/rules/lincodex.yml` cover an unavailable backend target, a 5xx share above 5% with at least 15 requests in 5 minutes, outbox lag, dead letters and stalled consumers, dead and lagging scheduled jobs, deliveries with an unknown outcome, stale delivery and quota gauges, a used-up mail quota, and overdue deliveries; the last one also requires `lincodex_mail_sender_running`, which the sending worker of TASK-016 must export, so it stays inert until then. `promtool test rules` gives every alert a firing case and every guard a silent one. Prometheus evaluates them and shows their state on its /alerts page and in Grafana; no Alertmanager or notification channel is configured, so no alert reaches a person. Future alerts cover latency budget breaches, disk pressure, ML errors, and dropped logs. Low traffic needs a window and minimum event count to avoid unstable rates and percentiles. Configure `No Data` and datasource-error behavior explicitly. A monitoring stack cannot reliably report a host failure on that same host; that requires an independent external health check. Compose and dashboard smoke checks do not verify alert delivery. Document alert rules and notification channels as implemented only after they have been tested.
|
||||
|
||||
## Requirements coverage
|
||||
|
||||
|
||||
+10
-2
@@ -248,6 +248,7 @@ A notification request is a row in `mail_requests` until the consumer `notificat
|
||||
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Deliveries created while `EMAIL_PROVIDER=disabled` stay pinned to `disabled` until the sending worker (TASK-016) moves them with `Rebind`, which is allowed only before the first attempt.
|
||||
- The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet.
|
||||
- To inspect deliveries, select metadata only, for example `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50`, and `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` shows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not select `recipient_email`, `subject`, `text_body`, `html_body`, or the `mail_requests` text columns, and never paste them into tickets or chats.
|
||||
- Without SQL, the internal /metrics endpoint shows `lincodex_mail_deliveries{kind,status}` for every kind and status, zero included, and `lincodex_mail_delivery_oldest_due_pending_age_seconds`, the time the earliest pending delivery has been due. The backend reads them every 30 seconds with one aggregate over `deliveries`; every instance reports the same values, so aggregate them with `max`. A read that fails keeps the previous values and logs `delivery metrics could not be read; the gauges are stale`. Until the sending worker exists (TASK-016), every stored delivery stays `pending` and its due age only grows. The age series appears only after the first successful read, so a fresh start never claims that nothing is late; `lincodex_mail_metrics_last_success_timestamp_seconds` is the Unix time of the last read in which every aggregate was read (0 from the start until the first one), and `LincodexMailMetricsStale` fires when it is more than 5 minutes old for 5 minutes. The alert `LincodexMailDeliveryUnknownOutcome` fires while any delivery has an unknown outcome. `LincodexMailDeliveriesOverdue` (a pending delivery due for more than 15 minutes) also requires `lincodex_mail_sender_running` to be 1; that gauge belongs to the sending worker of TASK-016, which must export it while its loop runs, so the alert stays silent while no sender exists, with `EMAIL_PROVIDER=disabled`, and without traffic.
|
||||
- Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in `waiting_quota` waits for the quota reset at `next_attempt_at`; see [Mail quotas](#mail-quotas). Without `next_attempt_at` its reset is unknown and it needs an operator decision.
|
||||
- Logs name a delivery only by `delivery_id` (with the event ID), never by address or subject. Skipped requests are logged at info level: `mail request skipped because it was already handled or its account was deleted` and `notification skipped because the recipient address is not verified`. A request that breaks the event contract is a `handler_rejected` dead letter of the consumer `notification_delivery`; see [Dead letters and replay](#dead-letters-and-replay). Replaying it is safe: the delivery ID keeps one delivery per request.
|
||||
|
||||
@@ -259,6 +260,7 @@ Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quo
|
||||
- Change `EMAIL_ACCOUNT` only together with a real change of the provider account, that is, a key of another account. The local count is kept per account label, so renaming the label for the same account starts a new count from zero while the provider keeps the old one. At startup the backend logs `mail quota usage` with the provider, account, and the current day and month usage and limits, and warns when other labels of the same provider have usage this month.
|
||||
- When a quota is used up, deliveries wait in `waiting_quota` until `next_attempt_at`: the next 00:00 UTC for the day, the first day of the next month at 00:00 UTC for the month. Nothing buys a plan, switches the account to a paid tier, or moves mail to another transport or account. The account itself can see that its mail waits and until when through the status reader described in [ARCHITECTURE.md](ARCHITECTURE.md#mail-quotas); no HTTP route shows it yet.
|
||||
- To see the state, select only counters and metadata, for example `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'`, and, for sends that were counted but never settled, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. Logs show `mail quota is used up; the delivery waits for the reset` and, when the provider itself refused, `the mail provider reported its quota used up; local sending stops until the reset`.
|
||||
- The internal /metrics endpoint shows the current windows of the configured account, read every 30 seconds: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted` (1 after a quota refusal by the provider), each with the labels `provider` and `window` (`day` or `month`). `EMAIL_ACCOUNT` is not a label, because the operator chooses its text; with `EMAIL_PROVIDER=disabled` there are no quota series. The alert `LincodexMailQuotaUsedUp` (severity info) fires while a window is used up.
|
||||
- Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored `next_attempt_at`; or deliberately switch the transport or account (see [Mail deliveries](#mail-deliveries) for what stays pinned). Do not lower `used_recipients` or edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused.
|
||||
- `provider_exhausted_at` on a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan.
|
||||
- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy (TASK-017).
|
||||
@@ -299,11 +301,17 @@ Start the core project first. Monitoring joins its Docker network. Monitoring st
|
||||
|
||||
Grafana is available at http://127.0.0.1:3000. Credentials come from GRAFANA_ADMIN_USER and GRAFANA_ADMIN_PASSWORD in .env. Prometheus, Loki, exporters, and backend metrics publish no host ports.
|
||||
|
||||
The `Lincodex product` dashboard in the Lincodex folder shows API request rate, error ratio, p50 and p95 latency of successful requests by route template, problem responses by code, outbox backlog and lag, relay, consumer, and scheduled job outcomes, mail deliveries by kind and status, the oldest due pending delivery, quota usage, and assessment answer saves. The answer save panel stays empty until the answer command is implemented. Prometheus loads the alert rules from `observability/prometheus/rules/`; their state is in the Prometheus rules API `/api/v1/rules`, which Grafana reaches through the Prometheus data source (Prometheus itself publishes no host port). No Alertmanager or notification channel is configured, so no alert reaches a person.
|
||||
|
||||
`make -C observability verify-product-metrics` checks this end to end on throwaway stacks: it starts an isolated core project `lincodex-metrics-check` on port 18085 and, separately, the monitoring project `lincodex-metrics-check-monitoring` with Grafana on 127.0.0.1:13085 (`METRICS_CHECK_HTTP_PORT` and `METRICS_CHECK_GRAFANA_PORT` change them), sends successful and failing API requests and a fixture mail delivery through the outbox, checks the values in Prometheus and every panel query of the product dashboard through Grafana, sends the fixture address in a query through Nginx and in a path straight to the backend, provokes a unique violation on the fixture address in PostgreSQL and checks that its log line omits the key, searches the metric exposition, all series and label values, the federated samples, and the Loki logs for the fixture address (after Loki shows both backend request lines of the run), and removes both projects with their volumes. It uses `EMAIL_PROVIDER=resend` with a placeholder key so the quota gauges exist; nothing sends mail in this build. It is an explicit end-to-end check, not part of `make -C observability check`: it starts two separate Compose projects and builds the core images. It starts every monitoring service except node-exporter, which reads only host metrics and whose root mount fails on Docker Desktop. It refuses to run when volumes or networks of these projects already exist, removes the images it built, and with `METRICS_CHECK_KEEP_ON_FAILURE=1` keeps both projects after a failure for inspection.
|
||||
|
||||
Prometheus retains metrics for 14 days with a 4 GB size limit. Loki retains logs for 7 days. Alloy discovery filters by Compose project and collects logs only from backend, frontend, postgres, redis, and seaweedfs. Kafka logs and metrics are not collected yet; read the logs with `make -C deploy logs`. Loki labels are limited to service and environment; do not add user IDs, addresses, resume text, request bodies, or full URLs.
|
||||
|
||||
What reaches Loki from the core services: the backend request log (`http request`, `http request error`, `http request failed`) names a request only by its request ID, method, route template (the same as the metric label, such as `/api/v1/me/invitations/{invitation_id}`), status and status class, problem code, latency, 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. Nginx in the frontend container logs the method, the path without the query string, status, timings, and request ID; a path that a client fills with an address would therefore appear in its log, which no API route invites. PostgreSQL runs with `log_error_verbosity=terse`, so an error line leaves out the DETAIL that quotes a duplicate or missing key, such as an address; the backend binds parameters, so the logged statement holds only placeholders. Handler logs follow the rules of their components, for example deliveries by `delivery_id` only.
|
||||
|
||||
Frontend telemetry is not connected in the React app yet. Nginx and Alloy provide a restricted /telemetry receiver and Faro configuration, but the UI SDK and end-to-end event check are absent.
|
||||
|
||||
Alloy uses docker-socket-proxy for container discovery. The proxy enables only the needed Docker API sections for containers, events, ping, and version; POST is disabled. Set the socket path with DOCKER_SOCKET_PATH. Rootless Docker may use a path such as /run/user/<uid>/docker.sock; use the path on your own host instead of copying another developer's local path. The proxy restricts API sections, but access to the Docker socket remains privileged and its exact configuration needs review.
|
||||
Alloy uses docker-socket-proxy for container discovery and log collection. The proxy enables only the needed Docker API sections for containers, events, networks, ping, and version; POST is disabled. Alloy's Docker discovery reads the networks of each container for its labels; without the networks section discovery fails with 403 and no log reaches Loki. The proxy sits alone with Alloy on the internal `docker-api` network, so no other monitoring or core container can call it. What the containers section still allows to Alloy: `GET /containers/{id}/json` returns the configuration of every container on the host, including `Config.Env` with the passwords and keys of the core services, and the same path prefix also allows `GET` of `/containers/{id}/logs`, `/containers/{id}/archive` (files from a container), and `/containers/{id}/export` (a container's whole file system). A compromised Alloy can therefore read the secrets of the stack; the network keeps every other container from doing the same. The `read_only` flag of the socket mount only protects the socket file and does not restrict any API call. Set the socket path with DOCKER_SOCKET_PATH. Rootless Docker may use a path such as /run/user/<uid>/docker.sock; use the path on your own host instead of copying another developer's local path. The proxy restricts API sections, but access to the Docker socket remains privileged and its exact configuration needs review.
|
||||
|
||||
PostgreSQL creates a separate exporter role only while initializing an empty volume and when POSTGRES_EXPORTER_USER and POSTGRES_EXPORTER_PASSWORD are set. Set both before the first make -C deploy up. Changing them after the volume exists does not rerun the init script.
|
||||
|
||||
@@ -566,7 +574,7 @@ go.mod declares `go 1.26.8` without a separate `toolchain` line, the default `GO
|
||||
|
||||
Prometheus scrapes backend /metrics on port 9090, PostgreSQL exporter, Redis exporter on port 9121, SeaweedFS on port 9327, node exporter, itself, and the optional ML target. Loki uses a single-binary filesystem store with 168-hour retention. Grafana provisions Prometheus and Loki datasources from observability/grafana/provisioning/.
|
||||
|
||||
The five checked-in dashboard JSON files are maintained as project dashboards: Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux system. The Redis dashboard covers availability, memory, cache hits/misses, evictions/expired keys, and client connections. The exporter collects aggregate metrics without scanning keys. The SeaweedFS dashboard covers availability, S3 request rate and duration, errors, disk, and memory; Prometheus retains only selected aggregate metrics without object paths. They were not copied from Grafana dashboard IDs. No external dashboard provenance or license is claimed for them.
|
||||
The six checked-in dashboard JSON files are maintained as project dashboards: Go runtime, PostgreSQL, Redis, SeaweedFS, Linux system, and Lincodex product (`lincodex-product.json`, described in [Separate monitoring Compose project](#separate-monitoring-compose-project)). Prometheus loads `prometheus/rules/*.yml`; `make -C observability check` validates them with `promtool check config` and runs their unit tests in `prometheus/tests/` with `promtool test rules`. The Redis dashboard covers availability, memory, cache hits/misses, evictions/expired keys, and client connections. The exporter collects aggregate metrics without scanning keys. The SeaweedFS dashboard covers availability, S3 request rate and duration, errors, disk, and memory; Prometheus retains only selected aggregate metrics without object paths. They were not copied from Grafana dashboard IDs. No external dashboard provenance or license is claimed for them.
|
||||
|
||||
The local monitoring stack is a single-node development/demo setup and provides no HA. Compose validation does not establish production retention, off-host backups, public access control, alert delivery, or core application behavior.
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ SQL linter dependencies are listed in `backend/requirements-quality.txt` beside
|
||||
|
||||
Go follows domain, usecase, port, adapter, and bootstrap boundaries. The HTTP adapter mounts the generated ogen handler in chi. SQL belongs in backend/db/queries/; schema changes belong in backend/db/migrations/. sqlc output and wire_gen.go are generated.
|
||||
|
||||
Shared backend settings live in backend/config/. The service uses go-logkit 0.6.0 through its slog bridge and go-httpkit 0.7.0 for request IDs, request logging, and panic recovery. It retains custom Prometheus middleware because it bounds method labels and uses chi route patterns; go-httpkit/metrics accepts the raw method name as a label.
|
||||
Shared backend settings live in backend/config/. The service uses go-logkit 0.6.0 through its slog bridge and go-httpkit 0.7.0 for request IDs and panic recovery. Request logging is the service's own `middleware.RequestLog`: the go-httpkit logger writes the raw path and every query value not on its fixed redaction list, so an address in a path or query would reach the logs. It retains custom Prometheus middleware because it bounds method labels and uses chi route patterns; go-httpkit/metrics accepts the raw method name as a label.
|
||||
|
||||
PostgreSQL uses pgxpool.NewWithConfig, and a generated SELECT 1 readiness query checks connectivity. Pool construction must not wait for the database during startup. go-pgkit 1.4.0 is not used because its constructor probes and retries before returning a pool, coupling service startup to database availability. Health handlers remain explicit: go-httpkit's helper returns ok/degraded with check details, while the shared contract uses ok/ready/not_ready. Do not add pgkit, httpkit/metrics, JWT or WebSocket without a concrete need and a check of the pinned version's behavior.
|
||||
|
||||
|
||||
+13
-1
@@ -28,7 +28,9 @@ Useful focused commands:
|
||||
| make -C deploy check | Render Compose configurations and run `check-workflows`, which fails when a workflow `aggregate` job does not need every other job or lacks `if: always()`, and `check-release`; see [Release manifest tests](#release-manifest-tests) |
|
||||
| make -C deploy smoke | Isolated technical smoke of service health routes |
|
||||
| make -C deploy test-e2e | Playwright browser suite against an isolated throwaway stack |
|
||||
| make -C observability check | Validate Prometheus, Loki, Alloy, and dashboard JSON |
|
||||
| make -C deploy release-smoke, release-e2e | The same smoke and browser suite against the release images; a passing run records evidence for the release manifest |
|
||||
| make -C observability check | Validate Prometheus config and alert rules with their unit tests, Loki, Alloy, and dashboard JSON |
|
||||
| make -C observability verify-product-metrics | Isolated core and monitoring stacks: product metrics in Prometheus and Grafana, no fixture address in metrics or Loki logs; see [Product metrics tests](#product-metrics-tests) |
|
||||
|
||||
make -C deploy test-e2e currently runs a technical browser suite, not a business-flow suite; see [Browser E2E suite](#browser-e2e-suite).
|
||||
|
||||
@@ -220,6 +222,16 @@ Unit tests (`make -C backend test`) cover the job runtime with an in-memory stor
|
||||
|
||||
`TestPostgresMigrations` also checks that migration 00008 creates and drops `scheduled_jobs`. The suite uses one PostgreSQL and a test-only kind. It does not measure throughput, does not cover clock skew between instances, a database failover, or a product handler, and does not check alert delivery.
|
||||
|
||||
## Product metrics tests
|
||||
|
||||
Unit tests (`make -C backend test`) cover the product metrics (TASK-022). In `internal/adapter/primary/http/`, requests through the real router and the real collector are labeled with the route template of their operation (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) and never with a path parameter, an address in the path, or a query string; unknown paths and methods keep `/api/v1/*`, `/api/*`, or `unmatched`; problem responses are counted by code (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), a plain 404 outside `/api` is not; and the exposition holds no email-like or UUID-like value; every contract problem code keeps its own label. The request log test sends an address and a UUID in paths and queries through the same router and checks that the JSON log names only route templates, statuses, problem codes, and query parameter counts, skips `/healthz` and `/readyz`, and holds neither value. `internal/adapter/primary/http/middleware/` tests the log and metrics middleware on a plain chi router: the shared route and problem code, no problem for a response that finally succeeded, the error level for 5xx, an unknown method logged as `OTHER`, and a collector without problem counting. In `internal/adapter/secondary/prometheus/`: latency by status class, every delivery kind and status pair exposed at zero and reset when a status empties, quota gauges without an account label, the answer save hook mapping unknown values to `other` and exposing no series before its first call, and a scan of the whole exposition after every hook was called with email and UUID fixtures. `internal/worker/deliverymetrics/` covers the due age of the earliest pending delivery (zero when it is not due yet), the current quota windows, a failed read that does not skip the other, and the loop lifecycle; `internal/bootstrap/` covers the skip without a database, the quota only for an active transport, and an application that runs the sampler against an unreachable database and still stops. `pkg/testutil/` tests the identifier scan itself.
|
||||
|
||||
`TestDeliveryStatistics` in `backend/integration_test/delivery_statistics_test.go` checks the sqlc query `GetDeliveryStatistics` on PostgreSQL: an empty table, then deliveries of three kinds in all five statuses, set within the table constraints, give exact counts per kind and status, and the earliest due time comes only from deliveries that are still pending.
|
||||
|
||||
`make -C observability check` validates the alert rules with `promtool check config` and runs `promtool test rules` on `observability/prometheus/tests/lincodex_rules_test.yml`: every alert fires in a positive case (backend down, 5xx share, outbox lag, dead letter, stalled consumer, dead and lagging jobs, unknown delivery outcome counted once across two instances, overdue deliveries, stale mail gauges, the used-up quota by count and by provider refusal), and the guards stay silent: quiet traffic with only failing requests, overdue deliveries without `lincodex_mail_sender_running`, a sampler that keeps succeeding, and a month window with room.
|
||||
|
||||
`make -C observability verify-product-metrics` is the end-to-end check described in [DEPLOY.md](DEPLOY.md#separate-monitoring-compose-project). It needs Docker and free host ports 18085 and 13085, builds the core images, and takes several minutes. It sends the fixture address in a query through Nginx and in a path straight to the backend and provokes a unique violation on it in PostgreSQL. It proves that the metrics reach Prometheus and the product dashboard queries run in Grafana, that PostgreSQL logs errors tersely, and that the fixture address is absent from the metric exposition, every series and label value, the federated samples, and the Loki logs of the core services in that run. It does not test alert delivery, production retention, load, or latency targets, and it does not send mail.
|
||||
|
||||
## Integration test sharding
|
||||
|
||||
`make -C backend test-int` runs the full suite through `backend/scripts/run-integration-suite.py`. The runner discovers every top-level `Test*` in `./integration_test/...`, sorts by package and name, and distributes tests round-robin. Each test belongs to exactly one shard with all its subtests. Changing the test set may change the assignment; duration-based balancing is not implemented.
|
||||
|
||||
+19
-10
@@ -228,7 +228,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
### Доставки писем
|
||||
|
||||
Реализовано (TASK-015): агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован в TASK-018; см. [Квоты почты](#квоты-почты). Запланировано: worker, который берет доставки к отправке, пропускает их через шлюз квот и вызывает `MailSender` (TASK-016), повторы и политика неизвестного исхода (TASK-017), метрики доставки (TASK-022) и проверка разрешений перед отправкой (TASK-462). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и сохраненные доставки никто не отправляет.
|
||||
Реализовано (TASK-015): агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован в TASK-018; см. [Квоты почты](#квоты-почты). Запланировано: worker, который берет доставки к отправке, пропускает их через шлюз квот и вызывает `MailSender` (TASK-016), повторы и политика неизвестного исхода (TASK-017) и проверка разрешений перед отправкой (TASK-462). Gauges состояний доставки реализованы в TASK-022; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и сохраненные доставки никто не отправляет.
|
||||
|
||||
Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит:
|
||||
|
||||
@@ -257,7 +257,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
- Запросы для эксплуатации выбирают столбцы метаданных (ID, вид, статус, попытки, время, провайдер) и никогда не выбирают тела, текст запроса и адрес; см. [DEPLOY.md](DEPLOY.md#доставки-писем).
|
||||
- Удаление аккаунта каскадно удаляет его запросы писем, доставки и их попытки. Очистка неподтвержденных аккаунтов блокирует их через `FOR UPDATE SKIP LOCKED`, как токены и сессии, поэтому никогда не ждет обработчик доставки или worker, который держит строку.
|
||||
- Правило хранения, которое удаляет или очищает завершенные доставки через ограниченный срок, еще не реализовано; пока его нет, строки остаются. Шифрование тел в хранилище тоже не реализовано.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText` и `EmailAddress` скрывают себя в выводе `fmt` и `slog`: доставка попадает в лог только как ID, вид, статус и провайдер. Ошибки обработчика называют нарушенное правило и никогда не цитируют payload, а адаптер заменяет текст ошибки PostgreSQL на SQLSTATE и имя ограничения. Метрик доставки пока нет; TASK-022 добавит их с labels только по виду, статусу и провайдеру, без адреса, ID аккаунта и темы.
|
||||
- `Delivery`, `MailContent`, `MailRequest`, `NotificationText` и `EmailAddress` скрывают себя в выводе `fmt` и `slog`: доставка попадает в лог только как ID, вид, статус и провайдер. Ошибки обработчика называют нарушенное правило и никогда не цитируют payload, а адаптер заменяет текст ошибки PostgreSQL на SQLSTATE и имя ограничения. Метрики доставки (TASK-022) несут только labels вида, статуса, провайдера и окна квоты, без адреса, ID пользователя или доставки, метки аккаунта провайдера и темы.
|
||||
|
||||
Статусы. Значения следуют исходам `MailSender`:
|
||||
|
||||
@@ -293,7 +293,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
### Квоты почты
|
||||
|
||||
Реализовано (TASK-018): окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Запланировано: worker отправки, который вызывает шлюз вокруг `MailSender.Send` и собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP (TASK-016), метрики квот (TASK-022) и API или сценарий identity, который показывает результат чтения статуса. Пока ничего не отправляется, поэтому текущая сборка ничего не считает.
|
||||
Реализовано (TASK-018): окна и лимиты квот в `backend/internal/domain/mail_quota.go`; порт `outbound.MailQuotaRepository` (`port/outbound/mail_quota.go`), запись через который идет через `UnitOfWork.MailQuotas()`, а чтение еще и через `postgres.MailQuotaStore`; миграция `00007_create_mail_quota_usage.sql` с таблицами `mail_quota_usage` и `mail_quota_reservations`; запросы в `backend/db/queries/mail_quota.sql`; в `backend/internal/usecase/notification/` - `QuotaGate` с `PrepareSend` и `SettleSend` (`quota.go`), отчет при запуске `ReportQuotaUsage` и чтение статуса для пользователя `DeliveryStatusReader` (`delivery_status.go`); `SendResult.QuotaPeriod` в почтовом порте, который заполняет адаптер Resend; отчет при запуске в bootstrap (`bootstrap/mail_quota.go`). Запланировано: worker отправки, который вызывает шлюз вокруг `MailSender.Send` и собирает его из конфигурации с `resend.IdempotencyWindow` или нулем для SMTP (TASK-016) и API или сценарий identity, который показывает результат чтения статуса. Пока ничего не отправляется, поэтому текущая сборка ничего не считает.
|
||||
|
||||
Лимиты. `EMAIL_QUOTA_DAILY` и `EMAIL_QUOTA_MONTHLY` ограничивают число получателей, отправленных через настроенный аккаунт провайдера (`EMAIL_PROVIDER` и `EMAIL_ACCOUNT`), за UTC-сутки, с 00:00 до 00:00 UTC, и за календарный месяц UTC. Считается каждый получатель, как считает Resend; у доставки один получатель. Значения по умолчанию - лимиты Resend Free, проверенные 05.10.2026: 100 и 3000; они действуют для `resend` и для `disabled`, который ничего не отправляет. У `smtp` значений по умолчанию нет, и без обоих значений он не запускается: лимиты relay не совпадают с лимитами Resend. Допустимы значения от 1 до 1000000000, суточный лимит не больше месячного. Значения, которое отключает квоту, нет, поэтому ни один провайдер не работает без шлюза. Лимиты - это конфигурация, а не доменные константы, и они не хранятся: измененный лимит действует со следующего резервирования, а лимит, сниженный ниже текущего расхода, откладывает каждую новую отправку до сброса окна.
|
||||
|
||||
@@ -333,7 +333,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| `accepted` | Ваше письмо отправлено. Это значит, что провайдер его принял, а не что оно дошло до ящика |
|
||||
| `rejected` | Ваше письмо не удалось отправить |
|
||||
|
||||
Операторы читают те же строки запросами из [DEPLOY.md](DEPLOY.md#квоты-почты). Шлюз пишет в журнал `mail quota is used up; the delivery waits for the reset` на уровне info и `the mail provider reported its quota used up; local sending stops until the reset` на уровне warn, только с ID доставки, провайдером, периодом и моментом сброса. Метрик квот пока нет; `MailQuotaRepository.Usage` - чтение, которое TASK-022 может отдать с метками provider и period.
|
||||
Операторы читают те же строки запросами из [DEPLOY.md](DEPLOY.md#квоты-почты). Шлюз пишет в журнал `mail quota is used up; the delivery waits for the reset` на уровне info и `the mail provider reported its quota used up; local sending stops until the reset` на уровне warn, только с ID доставки, провайдером, периодом и моментом сброса. Gauges квот (TASK-022) читаются через `MailQuotaUsageReader.Usage` для настроенного аккаунта только с labels provider и window; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts).
|
||||
|
||||
### Версии продуктовой политики
|
||||
|
||||
@@ -428,7 +428,8 @@ backend/
|
||||
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, relay outbox, публикации и потребления событий, identity, журнала согласий, организаций и членств, политики, хеширования паролей и почты
|
||||
adapter/primary/http/
|
||||
api/ generated ogen handler
|
||||
middleware/ метрики запросов
|
||||
middleware/ журнал и метрики запросов по шаблону маршрута
|
||||
observe/ наблюдения уровня запроса, например код problem
|
||||
problem/ ответы об ошибках по RFC 9457
|
||||
v1/ написанный вручную health endpoint
|
||||
router.go сборка chi router
|
||||
@@ -442,15 +443,16 @@ backend/
|
||||
postgres/sqlc/ generated SQL adapter
|
||||
redis/ адаптер кеша и проверка Redis
|
||||
seaweedfs/ S3-адаптер и проверка bucket
|
||||
prometheus/ ограниченные Go/process и request metrics
|
||||
prometheus/ ограниченные метрики Go/process, запросов, problem, outbox, обработчиков, заданий, доставок, квот и сохранения ответов
|
||||
worker/outboxrelay/ цикл relay outbox: захват, публикация, отметка, backoff и остановка
|
||||
worker/eventconsumer/ runtime обработчиков событий: транзакция дедупликации, повторы, dead letters, commit offsets и остановка
|
||||
worker/jobrunner/ runtime заданий по сроку: захват под lease, выполнение вместе с завершением, повторы, освобождение и остановка
|
||||
worker/retry/ backoff с jitter и ожидание с учетом context, общие для workers
|
||||
worker/deliverymetrics/ периодическое чтение агрегатов доставок и квот почты в метрики
|
||||
bootstrap/ конфигурация, wiring, lifecycle, shutdown
|
||||
db/ встроенные миграции и SQL-запросы; таблицы outbox, identity, политики, обработчиков событий, доставок, квот почты, заданий по сроку, журнала согласий и организаций
|
||||
codegen/ конфигурация ogen и sqlc
|
||||
pkg/testutil/ fake clock приложения, общий для тестов
|
||||
pkg/testutil/ fake clock приложения и поиск идентификаторов, общие для тестов
|
||||
```
|
||||
|
||||
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Типы журнала согласий лежат в `consent.go`. Типы организации, проверки и членства лежат в `organization.go` и `membership.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`.
|
||||
@@ -459,7 +461,7 @@ backend/
|
||||
|
||||
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка почты, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
|
||||
|
||||
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`. Пакет `mailer` остается кандидатом. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; usecase identity (подтверждение почты и сброс пароля) должны вызывать его при создании своих доставок, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
|
||||
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; usecase identity (подтверждение почты и сброс пароля) должны вызывать его при создании своих доставок, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
|
||||
|
||||
`api/` хранит контракты и инструменты и не является runtime hop в пути запроса. `api/core/` и `api/ml/` владеют исходным OpenAPI, fragments маршрутов и компонентов, а также коммитируемыми bundles. Схемы объединяет корневой `scripts/`. Сгенерированный Go-код лежит у потребителя: публичный handler - в `backend/internal/adapter/primary/http/api/`, внутренний ML client - в `backend/internal/adapter/secondary/ml/api/`, sqlc output - в `backend/internal/adapter/secondary/postgres/sqlc/`. Первый пакет монтируется в chi; два последних реализуют outbound adapters. `backend/cmd/app/main.go` остается точкой входа, а bootstrap отвечает за wiring и graceful shutdown.
|
||||
|
||||
@@ -698,13 +700,20 @@ k3s не входит в критический путь. Его можно ра
|
||||
|
||||
## Метрики, телеметрия и alerts
|
||||
|
||||
Сейчас Go экспортирует стандартные Go/process метрики, `lincodex_http_requests_total` с ограниченными labels `method`, шаблоном маршрута `route` и `status`, а также `lincodex_http_request_duration_seconds`. В labels нельзя помещать user/candidate/request IDs, полный URL, адреса или содержимое резюме. `/metrics` слушает на внутреннем listener и не входит в `/api/v1`. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS и Linux поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Счетчики и gauges backlog заданий по сроку описаны в разделе [Задания по сроку](#задания-по-сроку). Метрики inference и бизнес-событий пока не реализованы.
|
||||
Go экспортирует стандартные Go/process метрики и продуктовые метрики TASK-022 на внутреннем listener `/metrics`, вне `/api/v1`:
|
||||
|
||||
- API: `lincodex_http_requests_total{method,route,status}`, `lincodex_http_request_duration_seconds{method,route,status_class}` и `lincodex_http_problems_total{route,code}`. `route` - шаблон маршрута chi для операционных маршрутов, а под `/api/v1` - шаблон пути OpenAPI найденной операции, например `/api/v1/me/invitations/{invitation_id}`; router находит его через `FindPath` сгенерированного сервера. Путь или метод без операции сохраняет шаблон монтирования `/api/v1/*` или `/api/*`, а путь вне всех маршрутов получает `unmatched`. `status_class` - от `1xx` до `5xx`. `code` - код problem по RFC 9457: `problem.New` записывает его из закрытого каталога через пакет `observe` уровня запроса (`adapter/primary/http/observe/`), middleware учитывает его только для ответа 4xx или 5xx, а адаптер считает код вне своего зеркального списка как `other`. Ошибка без тела problem, например 503 от `/readyz`, учитывается только по статусу. Журнал запросов (`middleware.RequestLog`, заменяет logger из go-httpkit) использует тот же шаблон маршрута и пишет request ID, метод, статус и класс, код problem, задержку, размер ответа и число параметров query, но никогда не пишет исходный путь, ключ или значение query, заголовок, адрес клиента и user agent; `/healthz` и `/readyz` не журналируются.
|
||||
- Outbox и события: метрики relay, обработчиков и заданий по сроку описаны в разделах [Relay outbox](#relay-outbox), [Обработчики событий](#обработчики-событий) и [Задания по сроку](#задания-по-сроку). Отставание outbox показывает `lincodex_outbox_relay_oldest_pending_age_seconds`.
|
||||
- Почта: `lincodex_mail_deliveries{kind,status}` для каждого вида и статусов `pending`, `waiting_quota`, `unknown`, `accepted` и `rejected`, включая нулевые; `lincodex_mail_delivery_oldest_due_pending_age_seconds`; для активного транспорта - `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` с `provider` и `window` (`day` или `month`). Sampler в `backend/internal/worker/deliverymetrics/` читает их каждые 30 секунд через собственный pool на одно соединение: `postgres.DeliveryStatisticsStore` агрегирует `deliveries` по виду и статусу, а `MailQuotaUsageReader.Usage` читает текущие окна настроенного аккаунта. Агрегат доставок - запрос sqlc `GetDeliveryStatistics` в `db/queries/delivery.sql`. Запрос сканирует таблицу, что подходит для текущего объема; до миллионов строк нужен индекс или счетчики по статусам. `EMAIL_ACCOUNT` не становится label: это свободный текст оператора, который может назвать человека, а каждый процесс сообщает только свой аккаунт. Все экземпляры сообщают одинаковые значения по всей базе; агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`; `lincodex_mail_metrics_last_success_timestamp_seconds` показывает последнее чтение, в котором прочитаны все агрегаты (0 от запуска sampler до первого такого чтения), а gauge просрочки появляется только после первого успешного чтения. Счетчика исходов попыток пока нет, потому что worker отправки (TASK-016) еще не существует.
|
||||
- Ответы теста: `lincodex_assessment_answer_saves_total{format,outcome}` с исходами `stored`, `unchanged`, `rejected` и `failed`. PRD 6.6 требует наблюдать сохранение ответов; это понимается как команда ответа теста `SubmitMyAssessmentAnswer`. Команда не реализована, поэтому есть только hook `Metrics.ObserveAssessmentAnswerSave`, и серии не появятся, пока usecase не начнет вызывать его один раз на команду. Значение вне закрытых наборов превращается в `other`. Задержка и ошибки HTTP этой команды уже видны под маршрутом `/api/v1/me/assessment-attempts/{attempt_id}/answers`.
|
||||
|
||||
В labels нельзя помещать ID пользователя, кандидата, доставки или запроса, полный URL или query string, адреса и содержимое резюме. Unit-тесты прогоняют настоящий router и каждый hook метрик с fixture email и UUID и падают, если в выдаче есть значение, похожее на email или UUID. JSON dashboards Go runtime, PostgreSQL, Redis, SeaweedFS, Linux и продуктовый Lincodex поддерживаются в проекте; это не импортированные Grafana dashboard IDs. Метрики inference пока не реализованы.
|
||||
|
||||
План наблюдаемости включает метрики jobs: очередь, возраст старейшего готового задания, время ожидания и выполнения, retries и окончательные ошибки; состояние pgxpool должно собираться внутри Go ограниченными неблокирующими запросами. Nginx `stub_status` не дает latency по HTTP статусам; access logs могут измерять `request_time` и `upstream_response_time`. cAdvisor можно добавить при поддержке выбранного runtime. Redis exporter уже включен в отдельный monitoring Compose, Prometheus опрашивает его на внутреннем порту 9121. Метрики SeaweedFS опрашиваются напрямую на внутреннем порту 9327; сохраняются только выбранные агрегированные серии, без путей объектов. DCGM exporter понадобится только при локальной NVIDIA модели.
|
||||
|
||||
План браузерного пути: Faro Web SDK -> same-origin `/telemetry` -> Alloy `faro.receiver` -> Loki. React SDK пока не подключен. Собирать очищенные Web Vitals, JS errors, release и нормализованный маршрут; исключить console logs, формы, текст резюме и session replay. Удалять query string, fragment и ID из URL. Ограничить размер, частоту и origin приемника. Request/trace IDs остаются полями логов, не labels; хранение spans требует отдельного backend, например Tempo, и пока не поддерживается.
|
||||
|
||||
Планируемые alerts: недоступный target, высокая доля 5xx при достаточном числе запросов, превышение latency budget, старые или окончательно упавшие jobs, заполнение диска, ошибки ML и отброшенные логи. При низком трафике нужны окно и минимальное число событий, иначе процентили нестабильны. Настроить поведение `No Data` и ошибки datasource. Стек на том же хосте не может надежно сообщить о его остановке; для этого нужен внешний health check. Compose и dashboard smoke не проверяют доставку alerts. Правила и канал уведомления следует описывать как внедренные только после отдельной проверки.
|
||||
Правила alerts в `observability/prometheus/rules/lincodex.yml` покрывают недоступный target backend, долю 5xx выше 5% при не менее чем 15 запросах за 5 минут, отставание outbox, dead letters и застрявшие обработчики, мертвые и опаздывающие задания по сроку, доставки с неизвестным исходом, устаревшие gauges доставок и квот, исчерпанную квоту почты и просроченные доставки; последнее правило требует еще `lincodex_mail_sender_running`, который должен экспортировать worker отправки из TASK-016, поэтому до него оно не срабатывает. `promtool test rules` дает каждому alert случай срабатывания, а каждому ограничению - случай молчания. Prometheus вычисляет их и показывает состояние на странице /alerts и в Grafana; Alertmanager и канал уведомлений не настроены, поэтому alert никому не приходит. Планируемые alerts: превышение latency budget, заполнение диска, ошибки ML и отброшенные логи. При низком трафике нужны окно и минимальное число событий, иначе процентили нестабильны. Настроить поведение `No Data` и ошибки datasource. Стек на том же хосте не может надежно сообщить о его остановке; для этого нужен внешний health check. Compose и dashboard smoke не проверяют доставку alerts. Правила и канал уведомления следует описывать как внедренные только после отдельной проверки.
|
||||
|
||||
## Покрытие требований ТЗ
|
||||
|
||||
|
||||
+10
-2
@@ -250,6 +250,7 @@ Compose передает эти переменные из корневого `.e
|
||||
- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Доставки, созданные при `EMAIL_PROVIDER=disabled`, остаются закрепленными за `disabled`, пока worker отправки (TASK-016) не перенесет их через `Rebind`, что разрешено только до первой попытки.
|
||||
- Строки содержат адрес получателя и сформированные тела писем, а ожидающая строка `mail_requests` - исходный текст уведомления; тела писем подтверждения почты и сброса пароля содержат действующий одноразовый токен, пока его не использовали или пока не истек срок. Относитесь к доступу на чтение к `deliveries` как к доступу к этим ссылкам и защищайте дампы и резервные копии базы так же. Срок хранения завершенных доставок пока не реализован.
|
||||
- Для просмотра доставок выбирайте только метаданные, например `SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50` и `SELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number`. `SELECT count(*), min(created_at) FROM mail_requests` показывает запросы, которые обработчик еще не обработал; растущее число значит, что обработчик остановлен или его события уходят в dead letters. Не выбирайте `recipient_email`, `subject`, `text_body`, `html_body` и текстовые столбцы `mail_requests` и никогда не вставляйте их в задачи и чаты.
|
||||
- Без SQL внутренний endpoint /metrics показывает `lincodex_mail_deliveries{kind,status}` для каждого вида и статуса, включая нулевые, и `lincodex_mail_delivery_oldest_due_pending_age_seconds` - сколько времени самая ранняя доставка в `pending` уже ждет своего срока. Backend читает их каждые 30 секунд одним агрегатом по `deliveries`; все экземпляры сообщают одинаковые значения, поэтому агрегируйте их через `max`. Неудачное чтение сохраняет прежние значения и пишет в журнал `delivery metrics could not be read; the gauges are stale`. Пока нет worker отправки (TASK-016), каждая сохраненная доставка остается в `pending`, а ее просрочка только растет. Серия просрочки появляется только после первого успешного чтения, поэтому свежий запуск не заявляет, что ничего не просрочено; `lincodex_mail_metrics_last_success_timestamp_seconds` - Unix-время последнего чтения, в котором прочитаны все агрегаты (0 от запуска до первого такого чтения), а `LincodexMailMetricsStale` срабатывает, когда оно старше 5 минут в течение 5 минут. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока у какой-либо доставки неизвестный исход. `LincodexMailDeliveriesOverdue` (доставка в `pending` просрочена больше чем на 15 минут) требует еще `lincodex_mail_sender_running`, равный 1; этот gauge принадлежит worker отправки из TASK-016, который должен экспортировать его, пока работает его цикл, поэтому alert молчит, пока отправителя нет, при `EMAIL_PROVIDER=disabled` и без трафика.
|
||||
- Не правьте сохраненную доставку вручную: trigger отклоняет любое изменение получателя, содержимого или ключа идемпотентности и смену аккаунта провайдера после первой попытки, а история попыток отклоняет обновления. Доставка в `waiting_quota` ждет сброса квоты в `next_attempt_at`; см. [Квоты почты](#квоты-почты). Без `next_attempt_at` момент сброса неизвестен, и нужно решение оператора.
|
||||
- Логи называют доставку только по `delivery_id` (вместе с ID события), никогда по адресу или теме. Пропущенные запросы пишутся на уровне info: `mail request skipped because it was already handled or its account was deleted` и `notification skipped because the recipient address is not verified`. Запрос, нарушающий контракт события, становится dead letter класса `handler_rejected` обработчика `notification_delivery`; см. [Dead letters и повторный запуск](#dead-letters-и-повторный-запуск). Повторять его безопасно: ID доставки сохраняет одну доставку на запрос.
|
||||
|
||||
@@ -261,6 +262,7 @@ Compose передает эти переменные из корневого `.e
|
||||
- Меняйте `EMAIL_ACCOUNT` только вместе с настоящей сменой аккаунта провайдера, то есть с ключом другого аккаунта. Локальный счет ведется по метке аккаунта, поэтому переименование метки для того же аккаунта начинает счет с нуля, а у провайдера остается прежний. При запуске backend пишет в журнал `mail quota usage` с провайдером, аккаунтом, текущим расходом и лимитами суток и месяца и предупреждает, если у других меток того же провайдера есть расход в этом месяце.
|
||||
- Когда квота исчерпана, доставки ждут в `waiting_quota` до `next_attempt_at`: ближайших 00:00 UTC для суток и первого числа следующего месяца в 00:00 UTC для месяца. Ничто не покупает тариф, не переводит аккаунт на платный план и не переносит почту на другой транспорт или аккаунт. Сам аккаунт может узнать, что его письмо ждет и до какого времени, через чтение статуса, описанное в [ARCHITECTURE.md](ARCHITECTURE.md#квоты-почты); HTTP-маршрута для этого пока нет.
|
||||
- Чтобы увидеть состояние, выбирайте только счетчики и метаданные, например `SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10`, `SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota'` и для отправок, которые посчитаны, но так и не рассчитаны, `SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL`. В журнале видны `mail quota is used up; the delivery waits for the reset` и, если отказал сам провайдер, `the mail provider reported its quota used up; local sending stops until the reset`.
|
||||
- Внутренний endpoint /metrics показывает текущие окна настроенного аккаунта, которые читаются каждые 30 секунд: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` (1 после отказа провайдера по квоте), каждая с labels `provider` и `window` (`day` или `month`). `EMAIL_ACCOUNT` не становится label, потому что его текст выбирает оператор; при `EMAIL_PROVIDER=disabled` серий квот нет. Alert `LincodexMailQuotaUsedUp` (severity info) срабатывает, пока окно исчерпано.
|
||||
- Варианты, пока письма ждут: дождаться сброса, для этого ничего делать не нужно; или после осознанной смены тарифа у провайдера поднять лимиты и перезапустить backend, тогда новые отправки снова допускаются, а отложенные доставки сохраняют свой `next_attempt_at`; или осознанно сменить транспорт или аккаунт (что остается закрепленным, описано в [Доставки писем](#доставки-писем)). Не уменьшайте `used_recipients` и не правьте журнал вручную, чтобы освободить отправки: у провайдера свой счет, и такие отправки он только отклонит.
|
||||
- `provider_exhausted_at` в строке значит, что провайдер ответил отказом по квоте, хотя по локальному счету место было. Возможные причины: аккаунт отправляет письма еще откуда-то; Resend учитывает в той же квоте полученные (входящие) письма; или настроенный лимит выше тарифа. Приведите лимиты в соответствие с тарифом.
|
||||
- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов (TASK-017).
|
||||
@@ -301,11 +303,17 @@ GET /healthz проверяет процесс. GET /readyz проверяет
|
||||
|
||||
Grafana доступна на http://127.0.0.1:3000. Учетные данные берутся из GRAFANA_ADMIN_USER и GRAFANA_ADMIN_PASSWORD в .env. Prometheus, Loki, exporters и backend metrics не публикуют host ports.
|
||||
|
||||
Dashboard `Lincodex product` в папке Lincodex показывает частоту запросов API, долю ошибок, p50 и p95 задержки успешных запросов по шаблону маршрута, ответы problem по коду, backlog и отставание outbox, исходы relay, обработчиков и заданий по сроку, доставки писем по виду и статусу, самую просроченную доставку в `pending`, расход квоты и сохранение ответов теста. Панель сохранения ответов пуста, пока команда ответа не реализована. Prometheus загружает правила alerts из `observability/prometheus/rules/`; их состояние отдает API правил Prometheus `/api/v1/rules`, к которому Grafana обращается через data source Prometheus (сам Prometheus не публикует host port). Alertmanager и канал уведомлений не настроены, поэтому alert никому не приходит.
|
||||
|
||||
`make -C observability verify-product-metrics` проверяет это от начала до конца на одноразовых стендах: запускает изолированный core проект `lincodex-metrics-check` на порту 18085 и отдельно monitoring проект `lincodex-metrics-check-monitoring` с Grafana на 127.0.0.1:13085 (порты меняют `METRICS_CHECK_HTTP_PORT` и `METRICS_CHECK_GRAFANA_PORT`), отправляет успешные и ошибочные запросы API и fixture доставку письма через outbox, проверяет значения в Prometheus и каждый запрос панелей продуктового dashboard через Grafana, отправляет fixture адрес в query через Nginx и в пути напрямую в backend, вызывает в PostgreSQL нарушение уникальности по fixture адресу и проверяет, что строка журнала не содержит ключ, ищет fixture адрес в выдаче метрик, во всех сериях и значениях labels, в federate и в логах Loki (после того как Loki показал обе строки журнала запросов backend этого прогона), а затем удаляет оба проекта вместе с volumes. Проверка использует `EMAIL_PROVIDER=resend` с ключом-заглушкой, чтобы появились gauges квот; в этой сборке почту ничто не отправляет. Это явная сквозная проверка, а не часть `make -C observability check`: она запускает два отдельных Compose проекта и собирает образы core. Она запускает все сервисы monitoring, кроме node-exporter: он читает только метрики хоста, а его монтирование корня не работает в Docker Desktop. Проверка отказывается работать, если volumes или сети этих проектов уже существуют, удаляет собранные ею образы, а с `METRICS_CHECK_KEEP_ON_FAILURE=1` оставляет оба проекта после сбоя для разбора.
|
||||
|
||||
Prometheus хранит метрики 14 дней с лимитом 4 GB. Loki хранит логи 7 дней. Alloy discovery отфильтровывает Compose project и принимает логи только backend, frontend, postgres, redis и seaweedfs. Логи и метрики Kafka пока не собираются; читайте логи через `make -C deploy logs`. Разрешенные Loki labels ограничены service и environment; не добавляйте user ID, адреса, resume content, request body или полный URL в labels.
|
||||
|
||||
Что попадает в Loki от сервисов core: журнал запросов backend (`http request`, `http request error`, `http request failed`) называет запрос только по request ID, методу, шаблону маршрута (тому же, что и label метрик, например `/api/v1/me/invitations/{invitation_id}`), статусу и классу статуса, коду problem, задержке, размеру ответа и числу параметров query; он никогда не пишет исходный путь, ключ или значение query, заголовок, адрес клиента и user agent. Nginx в контейнере frontend пишет метод, путь без query string, статус, тайминги и request ID; поэтому путь, в который клиент сам вставил адрес, попал бы в его журнал, хотя ни один маршрут API этого не предполагает. PostgreSQL работает с `log_error_verbosity=terse`, поэтому строка ошибки не содержит DETAIL, который цитирует повторяющийся или отсутствующий ключ, например адрес; backend передает параметры отдельно, и в журнале оператора остаются только placeholders. Журналы обработчиков подчиняются правилам своих компонентов, например доставки называются только по `delivery_id`.
|
||||
|
||||
Frontend телеметрия пока не подключена в React-приложении. Nginx и Alloy имеют ограниченный /telemetry приемник и конфигурацию Faro, однако UI SDK и сквозная проверка событий отсутствуют.
|
||||
|
||||
Для обнаружения контейнеров Alloy использует docker-socket-proxy. Разрешены только нужные разделы Docker API для containers, events, ping и version; POST отключен. Путь к сокету задается DOCKER_SOCKET_PATH. На rootless Docker он может выглядеть как /run/user/<uid>/docker.sock; указывайте путь, действующий на вашем хосте, не копируйте чужой локальный путь. Прокси ограничивает API, но доступ к Docker socket все равно считайте привилегированным и проверяйте его точную конфигурацию.
|
||||
Для обнаружения контейнеров и сбора логов Alloy использует docker-socket-proxy. Разрешены только нужные разделы Docker API для containers, events, networks, ping и version; POST отключен. Docker discovery в Alloy читает сети каждого контейнера для своих labels; без раздела networks discovery падает с 403, и ни один лог не доходит до Loki. Прокси находится вдвоем с Alloy во внутренней сети `docker-api`, поэтому ни один другой контейнер monitoring или core не может к нему обратиться. Что раздел containers все равно разрешает Alloy: `GET /containers/{id}/json` отдает конфигурацию каждого контейнера хоста, включая `Config.Env` с паролями и ключами сервисов core, а тот же префикс пути разрешает `GET` для `/containers/{id}/logs`, `/containers/{id}/archive` (файлы из контейнера) и `/containers/{id}/export` (вся файловая система контейнера). Поэтому скомпрометированный Alloy может прочитать секреты стенда; сеть не дает сделать то же остальным контейнерам. Флаг `read_only` у монтирования сокета защищает только файл сокета и не ограничивает ни один вызов API. Путь к сокету задается DOCKER_SOCKET_PATH. На rootless Docker он может выглядеть как /run/user/<uid>/docker.sock; указывайте путь, действующий на вашем хосте, не копируйте чужой локальный путь. Прокси ограничивает API, но доступ к Docker socket все равно считайте привилегированным и проверяйте его точную конфигурацию.
|
||||
|
||||
База PostgreSQL создает отдельную роль postgres exporter только при инициализации пустого volume и наличии POSTGRES_EXPORTER_USER и POSTGRES_EXPORTER_PASSWORD. Задайте эти значения до первого make -C deploy up. Установка переменных после создания volume не запускает init script повторно.
|
||||
|
||||
@@ -568,7 +576,7 @@ go.mod объявляет `go 1.26.8` без отдельной строки `to
|
||||
|
||||
Prometheus опрашивает backend /metrics на порту 9090, PostgreSQL exporter, Redis exporter на порту 9121, SeaweedFS на порту 9327, node exporter, себя и необязательный ML target. Loki использует файловое хранилище в single-binary режиме с хранением 168 часов. Grafana загружает datasource Prometheus и Loki из observability/grafana/provisioning/.
|
||||
|
||||
Пять JSON dashboard в репозитории поддерживаются как панели проекта: Go runtime, PostgreSQL, Redis, SeaweedFS и Linux system. Redis dashboard показывает доступность, память, попадания/промахи кеша, вытеснение/истечение ключей и клиентские подключения. Экспортер собирает агрегированные метрики без сканирования ключей. SeaweedFS dashboard показывает доступность, частоту и длительность S3-запросов, ошибки, диск и память; Prometheus сохраняет только выбранные агрегированные метрики без путей объектов. Они не скопированы по Grafana dashboard ID. Для них не заявляется внешнее происхождение или лицензия.
|
||||
Шесть JSON dashboard в репозитории поддерживаются как панели проекта: Go runtime, PostgreSQL, Redis, SeaweedFS, Linux system и Lincodex product (`lincodex-product.json`, описан в разделе [Отдельный monitoring Compose](#отдельный-monitoring-compose)). Prometheus загружает `prometheus/rules/*.yml`; `make -C observability check` проверяет их через `promtool check config` и запускает их unit-тесты из `prometheus/tests/` через `promtool test rules`. Redis dashboard показывает доступность, память, попадания/промахи кеша, вытеснение/истечение ключей и клиентские подключения. Экспортер собирает агрегированные метрики без сканирования ключей. SeaweedFS dashboard показывает доступность, частоту и длительность S3-запросов, ошибки, диск и память; Prometheus сохраняет только выбранные агрегированные метрики без путей объектов. Они не скопированы по Grafana dashboard ID. Для них не заявляется внешнее происхождение или лицензия.
|
||||
|
||||
Локальный стек мониторинга рассчитан на разработку и демонстрацию на одном узле и не обеспечивает HA. Проверка Compose валидирует конфигурацию, но не подтверждает production retention, backup вне узла, контроль публичного доступа, доставку alerts или поведение core приложения.
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ Python-генератор datamodel-code-generator 0.83.0 читает api/ml/op
|
||||
|
||||
Go следует границам domain, usecase, port, adapter и bootstrap. HTTP adapter монтирует generated ogen handler в chi. SQL принадлежит backend/db/queries/, изменения схемы - backend/db/migrations/. sqlc output и wire_gen.go сгенерированы.
|
||||
|
||||
Общие backend параметры находятся в backend/config/. Используются go-logkit 0.6.0 через slog bridge и go-httpkit 0.7.0 для request ID, request logging и panic recovery. Собственный Prometheus middleware сохраняется: он ограничивает method labels и использует chi route patterns; go-httpkit/metrics принимает исходное имя метода как label.
|
||||
Общие backend параметры находятся в backend/config/. Используются go-logkit 0.6.0 через slog bridge и go-httpkit 0.7.0 для request ID и panic recovery. Журнал запросов - собственный `middleware.RequestLog`: logger из go-httpkit пишет исходный путь и каждое значение query вне своего фиксированного списка скрытия, поэтому адрес в пути или query попал бы в журналы. Собственный Prometheus middleware сохраняется: он ограничивает method labels и использует chi route patterns; go-httpkit/metrics принимает исходное имя метода как label.
|
||||
|
||||
Подключение к PostgreSQL создается через pgxpool.NewWithConfig, а generated SELECT 1 readiness query проверяет доступность БД. Pool constructor не должен ждать доступность БД при startup. go-pgkit 1.4.0 не используется: его constructor проверяет подключение и повторяет попытки до возврата pool, что связывало бы запуск сервиса с доступностью БД. Health handlers остаются явными: helper go-httpkit возвращает ok/degraded и детали проверок, а общий контракт использует ok/ready/not_ready. Не добавляйте pgkit, httpkit/metrics, JWT или WebSocket без конкретной потребности и проверки поведения закрепленной версии.
|
||||
|
||||
|
||||
+13
-1
@@ -28,7 +28,9 @@ make test запускает backend, frontend и ML тесты. make check та
|
||||
| make -C deploy check | Рендер Compose конфигураций, `check-workflows`, который падает, если job `aggregate` в workflow не зависит от всех остальных jobs или не имеет `if: always()`, и `check-release`; см. [Тесты манифеста выпуска](#тесты-манифеста-выпуска) |
|
||||
| make -C deploy smoke | Изолированный технический smoke по service health routes |
|
||||
| make -C deploy test-e2e | Браузерный набор Playwright на изолированном одноразовом стеке |
|
||||
| make -C observability check | Проверку Prometheus, Loki, Alloy и dashboard JSON |
|
||||
| make -C deploy release-smoke, release-e2e | Тот же smoke и браузерный набор на образах выпуска; успешный прогон записывает evidence для манифеста выпуска |
|
||||
| make -C observability check | Проверку конфигурации и правил alerts Prometheus с их unit-тестами, Loki, Alloy и dashboard JSON |
|
||||
| make -C observability verify-product-metrics | Изолированные стенды core и monitoring: продуктовые метрики в Prometheus и Grafana, отсутствие fixture адреса в метриках и логах Loki; см. [Тесты продуктовых метрик](#тесты-продуктовых-метрик) |
|
||||
|
||||
make -C deploy test-e2e сейчас запускает технический браузерный набор, а не проверку бизнес-сценариев; см. [Браузерный E2E набор](#браузерный-e2e-набор).
|
||||
|
||||
@@ -220,6 +222,16 @@ Unit-тесты (`make -C backend test`) проверяют runtime задани
|
||||
|
||||
`TestPostgresMigrations` также проверяет, что миграция 00008 создает и удаляет `scheduled_jobs`. Набор использует один PostgreSQL и тестовый вид задания. Он не измеряет пропускную способность, не покрывает расхождение часов между экземплярами, переключение базы данных и продуктовый обработчик и не проверяет доставку alerts.
|
||||
|
||||
## Тесты продуктовых метрик
|
||||
|
||||
Unit-тесты (`make -C backend test`) покрывают продуктовые метрики (TASK-022). В `internal/adapter/primary/http/` запросы через настоящий router и настоящий collector получают шаблон маршрута своей операции (`/api/v1/me/invitations/{invitation_id}`, `/api/v1/me/assessment-attempts/{attempt_id}`) и никогда не получают параметр пути, адрес в пути или query string; неизвестные пути и методы сохраняют `/api/v1/*`, `/api/*` или `unmatched`; ответы problem считаются по коду (`unauthenticated`, `not_found`, `method_not_allowed`, `not_implemented`), а обычный 404 вне `/api` - нет; в выдаче нет значений, похожих на email или UUID; каждый код problem контракта сохраняет свой label. Тест журнала запросов отправляет адрес и UUID в путях и query через тот же router и проверяет, что JSON-журнал называет только шаблоны маршрутов, статусы, коды problem и число параметров query, пропускает `/healthz` и `/readyz` и не содержит ни одного из значений. `internal/adapter/primary/http/middleware/` проверяет middleware журнала и метрик на простом router chi: общий маршрут и код problem, отсутствие problem для ответа, который в итоге успешен, уровень error для 5xx, неизвестный метод в журнале как `OTHER` и collector без учета problem. В `internal/adapter/secondary/prometheus/`: задержка по классу статуса, каждая пара вида и статуса доставки с нулем и сбросом, когда статус опустел, gauges квот без label аккаунта, hook сохранения ответов, который превращает неизвестные значения в `other` и не создает серий до первого вызова, и проверка всей выдачи после вызова каждого hook с fixture email и UUID. `internal/worker/deliverymetrics/` покрывает просрочку самой ранней доставки в `pending` (ноль, пока срок не наступил), текущие окна квоты, неудачное чтение, которое не отменяет второе, и жизненный цикл цикла чтения; `internal/bootstrap/` - пропуск без базы, квоты только для активного транспорта и приложение, которое запускает sampler против недоступной базы и все равно останавливается. `pkg/testutil/` проверяет сам поиск идентификаторов.
|
||||
|
||||
`TestDeliveryStatistics` в `backend/integration_test/delivery_statistics_test.go` проверяет запрос sqlc `GetDeliveryStatistics` на PostgreSQL: пустая таблица, затем доставки трех видов во всех пяти статусах, выставленных в рамках ограничений таблицы, дают точные числа по виду и статусу, а самый ранний срок берется только из доставок, которые еще в `pending`.
|
||||
|
||||
`make -C observability check` проверяет правила alerts через `promtool check config` и запускает `promtool test rules` для `observability/prometheus/tests/lincodex_rules_test.yml`: каждый alert срабатывает в положительном случае (backend недоступен, доля 5xx, отставание outbox, dead letter, застрявший обработчик, мертвые и опаздывающие задания, неизвестный исход доставки, учтенный один раз для двух экземпляров, просроченные доставки, устаревшие gauges почты, исчерпанная квота по счету и по отказу провайдера), а ограничения молчат: тихий трафик только из ошибочных запросов, просроченные доставки без `lincodex_mail_sender_running`, sampler, который продолжает успешно читать, и месячное окно с запасом.
|
||||
|
||||
`make -C observability verify-product-metrics` - сквозная проверка, описанная в [DEPLOY.md](DEPLOY.md#отдельный-monitoring-compose). Ей нужны Docker и свободные host ports 18085 и 13085; она собирает образы core и идет несколько минут. Она отправляет fixture адрес в query через Nginx и в пути напрямую в backend и вызывает по нему нарушение уникальности в PostgreSQL. Она доказывает, что метрики доходят до Prometheus, а запросы продуктового dashboard выполняются в Grafana, что PostgreSQL пишет ошибки кратко и что fixture адреса нет в выдаче метрик, во всех сериях и значениях labels, в federate и в логах Loki сервисов core в этом прогоне. Она не проверяет доставку alerts, production retention, нагрузку и целевую задержку и не отправляет почту.
|
||||
|
||||
## Шардирование интеграционных тестов
|
||||
|
||||
`make -C backend test-int` запускает полный набор через `backend/scripts/run-integration-suite.py`. Runner автоматически обнаруживает все верхнеуровневые `Test*` в `./integration_test/...`, сортирует их по пакету и имени, затем распределяет по шардам по кругу. Каждый тест попадает ровно в один шард вместе со всеми своими подтестами. Изменение набора тестов может изменить распределение; балансировка по длительности пока не используется.
|
||||
|
||||
@@ -7,7 +7,7 @@ PROMETHEUS_IMAGE := prom/prometheus:latest
|
||||
LOKI_IMAGE := grafana/loki:latest
|
||||
ALLOY_FILE := $(ROOT)/observability/alloy/app.alloy
|
||||
|
||||
.PHONY: help fmt fmt-check check
|
||||
.PHONY: help fmt fmt-check check verify-product-metrics
|
||||
|
||||
help: ## Show observability commands
|
||||
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-18s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
|
||||
@@ -22,8 +22,12 @@ fmt-check: ## Check Alloy formatting and dashboard JSON formatting
|
||||
diff -u "$(ALLOY_FILE)" "$$tmp"
|
||||
@python3 -c 'import json, pathlib, sys; bad=[]; root=pathlib.Path("$(ROOT)/observability/grafana/dashboards"); paths=sorted(root.glob("*.json")); [(bad.append(str(p)) if p.read_text() != json.dumps(json.loads(p.read_text()), indent=2) + "\n" else None) for p in paths]; print("dashboard formatting is clean" if not bad else "dashboard JSON formatting differs: " + ", ".join(bad)); sys.exit(bool(bad))'
|
||||
|
||||
check: fmt-check ## Validate Prometheus, Loki, Alloy, and dashboard files
|
||||
check: fmt-check ## Validate Prometheus config and alert rules, Loki, Alloy, and dashboard files
|
||||
$(DOCKER) run --rm --entrypoint /bin/promtool -v "$(ROOT)/observability/prometheus:/etc/prometheus:ro" "$(PROMETHEUS_IMAGE)" check config /etc/prometheus/prometheus.yml
|
||||
$(DOCKER) run --rm --entrypoint /bin/promtool -v "$(ROOT)/observability/prometheus:/etc/prometheus:ro" "$(PROMETHEUS_IMAGE)" test rules /etc/prometheus/tests/lincodex_rules_test.yml
|
||||
$(DOCKER) run --rm -v "$(ROOT)/observability/loki:/etc/loki:ro" "$(LOKI_IMAGE)" -config.file=/etc/loki/loki.yml -verify-config
|
||||
$(DOCKER) run --rm -v "$(ROOT)/observability/alloy:/etc/alloy:ro" "$(ALLOY_IMAGE)" validate /etc/alloy/app.alloy
|
||||
@python3 -c 'import json, pathlib; files=sorted(pathlib.Path("$(ROOT)/observability/grafana/dashboards").glob("*.json")); [json.loads(path.read_text()) for path in files]; assert files, "no Grafana dashboards found"; print(f"validated {len(files)} dashboard JSON file(s)")'
|
||||
|
||||
verify-product-metrics: ## Start isolated core and monitoring stacks, check the product metrics, dashboard, and log privacy, then remove them
|
||||
@bash "$(ROOT)/observability/scripts/verify-product-metrics.sh"
|
||||
@@ -4,10 +4,11 @@
|
||||
|
||||
Configuration for collecting metrics and logs, with dashboards for service health.
|
||||
|
||||
- `prometheus/` configures metric collection and ML targets.
|
||||
- `prometheus/` configures metric collection and ML targets; `prometheus/rules/` holds the alert rules and `prometheus/tests/` their `promtool` unit tests.
|
||||
- `loki/` configures log storage; `alloy/` handles log collection and forwarding.
|
||||
- `grafana/` contains data sources and dashboards for Go, PostgreSQL, Redis, SeaweedFS, and the host.
|
||||
- `grafana/` contains data sources and dashboards for Go, PostgreSQL, Redis, SeaweedFS, the host, and the Lincodex product metrics: API latency and errors, outbox lag, consumers and scheduled jobs, mail deliveries and quota, and assessment answer saves.
|
||||
- `scripts/verify-product-metrics.sh` is the end-to-end check behind `make -C observability verify-product-metrics`.
|
||||
|
||||
From the repository root, `make -C observability check` validates configuration using Docker. Start monitoring separately after the core services with `make -C deploy monitoring-up`; its Compose file lives in `deploy/docker/`.
|
||||
From the repository root, `make -C observability check` validates configuration and runs the alert rule tests using Docker. `make -C observability verify-product-metrics` is an explicit end-to-end check, not part of `check`: it starts two separate throwaway Compose projects, core and monitoring, and checks the product metrics, the dashboard, and that a fixture address reaches neither metrics nor logs. Start monitoring separately after the core services with `make -C deploy monitoring-up`; its Compose file lives in `deploy/docker/`.
|
||||
|
||||
See the [deployment guide](../docs/en/DEPLOY.md).
|
||||
@@ -4,10 +4,11 @@
|
||||
|
||||
Настройки сбора метрик и логов, а также готовые дашборды для технического состояния сервисов.
|
||||
|
||||
- `prometheus/` - сбор метрик и список ML-targets.
|
||||
- `prometheus/` - сбор метрик и список ML-targets; `prometheus/rules/` - правила alerts, `prometheus/tests/` - их unit-тесты для `promtool`.
|
||||
- `loki/` - хранение логов; `alloy/` - их сбор и отправка.
|
||||
- `grafana/` - источники данных и дашборды Go, PostgreSQL, Redis, SeaweedFS и хоста.
|
||||
- `grafana/` - источники данных и дашборды Go, PostgreSQL, Redis, SeaweedFS, хоста и продуктовых метрик Lincodex: задержка и ошибки API, отставание outbox, обработчики и задания по сроку, доставки и квоты почты, сохранение ответов теста.
|
||||
- `scripts/verify-product-metrics.sh` - сквозная проверка за `make -C observability verify-product-metrics`.
|
||||
|
||||
Из корня: `make -C observability check` проверяет конфигурации через Docker. Сам стек запускается отдельно после основных сервисов командой `make -C deploy monitoring-up`; его Compose-файл находится в `deploy/docker/`.
|
||||
Из корня: `make -C observability check` проверяет конфигурации и запускает тесты правил alerts через Docker. `make -C observability verify-product-metrics` - явная сквозная проверка, не входящая в `check`: она поднимает два отдельных одноразовых Compose проекта, core и monitoring, и проверяет продуктовые метрики, dashboard и то, что fixture адрес не попадает ни в метрики, ни в логи. Сам стек запускается отдельно после основных сервисов командой `make -C deploy monitoring-up`; его Compose-файл находится в `deploy/docker/`.
|
||||
|
||||
Подробнее: [развертывание](../docs/ru/DEPLOY.md).
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,6 +2,9 @@ global:
|
||||
scrape_interval: 30s
|
||||
evaluation_interval: 30s
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/*.yml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: prometheus
|
||||
static_configs:
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
# Alert rules for the Lincodex backend product metrics. Prometheus evaluates
|
||||
# them and shows their state on its /alerts page and to Grafana; no
|
||||
# Alertmanager is configured, so nothing is sent to a person yet.
|
||||
#
|
||||
# Gauges that describe database-wide state are reported by every backend
|
||||
# instance with the same value, so the rules aggregate them with max. Labels
|
||||
# stay bounded: route templates, status codes, problem codes, consumer and job
|
||||
# kind names, delivery kind and status, provider, and quota window.
|
||||
groups:
|
||||
- name: lincodex-api
|
||||
rules:
|
||||
- alert: LincodexBackendDown
|
||||
expr: up{job="backend"} == 0
|
||||
for: 2m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: Prometheus cannot scrape the backend metrics endpoint.
|
||||
description: The backend /metrics listener has not answered for 2 minutes; the API may be down as well.
|
||||
|
||||
- alert: LincodexApiHighServerErrorRate
|
||||
# The second condition needs at least 15 requests in 5 minutes, so a
|
||||
# single failure on a quiet stand does not page anyone.
|
||||
expr: |
|
||||
(
|
||||
sum(rate(lincodex_http_requests_total{job="backend",status=~"5.."}[5m]))
|
||||
/ sum(rate(lincodex_http_requests_total{job="backend"}[5m]))
|
||||
> 0.05
|
||||
)
|
||||
and
|
||||
sum(rate(lincodex_http_requests_total{job="backend"}[5m])) > 0.05
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: More than 5% of API requests fail with a server error.
|
||||
description: Check lincodex_http_problems_total by route and code and the backend logs in Loki.
|
||||
|
||||
- name: lincodex-events
|
||||
rules:
|
||||
- alert: LincodexOutboxRelayLagging
|
||||
expr: max(lincodex_outbox_relay_oldest_pending_age_seconds{job="backend"}) > 300
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: The earliest unpublished outbox event is older than 5 minutes.
|
||||
description: The relay does not keep up or cannot publish to Kafka; compare with the published rate of lincodex_outbox_relay_events_total and read the relay warnings.
|
||||
|
||||
- alert: LincodexEventConsumerDeadLetter
|
||||
expr: sum by (consumer) (increase(lincodex_event_consumer_records_total{job="backend",outcome="dead_lettered"}[15m])) > 0
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Consumer {{ $labels.consumer }} dead-lettered an event.
|
||||
description: The record needs an operator; its event ID is in the consumer error log.
|
||||
|
||||
- alert: LincodexEventConsumerStalled
|
||||
expr: sum by (consumer, stage) (increase(lincodex_event_consumer_failures_total{job="backend",stage=~"poll|commit"}[5m])) > 0
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Consumer {{ $labels.consumer }} keeps failing at {{ $labels.stage }}.
|
||||
description: The consumer cannot read Kafka or store its offsets; records wait or will be delivered again.
|
||||
|
||||
- alert: LincodexScheduledJobDead
|
||||
expr: sum by (kind) (increase(lincodex_scheduled_jobs_total{job="backend",outcome="dead"}[15m])) > 0
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: A scheduled job of kind {{ $labels.kind }} is dead.
|
||||
description: The job used up its attempts and needs an operator.
|
||||
|
||||
- alert: LincodexScheduledJobsLagging
|
||||
expr: max(lincodex_scheduled_jobs_oldest_due_age_seconds{job="backend"}) > 600
|
||||
for: 15m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: A due scheduled job has waited for more than 10 minutes.
|
||||
description: No instance claims due jobs; the worker may be disabled, failing, or missing the handler of their kind.
|
||||
|
||||
- name: lincodex-mail
|
||||
rules:
|
||||
- alert: LincodexMailDeliveryUnknownOutcome
|
||||
expr: sum(max by (kind) (lincodex_mail_deliveries{job="backend",status="unknown"})) > 0
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Mail deliveries have an unknown outcome.
|
||||
description: An attempt may have reached the provider without a conclusive answer; a retry needs the same idempotency key, and after the idempotency window an operator decides.
|
||||
|
||||
# Inert until the sending worker exists: TASK-016 must export
|
||||
# lincodex_mail_sender_running (1 while its loop runs) as part of its
|
||||
# definition of done. Without that series the rule matches nothing.
|
||||
- alert: LincodexMailDeliveriesOverdue
|
||||
expr: |
|
||||
max(lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend"}) > 900
|
||||
and on ()
|
||||
max(lincodex_mail_sender_running{job="backend"}) == 1
|
||||
for: 15m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: A pending mail delivery has been due for more than 15 minutes.
|
||||
description: The sending worker runs but does not pick up due deliveries; check its logs and the quota gauges.
|
||||
|
||||
- alert: LincodexMailMetricsStale
|
||||
expr: time() - max(lincodex_mail_metrics_last_success_timestamp_seconds{job="backend"}) > 300
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: The delivery and quota gauges have not been read for more than 5 minutes.
|
||||
description: The delivery metrics sampler cannot read PostgreSQL; the delivery and quota gauges show old values. Read its warnings in the backend logs.
|
||||
|
||||
- alert: LincodexMailQuotaUsedUp
|
||||
expr: |
|
||||
max by (provider, window) (lincodex_mail_quota_used_recipients{job="backend"})
|
||||
>= max by (provider, window) (lincodex_mail_quota_limit_recipients{job="backend"})
|
||||
or
|
||||
max by (provider, window) (lincodex_mail_quota_provider_exhausted{job="backend"}) == 1
|
||||
labels:
|
||||
severity: info
|
||||
annotations:
|
||||
summary: The {{ $labels.window }} mail quota of {{ $labels.provider }} is used up.
|
||||
description: New deliveries wait for the UTC window reset in status waiting_quota; nothing switches the plan or the transport automatically.
|
||||
@@ -0,0 +1,243 @@
|
||||
# Unit tests for rules/lincodex.yml; run with `make -C observability check`.
|
||||
# Every alert has a firing case; guarded alerts also have a silent one.
|
||||
rule_files:
|
||||
- ../rules/lincodex.yml
|
||||
evaluation_interval: 1m
|
||||
tests:
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_outbox_relay_oldest_pending_age_seconds{job="backend",instance="a"}
|
||||
values: 400x20
|
||||
- series: lincodex_outbox_relay_oldest_pending_age_seconds{job="backend",instance="b"}
|
||||
values: '0x20'
|
||||
alert_rule_test:
|
||||
- eval_time: 5m
|
||||
alertname: LincodexOutboxRelayLagging
|
||||
exp_alerts: []
|
||||
- eval_time: 15m
|
||||
alertname: LincodexOutboxRelayLagging
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: The earliest unpublished outbox event is older than 5 minutes.
|
||||
description: The relay does not keep up or cannot publish to Kafka; compare with the published rate of lincodex_outbox_relay_events_total and read the relay warnings.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: up{job="backend",instance="backend:9090"}
|
||||
values: 1 1 0 0 0 0 0
|
||||
alert_rule_test:
|
||||
- eval_time: 3m
|
||||
alertname: LincodexBackendDown
|
||||
exp_alerts: []
|
||||
- eval_time: 5m
|
||||
alertname: LincodexBackendDown
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: critical
|
||||
instance: backend:9090
|
||||
job: backend
|
||||
exp_annotations:
|
||||
summary: Prometheus cannot scrape the backend metrics endpoint.
|
||||
description: The backend /metrics listener has not answered for 2 minutes; the API may be down as well.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_event_consumer_records_total{job="backend",consumer="mail_delivery",outcome="dead_lettered"}
|
||||
values: 0 0 0 1 1 1
|
||||
- series: lincodex_event_consumer_failures_total{job="backend",consumer="mail_delivery",stage="poll"}
|
||||
values: 0+1x20
|
||||
- series: lincodex_event_consumer_failures_total{job="backend",consumer="mail_delivery",stage="handler"}
|
||||
values: 0+1x20
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: LincodexEventConsumerDeadLetter
|
||||
exp_alerts: []
|
||||
- eval_time: 5m
|
||||
alertname: LincodexEventConsumerDeadLetter
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
consumer: mail_delivery
|
||||
exp_annotations:
|
||||
summary: Consumer mail_delivery dead-lettered an event.
|
||||
description: The record needs an operator; its event ID is in the consumer error log.
|
||||
- eval_time: 5m
|
||||
alertname: LincodexEventConsumerStalled
|
||||
exp_alerts: []
|
||||
- eval_time: 16m
|
||||
alertname: LincodexEventConsumerStalled
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
consumer: mail_delivery
|
||||
stage: poll
|
||||
exp_annotations:
|
||||
summary: Consumer mail_delivery keeps failing at poll.
|
||||
description: The consumer cannot read Kafka or store its offsets; records wait or will be delivered again.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_scheduled_jobs_total{job="backend",kind="invitation.response_deadline",outcome="dead"}
|
||||
values: 0 0 1 1 1
|
||||
- series: lincodex_scheduled_jobs_oldest_due_age_seconds{job="backend",instance="a"}
|
||||
values: 700x30
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: LincodexScheduledJobDead
|
||||
exp_alerts: []
|
||||
- eval_time: 4m
|
||||
alertname: LincodexScheduledJobDead
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
kind: invitation.response_deadline
|
||||
exp_annotations:
|
||||
summary: A scheduled job of kind invitation.response_deadline is dead.
|
||||
description: The job used up its attempts and needs an operator.
|
||||
- eval_time: 10m
|
||||
alertname: LincodexScheduledJobsLagging
|
||||
exp_alerts: []
|
||||
- eval_time: 20m
|
||||
alertname: LincodexScheduledJobsLagging
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: A due scheduled job has waited for more than 10 minutes.
|
||||
description: No instance claims due jobs; the worker may be disabled, failing, or missing the handler of their kind.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_http_requests_total{job="backend",method="GET",route="/api/v1/healthz",status="200"}
|
||||
values: 0+10x20
|
||||
- series: lincodex_http_requests_total{job="backend",method="GET",route="/api/v1/healthz",status="500"}
|
||||
values: 0+5x20
|
||||
alert_rule_test:
|
||||
- eval_time: 20m
|
||||
alertname: LincodexApiHighServerErrorRate
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: More than 5% of API requests fail with a server error.
|
||||
description: Check lincodex_http_problems_total by route and code and the backend logs in Loki.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_http_requests_total{job="backend",method="GET",route="/api/v1/healthz",status="200"}
|
||||
values: '0x20'
|
||||
- series: lincodex_http_requests_total{job="backend",method="GET",route="/api/v1/healthz",status="500"}
|
||||
values: 0+1x20
|
||||
alert_rule_test:
|
||||
- eval_time: 8m
|
||||
alertname: LincodexApiHighServerErrorRate
|
||||
exp_alerts: []
|
||||
- eval_time: 15m
|
||||
alertname: LincodexApiHighServerErrorRate
|
||||
exp_alerts: []
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_mail_deliveries{job="backend",instance="a",kind="verification",status="unknown"}
|
||||
values: 1x10
|
||||
- series: lincodex_mail_deliveries{job="backend",instance="b",kind="verification",status="unknown"}
|
||||
values: 1x10
|
||||
- series: lincodex_mail_quota_used_recipients{job="backend",instance="a",provider="resend",window="day"}
|
||||
values: 100x10
|
||||
- series: lincodex_mail_quota_limit_recipients{job="backend",instance="a",provider="resend",window="day"}
|
||||
values: 100x10
|
||||
- series: lincodex_mail_quota_provider_exhausted{job="backend",instance="a",provider="resend",window="day"}
|
||||
values: '0x10'
|
||||
- series: lincodex_mail_quota_used_recipients{job="backend",instance="a",provider="resend",window="month"}
|
||||
values: 120x10
|
||||
- series: lincodex_mail_quota_limit_recipients{job="backend",instance="a",provider="resend",window="month"}
|
||||
values: 3000x10
|
||||
- series: lincodex_mail_quota_provider_exhausted{job="backend",instance="a",provider="resend",window="month"}
|
||||
values: '0x10'
|
||||
alert_rule_test:
|
||||
- eval_time: 10m
|
||||
alertname: LincodexMailDeliveryUnknownOutcome
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: Mail deliveries have an unknown outcome.
|
||||
description: An attempt may have reached the provider without a conclusive answer; a retry needs the same idempotency key, and after the idempotency window an operator decides.
|
||||
- eval_time: 10m
|
||||
alertname: LincodexMailQuotaUsedUp
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: info
|
||||
provider: resend
|
||||
window: day
|
||||
exp_annotations:
|
||||
summary: The day mail quota of resend is used up.
|
||||
description: New deliveries wait for the UTC window reset in status waiting_quota; nothing switches the plan or the transport automatically.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_mail_quota_used_recipients{job="backend",instance="a",provider="resend",window="month"}
|
||||
values: 120x10
|
||||
- series: lincodex_mail_quota_limit_recipients{job="backend",instance="a",provider="resend",window="month"}
|
||||
values: 3000x10
|
||||
- series: lincodex_mail_quota_provider_exhausted{job="backend",instance="a",provider="resend",window="month"}
|
||||
values: 0 0 0 0 0 1 1 1 1 1
|
||||
alert_rule_test:
|
||||
- eval_time: 3m
|
||||
alertname: LincodexMailQuotaUsedUp
|
||||
exp_alerts: []
|
||||
- eval_time: 7m
|
||||
alertname: LincodexMailQuotaUsedUp
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: info
|
||||
provider: resend
|
||||
window: month
|
||||
exp_annotations:
|
||||
summary: The month mail quota of resend is used up.
|
||||
description: New deliveries wait for the UTC window reset in status waiting_quota; nothing switches the plan or the transport automatically.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend",instance="a"}
|
||||
values: 2000x40
|
||||
alert_rule_test:
|
||||
- eval_time: 30m
|
||||
alertname: LincodexMailDeliveriesOverdue
|
||||
exp_alerts: []
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_mail_delivery_oldest_due_pending_age_seconds{job="backend",instance="a"}
|
||||
values: 2000x40
|
||||
- series: lincodex_mail_sender_running{job="backend",instance="a"}
|
||||
values: 1x40
|
||||
alert_rule_test:
|
||||
- eval_time: 10m
|
||||
alertname: LincodexMailDeliveriesOverdue
|
||||
exp_alerts: []
|
||||
- eval_time: 20m
|
||||
alertname: LincodexMailDeliveriesOverdue
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: A pending mail delivery has been due for more than 15 minutes.
|
||||
description: The sending worker runs but does not pick up due deliveries; check its logs and the quota gauges.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_mail_metrics_last_success_timestamp_seconds{job="backend",instance="a"}
|
||||
values: '0x20'
|
||||
alert_rule_test:
|
||||
- eval_time: 5m
|
||||
alertname: LincodexMailMetricsStale
|
||||
exp_alerts: []
|
||||
- eval_time: 12m
|
||||
alertname: LincodexMailMetricsStale
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: The delivery and quota gauges have not been read for more than 5 minutes.
|
||||
description: The delivery metrics sampler cannot read PostgreSQL; the delivery and quota gauges show old values. Read its warnings in the backend logs.
|
||||
- interval: 1m
|
||||
input_series:
|
||||
- series: lincodex_mail_metrics_last_success_timestamp_seconds{job="backend",instance="a"}
|
||||
values: 0+60x20
|
||||
alert_rule_test:
|
||||
- eval_time: 15m
|
||||
alertname: LincodexMailMetricsStale
|
||||
exp_alerts: []
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
#!/usr/bin/env bash
|
||||
# Starts an isolated core stack and, as a separate Compose project, the
|
||||
# monitoring stack; sends a successful and failing API requests and a fixture
|
||||
# mail delivery through the outbox, the relay, and the delivery consumer;
|
||||
# checks the product metrics in Prometheus and the product dashboard through
|
||||
# Grafana; and confirms that the fixture address appears in neither the
|
||||
# metrics nor the logs in Loki. Everything it creates is removed on exit.
|
||||
#
|
||||
# Mail: EMAIL_PROVIDER=resend with a placeholder key, so the quota gauges
|
||||
# exist. Nothing sends mail in this build: the sending worker is planned
|
||||
# (TASK-016), and the stored delivery stays pending.
|
||||
set -euo pipefail
|
||||
|
||||
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
core_file="$root/deploy/docker/docker-compose.yml"
|
||||
monitoring_file="$root/deploy/docker/docker-compose.monitoring.yml"
|
||||
env_file="$root/.env.example"
|
||||
project=lincodex-metrics-check
|
||||
monitoring_project=lincodex-metrics-check-monitoring
|
||||
app_network="${project}_default"
|
||||
storage_network="${project}_storage"
|
||||
port="${METRICS_CHECK_HTTP_PORT:-18085}"
|
||||
grafana_port="${METRICS_CHECK_GRAFANA_PORT:-13085}"
|
||||
grafana="http://127.0.0.1:$grafana_port"
|
||||
# Example-config credentials of the throwaway Grafana.
|
||||
grafana_auth="admin:replace-this-grafana-password"
|
||||
fixture_email="Metrics.Check.Fixture@example.com"
|
||||
fixture_email_lower=$(printf '%s' "$fixture_email" | tr '[:upper:]' '[:lower:]')
|
||||
evidence_dir="${METRICS_CHECK_EVIDENCE_DIR:-$(mktemp -d)}"
|
||||
core_started=0
|
||||
monitoring_started=0
|
||||
|
||||
core() {
|
||||
APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \
|
||||
APP_PUBLIC_URL="http://localhost:$port" EMAIL_PROVIDER=resend RESEND_API_KEY=re_placeholder_not_a_key \
|
||||
EMAIL_ACCOUNT=metrics-check docker compose --env-file "$env_file" -p "$project" -f "$core_file" "$@"
|
||||
}
|
||||
|
||||
monitoring() {
|
||||
APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" GRAFANA_PORT="$grafana_port" \
|
||||
docker compose --env-file "$env_file" -p "$monitoring_project" -f "$monitoring_file" "$@"
|
||||
}
|
||||
|
||||
fail() {
|
||||
printf 'FAIL: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
for volume in "${project}_postgres_data" "${project}_seaweedfs_data" "${project}_kafka_data" \
|
||||
"${monitoring_project}_prometheus_data" "${monitoring_project}_loki_data" "${monitoring_project}_grafana_data"; do
|
||||
if docker volume inspect "$volume" >/dev/null 2>&1; then
|
||||
fail "refusing to use the existing volume $volume"
|
||||
fi
|
||||
done
|
||||
for existing in "$app_network" "$storage_network" "${monitoring_project}_observability"; do
|
||||
if docker network inspect "$existing" >/dev/null 2>&1; then
|
||||
fail "refusing to use the existing network $existing"
|
||||
fi
|
||||
done
|
||||
|
||||
cleanup() {
|
||||
local result=$?
|
||||
trap - EXIT
|
||||
if (( result != 0 )) && [[ "${METRICS_CHECK_KEEP_ON_FAILURE:-}" == 1 ]]; then
|
||||
printf 'Kept projects %s and %s for inspection; remove them with docker compose down --volumes.\n' "$project" "$monitoring_project" >&2
|
||||
exit "$result"
|
||||
fi
|
||||
if (( monitoring_started )); then
|
||||
monitoring down --volumes --remove-orphans || result=1
|
||||
fi
|
||||
if (( core_started )); then
|
||||
core down --volumes --remove-orphans --rmi local || result=1
|
||||
fi
|
||||
printf 'Evidence kept in %s\n' "$evidence_dir"
|
||||
exit "$result"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
core config --quiet
|
||||
monitoring config --quiet
|
||||
core_started=1
|
||||
core up --build -d --wait --wait-timeout 180
|
||||
monitoring_started=1
|
||||
# node-exporter is left out: it reads host metrics only, and its rslave
|
||||
# root mount fails on Docker Desktop. Every service that the product metrics,
|
||||
# the dashboard, and the log path need is started.
|
||||
monitoring up -d prometheus-targets prometheus postgres-exporter redis-exporter loki alloy docker-socket-proxy grafana
|
||||
|
||||
wait_for() {
|
||||
local description=$1
|
||||
shift
|
||||
local attempt
|
||||
for attempt in $(seq 1 90); do
|
||||
if "$@" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
fail "timed out waiting for $description"
|
||||
}
|
||||
|
||||
wait_for "the API" curl --fail --silent "http://127.0.0.1:$port/api/v1/healthz"
|
||||
wait_for "Grafana" curl --fail --silent "$grafana/api/health"
|
||||
|
||||
# Requests: one success, one unknown route, one operation that requires a
|
||||
# session, one unsupported method, and an operation with a path parameter.
|
||||
attempt_id=0199b4f2-7c1e-7d3a-9f00-aabbccddeeff
|
||||
expect_status() {
|
||||
local method=$1 path=$2 want=$3 got
|
||||
got=$(curl --silent --output /dev/null --write-out '%{http_code}' -X "$method" "http://127.0.0.1:$port$path")
|
||||
[[ "$got" == "$want" ]] || fail "$method $path returned $got, want $want"
|
||||
printf '%s %s -> %s\n' "$method" "$path" "$got"
|
||||
}
|
||||
expect_status GET /api/v1/healthz 200
|
||||
expect_status GET /api/v1/missing 404
|
||||
expect_status GET /api/v1/identity/me 401
|
||||
expect_status POST /api/v1/healthz 405
|
||||
expect_status GET "/api/v1/me/assessment-attempts/$attempt_id" 401
|
||||
# Requests that carry the fixture address. The query goes through Nginx,
|
||||
# which logs the path without the query. No API path holds an address, and
|
||||
# Nginx would log one verbatim, so the path request goes straight to the
|
||||
# backend from inside the core network; it stands for any client-made path.
|
||||
query_request_id=$(curl --silent --output /dev/null --dump-header - \
|
||||
"http://127.0.0.1:$port/api/v1/healthz?email=$fixture_email" | tr -d '\r' | sed -n 's/^[Xx]-[Rr]equest-[Ii][Dd]: //p')
|
||||
[[ -n "$query_request_id" ]] || fail "the API returned no request ID"
|
||||
printf 'GET /api/v1/healthz?email=<fixture> -> request %s\n' "$query_request_id"
|
||||
path_request_id=metrics-check-path-$(date +%s)
|
||||
core exec -T frontend wget -q -O /dev/null --header "X-Request-ID: $path_request_id" \
|
||||
"http://backend:8080/api/v1/users/$fixture_email" >/dev/null 2>&1 || true
|
||||
printf 'GET backend:/api/v1/users/<fixture> -> request %s\n' "$path_request_id"
|
||||
|
||||
# The fixture delivery: a verified account, a mail request, and the outbox
|
||||
# event that announces it, written in one transaction like MailRequester
|
||||
# does. The relay publishes the event and the notification_delivery consumer
|
||||
# stores the delivery.
|
||||
user_id=$(python3 -c 'import uuid; print(uuid.uuid4())')
|
||||
request_id=$(python3 -c 'import uuid; print(uuid.uuid4())')
|
||||
event_id=$(python3 -c 'import uuid; print(uuid.uuid4())')
|
||||
psql() {
|
||||
core exec -T postgres sh -ec 'psql -v ON_ERROR_STOP=1 -At -U "$POSTGRES_USER" -d "$POSTGRES_DB"' "$@"
|
||||
}
|
||||
psql <<SQL
|
||||
BEGIN;
|
||||
INSERT INTO users (id, email, email_normalized, password_hash, scenario, onboarding_step, email_verified_at,
|
||||
registration_version, last_registered_at, version, created_at, updated_at)
|
||||
VALUES ('$user_id', '$fixture_email', '$fixture_email_lower',
|
||||
'\$argon2id\$v=19\$m=19456,t=2,p=1\$c2FsdHNhbHRzYWx0\$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA',
|
||||
'candidate', 'candidate_consents', now(), 1, now(), 1, now(), now());
|
||||
INSERT INTO mail_requests (id, recipient_user_id, kind, subject, body, link_path, created_at)
|
||||
VALUES ('$request_id', '$user_id', 'notification', 'Metrics check', 'Metrics check fixture body.', '/candidate/invitations', now());
|
||||
INSERT INTO outbox_events (event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload)
|
||||
VALUES ('$event_id', 'notification.mail_requested', 1, 'mail_request', '$request_id', 1,
|
||||
jsonb_build_object('mail_request_id', '$request_id', 'kind', 'notification'));
|
||||
COMMIT;
|
||||
SQL
|
||||
# PostgreSQL logs errors tersely, so the DETAIL of a unique violation, which
|
||||
# quotes the key, never reaches the container log. The duplicate account is
|
||||
# sent with bound parameters, like the backend does, so the statement text in
|
||||
# the log holds only placeholders.
|
||||
[[ "$(printf 'SHOW log_error_verbosity' | psql)" == terse ]] || fail "PostgreSQL does not log errors tersely"
|
||||
printf '%s\n' "INSERT INTO users (id, email, email_normalized, password_hash, scenario, onboarding_step, registration_version, last_registered_at, version, created_at, updated_at) SELECT gen_random_uuid(), \$1, \$2, password_hash, scenario, onboarding_step, 1, now(), 1, now(), now() FROM users LIMIT 1 \\bind '$fixture_email' '$fixture_email_lower' \\g" |
|
||||
psql >/dev/null 2>&1 && fail "the duplicate account was accepted"
|
||||
postgres_logs=$(core logs --no-color postgres)
|
||||
[[ "$postgres_logs" == *"duplicate key value violates unique constraint"* ]] || fail "PostgreSQL did not log the unique violation"
|
||||
if grep -qiF "$fixture_email_lower" <<<"$postgres_logs"; then
|
||||
fail "the PostgreSQL log quotes the fixture address"
|
||||
fi
|
||||
printf '%s\n' 'PostgreSQL logged the unique violation without its key value'
|
||||
delivery_stored() {
|
||||
[[ "$(printf "SELECT status FROM deliveries WHERE id = '%s'" "$request_id" | psql)" == pending ]]
|
||||
}
|
||||
wait_for "the fixture delivery" delivery_stored
|
||||
printf 'Fixture delivery %s stored as pending\n' "$request_id"
|
||||
stored_address=$(printf "SELECT count(*) FROM deliveries WHERE id = '%s' AND recipient_email = '%s'" "$request_id" "$fixture_email" | psql)
|
||||
[[ "$stored_address" == 1 ]] || fail "the fixture delivery does not hold the fixture address"
|
||||
|
||||
# Prometheus through the Grafana datasource proxy.
|
||||
prometheus_get() {
|
||||
curl --fail --silent --show-error -u "$grafana_auth" -G "$grafana/api/datasources/proxy/uid/prometheus$1" "${@:2}"
|
||||
}
|
||||
query_value() {
|
||||
prometheus_get /api/v1/query --data-urlencode "query=$1" |
|
||||
python3 -c 'import json, sys; result = json.load(sys.stdin)["data"]["result"]; print(sum(float(item["value"][1]) for item in result) if result else "none")'
|
||||
}
|
||||
expect_at_least() {
|
||||
local query=$1 minimum=$2 value
|
||||
value=$(query_value "$query")
|
||||
[[ "$value" != none ]] && python3 -c "import sys; sys.exit(0 if float('$value') >= $minimum else 1)" ||
|
||||
fail "$query = $value, want at least $minimum"
|
||||
printf '%s = %s\n' "$query" "$value"
|
||||
}
|
||||
delivery_scraped() {
|
||||
[[ "$(query_value 'max(lincodex_mail_deliveries{job="backend",kind="notification",status="pending"})')" == 1.0 ]]
|
||||
}
|
||||
wait_for "the delivery gauge in Prometheus" delivery_scraped
|
||||
{
|
||||
expect_at_least 'sum(lincodex_http_requests_total{job="backend",route="/api/v1/healthz",status="200"})' 1
|
||||
expect_at_least 'sum(lincodex_http_requests_total{job="backend",route="/api/v1/*",status="404"})' 1
|
||||
expect_at_least 'sum(lincodex_http_requests_total{job="backend",route="/api/v1/me/assessment-attempts/{attempt_id}",status="401"})' 1
|
||||
expect_at_least 'sum(lincodex_http_problems_total{job="backend",code="unauthenticated"})' 2
|
||||
expect_at_least 'sum(lincodex_http_problems_total{job="backend",code="not_found",route="/api/v1/*"})' 1
|
||||
expect_at_least 'sum(lincodex_http_problems_total{job="backend",code="method_not_allowed"})' 1
|
||||
expect_at_least 'sum(lincodex_http_request_duration_seconds_count{job="backend",status_class="2xx"})' 1
|
||||
expect_at_least 'sum(lincodex_outbox_relay_events_total{job="backend",outcome="published"})' 1
|
||||
expect_at_least 'count(lincodex_outbox_relay_oldest_pending_age_seconds{job="backend"})' 1
|
||||
expect_at_least 'sum(lincodex_event_consumer_records_total{job="backend",consumer="notification_delivery",outcome="applied"})' 1
|
||||
expect_at_least 'max(lincodex_mail_deliveries{job="backend",kind="notification",status="pending"})' 1
|
||||
expect_at_least 'count(lincodex_mail_deliveries{job="backend"})' 15
|
||||
expect_at_least 'max(lincodex_mail_quota_limit_recipients{job="backend",provider="resend",window="day"})' 100
|
||||
expect_at_least 'count(lincodex_mail_quota_used_recipients{job="backend"})' 2
|
||||
} | tee "$evidence_dir/prometheus-values.txt"
|
||||
prometheus_get /api/v1/rules >"$evidence_dir/rules.json"
|
||||
grep -q LincodexOutboxRelayLagging "$evidence_dir/rules.json" || fail "Prometheus did not load the alert rules"
|
||||
|
||||
# The dashboard: provisioned, and every panel query is accepted by
|
||||
# Prometheus.
|
||||
curl --fail --silent --show-error -u "$grafana_auth" "$grafana/api/dashboards/uid/lincodex-product" >"$evidence_dir/dashboard.json"
|
||||
python3 - "$evidence_dir/dashboard.json" <<'PY' >"$evidence_dir/panel-queries.txt"
|
||||
import json, sys
|
||||
dashboard = json.load(open(sys.argv[1]))["dashboard"]
|
||||
for panel in dashboard["panels"]:
|
||||
for target in panel.get("targets", []):
|
||||
print(panel["title"] + "\t" + target["expr"])
|
||||
PY
|
||||
panels=0
|
||||
while IFS=$'\t' read -r title expr; do
|
||||
status=$(prometheus_get /api/v1/query --data-urlencode "query=$expr" | python3 -c 'import json, sys; data = json.load(sys.stdin); print(data["status"], len(data["data"]["result"]))')
|
||||
[[ "$status" == success* ]] || fail "panel $title query failed: $status"
|
||||
printf '%s\t%s\n' "$title" "$status" >>"$evidence_dir/panel-results.txt"
|
||||
panels=$((panels + 1))
|
||||
done <"$evidence_dir/panel-queries.txt"
|
||||
printf 'Dashboard lincodex-product: %d panel queries accepted\n' "$panels"
|
||||
cat "$evidence_dir/panel-results.txt"
|
||||
|
||||
# Privacy: the whole metric exposition of the backend, every series and
|
||||
# label value in Prometheus, and the federated sample values must not hold
|
||||
# the fixture address, and the logs in Loki must not either.
|
||||
core exec -T frontend wget -q -O - http://backend:9090/metrics >"$evidence_dir/backend-metrics.txt"
|
||||
prometheus_get /api/v1/series --data-urlencode 'match[]={job=~".+"}' >"$evidence_dir/series.json"
|
||||
monitoring exec -T prometheus wget -q -O - 'http://localhost:9090/federate?match[]=%7Bjob%3D~%22.%2B%22%7D' >"$evidence_dir/federate.txt"
|
||||
: >"$evidence_dir/label-values.txt"
|
||||
for label in $(prometheus_get /api/v1/labels | python3 -c 'import json, sys; print("\n".join(json.load(sys.stdin)["data"]))'); do
|
||||
prometheus_get "/api/v1/label/$label/values" >>"$evidence_dir/label-values.txt"
|
||||
done
|
||||
now=$(date +%s)
|
||||
loki_get() {
|
||||
curl --fail --silent --show-error -u "$grafana_auth" -G "$grafana/api/datasources/proxy/uid/loki/loki/api/v1/query_range" \
|
||||
--data-urlencode "query=$1" --data-urlencode "start=$(((now - 3600) * 1000000000))" \
|
||||
--data-urlencode "end=$(((now + 60) * 1000000000))" --data-urlencode limit=5000
|
||||
}
|
||||
logs_collected() {
|
||||
local request_id
|
||||
for request_id in "$query_request_id" "$path_request_id"; do
|
||||
loki_get "{service=\"backend\"} |= \"$request_id\"" | grep -qF "$request_id" || return 1
|
||||
done
|
||||
}
|
||||
# The backend logged both requests that carried the fixture address; seeing
|
||||
# them proves that this run's logs reached Loki, so the absence check below
|
||||
# is not vacuous.
|
||||
wait_for "the backend request logs in Loki" logs_collected
|
||||
loki_get '{service=~".+"}' >"$evidence_dir/loki.json"
|
||||
log_lines=$(python3 -c 'import json, sys; print(sum(len(s["values"]) for s in json.load(open(sys.argv[1]))["data"]["result"]))' "$evidence_dir/loki.json")
|
||||
printf 'Loki returned %s log lines of the core services\n' "$log_lines"
|
||||
for file in backend-metrics.txt series.json federate.txt label-values.txt loki.json; do
|
||||
if grep -qiF "$fixture_email" "$evidence_dir/$file"; then
|
||||
fail "$file contains the fixture address"
|
||||
fi
|
||||
if grep -qF "$user_id" "$evidence_dir/$file" && [[ "$file" != loki.json ]]; then
|
||||
fail "$file contains the fixture user ID"
|
||||
fi
|
||||
printf 'No fixture address in %s (%s bytes)\n' "$file" "$(wc -c <"$evidence_dir/$file" | tr -d ' ')"
|
||||
done
|
||||
if grep -qF "$attempt_id" "$evidence_dir/backend-metrics.txt" "$evidence_dir/label-values.txt"; then
|
||||
fail "a path parameter reached the metric labels"
|
||||
fi
|
||||
printf '%s\n' 'Product metrics check passed.'
|
||||
Reference in new issue
Block a user