|
| 1 | +import type { Span } from '@sentry/core'; |
| 2 | +import { |
| 3 | + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, |
| 4 | + SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, |
| 5 | + getActiveSpan, |
| 6 | + getCurrentScope, |
| 7 | + getDefaultIsolationScope, |
| 8 | + getIsolationScope, |
| 9 | + getTraceMetaTags, |
| 10 | + logger, |
| 11 | + setHttpStatus, |
| 12 | + startSpan, |
| 13 | + winterCGRequestToRequestData, |
| 14 | + withIsolationScope, |
| 15 | + continueTrace, |
| 16 | +} from '@sentry/core'; |
| 17 | +import type { Handle, ResolveOptions } from '@sveltejs/kit'; |
| 18 | + |
| 19 | +import { DEBUG_BUILD } from '../common/debug-build'; |
| 20 | +import { flushIfServerless, getTracePropagationData, sendErrorToSentry } from './utils'; |
| 21 | + |
| 22 | +export type SentryHandleOptions = { |
| 23 | + /** |
| 24 | + * Controls whether the SDK should capture errors and traces in requests that don't belong to a |
| 25 | + * route defined in your SvelteKit application. |
| 26 | + * |
| 27 | + * By default, this option is set to `false` to reduce noise (e.g. bots sending random requests to your server). |
| 28 | + * |
| 29 | + * Set this option to `true` if you want to monitor requests events without a route. This might be useful in certain |
| 30 | + * scenarios, for instance if you registered other handlers that handle these requests. |
| 31 | + * If you set this option, you might want adjust the the transaction name in the `beforeSendTransaction` |
| 32 | + * callback of your server-side `Sentry.init` options. You can also use `beforeSendTransaction` to filter out |
| 33 | + * transactions that you still don't want to be sent to Sentry. |
| 34 | + * |
| 35 | + * @default false |
| 36 | + */ |
| 37 | + handleUnknownRoutes?: boolean; |
| 38 | + |
| 39 | + /** |
| 40 | + * Controls if `sentryHandle` should inject a script tag into the page that enables instrumentation |
| 41 | + * of `fetch` calls in `load` functions. |
| 42 | + * |
| 43 | + * @default true |
| 44 | + */ |
| 45 | + injectFetchProxyScript?: boolean; |
| 46 | + |
| 47 | + /** |
| 48 | + * If this option is set, the `sentryHandle` handler will add a nonce attribute to the script |
| 49 | + * tag it injects into the page. This script is used to enable instrumentation of `fetch` calls |
| 50 | + * in `load` functions. |
| 51 | + * |
| 52 | + * Use this if your CSP policy blocks the fetch proxy script injected by `sentryHandle`. |
| 53 | + */ |
| 54 | + fetchProxyScriptNonce?: string; |
| 55 | +}; |
| 56 | + |
| 57 | +/** |
| 58 | + * Exported only for testing |
| 59 | + */ |
| 60 | +export const FETCH_PROXY_SCRIPT = ` |
| 61 | + const f = window.fetch; |
| 62 | + if(f){ |
| 63 | + window._sentryFetchProxy = function(...a){return f(...a)} |
| 64 | + window.fetch = function(...a){return window._sentryFetchProxy(...a)} |
| 65 | + } |
| 66 | +`; |
| 67 | + |
| 68 | +/** |
| 69 | + * Adds Sentry tracing <meta> tags to the returned html page. |
| 70 | + * Adds Sentry fetch proxy script to the returned html page if enabled in options. |
| 71 | + * Also adds a nonce attribute to the script tag if users specified one for CSP. |
| 72 | + * |
| 73 | + * Exported only for testing |
| 74 | + */ |
| 75 | +export function addSentryCodeToPage(options: SentryHandleOptions): NonNullable<ResolveOptions['transformPageChunk']> { |
| 76 | + const { fetchProxyScriptNonce, injectFetchProxyScript } = options; |
| 77 | + // if injectFetchProxyScript is not set, we default to true |
| 78 | + const shouldInjectScript = injectFetchProxyScript !== false; |
| 79 | + const nonce = fetchProxyScriptNonce ? `nonce="${fetchProxyScriptNonce}"` : ''; |
| 80 | + |
| 81 | + return ({ html }) => { |
| 82 | + const metaTags = getTraceMetaTags(); |
| 83 | + const headWithMetaTags = metaTags ? `<head>\n${metaTags}` : '<head>'; |
| 84 | + |
| 85 | + const headWithFetchScript = shouldInjectScript ? `\n<script ${nonce}>${FETCH_PROXY_SCRIPT}</script>` : ''; |
| 86 | + |
| 87 | + const modifiedHead = `${headWithMetaTags}${headWithFetchScript}`; |
| 88 | + |
| 89 | + return html.replace('<head>', modifiedHead); |
| 90 | + }; |
| 91 | +} |
| 92 | + |
| 93 | +/** |
| 94 | + * A SvelteKit handle function that wraps the request for Sentry error and |
| 95 | + * performance monitoring. |
| 96 | + * |
| 97 | + * This doesn't currently use OTEL, as it isn't available outside of Node |
| 98 | + * |
| 99 | + * Usage: |
| 100 | + * ``` |
| 101 | + * // src/hooks.server.ts |
| 102 | + * import { sentryHandle } from '@sentry/sveltekit'; |
| 103 | + * |
| 104 | + * export const handle = sentryHandle(); |
| 105 | + * |
| 106 | + * // Optionally use the `sequence` function to add additional handlers. |
| 107 | + * // export const handle = sequence(sentryHandle(), yourCustomHandler); |
| 108 | + * ``` |
| 109 | + */ |
| 110 | +export function sentryHandle(handlerOptions?: SentryHandleOptions): Handle { |
| 111 | + const options = { |
| 112 | + handleUnknownRoutes: false, |
| 113 | + injectFetchProxyScript: true, |
| 114 | + ...handlerOptions, |
| 115 | + }; |
| 116 | + |
| 117 | + const sentryRequestHandler: Handle = input => { |
| 118 | + // event.isSubRequest was added in SvelteKit 1.21.0 and we can use it to check |
| 119 | + // if we should create a new execution context or not. |
| 120 | + // In case of a same-origin `fetch` call within a server`load` function, |
| 121 | + // SvelteKit will actually just re-enter the `handle` function and set `isSubRequest` |
| 122 | + // to `true` so that no additional network call is made. |
| 123 | + // We want the `http.server` span of that nested call to be a child span of the |
| 124 | + // currently active span instead of a new root span to correctly reflect this |
| 125 | + // behavior. |
| 126 | + // As a fallback for Kit < 1.21.0, we check if there is an active span only if there's none, |
| 127 | + // we create a new execution context. |
| 128 | + const isSubRequest = typeof input.event.isSubRequest === 'boolean' ? input.event.isSubRequest : !!getActiveSpan(); |
| 129 | + |
| 130 | + if (isSubRequest) { |
| 131 | + return instrumentHandle(input, options); |
| 132 | + } |
| 133 | + |
| 134 | + return withIsolationScope(isolationScope => { |
| 135 | + // We only call continueTrace in the initial top level request to avoid |
| 136 | + // creating a new root span for the sub request. |
| 137 | + isolationScope.setSDKProcessingMetadata({ |
| 138 | + normalizedRequest: winterCGRequestToRequestData(input.event.request.clone()), |
| 139 | + }); |
| 140 | + return continueTrace(getTracePropagationData(input.event), () => instrumentHandle(input, options)); |
| 141 | + }); |
| 142 | + }; |
| 143 | + |
| 144 | + return sentryRequestHandler; |
| 145 | +} |
| 146 | + |
| 147 | +async function instrumentHandle( |
| 148 | + { event, resolve }: Parameters<Handle>[0], |
| 149 | + options: SentryHandleOptions, |
| 150 | +): Promise<Response> { |
| 151 | + if (!event.route?.id && !options.handleUnknownRoutes) { |
| 152 | + return resolve(event); |
| 153 | + } |
| 154 | + |
| 155 | + const routeName = `${event.request.method} ${event.route?.id || event.url.pathname}`; |
| 156 | + |
| 157 | + if (getIsolationScope() !== getDefaultIsolationScope()) { |
| 158 | + getIsolationScope().setTransactionName(routeName); |
| 159 | + } else { |
| 160 | + DEBUG_BUILD && logger.warn('Isolation scope is default isolation scope - skipping setting transactionName'); |
| 161 | + } |
| 162 | + |
| 163 | + try { |
| 164 | + const resolveResult = await startSpan( |
| 165 | + { |
| 166 | + op: 'http.server', |
| 167 | + attributes: { |
| 168 | + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.sveltekit', |
| 169 | + [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: event.route?.id ? 'route' : 'url', |
| 170 | + 'http.method': event.request.method, |
| 171 | + }, |
| 172 | + name: routeName, |
| 173 | + }, |
| 174 | + async (span?: Span) => { |
| 175 | + getCurrentScope().setSDKProcessingMetadata({ |
| 176 | + normalizedRequest: winterCGRequestToRequestData(event.request.clone()), |
| 177 | + }); |
| 178 | + const res = await resolve(event, { |
| 179 | + transformPageChunk: addSentryCodeToPage(options), |
| 180 | + }); |
| 181 | + if (span) { |
| 182 | + setHttpStatus(span, res.status); |
| 183 | + } |
| 184 | + return res; |
| 185 | + }, |
| 186 | + ); |
| 187 | + return resolveResult; |
| 188 | + } catch (e: unknown) { |
| 189 | + sendErrorToSentry(e, 'handle'); |
| 190 | + throw e; |
| 191 | + } finally { |
| 192 | + await flushIfServerless(); |
| 193 | + } |
| 194 | +} |
0 commit comments