|
| 1 | +import { getDefaultIsolationScope, getIsolationScope, logger, withIsolationScope } from '@sentry/core'; |
| 2 | +import type { EventHandler } from 'h3'; |
| 3 | +import { flushIfServerless } from '../util/flush'; |
| 4 | + |
| 5 | +/** |
| 6 | + * A helper to patch a given `h3` event handler, ensuring that |
| 7 | + * requests are properly isolated and data is flushed to Sentry. |
| 8 | + */ |
| 9 | +export function patchEventHandler(handler: EventHandler): EventHandler { |
| 10 | + return new Proxy(handler, { |
| 11 | + async apply(handlerTarget, handlerThisArg, handlerArgs: Parameters<EventHandler>) { |
| 12 | + // In environments where we cannot make use of the OTel |
| 13 | + // http instrumentation (e.g. when using top level import |
| 14 | + // of the server instrumentation file instead of |
| 15 | + // `--import` or dynamic import, like on vercel) |
| 16 | + // we still need to ensure requests are properly isolated |
| 17 | + // by comparing the current isolation scope to the default |
| 18 | + // one. |
| 19 | + // Requests are properly isolated if they differ. |
| 20 | + // If that's not the case, we fork the isolation scope here. |
| 21 | + const isolationScope = getIsolationScope(); |
| 22 | + const newIsolationScope = isolationScope === getDefaultIsolationScope() ? isolationScope.clone() : isolationScope; |
| 23 | + |
| 24 | + logger.log( |
| 25 | + `[Sentry] Patched h3 event handler. ${ |
| 26 | + isolationScope === newIsolationScope ? 'Using existing' : 'Created new' |
| 27 | + } isolation scope.`, |
| 28 | + ); |
| 29 | + |
| 30 | + return withIsolationScope(newIsolationScope, async () => { |
| 31 | + try { |
| 32 | + return await handlerTarget.apply(handlerThisArg, handlerArgs); |
| 33 | + } finally { |
| 34 | + await flushIfServerless(); |
| 35 | + } |
| 36 | + }); |
| 37 | + }, |
| 38 | + }); |
| 39 | +} |
0 commit comments