Skip to content

Commit 0a4a072

Browse files
authored
fix(sveltekit): Handle server-only and shared load functions (#7581)
Previously, our server `wrapLoadWithSentry` wrapper assumed that `load` in `+page.ts` and `+page.server.ts` work identically. Unfortunately, the load `event` arg has different contents for both, namely that the server-only load event contains a `request` object while the shared (client and server) load event doesn't. This patch fixes that by distinguishing between the two load types within the wrapper. Users can still use the same wrapper for both cases. Furthermore, this patch removes the usage of domains in the load wrapper, as on the server-side, as we're already in a domain when `handleSentry` is used. Creating another domain here, caused the creation of a new transaction instead of adding the span to the transaction that was created by `handleSentry`.
1 parent c5f8e48 commit 0a4a072

File tree

2 files changed

+208
-57
lines changed

2 files changed

+208
-57
lines changed

packages/sveltekit/src/server/load.ts

Lines changed: 52 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
11
/* eslint-disable @sentry-internal/sdk/no-optional-chaining */
2+
import { trace } from '@sentry/core';
23
import { captureException } from '@sentry/node';
3-
import { addExceptionMechanism, isThenable, objectify } from '@sentry/utils';
4-
import type { HttpError, Load, ServerLoad } from '@sveltejs/kit';
5-
import * as domain from 'domain';
4+
import type { DynamicSamplingContext, TraceparentData, TransactionContext } from '@sentry/types';
5+
import {
6+
addExceptionMechanism,
7+
baggageHeaderToDynamicSamplingContext,
8+
extractTraceparentData,
9+
objectify,
10+
} from '@sentry/utils';
11+
import type { HttpError, Load, LoadEvent, ServerLoad, ServerLoadEvent } from '@sveltejs/kit';
612

713
function isHttpError(err: unknown): err is HttpError {
814
return typeof err === 'object' && err !== null && 'status' in err && 'body' in err;
@@ -45,25 +51,52 @@ function sendErrorToSentry(e: unknown): unknown {
4551
*/
4652
export function wrapLoadWithSentry<T extends ServerLoad | Load>(origLoad: T): T {
4753
return new Proxy(origLoad, {
48-
apply: (wrappingTarget, thisArg, args: Parameters<ServerLoad>) => {
49-
return domain.create().bind(() => {
50-
let maybePromiseResult: ReturnType<T>;
54+
apply: (wrappingTarget, thisArg, args: Parameters<ServerLoad | Load>) => {
55+
const [event] = args;
56+
const routeId = event.route && event.route.id;
5157

52-
try {
53-
maybePromiseResult = wrappingTarget.apply(thisArg, args);
54-
} catch (e) {
55-
sendErrorToSentry(e);
56-
throw e;
57-
}
58+
const { traceparentData, dynamicSamplingContext } = getTracePropagationData(event);
5859

59-
if (isThenable(maybePromiseResult)) {
60-
Promise.resolve(maybePromiseResult).then(null, e => {
61-
sendErrorToSentry(e);
62-
});
63-
}
60+
const traceLoadContext: TransactionContext = {
61+
op: 'function.sveltekit.load',
62+
name: routeId ? routeId : event.url.pathname,
63+
status: 'ok',
64+
metadata: {
65+
source: routeId ? 'route' : 'url',
66+
dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,
67+
},
68+
...traceparentData,
69+
};
6470

65-
return maybePromiseResult;
66-
})();
71+
return trace(traceLoadContext, () => wrappingTarget.apply(thisArg, args), sendErrorToSentry);
6772
},
6873
});
6974
}
75+
76+
function getTracePropagationData(event: ServerLoadEvent | LoadEvent): {
77+
traceparentData?: TraceparentData;
78+
dynamicSamplingContext?: Partial<DynamicSamplingContext>;
79+
} {
80+
if (!isServerOnlyLoad(event)) {
81+
return {};
82+
}
83+
84+
const sentryTraceHeader = event.request.headers.get('sentry-trace');
85+
const baggageHeader = event.request.headers.get('baggage');
86+
const traceparentData = sentryTraceHeader ? extractTraceparentData(sentryTraceHeader) : undefined;
87+
const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggageHeader);
88+
89+
return { traceparentData, dynamicSamplingContext };
90+
}
91+
92+
/**
93+
* Our server-side wrapLoadWithSentry can be used to wrap two different kinds of `load` functions:
94+
* - load functions from `+(page|layout).ts`: These can be called both on client and on server
95+
* - load functions from `+(page|layout).server.ts`: These are only called on the server
96+
*
97+
* In both cases, load events look differently. We can distinguish them by checking if the
98+
* event has a `request` field (which only the server-exclusive load event has).
99+
*/
100+
function isServerOnlyLoad(event: ServerLoadEvent | LoadEvent): event is ServerLoadEvent {
101+
return 'request' in event;
102+
}

packages/sveltekit/test/server/load.test.ts

Lines changed: 156 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,15 @@ const MOCK_LOAD_ARGS: any = {
5454
id: '/users/[id]',
5555
},
5656
url: new URL('http://localhost:3000/users/123'),
57+
};
58+
59+
const MOCK_LOAD_NO_ROUTE_ARGS: any = {
60+
params: { id: '123' },
61+
url: new URL('http://localhost:3000/users/123'),
62+
};
63+
64+
const MOCK_SERVER_ONLY_LOAD_ARGS: any = {
65+
...MOCK_LOAD_ARGS,
5766
request: {
5867
headers: {
5968
get: (key: string) => {
@@ -75,6 +84,32 @@ const MOCK_LOAD_ARGS: any = {
7584
},
7685
};
7786

87+
const MOCK_SERVER_ONLY_NO_TRACE_LOAD_ARGS: any = {
88+
...MOCK_LOAD_ARGS,
89+
request: {
90+
headers: {
91+
get: (_: string) => {
92+
return null;
93+
},
94+
},
95+
},
96+
};
97+
98+
const MOCK_SERVER_ONLY_NO_BAGGAGE_LOAD_ARGS: any = {
99+
...MOCK_LOAD_ARGS,
100+
request: {
101+
headers: {
102+
get: (key: string) => {
103+
if (key === 'sentry-trace') {
104+
return '1234567890abcdef1234567890abcdef-1234567890abcdef-1';
105+
}
106+
107+
return null;
108+
},
109+
},
110+
},
111+
};
112+
78113
beforeAll(() => {
79114
addTracingExtensions();
80115
});
@@ -101,44 +136,6 @@ describe('wrapLoadWithSentry', () => {
101136
expect(mockCaptureException).toHaveBeenCalledTimes(1);
102137
});
103138

104-
// TODO: enable this once we figured out how tracing the load function doesn't result in creating a new transaction
105-
it.skip('calls trace function', async () => {
106-
async function load({ params }: Parameters<ServerLoad>[0]): Promise<ReturnType<ServerLoad>> {
107-
return {
108-
post: params.id,
109-
};
110-
}
111-
112-
const wrappedLoad = wrapLoadWithSentry(load);
113-
await wrappedLoad(MOCK_LOAD_ARGS);
114-
115-
expect(mockTrace).toHaveBeenCalledTimes(1);
116-
expect(mockTrace).toHaveBeenCalledWith(
117-
{
118-
op: 'function.sveltekit.load',
119-
name: '/users/[id]',
120-
parentSampled: true,
121-
parentSpanId: '1234567890abcdef',
122-
status: 'ok',
123-
traceId: '1234567890abcdef1234567890abcdef',
124-
metadata: {
125-
dynamicSamplingContext: {
126-
environment: 'production',
127-
public_key: 'dogsarebadatkeepingsecrets',
128-
release: '1.0.0',
129-
sample_rate: '1',
130-
trace_id: '1234567890abcdef1234567890abcdef',
131-
transaction: 'dogpark',
132-
user_segment: 'segmentA',
133-
},
134-
source: 'route',
135-
},
136-
},
137-
expect.any(Function),
138-
expect.any(Function),
139-
);
140-
});
141-
142139
describe('with error() helper', () => {
143140
it.each([
144141
// [statusCode, timesCalled]
@@ -189,4 +186,125 @@ describe('wrapLoadWithSentry', () => {
189186
{ handled: false, type: 'sveltekit', data: { function: 'load' } },
190187
);
191188
});
189+
190+
describe('calls trace', () => {
191+
async function load({ params }: Parameters<ServerLoad>[0]): Promise<ReturnType<ServerLoad>> {
192+
return {
193+
post: params.id,
194+
};
195+
}
196+
197+
describe('for server-only load', () => {
198+
it('attaches trace data if available', async () => {
199+
const wrappedLoad = wrapLoadWithSentry(load);
200+
await wrappedLoad(MOCK_SERVER_ONLY_LOAD_ARGS);
201+
202+
expect(mockTrace).toHaveBeenCalledTimes(1);
203+
expect(mockTrace).toHaveBeenCalledWith(
204+
{
205+
op: 'function.sveltekit.load',
206+
name: '/users/[id]',
207+
parentSampled: true,
208+
parentSpanId: '1234567890abcdef',
209+
status: 'ok',
210+
traceId: '1234567890abcdef1234567890abcdef',
211+
metadata: {
212+
dynamicSamplingContext: {
213+
environment: 'production',
214+
public_key: 'dogsarebadatkeepingsecrets',
215+
release: '1.0.0',
216+
sample_rate: '1',
217+
trace_id: '1234567890abcdef1234567890abcdef',
218+
transaction: 'dogpark',
219+
user_segment: 'segmentA',
220+
},
221+
source: 'route',
222+
},
223+
},
224+
expect.any(Function),
225+
expect.any(Function),
226+
);
227+
});
228+
229+
it("doesn't attach trace data if it's not available", async () => {
230+
const wrappedLoad = wrapLoadWithSentry(load);
231+
await wrappedLoad(MOCK_SERVER_ONLY_NO_TRACE_LOAD_ARGS);
232+
233+
expect(mockTrace).toHaveBeenCalledTimes(1);
234+
expect(mockTrace).toHaveBeenCalledWith(
235+
{
236+
op: 'function.sveltekit.load',
237+
name: '/users/[id]',
238+
status: 'ok',
239+
metadata: {
240+
source: 'route',
241+
},
242+
},
243+
expect.any(Function),
244+
expect.any(Function),
245+
);
246+
});
247+
248+
it("doesn't attach the DSC data if the baggage header not available", async () => {
249+
const wrappedLoad = wrapLoadWithSentry(load);
250+
await wrappedLoad(MOCK_SERVER_ONLY_NO_BAGGAGE_LOAD_ARGS);
251+
252+
expect(mockTrace).toHaveBeenCalledTimes(1);
253+
expect(mockTrace).toHaveBeenCalledWith(
254+
{
255+
op: 'function.sveltekit.load',
256+
name: '/users/[id]',
257+
parentSampled: true,
258+
parentSpanId: '1234567890abcdef',
259+
status: 'ok',
260+
traceId: '1234567890abcdef1234567890abcdef',
261+
metadata: {
262+
dynamicSamplingContext: {},
263+
source: 'route',
264+
},
265+
},
266+
expect.any(Function),
267+
expect.any(Function),
268+
);
269+
});
270+
});
271+
272+
it('for shared load', async () => {
273+
const wrappedLoad = wrapLoadWithSentry(load);
274+
await wrappedLoad(MOCK_LOAD_ARGS);
275+
276+
expect(mockTrace).toHaveBeenCalledTimes(1);
277+
expect(mockTrace).toHaveBeenCalledWith(
278+
{
279+
op: 'function.sveltekit.load',
280+
name: '/users/[id]',
281+
status: 'ok',
282+
metadata: {
283+
source: 'route',
284+
},
285+
},
286+
expect.any(Function),
287+
expect.any(Function),
288+
);
289+
});
290+
291+
it('falls back to the raw url if `event.route.id` is not available', async () => {
292+
const wrappedLoad = wrapLoadWithSentry(load);
293+
await wrappedLoad(MOCK_LOAD_NO_ROUTE_ARGS);
294+
295+
expect(mockTrace).toHaveBeenCalledTimes(1);
296+
expect(mockTrace).toHaveBeenCalledWith(
297+
{
298+
op: 'function.sveltekit.load',
299+
name: '/users/123',
300+
status: 'ok',
301+
metadata: {
302+
source: 'url',
303+
},
304+
},
305+
expect.any(Function),
306+
expect.any(Function),
307+
);
308+
});
309+
});
192310
});

0 commit comments

Comments
 (0)