Skip to content

Commit e0316f7

Browse files
committed
wip but detect tracing config at SDK setup time
1 parent 2b8d229 commit e0316f7

File tree

6 files changed

+87
-11
lines changed

6 files changed

+87
-11
lines changed

packages/sveltekit/src/server-common/processKitSpans.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import { type SpanJSON, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_
99
export function svelteKitSpansIntegration(): Integration {
1010
return {
1111
name: 'SvelteKitSpansEnhancment',
12+
// Using preprocessEvent to ensure the processing happens before user-configured
13+
// event processors are executed
1214
preprocessEvent(event) {
1315
if (event.type === 'transaction') {
1416
event.spans?.forEach(_enhanceKitSpan);

packages/sveltekit/src/server-common/utils.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import { captureException, objectify } from '@sentry/core';
1+
import { captureException, GLOBAL_OBJ, objectify } from '@sentry/core';
22
import type { RequestEvent } from '@sveltejs/kit';
33
import { isHttpError, isRedirect } from '../common/utils';
4+
import type { GlobalWithSentryValues } from '../vite/injectGlobalValues';
45

56
/**
67
* Takes a request event and extracts traceparent and DSC data
@@ -52,3 +53,17 @@ export function sendErrorToSentry(e: unknown, handlerFn: 'handle' | 'load' | 'se
5253

5354
return objectifiedErr;
5455
}
56+
57+
/**
58+
* During build, we inject the SvelteKit tracing config into the global object of the server.
59+
* @returns tracing config (available since 2.31.0)
60+
*/
61+
export function getKitTracingConfig(): { instrumentation: boolean; tracing: boolean } {
62+
const globalWithSentryValues: GlobalWithSentryValues = GLOBAL_OBJ;
63+
const kitTracingConfig = globalWithSentryValues.__sentry_sveltekit_tracing_config;
64+
65+
return {
66+
instrumentation: kitTracingConfig?.instrumentation?.server ?? false,
67+
tracing: kitTracingConfig?.tracing?.server ?? false,
68+
};
69+
}

packages/sveltekit/src/server/sdk.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,35 @@
11
import { applySdkMetadata } from '@sentry/core';
22
import type { NodeClient, NodeOptions } from '@sentry/node';
3-
import { getDefaultIntegrations as getDefaultNodeIntegrations, init as initNodeSdk } from '@sentry/node';
3+
import {
4+
getDefaultIntegrations as getDefaultNodeIntegrations,
5+
httpIntegration,
6+
init as initNodeSdk,
7+
} from '@sentry/node';
48
import { svelteKitSpansIntegration } from '../server-common/processKitSpans';
59
import { rewriteFramesIntegration } from '../server-common/rewriteFramesIntegration';
10+
import { getKitTracingConfig } from '../server-common/utils';
611

712
/**
813
* Initialize the Server-side Sentry SDK
914
* @param options
1015
*/
1116
export function init(options: NodeOptions): NodeClient | undefined {
17+
const defaultIntegrations = [...getDefaultNodeIntegrations(options), rewriteFramesIntegration()];
18+
19+
const config = getKitTracingConfig();
20+
if (config.instrumentation) {
21+
// Whenever `instrumentation` is enabled, we don't need httpIntegration to emit spans
22+
// - if `tracing` is enabled, kit will emit the root span
23+
// - if `tracing` is disabled, our handler will emit the root span
24+
defaultIntegrations.push(httpIntegration({ disableIncomingRequestSpans: true }));
25+
if (config.tracing) {
26+
// If `tracing` is enabled, we need to instrument spans for the server
27+
defaultIntegrations.push(svelteKitSpansIntegration());
28+
}
29+
}
30+
1231
const opts = {
13-
defaultIntegrations: [
14-
...getDefaultNodeIntegrations(options),
15-
rewriteFramesIntegration(),
16-
svelteKitSpansIntegration(),
17-
],
32+
defaultIntegrations,
1833
...options,
1934
};
2035

packages/sveltekit/src/vite/injectGlobalValues.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import type { InternalGlobal } from '@sentry/core';
2+
import type { SvelteKitTracingConfig } from './svelteConfig';
23

34
export type GlobalSentryValues = {
45
__sentry_sveltekit_output_dir?: string;
6+
__sentry_sveltekit_tracing_config?: SvelteKitTracingConfig;
57
};
68

79
/**

packages/sveltekit/src/vite/sourceMaps.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import type { Plugin, UserConfig } from 'vite';
1111
import { WRAPPED_MODULE_SUFFIX } from '../common/utils';
1212
import type { GlobalSentryValues } from './injectGlobalValues';
1313
import { getGlobalValueInjectionCode, VIRTUAL_GLOBAL_VALUES_FILE } from './injectGlobalValues';
14-
import { getAdapterOutputDir, getHooksFileName, loadSvelteConfig } from './svelteConfig';
14+
import { getAdapterOutputDir, getHooksFileName, getTracingConfig, loadSvelteConfig } from './svelteConfig';
1515
import type { CustomSentryVitePluginOptions } from './types';
1616

1717
// sorcery has no types, so these are some basic type definitions:
@@ -153,8 +153,11 @@ export async function makeCustomSentryVitePlugins(options?: CustomSentryVitePlug
153153

154154
const globalSentryValues: GlobalSentryValues = {
155155
__sentry_sveltekit_output_dir: adapterOutputDir,
156+
__sentry_sveltekit_tracing_config: getTracingConfig(svelteConfig),
156157
};
157158

159+
console.log('xx globalSentryValues', globalSentryValues);
160+
158161
const sourceMapSettingsPlugin: Plugin = {
159162
name: 'sentry-sveltekit-update-source-map-setting-plugin',
160163
apply: 'build', // only apply this plugin at build time
@@ -235,8 +238,10 @@ export async function makeCustomSentryVitePlugins(options?: CustomSentryVitePlug
235238
transform: async (code, id) => {
236239
// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- not end user input + escaped anyway
237240
const isServerHooksFile = new RegExp(`/${escapeStringForRegex(serverHooksFile)}(.(js|ts|mjs|mts))?`).test(id);
241+
const isInstrumentationServerFile = /instrumentation\.server\./.test(id);
238242

239-
if (isServerHooksFile) {
243+
if (isServerHooksFile || isInstrumentationServerFile) {
244+
console.log('xx inject global values', id);
240245
const ms = new MagicString(code);
241246
ms.append(`\n; import "${VIRTUAL_GLOBAL_VALUES_FILE}";\n`);
242247
return {

packages/sveltekit/src/vite/svelteConfig.ts

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,31 @@ import * as path from 'path';
44
import * as url from 'url';
55
import type { SupportedSvelteKitAdapters } from './detectAdapter';
66

7+
export type SvelteKitTracingConfig = {
8+
tracing?: {
9+
server: boolean;
10+
};
11+
instrumentation?: {
12+
server: boolean;
13+
};
14+
};
15+
16+
/**
17+
* Experimental tracing and instrumentation config is available
18+
* @since 2.31.0
19+
*/
20+
type BackwardsForwardsCompatibleKitConfig = Config['kit'] & { experimental?: SvelteKitTracingConfig };
21+
22+
interface BackwardsForwardsCompatibleSvelteConfig extends Config {
23+
kit?: BackwardsForwardsCompatibleKitConfig;
24+
}
25+
726
/**
827
* Imports the svelte.config.js file and returns the config object.
928
* The sveltekit plugins import the config in the same way.
1029
* See: https://github.com/sveltejs/kit/blob/master/packages/kit/src/core/config/index.js#L63
1130
*/
12-
export async function loadSvelteConfig(): Promise<Config> {
31+
export async function loadSvelteConfig(): Promise<BackwardsForwardsCompatibleSvelteConfig> {
1332
// This can only be .js (see https://github.com/sveltejs/kit/pull/4031#issuecomment-1049475388)
1433
const SVELTE_CONFIG_FILE = 'svelte.config.js';
1534

@@ -23,7 +42,7 @@ export async function loadSvelteConfig(): Promise<Config> {
2342
const svelteConfigModule = await import(`${url.pathToFileURL(configFile).href}`);
2443

2544
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
26-
return (svelteConfigModule?.default as Config) || {};
45+
return (svelteConfigModule?.default as BackwardsForwardsCompatibleSvelteConfig) || {};
2746
} catch (e) {
2847
// eslint-disable-next-line no-console
2948
console.warn("[Source Maps Plugin] Couldn't load svelte.config.js:");
@@ -110,3 +129,21 @@ async function getNodeAdapterOutputDir(svelteConfig: Config): Promise<string> {
110129

111130
return outputDir;
112131
}
132+
133+
/**
134+
* Returns the Sveltekit tracing config users can enable in svelte.config.js.
135+
* Available in Kit @since 2.31.0
136+
*/
137+
export function getTracingConfig(
138+
svelteConfig: BackwardsForwardsCompatibleSvelteConfig,
139+
): BackwardsForwardsCompatibleKitConfig['experimental'] {
140+
const experimentalConfig = svelteConfig.kit?.experimental;
141+
return {
142+
instrumentation: {
143+
server: experimentalConfig?.instrumentation?.server ?? false,
144+
},
145+
tracing: {
146+
server: experimentalConfig?.tracing?.server ?? false,
147+
},
148+
};
149+
}

0 commit comments

Comments
 (0)