Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions supabase/functions/_backend/utils/posthog.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Context } from 'hono'
import { cloudlog, cloudlogErr, serializeError } from './logging.ts'
import { drizzleErrorFingerprintSegment, readPgErrorCode } from './pg_errors.ts'
import { drizzleErrorFingerprintSegment, isDatabaseOriginError, readPgErrorCode, readPgErrorField, readQuickErrorOriginalCause } from './pg_errors.ts'
import { existInEnv, getEnv, trimTrailingSlashes } from './utils.ts'

const POSTHOG_CAPTURE_URL = 'https://eu.i.posthog.com/capture/'
Expand Down Expand Up @@ -276,6 +276,28 @@
}]
}

// A DrizzleQueryError message ends with a `params: ...` line that repeats the
// bound query values (org UUIDs and other request data). Those carry no
// diagnostic value, so drop them before the message leaves the worker.
function stripDrizzleQueryParams(message: string | undefined): string {
if (!message)
return ''
const paramsIndex = message.search(/\n\s*params:/i)

Check warning on line 285 in supabase/functions/_backend/utils/posthog.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Simplify this regular expression to reduce its runtime, as it has super-linear performance due to backtracking.

See more on https://sonarcloud.io/project/issues?id=Cap-go_capgo&issues=AaCK98wMUubz6HoPC7PB&open=AaCK98wMUubz6HoPC7PB&pullRequest=3299
return paramsIndex === -1 ? message : message.slice(0, paramsIndex).trimEnd()
}

// The real Postgres failure hides one or two levels down: Drizzle exposes it on
// `.cause`, and quickError() stores it under `.cause.originalCause`. Return the
// serialized reason (name + param-free message) so error tracking keeps it.
function serializeDatabaseCause(databaseError: unknown) {
const nestedCause = readPgErrorField(databaseError, 'cause')
const serialized = serializeError(nestedCause ?? databaseError)
return {
name: serialized.name,
message: stripDrizzleQueryParams(serialized.message),
}
}

export async function capturePosthogException(c: Context, payload: {
error: unknown
functionName: string
Expand Down Expand Up @@ -313,9 +335,14 @@
topFrame?.filename || 'unknown',
String(payload.status ?? 500),
].join(':')
const pgErrorCode = payload.kind === 'drizzle_error'
? readPgErrorCode(payload.error)
: undefined
// Resolve the underlying database error whether the failure reached us raw
// (Drizzle) or wrapped in an HTTP error by quickError(). Enriching from it
// keeps a route that maps a query failure to quickError(..., cause) as
// diagnosable as a raw Drizzle error.
const databaseError = readQuickErrorOriginalCause(payload.error) ?? payload.error
const hasDatabaseCause = isDatabaseOriginError(databaseError)
const pgErrorCode = hasDatabaseCause ? readPgErrorCode(databaseError) : undefined
const databaseCause = hasDatabaseCause ? serializeDatabaseCause(databaseError) : undefined

const body = {
token: apiKey,
Expand All @@ -324,7 +351,7 @@
distinct_id: distinctId,
$exception_list: [{
type: serializedError.name || 'Error',
value: serializedError.message,
value: stripDrizzleQueryParams(serializedError.message),
mechanism: {
handled: true,
synthetic: false,
Expand All @@ -342,6 +369,7 @@
status: payload.status,
url_path: requestPath,
...(pgErrorCode ? { pg_error_code: pgErrorCode } : {}),
...(databaseCause ? { database_cause: databaseCause } : {}),
},
timestamp: new Date().toISOString(),
}
Expand Down
53 changes: 53 additions & 0 deletions tests/posthog.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,59 @@ describe('posthog helper', () => {
expect(body.properties.pg_error_code).toBe('42P01')
})

it('strips bound query parameters and keeps the Postgres cause for drizzle errors', async () => {
const { capturePosthogException } = await import('../supabase/functions/_backend/utils/posthog.ts')
envState.posthogApiHost = 'https://eu.i.posthog.com/i/v0/e'

await capturePosthogException(createContext(), {
error: Object.assign(new Error('Failed query: select "campaigns" from "notification_campaigns" where "owner_org" = $1\nparams: 00000000-0000-0000-0000-000000000000'), {
name: 'DrizzleQueryError',
cause: Object.assign(new Error('canceling statement due to statement timeout'), {
code: '57014',
}),
}),
functionName: 'api',
kind: 'drizzle_error',
status: 500,
})

const body = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)
const value = body.properties.$exception_list[0].value
expect(value).not.toContain('params:')
expect(value).not.toContain('00000000-0000-0000-0000-000000000000')
expect(body.properties.pg_error_code).toBe('57014')
expect(body.properties.database_cause.message).toBe('canceling statement due to statement timeout')
})

it('keeps the Postgres cause when a route wraps the failure in an HTTP error', async () => {
const { capturePosthogException } = await import('../supabase/functions/_backend/utils/posthog.ts')
envState.posthogApiHost = 'https://eu.i.posthog.com/i/v0/e'

const originalCause = Object.assign(new Error('Failed query: select "campaigns" from "notification_campaigns" where "owner_org" = $1\nparams: 00000000-0000-0000-0000-000000000000'), {
name: 'DrizzleQueryError',
cause: Object.assign(new Error('relation "notification_campaigns" does not exist'), {
code: '42P01',
}),
})
const httpException = Object.assign(new Error('Failed to load organization notification overview'), {
status: 503,
getResponse: () => new Response(),
cause: { error: 'notification_overview_unavailable', message: 'Failed to load organization notification overview', moreInfo: {}, originalCause: originalCause },
})

await capturePosthogException(createContext(), {
error: httpException,
functionName: 'api',
kind: 'http_exception',
status: 503,
})

const body = JSON.parse(fetchMock.mock.calls[0]?.[1]?.body as string)
expect(body.properties.$exception_list[0].value).not.toContain('params:')
expect(body.properties.pg_error_code).toBe('42P01')
expect(body.properties.database_cause.message).toBe('relation "notification_campaigns" does not exist')
})

it('logs and skips exception delivery when the configured PostHog host is invalid', async () => {
const { capturePosthogException } = await import('../supabase/functions/_backend/utils/posthog.ts')
envState.posthogApiHost = '://bad-host'
Expand Down
Loading