Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(sveltekit): Fix SvelteKit Cloudflare usage #14672

Open
wants to merge 15 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions packages/sveltekit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
"./package.json": "./package.json",
".": {
"types": "./build/types/index.types.d.ts",
"worker": {
"import": "./build/esm/index.worker.js",
"require": "./build/cjs/index.worker.js"
},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not directly applicable to this line but: I had to make this change to the node export to start the build:

Suggested change
},
"node": {
"require": "./build/cjs/index.server.js",
"import": "./build/esm/index.server.js"
}

However, even after this change, I get another error a bit later

Copy link
Contributor

@aloisklink aloisklink Dec 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @Lms24 if this isn't the right place to discuss this, but is there any reason why we don't make this change in a separate PR?

I'm having an issue where trying to import import * as Sentry from '@sentry/sveltekit'; using ESM in Node.JS has all the @sentry/node imports under Sentry.default, and the above change seems to fix it.

From reading #9872 (comment), it looks like ESM used to be broken, but I think 7f2e804 might have fixed it? But a similar change for remix seems to have not worked: #12742

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aloisklink sorry for only seeing your comment now: I agree, we should make this change separately. Thing is, as far as I know, SvelteKit transpiles to CJS (at least for Node-based environments). So I'm a bit hesitant to add an ESM entry point, especially because this works even less well than it currently works in CJS, with OpenTelemetry.

Feel free to submit a PR and let's see what our tests have to see

"browser": {
"import": "./build/esm/index.client.js",
"require": "./build/cjs/index.client.js"
Expand All @@ -44,6 +48,7 @@
"@sentry/node": "8.43.0",
"@sentry/opentelemetry": "8.43.0",
"@sentry/svelte": "8.43.0",
"@sentry/cloudflare": "8.43.0",
"@sentry/vite-plugin": "2.22.6",
"magic-string": "0.30.7",
"magicast": "0.2.8",
Expand Down
2 changes: 1 addition & 1 deletion packages/sveltekit/rollup.npm.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollu

export default makeNPMConfigVariants(
makeBaseNPMConfig({
entrypoints: ['src/index.server.ts', 'src/index.client.ts', 'src/client/index.ts', 'src/server/index.ts'],
entrypoints: ['src/index.server.ts', 'src/index.client.ts', 'src/index.worker.ts', 'src/client/index.ts', 'src/server/index.ts', 'src/worker/index.ts'],
packageSpecificConfig: {
external: ['$app/stores'],
output: {
Expand Down
4 changes: 4 additions & 0 deletions packages/sveltekit/src/index.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
export * from './client';
export * from './vite';
export * from './server';
export * from './worker';

// Use the ./server version of some functions that are also exported from ./worker
export { wrapServerLoadWithSentry, wrapServerRouteWithSentry, sentryHandle } from './server';

import type { Client, Integration, Options, StackParser } from '@sentry/core';
import type { HandleClientError, HandleServerError } from '@sveltejs/kit';
Expand Down
2 changes: 2 additions & 0 deletions packages/sveltekit/src/index.worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './worker';
// export * from './vite';
218 changes: 218 additions & 0 deletions packages/sveltekit/src/worker/handle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
import type { Span } from '@sentry/core';
import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
getActiveSpan,
getCurrentScope,
getDefaultIsolationScope,
getIsolationScope,
getTraceMetaTags,
logger,
setHttpStatus,
startSpan,
winterCGRequestToRequestData,
withIsolationScope,
} from '@sentry/core';
import { CloudflareOptions, continueTrace, wrapRequestHandler } from '@sentry/cloudflare';
import type { Handle, ResolveOptions } from '@sveltejs/kit';

import { DEBUG_BUILD } from '../common/debug-build';
import { flushIfServerless, getTracePropagationData, sendErrorToSentry } from './utils';

export type SentryHandleOptions = {
/**
* Controls whether the SDK should capture errors and traces in requests that don't belong to a
* route defined in your SvelteKit application.
*
* By default, this option is set to `false` to reduce noise (e.g. bots sending random requests to your server).
*
* Set this option to `true` if you want to monitor requests events without a route. This might be useful in certain
* scenarios, for instance if you registered other handlers that handle these requests.
* If you set this option, you might want adjust the the transaction name in the `beforeSendTransaction`
* callback of your server-side `Sentry.init` options. You can also use `beforeSendTransaction` to filter out
* transactions that you still don't want to be sent to Sentry.
*
* @default false
*/
handleUnknownRoutes?: boolean;

/**
* Controls if `sentryHandle` should inject a script tag into the page that enables instrumentation
* of `fetch` calls in `load` functions.
*
* @default true
*/
injectFetchProxyScript?: boolean;

/**
* If this option is set, the `sentryHandle` handler will add a nonce attribute to the script
* tag it injects into the page. This script is used to enable instrumentation of `fetch` calls
* in `load` functions.
*
* Use this if your CSP policy blocks the fetch proxy script injected by `sentryHandle`.
*/
fetchProxyScriptNonce?: string;
};

/**
* Exported only for testing
*/
export const FETCH_PROXY_SCRIPT = `
const f = window.fetch;
if(f){
window._sentryFetchProxy = function(...a){return f(...a)}
window.fetch = function(...a){return window._sentryFetchProxy(...a)}
}
`;

/**
* Adds Sentry tracing <meta> tags to the returned html page.
* Adds Sentry fetch proxy script to the returned html page if enabled in options.
* Also adds a nonce attribute to the script tag if users specified one for CSP.
*
* Exported only for testing
*/
export function addSentryCodeToPage(options: SentryHandleOptions): NonNullable<ResolveOptions['transformPageChunk']> {
const { fetchProxyScriptNonce, injectFetchProxyScript } = options;
// if injectFetchProxyScript is not set, we default to true
const shouldInjectScript = injectFetchProxyScript !== false;
const nonce = fetchProxyScriptNonce ? `nonce="${fetchProxyScriptNonce}"` : '';

return ({ html }) => {
const metaTags = getTraceMetaTags();
const headWithMetaTags = metaTags ? `<head>\n${metaTags}` : '<head>';

const headWithFetchScript = shouldInjectScript ? `\n<script ${nonce}>${FETCH_PROXY_SCRIPT}</script>` : '';

const modifiedHead = `${headWithMetaTags}${headWithFetchScript}`;

return html.replace('<head>', modifiedHead);
};
}

/**
* A SvelteKit handle function that wraps the request for Sentry error and
* performance monitoring.
*
* This doesn't currently use OTEL, as it isn't available outside of Node
*
* Usage:
* ```
* // src/hooks.server.ts
* import { sentryHandle } from '@sentry/sveltekit';
*
* export const handle = sentryHandle();
*
* // Optionally use the `sequence` function to add additional handlers.
* // export const handle = sequence(sentryHandle(), yourCustomHandler);
* ```
*/
export function sentryHandle(handlerOptions?: SentryHandleOptions): Handle {
const options = {
handleUnknownRoutes: false,
injectFetchProxyScript: true,
...handlerOptions,
};

const sentryRequestHandler: Handle = input => {
// event.isSubRequest was added in SvelteKit 1.21.0 and we can use it to check
// if we should create a new execution context or not.
// In case of a same-origin `fetch` call within a server`load` function,
// SvelteKit will actually just re-enter the `handle` function and set `isSubRequest`
// to `true` so that no additional network call is made.
// We want the `http.server` span of that nested call to be a child span of the
// currently active span instead of a new root span to correctly reflect this
// behavior.
// As a fallback for Kit < 1.21.0, we check if there is an active span only if there's none,
// we create a new execution context.
const isSubRequest = typeof input.event.isSubRequest === 'boolean' ? input.event.isSubRequest : !!getActiveSpan();

if (isSubRequest) {
return instrumentHandle(input, options);
}

return withIsolationScope(isolationScope => {
// We only call continueTrace in the initial top level request to avoid
// creating a new root span for the sub request.
isolationScope.setSDKProcessingMetadata({
normalizedRequest: winterCGRequestToRequestData(input.event.request.clone()),
});
return continueTrace(getTracePropagationData(input.event), () => instrumentHandle(input, options));
});
};

return sentryRequestHandler;
}

async function instrumentHandle(
{ event, resolve }: Parameters<Handle>[0],
options: SentryHandleOptions,
): Promise<Response> {
if (!event.route?.id && !options.handleUnknownRoutes) {
return resolve(event);
}

const routeName = `${event.request.method} ${event.route?.id || event.url.pathname}`;

if (getIsolationScope() !== getDefaultIsolationScope()) {
getIsolationScope().setTransactionName(routeName);
} else {
DEBUG_BUILD && logger.warn('Isolation scope is default isolation scope - skipping setting transactionName');
}

try {
const resolveResult = await startSpan(
{
op: 'http.server',
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.sveltekit',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: event.route?.id ? 'route' : 'url',
'http.method': event.request.method,
},
name: routeName,
},
async (span?: Span) => {
getCurrentScope().setSDKProcessingMetadata({
normalizedRequest: winterCGRequestToRequestData(event.request.clone()),
});
const res = await resolve(event, {
transformPageChunk: addSentryCodeToPage(options),
});
if (span) {
setHttpStatus(span, res.status);
}
return res;
},
);
return resolveResult;
} catch (e: unknown) {
sendErrorToSentry(e, 'handle');
throw e;
} finally {
await flushIfServerless();
}
}

/** Initializes Sentry SvelteKit Cloudflare SDK
* This should be before the sentryHandle() call.
* */
export function initCloudflareSentryHandle(handlerOptions: CloudflareOptions): Handle {
const options = { ...handlerOptions };

const handleInitSentry: Handle = ({ event, resolve }) => {
// if event.platform exists (should be there in a cloudflare worker), then do the cloudflare sentry init
return event.platform
? wrapRequestHandler(
{
options,
request: event.request,
// @ts-expect-error This will exist in Cloudflare
context: event.platform.context,
},
() => resolve(event),
)
: resolve(event);
};

return handleInitSentry;
}
80 changes: 80 additions & 0 deletions packages/sveltekit/src/worker/handleError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { consoleSandbox } from '@sentry/core';
import { captureException } from '@sentry/cloudflare';
import type { HandleServerError } from '@sveltejs/kit';

import { flushIfServerless } from './utils';

// The SvelteKit default error handler just logs the error's stack trace to the console
// see: https://github.com/sveltejs/kit/blob/369e7d6851f543a40c947e033bfc4a9506fdc0a8/packages/kit/src/runtime/server/index.js#L43
function defaultErrorHandler({ error }: Parameters<HandleServerError>[0]): ReturnType<HandleServerError> {
// @ts-expect-error this conforms to the default implementation (including this ts-expect-error)
// eslint-disable-next-line no-console
consoleSandbox(() => console.error(error && error.stack));
}

type HandleServerErrorInput = Parameters<HandleServerError>[0];

/**
* Backwards-compatible HandleServerError Input type for SvelteKit 1.x and 2.x
* `message` and `status` were added in 2.x.
* For backwards-compatibility, we make them optional
*
* @see https://kit.svelte.dev/docs/migrating-to-sveltekit-2#improved-error-handling
*/
type SafeHandleServerErrorInput = Omit<HandleServerErrorInput, 'status' | 'message'> &
Partial<Pick<HandleServerErrorInput, 'status' | 'message'>>;

/**
* Wrapper for the SvelteKit error handler that sends the error to Sentry.
*
* @param handleError The original SvelteKit error handler.
*/
export function handleErrorWithSentry(handleError: HandleServerError = defaultErrorHandler): HandleServerError {
return async (input: SafeHandleServerErrorInput): Promise<void | App.Error> => {
if (isNotFoundError(input)) {
// We're extra cautious with SafeHandleServerErrorInput - this type is not compatible with HandleServerErrorInput
// @ts-expect-error - we're still passing the same object, just with a different (backwards-compatible) type
return handleError(input);
}

captureException(input.error, {
mechanism: {
type: 'sveltekit',
handled: false,
},
});

await flushIfServerless();

// We're extra cautious with SafeHandleServerErrorInput - this type is not compatible with HandleServerErrorInput
// @ts-expect-error - we're still passing the same object, just with a different (backwards-compatible) type
return handleError(input);
};
}

/**
* When a page request fails because the page is not found, SvelteKit throws a "Not found" error.
*/
function isNotFoundError(input: SafeHandleServerErrorInput): boolean {
const { error, event, status } = input;

// SvelteKit 2.0 offers a reliable way to check for a Not Found error:
if (status === 404) {
return true;
}

// SvelteKit 1.x doesn't offer a reliable way to check for a Not Found error.
// So we check the route id (shouldn't exist) and the raw stack trace
// We can delete all of this below whenever we drop Kit 1.x support
const hasNoRouteId = !event.route || !event.route.id;

const rawStack: string =
(error != null &&
typeof error === 'object' &&
'stack' in error &&
typeof error.stack === 'string' &&
error.stack) ||
'';

return hasNoRouteId && rawStack.startsWith('Error: Not found:');
}
Loading
Loading