import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes'; import { DB_QUERY } from '@sentry/conventions/op'; import { addBreadcrumb, captureException, DB_SPAN_NAME_FALLBACK, debug, type Span, type SpanAttributes, SPAN_STATUS_ERROR, startSpan, type StartSpanOptions, } from '@sentry/core'; import { flushIfServerless } from '@sentry/core/server'; import { getSqlQueryAttributes, getSqlSpanName, sanitizeSqlQuery, type SqlDialect } from '@sentry/server-utils'; import type { Database, PreparedStatement } from 'db0'; import { type DatabaseConnectionConfig, type DatabaseSpanData, getDatabaseSpanData } from './database-span-data'; import { DB_QUERY_TEXT, DB_SYSTEM_NAME } from '@sentry/conventions/attributes'; type MaybeInstrumentedDatabase = Database & { __sentry_instrumented__?: boolean; }; /** * Keeps track of prepared statements that have been patched. */ const patchedStatement = new WeakSet(); /** * The Sentry origin for the database plugin. */ const NUXT_DATABASE_ORIGIN = 'auto.db.nuxt'; /** * Creates the Nitro database plugin setup by instrumenting the configured database instances. * * Called from the version-specific plugin entry points (database.server.ts / database-legacy.server.ts) * which supply the correct `useDatabase` import for their respective Nitro version. */ export function createDatabasePlugin( useDatabase: (name: string) => Database, databaseConfig: Record, ): void { try { const databaseInstances = Object.keys(databaseConfig); debug.log('[Nitro Database Plugin]: Instrumenting databases...'); for (const instance of databaseInstances) { debug.log('[Nitro Database Plugin]: Instrumenting database instance:', instance); const db = useDatabase(instance); instrumentDatabase(db, databaseConfig[instance]); } debug.log('[Nitro Database Plugin]: Databases instrumented.'); } catch (error) { // During build time, we can't use the useDatabase function, so we just log an error. if (error instanceof Error && /Cannot access 'instances'/.test(error.message)) { debug.log('[Nitro Database Plugin]: Database instrumentation skipped during build time.'); return; } debug.error('[Nitro Database Plugin]: Failed to instrument database:', error); } } /** * Instruments a database instance with Sentry. */ function instrumentDatabase(db: MaybeInstrumentedDatabase, config?: DatabaseConnectionConfig): void { if (db.__sentry_instrumented__) { debug.log('[Nitro Database Plugin]: Database already instrumented. Skipping...'); return; } const metadata: DatabaseSpanData = { // A connector name like `bun-sqlite` or `mysql2` names the driver, the dialect names the database system. [DB_SYSTEM_NAME]: db.dialect ?? config?.connector, ...getDatabaseSpanData(config), }; // The connector name (e.g. `planetscale`) does not identify the SQL flavour, `db.dialect` does. // MySQL reads `"..."` and `\'` as string syntax, so the sanitizer has to know about it. const dialect: SqlDialect | undefined = db.dialect === 'mysql' ? 'mysql' : undefined; db.prepare = new Proxy(db.prepare, { apply(target, thisArg, args: Parameters) { const [query] = args; let statement: PreparedStatement; try { statement = target.apply(thisArg, args); } catch (error) { // Connectors like `bun-sqlite` and `better-sqlite3` compile the statement in `prepare`, so an invalid query // throws here and not when the statement runs. startSpan(createStartSpanOptions(query, metadata, dialect), span => captureDatabaseError(span, error)); void flushIfServerless(); throw error; } return instrumentPreparedStatement(statement, query, metadata, dialect); }, }); // Sadly the `.sql` template tag doesn't call `db.prepare` internally and it calls the connector's `.prepare` directly // So we have to patch it manually, and would mean we would have less info in the spans. // https://github.com/unjs/db0/blob/main/src/database.ts#L64 db.sql = new Proxy(db.sql, { apply(target, thisArg, args: Parameters) { const [strings, ...values] = args; const query = strings ? buildSqlTemplateQuery(strings, values) : ''; const opts = createStartSpanOptions(query, metadata, dialect); return startSpan( opts, handleSpanStart(() => target.apply(thisArg, args)), ); }, }); db.exec = new Proxy(db.exec, { apply(target, thisArg, args: Parameters) { return startSpan( createStartSpanOptions(args[0], metadata, dialect), handleSpanStart(() => target.apply(thisArg, args), { query: args[0], dialect }), ); }, }); db.__sentry_instrumented__ = true; } /** * Rebuilds the parameterized statement that db0 hands to the connector from the `.sql` template * tag's arguments. Mirrors db0's own template handling: interpolated values become `?` placeholders, * except values wrapped in `{}`, which db0 inlines into the statement (e.g. table names). * * @see https://github.com/unjs/db0/blob/main/src/template.ts */ function buildSqlTemplateQuery(strings: TemplateStringsArray, values: unknown[]): string { let query = strings[0] || ''; for (let i = 1; i < strings.length; i++) { const chunk = strings[i] ?? ''; if (query.endsWith('{') && chunk.startsWith('}')) { query = `${query.slice(0, -1)}${values[i - 1]}${chunk.slice(1)}`; } else { query += `?${chunk}`; } } return query.trim(); } /** * Instruments a DB prepared statement with Sentry. * * This is meant to be used as a top-level call, under the hood it calls `instrumentPreparedStatementQueries` * to patch the query methods. The reason for this abstraction is to ensure that the `bind` method is also patched. */ function instrumentPreparedStatement( statement: PreparedStatement, query: string, data: DatabaseSpanData, dialect: SqlDialect | undefined, ): PreparedStatement { // statement.bind() returns a new instance of D1PreparedStatement, so we have to patch it as well. // eslint-disable-next-line @typescript-eslint/unbound-method statement.bind = new Proxy(statement.bind, { apply(target, thisArg, args: Parameters) { return instrumentPreparedStatementQueries(target.apply(thisArg, args), query, data, dialect); }, }); return instrumentPreparedStatementQueries(statement, query, data, dialect); } /** * Patches the query methods of a DB prepared statement with Sentry. */ function instrumentPreparedStatementQueries( statement: PreparedStatement, query: string, data: DatabaseSpanData, dialect: SqlDialect | undefined, ): PreparedStatement { if (patchedStatement.has(statement)) { return statement; } // eslint-disable-next-line @typescript-eslint/unbound-method statement.get = new Proxy(statement.get, { apply(target, thisArg, args: Parameters) { return startSpan( createStartSpanOptions(query, data, dialect), handleSpanStart(() => target.apply(thisArg, args), { query, dialect }), ); }, }); // eslint-disable-next-line @typescript-eslint/unbound-method statement.run = new Proxy(statement.run, { apply(target, thisArg, args: Parameters) { return startSpan( createStartSpanOptions(query, data, dialect), handleSpanStart(() => target.apply(thisArg, args), { query, dialect }), ); }, }); // eslint-disable-next-line @typescript-eslint/unbound-method statement.all = new Proxy(statement.all, { apply(target, thisArg, args: Parameters) { return startSpan( createStartSpanOptions(query, data, dialect), handleSpanStart(() => target.apply(thisArg, args), { query, dialect }), ); }, }); patchedStatement.add(statement); return statement; } /** * Creates a span start callback handler. */ function handleSpanStart(fn: () => unknown, breadcrumbOpts?: { query: string; dialect: SqlDialect | undefined }) { return async (span: Span) => { try { const result = await fn(); if (breadcrumbOpts) { createBreadcrumb(breadcrumbOpts.query, breadcrumbOpts.dialect); } return result; } catch (error) { captureDatabaseError(span, error); // Re-throw the error to be handled by the caller throw error; } finally { await flushIfServerless(); } }; } function captureDatabaseError(span: Span, error: unknown): void { span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); captureException(error, { mechanism: { handled: false, type: NUXT_DATABASE_ORIGIN, }, }); } function createBreadcrumb(query: string, dialect: SqlDialect | undefined): void { // The breadcrumb carries the same query text as the span, so it is sanitized and guarded the same way. const queryText = query ? sanitizeSqlQuery(query, dialect) : undefined; addBreadcrumb({ category: 'query', message: queryText, data: { [DB_QUERY_TEXT]: queryText, }, }); } /** * Creates a start span options object. */ function createStartSpanOptions( query: string, data: DatabaseSpanData, dialect: SqlDialect | undefined, ): StartSpanOptions { const attributes: SpanAttributes = { ...getSqlQueryAttributes(query, dialect), [SENTRY_ORIGIN]: NUXT_DATABASE_ORIGIN, [SENTRY_OP]: DB_QUERY, ...data, }; return { name: getSqlSpanName(attributes, DB_SPAN_NAME_FALLBACK), attributes }; }