-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
SG60
wants to merge
8
commits into
getsentry:develop
Choose a base branch
from
SG60:patch-1
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+589
−189
Open
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
fc47659
fix(sveltekit): Don't use node apis in cloudflare workers
SG60 31aa1d4
fix(sveltekit): provide a handle function to init cloudflare workers …
SG60 dc969b9
chore(sveltekit): refactor some common server-side code
SG60 218c2cf
chore(sveltekit): refactor the rest of the common server-side code
SG60 5aa9d54
fix(sveltekit): avoid importing fs and path in workers contexts
SG60 28b2fd3
Merge branch 'develop' into patch-1
SG60 dc510d2
test(sveltekit-cloudflare-pages): add an e2e test for @sentry/sveltek…
SG60 2c443a8
test(sveltekit-cloudflare): simpler e2e test
SG60 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export * from './worker'; | ||
// export * from './vite'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
import type { continueTrace, 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 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; | ||
}; | ||
|
||
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. | ||
*/ | ||
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); | ||
}; | ||
} | ||
|
||
export 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(); | ||
} | ||
} | ||
|
||
/** | ||
* A SvelteKit handle function that wraps the request for Sentry error and | ||
* performance monitoring. | ||
* | ||
* Some environments require a different continueTrace function. E.g. Node can use | ||
* the Opentelemetry SDK, whereas Cloudflare cannot. | ||
*/ | ||
export function sentryHandleGeneric( | ||
continueTraceFunction: typeof continueTrace, | ||
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 continueTraceFunction(getTracePropagationData(input.event), () => instrumentHandle(input, options)); | ||
}); | ||
}; | ||
|
||
return sentryRequestHandler; | ||
} |
5 changes: 2 additions & 3 deletions
5
packages/sveltekit/src/server/handleError.ts → ...veltekit/src/server-common/handleError.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
8 changes: 6 additions & 2 deletions
8
packages/sveltekit/src/server/load.ts → packages/sveltekit/src/server-common/load.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
8 changes: 6 additions & 2 deletions
8
packages/sveltekit/src/server/serverRoute.ts → ...veltekit/src/server-common/serverRoute.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 1 addition & 2 deletions
3
packages/sveltekit/src/server/utils.ts → ...ages/sveltekit/src/server-common/utils.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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:However, even after this change, I get another error a bit later
There was a problem hiding this comment.
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 underSentry.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
There was a problem hiding this comment.
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