docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
@@ -1,55 +0,0 @@
import { describe, it, expect } from 'vitest'
import { isClientDisconnectError } from '../is-client-disconnect'
describe('isClientDisconnectError', () => {
it('matches React\'s cancel error for a stream the client closed', () => {
expect(isClientDisconnectError(new Error('The destination stream closed early.'))).toBe(true)
})
it('matches the sibling cancel error React raises on a write failure', () => {
expect(
isClientDisconnectError(new Error('The destination stream errored while writing data.')),
).toBe(true)
})
it('matches Next\'s own ResponseAborted error by name', () => {
const aborted = Object.assign(new Error('The response was aborted'), {
name: 'ResponseAborted',
})
expect(isClientDisconnectError(aborted)).toBe(true)
})
it('does not match an ordinary error', () => {
expect(isClientDisconnectError(new Error('boom'))).toBe(false)
expect(isClientDisconnectError(new TypeError('fetch failed'))).toBe(false)
})
it('does not match a real provider timeout or socket reset', () => {
// AbortSignal.timeout throws this shape all over lib/providers; treating
// it as a client disconnect would hide genuine integration failures.
expect(isClientDisconnectError(new DOMException('Aborted', 'AbortError'))).toBe(false)
expect(
isClientDisconnectError(Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' })),
).toBe(false)
expect(
isClientDisconnectError(
Object.assign(new Error('Premature close'), { code: 'ERR_STREAM_PREMATURE_CLOSE' }),
),
).toBe(false)
})
it('matches the message exactly, so a real error cannot hide behind the phrase', () => {
expect(
isClientDisconnectError(
new Error('Supabase query failed: The destination stream closed early.'),
),
).toBe(false)
})
it('is false for anything that is not an error object', () => {
expect(isClientDisconnectError(null)).toBe(false)
expect(isClientDisconnectError(undefined)).toBe(false)
expect(isClientDisconnectError('The destination stream closed early.')).toBe(false)
expect(isClientDisconnectError(42)).toBe(false)
})
})
-103
View File
@@ -1,103 +0,0 @@
/**
* The redaction primitives themselves.
*
* sink.test.ts and lib/__tests__/logger-sink.test.ts cover redaction on the
* way INTO the sink; this file locks in the primitive's own contract: which
* shapes are scrubbed, that scrubbing is idempotent, and that serialized
* errors keep a (redacted) stack in every environment: the sink only runs in
* production, and a stackless event is useless to group on.
*/
import { describe, it, expect, afterEach, vi } from 'vitest'
import { redact, redactString, REDACTED } from '../redact'
afterEach(() => {
vi.unstubAllEnvs()
})
describe('redactString', () => {
it('replaces the WHOLE string when a personnummer appears', () => {
expect(redactString('payment for 800101-1234 failed')).toBe(REDACTED)
expect(redactString('customer 19800101-1234')).toBe(REDACTED)
})
it('preserves UUIDs', () => {
const s = 'company 57484518-3409-4b29-9d23-5d22f08bda63 ok'
expect(redactString(s)).toBe(s)
})
it('scrubs gnubok API keys in place, keeping the rest of the line', () => {
expect(redactString('auth failed for key gnubok_sk_live_abc123 on /v1')).toBe(
'auth failed for key [REDACTED_API_KEY] on /v1',
)
expect(redactString('invite gnubok_inv_XyZ_9 expired')).toBe(
'invite [REDACTED_API_KEY] expired',
)
})
it('scrubs Swedish IBANs, compact and space-grouped', () => {
expect(redactString('payout to SE4550000000058398257466 bounced')).toBe(
'payout to [REDACTED_IBAN] bounced',
)
expect(redactString('iban SE45 5000 0000 0583 9825 7466 rejected')).toBe(
'iban [REDACTED_IBAN] rejected',
)
})
it('scrubs email addresses in place', () => {
expect(redactString('reminder sent to [email protected] just now')).toBe(
'reminder sent to [REDACTED_EMAIL] just now',
)
})
it('does not mistake package specs for emails', () => {
const s = 'installing @anthropic-ai/[email protected]'
expect(redactString(s)).toBe(s)
})
it('scrubs several kinds of secret in one string', () => {
expect(
redactString('key gnubok_sk_live_secret1 for [email protected] on SE4550000000058398257466'),
).toBe('key [REDACTED_API_KEY] for [REDACTED_EMAIL] on [REDACTED_IBAN]')
})
it('is idempotent: a second pass changes nothing', () => {
const inputs = [
'key gnubok_sk_live_secret1 for [email protected] on SE4550000000058398257466',
'payment for 800101-1234 failed',
'plain harmless message',
]
for (const input of inputs) {
const once = redactString(input)
expect(redactString(once)).toBe(once)
}
})
})
describe('redact() on Error instances', () => {
it('keeps a stack on the serialized error in production', () => {
vi.stubEnv('NODE_ENV', 'production')
const err = new Error('clean failure')
const out = redact(err) as { name: string; message: string; stack?: string }
expect(out.name).toBe('Error')
expect(out.message).toBe('clean failure')
expect(typeof out.stack).toBe('string')
expect(out.stack).toContain('clean failure')
})
it('redacts the stack like any other string', () => {
// The first stack line carries the message, so a personnummer in the
// message means the whole stack is nuked (whole-string personnummer rule).
const pii = new Error('no match for 800101-1234')
const outPii = redact(pii) as { message: string; stack?: string }
expect(outPii.message).toBe(REDACTED)
expect(outPii.stack).toBe(REDACTED)
// Substring secrets are scrubbed in place: the frames stay readable.
const keyErr = new Error('bad key gnubok_sk_live_abc')
const outKey = redact(keyErr) as { message: string; stack?: string }
expect(outKey.message).toBe('bad key [REDACTED_API_KEY]')
expect(outKey.stack).toContain('[REDACTED_API_KEY]')
expect(outKey.stack).not.toContain('gnubok_sk_live_abc')
expect(outKey.stack).toContain('at ')
})
})
-224
View File
@@ -1,224 +0,0 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import {
captureException,
captureMessage,
flushObservability,
getEnvironment,
getObservabilitySink,
getRelease,
isObservabilityConfigured,
noopSink,
registerObservabilitySink,
resetObservabilitySink,
type ObservabilityContext,
type ObservabilityLevel,
type ObservabilitySink,
} from '../sink'
interface Captured {
kind: 'exception' | 'message'
error?: unknown
message?: string
level?: ObservabilityLevel
context: ObservabilityContext
}
function makeFakeSink(): { sink: ObservabilitySink; events: Captured[]; flushes: number[] } {
const events: Captured[] = []
const flushes: number[] = []
const sink: ObservabilitySink = {
name: 'fake',
captureException(error, context) {
events.push({ kind: 'exception', error, context })
},
captureMessage(message, level, context) {
events.push({ kind: 'message', message, level, context })
},
async flush(timeoutMs) {
flushes.push(timeoutMs ?? -1)
return true
},
}
return { sink, events, flushes }
}
describe('observability sink', () => {
beforeEach(() => {
resetObservabilitySink()
vi.unstubAllEnvs()
})
afterEach(() => {
resetObservabilitySink()
vi.unstubAllEnvs()
})
it('defaults to the no-op sink and reports itself as unconfigured', () => {
expect(getObservabilitySink()).toBe(noopSink)
expect(isObservabilityConfigured()).toBe(false)
// Must not throw with no provider installed.
expect(() => captureException(new Error('boom'))).not.toThrow()
expect(() => captureMessage('hello', 'error')).not.toThrow()
})
it('registers an adapter and routes events to it', () => {
const { sink, events } = makeFakeSink()
registerObservabilitySink(sink)
expect(isObservabilityConfigured()).toBe(true)
captureMessage('something happened', 'warning', { operation: 'test.op' })
expect(events).toHaveLength(1)
expect(events[0]).toMatchObject({
kind: 'message',
message: 'something happened',
level: 'warning',
})
expect(events[0].context.operation).toBe('test.op')
})
it('resetObservabilitySink restores the no-op default', () => {
const { sink, events } = makeFakeSink()
registerObservabilitySink(sink)
resetObservabilitySink()
captureMessage('after reset', 'error')
expect(events).toHaveLength(0)
expect(isObservabilityConfigured()).toBe(false)
})
it('serializes Error instances before they reach the adapter', () => {
const { sink, events } = makeFakeSink()
registerObservabilitySink(sink)
const err = new Error('database exploded')
;(err as Error & { code?: string }).code = '23505'
captureException(err, { operation: 'test.op' })
expect(events[0].error).not.toBeInstanceOf(Error)
expect(events[0].error).toMatchObject({
name: 'Error',
message: 'database exploded',
code: '23505',
})
})
it('redacts denylisted keys in context before the adapter sees them', () => {
const { sink, events } = makeFakeSink()
registerObservabilitySink(sink)
captureMessage('login failed', 'error', {
user: 'alice',
personnummer: '800101-1234',
headers: { authorization: 'Bearer abc', cookie: 'sess=xyz' },
nested: { payload: { password: 'hunter2', iban: 'SE1234567890' } },
})
const ctx = events[0].context as {
user: string
personnummer: string
headers: { authorization: string; cookie: string }
nested: { payload: { password: string; iban: string } }
}
expect(ctx.personnummer).toBe('[REDACTED]')
expect(ctx.headers.authorization).toBe('[REDACTED]')
expect(ctx.headers.cookie).toBe('[REDACTED]')
expect(ctx.nested.payload.password).toBe('[REDACTED]')
expect(ctx.nested.payload.iban).toBe('[REDACTED]')
expect(ctx.user).toBe('alice')
})
it('redacts personnummer-shaped strings in messages, errors and context values', () => {
const { sink, events } = makeFakeSink()
registerObservabilitySink(sink)
captureMessage('failed for 19800101-1234', 'error', { note: 'customer 800101-1234 blocked' })
captureException(new Error('no match for 800101-1234'), { note: 'ok' })
expect(events[0].message).toBe('[REDACTED]')
expect((events[0].context as { note: string }).note).toBe('[REDACTED]')
expect((events[1].error as { message: string }).message).toBe('[REDACTED]')
})
it('preserves UUIDs, which are not personnummer', () => {
const { sink, events } = makeFakeSink()
registerObservabilitySink(sink)
captureMessage('ok', 'info', { companyId: '57484518-3409-4b29-9d23-5d22f08bda63' })
expect(events[0].context.companyId).toBe('57484518-3409-4b29-9d23-5d22f08bda63')
})
it('stamps release, environment and runtime, and callers cannot override them', () => {
vi.stubEnv('OBSERVABILITY_RELEASE', '')
vi.stubEnv('NEXT_PUBLIC_BUILD_ID', 'abc123sha')
vi.stubEnv('OBSERVABILITY_ENVIRONMENT', 'preview')
const { sink, events } = makeFakeSink()
registerObservabilitySink(sink)
captureMessage('tagged', 'error', { release: 'spoofed', environment: 'spoofed' })
expect(events[0].context.release).toBe('abc123sha')
expect(events[0].context.environment).toBe('preview')
expect(events[0].context.runtime).toBe('server')
})
it('reads the release from the same value next.config.ts inlines, with fallbacks', () => {
vi.stubEnv('OBSERVABILITY_RELEASE', '')
vi.stubEnv('NEXT_PUBLIC_BUILD_ID', '')
vi.stubEnv('VERCEL_GIT_COMMIT_SHA', '')
expect(getRelease()).toBeNull()
vi.stubEnv('VERCEL_GIT_COMMIT_SHA', 'runtime-sha')
expect(getRelease()).toBe('runtime-sha')
vi.stubEnv('NEXT_PUBLIC_BUILD_ID', 'build-sha')
expect(getRelease()).toBe('build-sha')
vi.stubEnv('OBSERVABILITY_RELEASE', 'explicit')
expect(getRelease()).toBe('explicit')
})
it('derives the environment from VERCEL_ENV when no override is set', () => {
vi.stubEnv('OBSERVABILITY_ENVIRONMENT', '')
vi.stubEnv('VERCEL_ENV', 'production')
expect(getEnvironment()).toBe('production')
})
it('never lets a throwing adapter escape into the caller', () => {
registerObservabilitySink({
name: 'broken',
captureException() {
throw new Error('provider down')
},
captureMessage() {
throw new Error('provider down')
},
async flush() {
throw new Error('provider down')
},
})
expect(() => captureException(new Error('app error'))).not.toThrow()
expect(() => captureMessage('app message', 'error')).not.toThrow()
})
it('flush returns true by default and false when the adapter rejects', async () => {
expect(await flushObservability()).toBe(true)
const { sink, flushes } = makeFakeSink()
registerObservabilitySink(sink)
expect(await flushObservability(500)).toBe(true)
expect(flushes).toEqual([500])
registerObservabilitySink({
name: 'broken',
captureException() {},
captureMessage() {},
async flush() {
throw new Error('provider down')
},
})
expect(await flushObservability()).toBe(false)
})
})
-35
View File
@@ -1,35 +0,0 @@
/**
* Observability: the one place errors leave this process for a human to see.
*
* Import from `@/lib/observability`. The interface a vendor adapter has to
* satisfy, and the guarantees it has to honour, are documented in full in
* `./sink.ts`. The short version:
*
* 1. Write an adapter object satisfying `ObservabilitySink`.
* 2. Register it once from a server-side init path:
* registerObservabilitySink(myAdapter)
* 3. Nothing else changes. Call sites already route through the interface,
* and until step 2 happens the sink is a no-op, so core and self-hosted
* builds run with zero third-party runtime code.
*
* Almost nothing should call `captureException` / `captureMessage` directly:
* log through `createLogger()` (`@/lib/logger`) instead. The logger forwards
* every `error` record, plus anything flagged `alert: true`, to the sink with
* the request context already bound, so the event arrives correlated with the
* log line rather than orphaned. Direct calls are for code that has no logger
* in scope.
*
* Env vars (all optional, see `.env.example`): `OBSERVABILITY_DSN`,
* `NEXT_PUBLIC_OBSERVABILITY_DSN`, `OBSERVABILITY_ENVIRONMENT`,
* `OBSERVABILITY_RELEASE`. They are read by the adapter, not by this module:
* setting them without registering an adapter changes nothing.
*/
export {
captureException,
captureMessage,
registerObservabilitySink,
type ObservabilityContext,
type ObservabilityLevel,
type ObservabilitySink,
} from './sink'
-52
View File
@@ -1,52 +0,0 @@
/**
* Is this error a client hanging up mid-response, rather than a failure?
*
* When a browser navigates away while a page or RSC payload is still
* streaming, the HTTP response closes, Next destroys the stream it handed
* React (`node_modules/next/dist/server/pipe-readable.js`), and React's
* `createCancelHandler` aborts the in-flight render with a bare
* `Error('The destination stream closed early.')`. Both renderers do it: the
* Flight server (react-server-dom-webpack-server.node.production.js:3922) and
* react-dom's SSR streamer (react-dom-server.node.production.js:7822, :8099).
* The response itself still completes: every occurrence we sampled in
* production rode on a 200.
*
* Next means to swallow these. `create-error-handler.js` early-returns on
* `isAbortError`, but that predicate knows only `name === 'AbortError'` and
* `name === 'ResponseAborted'` (pipe-readable.js:32), and React's cancel error
* is a plain `Error`, so it falls through to `onRequestError` and is reported
* as an exception that never happened. This predicate closes that gap on our
* side. It is a Next filtering gap, not a version bug: 16.3.1 and 16.3.4 are
* byte-identical here, so upgrading is not the fix.
*
* Matching is on the EXACT message. A React rewording brings the noise back,
* which is the safe direction; a substring match would let a real error hide
* behind the phrase.
*
* Deliberately NOT matched: a bare `AbortError`, `ECONNRESET`,
* `ERR_STREAM_PREMATURE_CLOSE`. Those are how this codebase's outbound calls
* report genuine failures (`AbortSignal.timeout` in `lib/http/fetch-with-timeout`
* and every provider client; `lib/providers/with-provider-call` treats them as
* retryable provider faults), and swallowing them would hide real integration
* breakage. They also buy nothing here: Next already filters `AbortError`
* before instrumentation ever sees it.
*/
const CLIENT_DISCONNECT_MESSAGES = new Set([
'The destination stream closed early.',
'The destination stream errored while writing data.',
])
/**
* Next's own error for a response the client aborted
* (`server/web/spec-extension/adapters/next-request.js:39`). Unlike a plain
* `AbortError`, this name is only ever produced by that one situation.
*/
const RESPONSE_ABORTED_NAME = 'ResponseAborted'
export function isClientDisconnectError(error: unknown): boolean {
if (typeof error !== 'object' || error === null) return false
const { name, message } = error as { name?: unknown; message?: unknown }
if (name === RESPONSE_ABORTED_NAME) return true
return typeof message === 'string' && CLIENT_DISCONNECT_MESSAGES.has(message)
}
-115
View File
@@ -1,115 +0,0 @@
/**
* PII redaction primitives.
*
* This module is the single source of truth for what must never leave the
* process in clear text. It lives under `lib/observability/` rather than
* inside `lib/logger.ts` so that the logger AND the observability sink share
* one implementation: if the denylist lived in the logger only, a direct
* `captureException()` call would reach a third-party provider unredacted.
* Keeping one copy makes drift between the two paths impossible.
*
* The logs this guards carry personnummer, bank account numbers and financial
* data. Under GDPR that data must not be shipped to an error-tracking vendor,
* so redaction runs on every path into the sink, not just on the log path.
*
* Three mechanisms:
* 1. A key denylist (`REDACT_KEYS`): any object key matching case-insensitively
* has its whole value replaced, however deeply nested.
* 2. A personnummer regex applied to every string. UUIDs are stripped first,
* because a UUID's hex runs can otherwise look like a 10/12-digit
* personnummer and would nuke useful ids. A hit replaces the WHOLE string:
* the digits around a personnummer are usually themselves identifying.
* 3. Substring patterns for emails, Swedish IBANs and gnubok API keys,
* replaced in place with a placeholder naming what was removed. These are
* self-delimiting secrets, so the rest of the string (a log line, a stack
* trace) stays useful.
*
* `redact()` is idempotent: running it twice is safe and produces the same
* result, which is what lets the sink re-redact records the logger already
* cleaned without changing them.
*
* This module must not import anything (least of all the logger): it sits at
* the bottom of the import graph so nothing can create a cycle through it.
*/
export const REDACTED = '[REDACTED]'
export const REDACT_KEYS = new Set([
'password',
'token',
'access_token',
'refresh_token',
'apikey',
'api_key',
'secret',
'authorization',
'cookie',
'bank_account',
'bankaccount',
'iban',
'personnummer',
'ssn',
'credentials',
])
const UUID_PATTERN = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi
const PERSONNUMMER_PATTERN = /\b\d{6}-?\d{4}\b|\b\d{8}-?\d{4}\b/
// gnubok API keys (secret keys and invite tokens). The wire-format prefix is
// permanent (see CLAUDE.md: the gnubok_* prefixes are kept on purpose), so
// this pattern will not rot with the Accounted rename.
const API_KEY_PATTERN = /gnubok_(?:sk|inv)_[A-Za-z0-9_]+/g
// Swedish IBAN: SE + 22 digits, optionally grouped with spaces
// ("SE4550000000058398257466" or "SE45 5000 0000 0583 9825 7466").
const SE_IBAN_PATTERN = /\bSE(?:\s?\d){22}\b/g
// Pragmatic email shape: enough to catch real addresses in log lines without
// matching package specs like "[email protected]" (the domain must end in a TLD).
const EMAIL_PATTERN = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g
export function redactString(value: string): string {
// Strip UUIDs first to avoid false-positive personnummer matches
const stripped = value.replace(UUID_PATTERN, '')
if (PERSONNUMMER_PATTERN.test(stripped)) {
return REDACTED
}
// Substring secrets are replaced in place (distinct placeholders, so an
// adapter or a human can tell WHAT was removed). The placeholders contain
// no digits and no '@', so re-running redactString over them is a no-op:
// this is what keeps redact() idempotent.
return value
.replace(API_KEY_PATTERN, '[REDACTED_API_KEY]')
.replace(SE_IBAN_PATTERN, '[REDACTED_IBAN]')
.replace(EMAIL_PATTERN, '[REDACTED_EMAIL]')
}
export function redact(value: unknown, keyPath = ''): unknown {
if (value === null || value === undefined) return value
if (typeof value === 'string') return redactString(value)
if (typeof value === 'number' || typeof value === 'boolean') return value
if (value instanceof Date) return value.toISOString()
if (value instanceof Error) {
return {
name: value.name,
message: redactString(value.message),
// The stack is kept (redacted like any other string) in EVERY
// environment: the observability sink only runs in production, and a
// stackless event is useless to group on. Production STDOUT still drops
// it: that stripping happens in the logger's emit path (lib/logger.ts),
// which is the only consumer that wants stackless records.
stack: typeof value.stack === 'string' ? redactString(value.stack) : undefined,
code: (value as Error & { code?: unknown }).code,
}
}
if (Array.isArray(value)) return value.map((v, i) => redact(v, `${keyPath}[${i}]`))
if (typeof value === 'object') {
const out: Record<string, unknown> = {}
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
if (REDACT_KEYS.has(k.toLowerCase())) {
out[k] = REDACTED
} else {
out[k] = redact(v, keyPath ? `${keyPath}.${k}` : k)
}
}
return out
}
return value
}
-231
View File
@@ -1,231 +0,0 @@
/**
* Provider-agnostic observability sink.
*
* WHY THIS EXISTS
* ---------------
* This codebase has no error tracking. Everything goes to `console.*` and
* whatever Vercel keeps in its short log retention window; nothing aggregates,
* nothing alerts, and none of the 16 scheduled cron jobs report a failure
* anywhere a human will see it. The observable cost is bugs that ran broken
* for every user until a customer wrote in.
*
* This module is the seam. Call sites (mainly `lib/logger.ts`) talk to a small
* stable interface; a vendor adapter is registered once at startup. Until an
* adapter is registered the sink is a no-op, so nothing changes today and the
* self-hosted build stays free of a third-party runtime dependency.
*
* WHAT A VENDOR ADAPTER MUST IMPLEMENT
* ------------------------------------
* Provide an object satisfying `ObservabilitySink` and register it once, from
* a server-side init path, before any request is served:
*
* registerObservabilitySink({
* name: 'my-vendor',
* captureException(error, context) { ... },
* captureMessage(message, level, context) { ... },
* async flush(timeoutMs) { return true },
* })
*
* Contract the adapter must honour:
*
* - `captureException(error, context)` and `captureMessage(...)` are
* SYNCHRONOUS and MUST NOT THROW and MUST NOT return a promise the caller
* is expected to await. They are called from logging paths that run inside
* request handlers, cron loops and the bookkeeping engine; a slow or
* throwing sink would become an outage in the accounting path. Queue
* internally and ship in the background. (The wrappers in this file also
* guard with try/catch, but do not rely on that.)
* - `error` is NEVER a live `Error` instance. It arrives already serialized
* and redacted as `{ name, message, stack?, code? }` (or an arbitrary
* redacted value when a non-Error was thrown). Adapters that want a real
* stack should reconstruct it from `error.stack`.
* - `context` is a flat bag of ALREADY-REDACTED primitives/objects. Do not
* re-fetch the original values from anywhere. Reserved keys the adapter
* should map onto vendor concepts rather than dumping as extras:
* release release / version tag (git sha, see `getRelease()`)
* environment 'production' | 'preview' | 'development' | custom
* runtime 'server' | 'client'
* module logger module name, e.g. 'api/invoice.send'
* operation route / cron operation name
* requestId correlation id, also on the X-Request-Id response header
* companyId tenant id (safe: an opaque uuid, not PII)
* userId auth user id (opaque uuid)
* logMessage the human-readable log line the event came from
* alert true when the call site explicitly demanded paging
* cron true when the event came from a scheduled job
* Everything else is free-form structured context; treat it as extras.
* - `flush(timeoutMs)` resolves `true` when the queue drained, `false` on
* timeout. It must never reject. Serverless functions freeze immediately
* after the response, so an adapter that buffers MUST implement this.
* - The adapter is responsible for its own sampling, rate limiting and
* grouping. This layer deliberately does not dedupe: suppressing the first
* occurrence of a failure is how outages stay invisible.
*
* GDPR NOTE (non-negotiable)
* --------------------------
* Every public entry point in this file runs `redact()` from
* `./redact` before the sink sees anything. That is a structural guarantee,
* not a convention: there is no code path from application data to a vendor
* that skips the personnummer regex and the key denylist. Do not add one, and
* do not "optimise away" the second redaction pass on records the logger has
* already cleaned (redaction is idempotent and the cost is on the error path
* only).
*/
import { redact, redactString } from './redact'
/** Severity as the sink sees it. Maps onto every vendor's level vocabulary. */
export type ObservabilityLevel = 'debug' | 'info' | 'warning' | 'error'
/** Flat bag of already-redacted structured fields. See the header for reserved keys. */
export type ObservabilityContext = Record<string, unknown>
export interface ObservabilitySink {
/** Adapter name, used by `isObservabilityConfigured()` and diagnostics. */
readonly name: string
/** Report a failure. Synchronous, must not throw. */
captureException(error: unknown, context: ObservabilityContext): void
/** Report a noteworthy event without an Error object. Synchronous, must not throw. */
captureMessage(message: string, level: ObservabilityLevel, context: ObservabilityContext): void
/** Drain the queue. Resolves false on timeout; must never reject. */
flush(timeoutMs?: number): Promise<boolean>
}
/**
* Default implementation: drops everything on the floor.
*
* Deliberately silent rather than console-logging, because the logger has
* already written the same record to the console by the time the sink is
* called. Duplicating it here would double every error line.
*/
export const noopSink: ObservabilitySink = {
name: 'noop',
captureException() {},
captureMessage() {},
flush: async () => true,
}
// Module-level singleton, same pattern as `lib/events/bus.ts`.
let activeSink: ObservabilitySink = noopSink
/**
* Register the vendor adapter. Call once, from a server-side init path, before
* traffic is served. A second call replaces the first (last one wins), which
* keeps dev hot-reload from stacking adapters.
*/
export function registerObservabilitySink(sink: ObservabilitySink): void {
activeSink = sink
}
export function getObservabilitySink(): ObservabilitySink {
return activeSink
}
/** False while the no-op default is installed, i.e. no provider is configured. */
export function isObservabilityConfigured(): boolean {
return activeSink !== noopSink
}
/** Restore the no-op default. Intended for tests and for disabling at runtime. */
export function resetObservabilitySink(): void {
activeSink = noopSink
}
/**
* Release tag for every event, so a spike can be attributed to a deploy from
* day one.
*
* `next.config.ts` inlines `VERCEL_GIT_COMMIT_SHA` into `NEXT_PUBLIC_BUILD_ID`
* at build time (it powers the DeployReloadPrompt and /api/version), which
* makes it the one release identifier that is already present in BOTH the
* server and the client bundle. Reading the same value here means the sink,
* the reload prompt and /api/version all agree on what "this deploy" is.
* `process.env.NEXT_PUBLIC_BUILD_ID` must stay written out literally: Next
* does a textual substitution on it, so a computed lookup would not be
* replaced. `VERCEL_GIT_COMMIT_SHA` is the runtime fallback for server-only
* contexts that were not built by Next (scripts, standalone workers).
*
* Returns null on dev and self-hosted builds, where there is no release to tag.
*/
export function getRelease(): string | null {
const override = process.env.OBSERVABILITY_RELEASE
if (override) return override
const buildId = process.env.NEXT_PUBLIC_BUILD_ID
if (buildId) return buildId
const sha = process.env.VERCEL_GIT_COMMIT_SHA
return sha ? sha : null
}
/** production | preview | development, or an explicit override. */
export function getEnvironment(): string {
return (
process.env.OBSERVABILITY_ENVIRONMENT ||
process.env.VERCEL_ENV ||
process.env.NODE_ENV ||
'development'
)
}
/**
* Redact caller-supplied context, then stamp the reserved fields.
*
* The reserved fields are applied AFTER the spread so a caller cannot
* accidentally (or maliciously) override the release/environment tagging with
* a context key of the same name.
*/
function enrich(context: ObservabilityContext | undefined): ObservabilityContext {
const safe = (redact(context ?? {}) as ObservabilityContext) ?? {}
return {
...safe,
release: getRelease(),
environment: getEnvironment(),
runtime: typeof window === 'undefined' ? 'server' : 'client',
}
}
/**
* Report a failure to the configured provider.
*
* Redacts both the error and the context first. Never throws: a broken sink
* must not take down the code path that was merely trying to report a problem.
*/
export function captureException(error: unknown, context: ObservabilityContext = {}): void {
try {
activeSink.captureException(redact(error), enrich(context))
} catch {
// A failing provider must never surface as an application error.
}
}
/**
* Report a noteworthy event that has no Error object attached.
*
* Redacts the message and the context first. Never throws.
*/
export function captureMessage(
message: string,
level: ObservabilityLevel = 'error',
context: ObservabilityContext = {},
): void {
try {
activeSink.captureMessage(redactString(message), level, enrich(context))
} catch {
// A failing provider must never surface as an application error.
}
}
/**
* Drain the provider's queue.
*
* Serverless functions freeze the moment the response is returned, so any
* long-running path that must not lose its last events (cron handlers, queue
* workers) should await this before returning. Resolves false if the provider
* timed out or threw; never rejects.
*/
export async function flushObservability(timeoutMs = 2000): Promise<boolean> {
try {
return await activeSink.flush(timeoutMs)
} catch {
return false
}
}