|
| 1 | +import { |
| 2 | + type SpanAttributes, |
| 3 | + captureException, |
| 4 | + debug, |
| 5 | + flushIfServerless, |
| 6 | + SEMANTIC_ATTRIBUTE_SENTRY_OP, |
| 7 | + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, |
| 8 | + SPAN_STATUS_ERROR, |
| 9 | + SPAN_STATUS_OK, |
| 10 | + startSpan, |
| 11 | +} from '@sentry/core'; |
| 12 | +import type { Database } from 'db0'; |
| 13 | +// eslint-disable-next-line import/no-extraneous-dependencies |
| 14 | +import { defineNitroPlugin, useDatabase } from 'nitropack/runtime'; |
| 15 | + |
| 16 | +/** |
| 17 | + * Creates a Nitro plugin that instruments the database calls. |
| 18 | + */ |
| 19 | +export default defineNitroPlugin(() => { |
| 20 | + const db = useDatabase(); |
| 21 | + |
| 22 | + debug.log('@sentry/nuxt: Instrumenting database...'); |
| 23 | + |
| 24 | + instrumentDatabase(db); |
| 25 | + |
| 26 | + debug.log('@sentry/nuxt: Database instrumented.'); |
| 27 | +}); |
| 28 | + |
| 29 | +function instrumentDatabase(db: Database): void { |
| 30 | + db.sql = new Proxy(db.sql, { |
| 31 | + apply(target, thisArg, args: Parameters<typeof db.sql>) { |
| 32 | + const query = args[0]?.[0]; |
| 33 | + const attributes = getSpanAttributes(db, query); |
| 34 | + |
| 35 | + return startSpan( |
| 36 | + { |
| 37 | + name: query || 'db.query', |
| 38 | + attributes, |
| 39 | + }, |
| 40 | + async span => { |
| 41 | + try { |
| 42 | + const result = await target.apply(thisArg, args); |
| 43 | + span.setStatus({ code: SPAN_STATUS_OK }); |
| 44 | + |
| 45 | + return result; |
| 46 | + } catch (error) { |
| 47 | + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); |
| 48 | + captureException(error, { |
| 49 | + mechanism: { |
| 50 | + handled: false, |
| 51 | + type: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN], |
| 52 | + }, |
| 53 | + }); |
| 54 | + |
| 55 | + // Re-throw the error to be handled by the caller |
| 56 | + throw error; |
| 57 | + } finally { |
| 58 | + await flushIfServerless(); |
| 59 | + } |
| 60 | + }, |
| 61 | + ); |
| 62 | + }, |
| 63 | + }); |
| 64 | +} |
| 65 | + |
| 66 | +function getSpanAttributes(db: Database, query?: string): SpanAttributes { |
| 67 | + const attributes: SpanAttributes = { |
| 68 | + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.nuxt', |
| 69 | + [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db', |
| 70 | + 'db.system': db.dialect, |
| 71 | + }; |
| 72 | + |
| 73 | + if (query) { |
| 74 | + attributes['db.query'] = query; |
| 75 | + } |
| 76 | + |
| 77 | + return attributes; |
| 78 | +} |
0 commit comments