Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"start": "PORT=3030 node dist/server/node.js",
"start:cloudflare": "wrangler dev --config ./dist/server/wrangler.json --port 3030",
"test:prod": "TEST_ENV=production playwright test",
"test:observe": "SOLID_OBSERVE=1 TEST_ENV=production playwright test",
"test:build": "pnpm install && pnpm build",
"test:build:observe": "pnpm install && pnpm build:observe",
"test:assert": "pnpm test:prod"
Expand Down Expand Up @@ -39,7 +40,7 @@
"variants": [
{
"build-command": "pnpm test:build:observe",
"assert-command": "pnpm test:prod",
"assert-command": "pnpm test:observe",
"label": "solid-2-ssr (observe build)"
},
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect, test } from '@playwright/test';
import { CODE_FUNCTION_NAME, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
import { FUNCTION, HTTP_SERVER } from '@sentry/conventions/op';
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';

test('adds a span for a server function execution on observe builds', async ({ page }) => {
test.skip(process.env.SOLID_OBSERVE !== '1', 'Only observe builds record server function executions');

const functionSpanPromise = waitForStreamedSpan('solid-2-ssr', span => {
return (
getSpanOp(span) === FUNCTION && span.attributes?.[SENTRY_ORIGIN]?.value === 'auto.function.solid.server_function'
);
});
// The server function's request span, found by its method within the trace of the function span.
const serverSpanPromise = functionSpanPromise.then(functionSpan =>
waitForStreamedSpan(
'solid-2-ssr',
span =>
getSpanOp(span) === HTTP_SERVER &&
span.is_segment &&
span.trace_id === functionSpan.trace_id &&
span.name.startsWith('POST'),
0,
),
);

await page.goto('/');
await page.locator('#serverFunctionErrorBtn').click();

const [functionSpan, serverSpan] = await Promise.all([functionSpanPromise, serverSpanPromise]);

expect(functionSpan.status).toBe('error');
expect(functionSpan.attributes?.[CODE_FUNCTION_NAME]?.value).toEqual(expect.any(String));
expect(functionSpan.name).toBe(functionSpan.attributes?.[CODE_FUNCTION_NAME]?.value);
expect(functionSpan.parent_span_id).toBe(serverSpan.span_id);
});
1 change: 1 addition & 0 deletions packages/solid/src/solid2/index.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
export * from './client';
export { solidServerErrorsIntegration } from './server/errors';
export { solidServerTracePropagationIntegration } from './server/tracePropagation';
export { solidServerObserveIntegration } from './server/observe';
2 changes: 2 additions & 0 deletions packages/solid/src/solid2/server/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { addServerTimingTraceHeader, defineCloudflareOptions as defineCloudflare
import type { Integration } from '@sentry/core';
import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, defineIntegration } from '@sentry/core';
import { solidServerErrorsIntegration } from './errors';
import { solidServerObserveIntegration } from './observe';
import { solidServerTracePropagationIntegration } from './tracePropagation';

// Sends the trace to the browser on every document response, so the pageload continues it, as `init` does on Node.
Expand Down Expand Up @@ -48,6 +49,7 @@ export const defineCloudflareOptions: typeof defineCloudflareOptionsBase = (
...defaults,
solidServerErrorsIntegration(),
solidServerTracePropagationIntegration(),
solidServerObserveIntegration(),
serverTimingTraceHeaderIntegration(),
];
return typeof userIntegrations === 'function'
Expand Down
1 change: 1 addition & 0 deletions packages/solid/src/solid2/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from '@sentry/node';
export { init, getDefaultIntegrations } from './sdk';
export { solidServerErrorsIntegration } from './errors';
export { solidServerTracePropagationIntegration } from './tracePropagation';
export { solidServerObserveIntegration } from './observe';
110 changes: 110 additions & 0 deletions packages/solid/src/solid2/server/observe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import {
CODE_FUNCTION_NAME,
HTTP_REQUEST_METHOD,
HTTP_ROUTE,
SENTRY_OP,
SENTRY_ORIGIN,
SENTRY_SEGMENT_NAME_SOURCE,
URL_PATH_PARAMETER_KEY_BASE,
} from '@sentry/conventions/attributes';
import { FUNCTION, HTTP_SERVER } from '@sentry/conventions/op';
import {
_INTERNAL_performanceTimeToSeconds as performanceTimeToSeconds,
defineIntegration,
getActiveSpan,
getDefaultIsolationScope,
getIsolationScope,
getRootSpan,
SPAN_STATUS_ERROR,
spanToJSON,
// The rule counts all of `@sentry/solid` as browser code, but this module only runs on the server.
// oxlint-disable-next-line sdk/no-unguarded-span-apis
startInactiveSpan,
updateSpanName,
} from '@sentry/core';
import type { InvocationEvent, RenderEvent } from '@solidjs/web';
import { OBSERVE } from 'solid-js';

const INTEGRATION_NAME = 'SolidServerObserve';

/** A span for a server function execution, under the span of the request or render that ran it. */
function recordInvocationSpan({ id, at, durationMs, outcome }: InvocationEvent): void {
// Record times are `performance.now()` values. Without a usable time origin, the span cannot be placed.
const startTime = performanceTimeToSeconds(at);
const endTime = performanceTimeToSeconds(at + durationMs, at);
if (startTime === undefined || endTime === undefined) {
return;
}

const span = startInactiveSpan({
name: id,
startTime,
onlyIfParent: true,
attributes: {
[SENTRY_OP]: FUNCTION,
[SENTRY_ORIGIN]: 'auto.function.solid.server_function',
[CODE_FUNCTION_NAME]: id,
},
});
if (outcome === 'error') {
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
}
span.end(endTime);
}

/**
* Names the `http.server` span after the route the router declared for the render, e.g. `GET /user/:id`, unless it
* is named after a route already (by `withSentryRouterRouting`).
*/
function nameRequestAfterRenderRoute({ route }: RenderEvent): void {
const activeSpan = getActiveSpan();
// Without a matching route, the router reports the raw path as `name` and no `params`.
if (!route?.name || !route.params || !activeSpan) {
return;
}

const rootSpan = getRootSpan(activeSpan);
const { attributes } = spanToJSON(rootSpan);
if (
attributes?.[SENTRY_OP] !== HTTP_SERVER ||
attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' ||
!rootSpan.isRecording()
) {
return;
}

const method = attributes[HTTP_REQUEST_METHOD];
const name = `${typeof method === 'string' ? method : 'GET'} ${route.name}`;
updateSpanName(rootSpan, name);
rootSpan.setAttributes({
[HTTP_ROUTE]: route.name,
[SENTRY_SEGMENT_NAME_SOURCE]: 'route',
});
for (const [key, value] of Object.entries(route.params ?? {})) {
if (typeof value === 'string') {
rootSpan.setAttribute(`${URL_PATH_PARAMETER_KEY_BASE}.${key}`, value);
}
}

// Outside a request, the isolation scope is shared by the whole process.
const isolationScope = getIsolationScope();
if (isolationScope !== getDefaultIsolationScope()) {
isolationScope.setTransactionName(name);
}
}

/**
* Turns the records of Solid's observe and dev builds into Sentry data: a span for every server function execution,
* and the route of a render as the name of its request span, with any router. Production builds have no records, so
* this does nothing there.
*/
export const solidServerObserveIntegration = defineIntegration(() => {
return {
name: INTEGRATION_NAME,
setup() {
// Solid keeps one entry per listener function, so a client set up per request on Workers adds no duplicates.
OBSERVE?.records.subscribe('invocation', recordInvocationSpan);
OBSERVE?.records.subscribe('render', nameRequestAfterRenderRoute);
},
};
});
2 changes: 2 additions & 0 deletions packages/solid/src/solid2/server/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
init as initNodeSdk,
} from '@sentry/node';
import { solidServerErrorsIntegration } from './errors';
import { solidServerObserveIntegration } from './observe';
import { solidServerTracePropagationIntegration } from './tracePropagation';

/**
Expand Down Expand Up @@ -34,5 +35,6 @@ export function getDefaultIntegrations(options: NodeOptions): Integration[] {
...getNodeDefaultIntegrations(options),
solidServerErrorsIntegration(),
solidServerTracePropagationIntegration(),
solidServerObserveIntegration(),
];
}
179 changes: 179 additions & 0 deletions packages/solid/test/solid2/server/observe.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import {
CODE_FUNCTION_NAME,
HTTP_REQUEST_METHOD,
HTTP_ROUTE,
SENTRY_OP,
SENTRY_ORIGIN,
SENTRY_SEGMENT_NAME_SOURCE,
URL_PATH_PARAMETER_KEY_BASE,
} from '@sentry/conventions/attributes';
import { FUNCTION, HTTP_SERVER } from '@sentry/conventions/op';
import type { StreamedSpanJSON } from '@sentry/core';
import {
createTransport,
getIsolationScope,
setCurrentClient,
spanToJSON,
startSpan,
startSpanManual,
withIsolationScope,
} from '@sentry/core';
import { NodeClient } from '@sentry/node';
import type { InvocationEvent, RenderEvent } from '@solidjs/web';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { solidServerObserveIntegration } from '../../../src/solid2/server';

type Listener = (event: unknown, live: unknown) => void;

const { listeners } = vi.hoisted(() => ({ listeners: new Map<string, Listener>() }));

// The production build has no `OBSERVE`; observe and dev builds do.
vi.mock('solid-js', async importOriginal => ({
...(await importOriginal<object>()),
OBSERVE: {
records: {
subscribe: (type: string, listener: Listener) => {
listeners.set(type, listener);
return () => listeners.delete(type);
},
},
},
}));

function emit(type: 'invocation', event: InvocationEvent): void;
function emit(type: 'render', event: RenderEvent): void;
function emit(type: string, event: unknown): void {
listeners.get(type)?.(event, {});
}

describe('solidServerObserveIntegration', () => {
let ended: StreamedSpanJSON[];

beforeEach(() => {
listeners.clear();
ended = [];
const client = new NodeClient({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
tracesSampleRate: 1,
integrations: [],
transport: () => createTransport({ recordDroppedEvent: () => undefined }, _ => Promise.resolve({})),
stackParser: () => [],
});
setCurrentClient(client);
client.init();
client.on('spanEnd', span => {
ended.push(spanToJSON(span));
});
solidServerObserveIntegration().setup!(client);
});

describe('server function executions', () => {
it('adds a span under the active span, with the recorded timing', () => {
const at = performance.now() - 50;

const parentSpanId = startSpan({ name: 'POST /_server' }, span => {
emit('invocation', { id: 'src/api.ts#getUser', direct: false, at, durationMs: 20, outcome: 'ok' });
return span.spanContext().spanId;
});

const span = ended.find(one => one.name === 'src/api.ts#getUser');
expect(span).toMatchObject({
parent_span_id: parentSpanId,
status: 'ok',
attributes: expect.objectContaining({
[SENTRY_OP]: FUNCTION,
[SENTRY_ORIGIN]: 'auto.function.solid.server_function',
[CODE_FUNCTION_NAME]: 'src/api.ts#getUser',
}),
});
expect(span?.start_timestamp).toBeCloseTo((performance.timeOrigin + at) / 1000, 3);
expect(span?.end_timestamp).toBeCloseTo((performance.timeOrigin + at + 20) / 1000, 3);
});

it('marks a failed execution', () => {
startSpan({ name: 'POST /_server' }, () => {
emit('invocation', { id: 'fail', direct: false, at: performance.now(), durationMs: 1, outcome: 'error' });
});

expect(ended.find(one => one.name === 'fail')?.status).toBe('error');
});

it('adds no span outside a request', () => {
emit('invocation', { id: 'orphan', direct: false, at: performance.now(), durationMs: 1, outcome: 'ok' });

expect(ended).toEqual([]);
});
});

describe('render routes', () => {
const render = (route?: RenderEvent['route']): RenderEvent => ({
mode: 'stream',
at: performance.now(),
durationMs: 1,
boundaries: 0,
outcome: 'complete',
route,
});

it('names the request span after the route of the render', () => {
withIsolationScope(() => {
startSpanManual(
{ name: 'GET /user/5', op: HTTP_SERVER, attributes: { [HTTP_REQUEST_METHOD]: 'GET' } },
span => {
emit('render', render({ name: '/user/:id', to: '/user/5', params: { id: '5' } }));

expect(spanToJSON(span)).toMatchObject({
name: 'GET /user/:id',
attributes: expect.objectContaining({
[HTTP_ROUTE]: '/user/:id',
[SENTRY_SEGMENT_NAME_SOURCE]: 'route',
[`${URL_PATH_PARAMETER_KEY_BASE}.id`]: '5',
}),
});
expect(getIsolationScope().getScopeData().transactionName).toBe('GET /user/:id');
span.end();
},
);
});
});

it('keeps a name the router wrapper set', () => {
startSpanManual(
{ name: 'GET /user/:userId', op: HTTP_SERVER, attributes: { [SENTRY_SEGMENT_NAME_SOURCE]: 'route' } },
span => {
emit('render', render({ name: '/user/:id', params: {} }));

expect(spanToJSON(span).name).toBe('GET /user/:userId');
span.end();
},
);
});

it('leaves other spans alone', () => {
startSpanManual({ name: 'some work', op: FUNCTION }, span => {
emit('render', render({ name: '/user/:id', params: {} }));

expect(spanToJSON(span).name).toBe('some work');
span.end();
});
});

it('keeps the name when no route matched', () => {
startSpanManual({ name: 'GET /missing', op: HTTP_SERVER }, span => {
emit('render', render({ name: '/missing', to: '/missing' }));

expect(spanToJSON(span).name).toBe('GET /missing');
span.end();
});
});

it('does nothing without a route', () => {
startSpanManual({ name: 'GET /user/5', op: HTTP_SERVER }, span => {
emit('render', render());

expect(spanToJSON(span).name).toBe('GET /user/5');
span.end();
});
});
});
});
Loading