refactor(server): audit.WriteOrLog wrapper; migrate 13 sites (T5)

Add audit.WriteOrLog: a one-line wrapper around Write that logs at
Warn and swallows the error, matching the package contract that
audit failures must not break user-facing operations.

Migrate the 13 call sites across 7 files in internal/api/ from the
3-line "if err != nil { logger.Warn(...) }" shape to a single call.
audit.Write stays exported for tests + any future caller that
needs strict semantics.

Adds three tests: success (no log), failure-via-closed-pool (Warn
record with action+err keys), and nil-logger (no panic). Tests
skip when MINSTREL_TEST_DATABASE_URL is unset, matching the
existing harness convention.
This commit is contained in:
2026-05-07 21:33:14 -04:00
parent 49218e5231
commit 965df28127
9 changed files with 103 additions and 46 deletions
+13
View File
@@ -12,6 +12,7 @@ package audit
import (
"context"
"encoding/json"
"log/slog"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
@@ -75,3 +76,15 @@ func Write(ctx context.Context, pool *pgxpool.Pool, actorID, targetID pgtype.UUI
Metadata: jsonMeta,
})
}
// WriteOrLog writes the audit row; on error, logs at Warn and swallows
// (audit failures must not break user-facing operations — see package doc).
// Use this when the audit is observability, not gating; use Write directly
// when the caller needs strict semantics (e.g. tests).
func WriteOrLog(ctx context.Context, pool *pgxpool.Pool, logger *slog.Logger, actorID, targetID pgtype.UUID, action Action, metadata map[string]any) {
if err := Write(ctx, pool, actorID, targetID, action, metadata); err != nil {
if logger != nil {
logger.Warn("audit failed", "action", string(action), "err", err)
}
}
}