Repository navigation
feat(sveltekit): Serve the managed tunnel from sentryHandle under the app's base path
#25415
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
Changes from all commits
2a1c1f3
e44ffbe
7077bc3
f663ab2
4a3bc1c
b116a00
3751e85
ec3741a
570e532
cb4a1dc
58661de
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,7 +10,7 @@ export const handle = sequence( | |
| environment: 'qa', // dynamic sampling bias to keep spans | ||
| dsn: E2E_TEST_DSN, | ||
| debug: !!process.env.DEBUG, | ||
| tunnel: 'http://localhost:3031/', // proxy server | ||
| tunnel: __E2E_TEST_TUNNEL__ ? true : 'http://localhost:3031/', // proxy server | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same q here |
||
| tracesSampleRate: 1.0, | ||
| }), | ||
| sentryHandle(), | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { expect, test } from '@playwright/test'; | ||
| import { getSpanOp, isServerSpanAt, waitForStreamedSpan, watchForTunnelSpan } from '@sentry-internal/test-utils'; | ||
|
|
||
| test.skip(!process.env.E2E_TEST_TUNNEL, 'Only runs in the tunnel variant'); | ||
|
|
||
| const APP_NAME = 'sveltekit-3-cloudflare-workers'; | ||
| const TUNNEL_PATH = /^\/app\/[a-z0-9]{1,7}$/; | ||
|
|
||
| test('serves the managed tunnel from the Worker under the base path', async ({ page }) => { | ||
| const pageloadSpanPromise = waitForStreamedSpan(APP_NAME, span => getSpanOp(span) === 'pageload' && span.is_segment); | ||
| const raceTunnelSpan = watchForTunnelSpan(APP_NAME, isServerSpanAt(TUNNEL_PATH)); | ||
| const tunnelResponsePromise = page.waitForResponse( | ||
| response => response.request().method() === 'POST' && TUNNEL_PATH.test(new URL(response.url()).pathname), | ||
| ); | ||
|
|
||
| await page.goto('/app/'); | ||
|
|
||
| expect((await tunnelResponsePromise).status()).toBe(200); | ||
| await expect(pageloadSpanPromise).resolves.toBeDefined(); | ||
| expect( | ||
| await raceTunnelSpan(isServerSpanAt('/app/server-load-error'), () => page.request.get('/app/server-load-error')), | ||
| ).toBe('anchor'); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import { expect, test } from '@playwright/test'; | ||
| import { waitForError, watchForTunnelSpan } from '@sentry-internal/test-utils'; | ||
| import type { SerializedStreamedSpan } from '@sentry-internal/test-utils'; | ||
|
|
||
| test.skip(!process.env.E2E_TEST_TUNNEL, 'Only runs in the tunnel variant'); | ||
|
|
||
| const APP_NAME = 'sveltekit-3'; | ||
| const TUNNEL_PATH = /^\/app\/[a-z0-9]{1,7}$/; | ||
|
|
||
| // Kit's own `sveltekit.handle.root` span starts with only `http.url`, no `url.path`. | ||
| function getSpanPath(span: SerializedStreamedSpan): string { | ||
| const url = String(span.attributes['http.url']?.value ?? span.attributes['url.path']?.value ?? ''); | ||
|
|
||
| return url.startsWith('http') ? new URL(url).pathname : url; | ||
| } | ||
|
|
||
| test('sends client events through the managed tunnel under the base path, without spans of it', async ({ page }) => { | ||
| const errorEventPromise = waitForError(APP_NAME, event => event?.exception?.values?.[0]?.value === 'Click Error'); | ||
| const raceTunnelSpan = watchForTunnelSpan(APP_NAME, span => TUNNEL_PATH.test(getSpanPath(span))); | ||
|
|
||
| // The pageload envelope is the first tunnel request, and it's only sent once the app hydrated. | ||
| const tunnelResponsePromise = page.waitForResponse( | ||
| response => response.request().method() === 'POST' && TUNNEL_PATH.test(new URL(response.url()).pathname), | ||
| ); | ||
| await page.goto('/app/client-error'); | ||
|
|
||
| expect((await tunnelResponsePromise).status()).toBe(200); | ||
|
|
||
| await page.getByText('Throw error').click(); | ||
| await expect(errorEventPromise).resolves.toBeDefined(); | ||
|
|
||
| expect( | ||
| await raceTunnelSpan( | ||
| span => getSpanPath(span).endsWith('/app/users/123'), | ||
| () => page.request.get('/app/users/123'), | ||
| ), | ||
| ).toBe('anchor'); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import type { SerializedStreamedSpan } from '@sentry/core'; | ||
| import { getSpanOp, waitForStreamedSpan } from './event-proxy-server'; | ||
|
|
||
| type SpanMatcher = (span: SerializedStreamedSpan) => boolean; | ||
|
|
||
| /** | ||
| * Matches an `http.server` span whose `url.path` equals or matches `path`. | ||
| */ | ||
| export function isServerSpanAt(path: string | RegExp): SpanMatcher { | ||
| return span => { | ||
| const urlPath = String(span.attributes['url.path']?.value ?? ''); | ||
|
|
||
| return getSpanOp(span) === 'http.server' && (typeof path === 'string' ? urlPath === path : path.test(urlPath)); | ||
|
logaretm marked this conversation as resolved.
|
||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Starts listening for a span of a tunnel request. Call it before the tunnel traffic, then call the returned function | ||
| * with a regular request made after it. Spans flush in order, so it resolves to `'tunnel'` if the tunnel request | ||
| * created a span, and to `'anchor'` otherwise, without waiting on a timeout. | ||
| */ | ||
| export function watchForTunnelSpan( | ||
| proxyServerName: string, | ||
| isTunnelSpan: SpanMatcher, | ||
| ): (isAnchorSpan: SpanMatcher, requestAnchor: () => Promise<unknown>) => Promise<'tunnel' | 'anchor'> { | ||
| const tunnelSpanPromise = waitForStreamedSpan(proxyServerName, isTunnelSpan); | ||
|
|
||
| return async (isAnchorSpan, requestAnchor) => { | ||
| const anchorSpanPromise = waitForStreamedSpan(proxyServerName, isAnchorSpan); | ||
| await requestAnchor(); | ||
|
|
||
| return Promise.race([ | ||
| tunnelSpanPromise.then(() => 'tunnel' as const), | ||
| anchorSpanPromise.then(() => 'anchor' as const), | ||
| ]); | ||
| }; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import type { Options } from '@sentry/core'; | ||
| import { _INTERNAL_applyTunnelDefaults as applyTunnelDefaults, GLOBAL_OBJ } from '@sentry/core'; | ||
|
|
||
| /** Set by `sentrySvelteKit()` to the app's `paths.base`. */ | ||
| export const TUNNEL_BASE_PATH_GLOBAL = '__sentry_sveltekit_base_path'; | ||
|
|
||
| /** | ||
| * Serves the managed tunnel under the app's base path, which SvelteKit requires for every request it handles. | ||
| * A `basePath` the user set wins. | ||
| */ | ||
| export function applyTunnelBasePath(options: Pick<Options, 'tunnel'>): void { | ||
| const basePath = (GLOBAL_OBJ as { [TUNNEL_BASE_PATH_GLOBAL]?: string })[TUNNEL_BASE_PATH_GLOBAL]; | ||
| options.tunnel = applyTunnelDefaults(options.tunnel, { basePath }); | ||
| } |
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. m/q: can we use |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| import { escapeStringForRegex } from '@sentry/core'; | ||
| import MagicString from 'magic-string'; | ||
| import type { Plugin } from 'vite'; | ||
| import { TUNNEL_BASE_PATH_GLOBAL } from '../common/tunnel'; | ||
| import type { ResolvedKitConfig } from './kitConfig'; | ||
| import { getHooksFileName } from './svelteConfig'; | ||
|
|
||
| const VIRTUAL_BASE_PATH_FILE = '\0sentry-sveltekit-tunnel-base-path'; | ||
|
|
||
| /** | ||
| * Hands the app's `paths.base` to the client and server SDKs so `tunnel: true` works under a base path without | ||
| * the user repeating it. It's imported first in the hooks files, so it's set before any `init` they import. | ||
| */ | ||
| export function makeTunnelBasePathPlugin(getKitConfig: () => Promise<ResolvedKitConfig>): Plugin { | ||
| let basePath = ''; | ||
| let entryFileRegexp: RegExp | undefined; | ||
|
|
||
| return { | ||
| name: 'sentry-sveltekit-tunnel-base-path', | ||
|
|
||
| configResolved: async () => { | ||
| const kitConfig = await getKitConfig(); | ||
| basePath = kitConfig.paths?.base || ''; | ||
|
|
||
| const hooksFiles = [getHooksFileName(kitConfig, 'server'), getHooksFileName(kitConfig, 'client')] | ||
| .map(escapeStringForRegex) | ||
| .join('|'); | ||
| // oxlint-disable-next-line sdk/no-regexp-constructor -- not end user input + escaped anyway | ||
| entryFileRegexp = new RegExp(`/(?:${hooksFiles}|src/instrumentation\\.server)\\.(?:js|ts|mjs|mts)$`); | ||
| }, | ||
|
|
||
| resolveId: id => (id === VIRTUAL_BASE_PATH_FILE ? { id, moduleSideEffects: true } : null), | ||
|
|
||
| load: id => | ||
| id === VIRTUAL_BASE_PATH_FILE | ||
| ? `globalThis[${JSON.stringify(TUNNEL_BASE_PATH_GLOBAL)}] = ${JSON.stringify(basePath)};` | ||
| : null, | ||
|
|
||
| transform: (code, id) => { | ||
| if (!basePath || !entryFileRegexp?.test(id)) { | ||
| return null; | ||
| } | ||
|
|
||
| const ms = new MagicString(code); | ||
| ms.prepend(`import ${JSON.stringify(VIRTUAL_BASE_PATH_FILE)};\n`); | ||
|
|
||
| return { code: ms.toString(), map: ms.generateMap({ hires: true }) }; | ||
| }, | ||
| }; | ||
| } |
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.
super-l: Can we import the env variable instead of the build time transform? Basically like for
E2E_TEST_DSN?