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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the tests are in the tunnel because this is the only app that runs under a base path.

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { expect, test } from '@playwright/test';
import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';

// This app runs under a base path (`/app/`), so it also tests the build file filter with a base path.
const BUILD_FILE_PATH = '/app/_build/assets/entry.js.map';
const PAGE_PATH = '/app/after-build-file';

// In development, the server SDK does not know the base path when it initializes.
test.skip(process.env.TEST_ENV === 'development', 'Production only');

test('does not send a server span for a build file under the base path', async ({ baseURL }) => {
const segmentPaths: string[] = [];
const pageSegmentPromise = waitForStreamedSpans('solidstart-1-tunnel', spans => {
segmentPaths.push(
...spans
.filter(span => span.is_segment && getSpanOp(span) === 'http.server')
.map(span => `${span.attributes['url.path']?.value}`),
);
return segmentPaths.includes(PAGE_PATH);
});

await fetch(`${baseURL}${BUILD_FILE_PATH}`);
// A span for the build file would arrive before the span of this later request.
await fetch(`${baseURL}${PAGE_PATH}`);
await pageSegmentPromise;

expect(segmentPaths).not.toContain(BUILD_FILE_PATH);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { expect, test } from '@playwright/test';
import { getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';

// This app runs under a base path (`/app/`), so it also tests the build file filter with a base path.
const BUILD_FILE_PATH = '/app/_build/assets/entry.js.map';
const PAGE_PATH = '/app/after-build-file';

// In development, the server SDK does not know the base path when it initializes.
test.skip(process.env.TEST_ENV === 'development', 'Production only');

test('does not send a server span for a build file under the base path', async ({ baseURL }) => {
const segmentPaths: string[] = [];
const pageSegmentPromise = waitForStreamedSpans('solidstart-2-tunnel', spans => {
segmentPaths.push(
...spans
.filter(span => span.is_segment && getSpanOp(span) === 'http.server')
.map(span => `${span.attributes['url.path']?.value}`),
);
return segmentPaths.includes(PAGE_PATH);
});

await fetch(`${baseURL}${BUILD_FILE_PATH}`);
// A span for the build file would arrive before the span of this later request.
await fetch(`${baseURL}${PAGE_PATH}`);
await pageSegmentPromise;

expect(segmentPaths).not.toContain(BUILD_FILE_PATH);
});
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils';
import { collectStreamedSpans, getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';

test('sends a server action span on pageload', async ({ page }) => {
const spansPromise = collectStreamedSpans(
Expand Down Expand Up @@ -46,3 +46,40 @@ test('sends a server action span on client navigation', async ({ page }) => {
'code.function.name': { value: 'getPrefecture', type: 'string' },
});
});

['/_build/assets/entry.js.map', '/_build/.vite/manifest.json'].forEach(path => {
test(`does not send a server span for the file ${path}`, async ({ baseURL }) => {
const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);

expect(segmentPaths).not.toContain(path);
});
});

// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot
// pass by accident.
['/users/jane.doe', '/users/_build/'].forEach(path => {
test(`sends a server span for the route ${path}`, async ({ baseURL }) => {
const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);

expect(segmentPaths).toContain(path);
});
});

/**
* Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives
* after any segment for `path`.
*/
async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise<string[]> {
const pagePath = `/users/after${path.replace(/\W+/g, '-')}`;
const segmentPaths: string[] = [];
const pageSegmentPromise = waitForStreamedSpans('solidstart-2', spans => {
segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes['url.path']?.value}`));
return segmentPaths.includes(pagePath);
});

await fetch(`${baseURL}${path}`);
await fetch(`${baseURL}${pagePath}`);
await pageSegmentPromise;

return segmentPaths;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
import { SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
import { waitForTransaction } from '@sentry-internal/test-utils';

Expand Down Expand Up @@ -49,3 +49,46 @@ test('sends a server action transaction on client navigation', async ({ page })
]),
);
});

[
// SolidStart build output that the HTTP integration does not ignore.
'/_build/assets/entry.js.map',
'/_build/.vite/manifest.json',
// Common static file that the HTTP integration ignores.
'/favicon.ico',
].forEach(path => {
test(`does not send a server transaction for the file ${path}`, async ({ baseURL }) => {
const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path);

expect(transactionPaths).not.toContain(path);
});
});

// Routes that look like build output. They also show that the helper sees sent transactions, so the tests above cannot
// pass by accident.
['/users/jane.doe', '/users/_build/'].forEach(path => {
test(`sends a server transaction for the route ${path}`, async ({ baseURL }) => {
const transactionPaths = await getServerTransactionPathsUntilPage(`${baseURL}`, path);

expect(transactionPaths).toContain(path);
});
});

/**
* Requests `path`, then a page. Returns the `url.path` of each server transaction up to the page's transaction,
* which arrives after any transaction for `path`.
*/
async function getServerTransactionPathsUntilPage(baseURL: string, path: string): Promise<string[]> {
const pagePath = `/users/after${path.replace(/\W+/g, '-')}`;
const transactionPaths: string[] = [];
const pageTransactionPromise = waitForTransaction('solidstart', transactionEvent => {
transactionPaths.push(`${transactionEvent.contexts?.trace?.data?.[URL_PATH]}`);
return transactionPaths.includes(pagePath);
});

await fetch(`${baseURL}${path}`);
await fetch(`${baseURL}${pagePath}`);
await pageTransactionPromise;

return transactionPaths;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { URL_PATH } from '@sentry/conventions/attributes';
import { expect, test } from '@playwright/test';
import { collectStreamedSpans, getSpanOp } from '@sentry-internal/test-utils';
import { collectStreamedSpans, getSpanOp, waitForStreamedSpans } from '@sentry-internal/test-utils';

test('sends a server action span on pageload', async ({ page }) => {
const spansPromise = collectStreamedSpans(
Expand Down Expand Up @@ -46,3 +47,46 @@ test('sends a server action span on client navigation', async ({ page }) => {
'code.function.name': { value: 'getPrefecture', type: 'string' },
});
});

[
// SolidStart build output that the HTTP integration does not ignore.
'/_build/assets/entry.js.map',
'/_build/.vite/manifest.json',
// Common static file that the HTTP integration ignores.
'/favicon.ico',
].forEach(path => {
test(`does not send a server span for the file ${path}`, async ({ baseURL }) => {
const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);

expect(segmentPaths).not.toContain(path);
});
});

// Routes that look like build output. They also show that the helper sees sent segments, so the tests above cannot
// pass by accident.
['/users/jane.doe', '/users/_build/'].forEach(path => {
test(`sends a server span for the route ${path}`, async ({ baseURL }) => {
const segmentPaths = await getServerSegmentPathsUntilPage(`${baseURL}`, path);

expect(segmentPaths).toContain(path);
});
});

/**
* Requests `path`, then a page. Returns the `url.path` of each server segment up to the page's segment, which arrives
* after any segment for `path`.
*/
async function getServerSegmentPathsUntilPage(baseURL: string, path: string): Promise<string[]> {
const pagePath = `/users/after${path.replace(/\W+/g, '-')}`;
const segmentPaths: string[] = [];
const pageSegmentPromise = waitForStreamedSpans('solidstart', spans => {
segmentPaths.push(...spans.filter(span => span.is_segment).map(span => `${span.attributes[URL_PATH]?.value}`));
return segmentPaths.includes(pagePath);
});

await fetch(`${baseURL}${path}`);
await fetch(`${baseURL}${pagePath}`);
await pageSegmentPromise;

return segmentPaths;
}
18 changes: 13 additions & 5 deletions packages/solidstart/src/common/tunnel.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import type { Options } from '@sentry/core';
import { applyBrowserTunnelDefaults } from '@sentry/core';
import { applyBrowserTunnelDefaults, GLOBAL_OBJ } from '@sentry/core';

/** Set on the server by `withSentry` to the app's `server.baseURL`. */
/** Holds the app's `server.baseURL` on SolidStart 1 servers. Set by the server bundle and the `instrument.server` file. */
export const TUNNEL_BASE_PATH_GLOBAL = '__sentry_solidstart_base_path';

declare const __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__: string | undefined;

/**
* Returns the app's base path without a trailing slash. The build defines it where it bundles the SDK: in the browser
* and in the SolidStart 2 server. The SolidStart 1 server loads the SDK as an external module and reads the global.
*/
export function getBasePath(): string {
return typeof __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__ !== 'undefined'
? __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__
: ((GLOBAL_OBJ as { [TUNNEL_BASE_PATH_GLOBAL]?: string })[TUNNEL_BASE_PATH_GLOBAL] ?? '');
}

/**
* Serves the browser's managed tunnel under the app's base path, which `withSentry` (SolidStart 1) or
* `sentrySolidStart` (SolidStart 2) defines at build time. A `basePath` the user set wins.
*/
export function applyTunnelBasePath(options: Pick<Options, 'tunnel'>): void {
const basePath =
typeof __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__ !== 'undefined' ? __SENTRY_SOLIDSTART_TUNNEL_BASE_PATH__ : '';
options.tunnel = applyBrowserTunnelDefaults(options.tunnel, { basePath });
options.tunnel = applyBrowserTunnelDefaults(options.tunnel, { basePath: getBasePath() });
}
19 changes: 16 additions & 3 deletions packages/solidstart/src/server/sdk.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata } from '@sentry/core';
import { URL_PATH } from '@sentry/conventions/attributes';
import { HTTP_SERVER } from '@sentry/conventions/op';
import { _INTERNAL_captureOptionsSetByUser, applySdkMetadata, escapeStringForRegex } from '@sentry/core';
import type { NodeClient, NodeOptions } from '@sentry/node';
import { init as initNodeSdk } from '@sentry/node';
import { filterLowQualityTransactions } from './utils';
import { getBasePath } from '../common/tunnel';

/**
* Initializes the server side of the Solid Start SDK
*/
export function init(options: NodeOptions): NodeClient | undefined {
const opts = {
..._INTERNAL_captureOptionsSetByUser(options),
ignoreSpans: [...(options.ignoreSpans || []), getBuildAssetRequestFilter()],
};

applySdkMetadata(opts, 'solidstart', ['solidstart', 'node']);
filterLowQualityTransactions(opts);

return initNodeSdk(opts);
}

/**
* SolidStart serves its client build under `<base path>/_build/`. Matches `url.path`, because a span name has no path
* yet when `ignoreSpans` runs.
*/
function getBuildAssetRequestFilter(): NonNullable<NodeOptions['ignoreSpans']>[number] {
const basePath = getBasePath();
// A full URL as the base (a CDN) is not part of the request path.
const pathPrefix = basePath.includes('://') ? '' : basePath;
return { op: HTTP_SERVER, attributes: { [URL_PATH]: new RegExp(`^${escapeStringForRegex(pathPrefix)}/_build/`) } };
}
34 changes: 0 additions & 34 deletions packages/solidstart/src/server/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
import type { EventProcessor, Options } from '@sentry/core';
import { debug } from '@sentry/core';
import { getGlobalScope } from '@sentry/node';

/**
* Determines if a thrown "error" is a redirect Response which Solid Start users can throw to redirect to another route.
* see: https://docs.solidjs.com/solid-router/reference/data-apis/response-helpers#redirect
Expand All @@ -16,33 +12,3 @@ export function isRedirect(error: unknown): boolean {
const hasValidStatus = error.status >= 300 && error.status <= 308;
return hasValidLocation && hasValidStatus;
}

/**
* Filter function for low quality transactions
*
* Exported only for tests
*/
export function lowQualityTransactionsFilter(options: Options): EventProcessor {
return Object.assign(
(event => {
if (event.type !== 'transaction') {
return event;
}
// Filter out transactions for build assets
if (event.transaction?.match(/^GET \/_build\//)) {
options.debug && debug.log('SolidStartLowQualityTransactionsFilter filtered transaction', event.transaction);
return null;
}
return event;
}) satisfies EventProcessor,
{ id: 'SolidStartLowQualityTransactionsFilter' },
);
}

/**
* Adds an event processor to filter out low quality transactions,
* e.g. to filter out transactions for build assets
*/
export function filterLowQualityTransactions(options: Options): void {
getGlobalScope().addEventProcessor(lowQualityTransactionsFilter(options));
}
19 changes: 16 additions & 3 deletions packages/solidstart/src/vite/buildInstrumentationFile.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,30 @@
import { consoleSandbox } from '@sentry/core';
import { consoleSandbox, stringifyForCodeInjection } from '@sentry/core';
import * as fs from 'fs';
import * as path from 'path';
import type { Plugin, UserConfig } from 'vite';
import { TUNNEL_BASE_PATH_GLOBAL } from '../common/tunnel';
import type { SentrySolidStartPluginOptions } from './types';

/**
* A Sentry plugin for SolidStart to build the server
* `instrument.server.ts` file.
*/
export function makeBuildInstrumentationFilePlugin(options: SentrySolidStartPluginOptions = {}): Plugin {
export function makeBuildInstrumentationFilePlugin(options: SentrySolidStartPluginOptions = {}, basePath = ''): Plugin {
let instrumentationFile: string | undefined;

return {
name: 'sentry-solidstart-build-instrumentation-file',
apply: 'build',
enforce: 'post',
// `node --import` loads this file before the server bundle, so the file sets the base path for `Sentry.init` itself.
banner(chunk) {
// Vite reports module IDs with forward slashes, also on Windows.
const isInstrumentationFile =
!!chunk.facadeModuleId && path.resolve(chunk.facadeModuleId) === instrumentationFile;
return basePath && isInstrumentationFile
? `globalThis.${TUNNEL_BASE_PATH_GLOBAL} = ${stringifyForCodeInjection(basePath)};`
: '';
},
async config(config: UserConfig, { command }) {
const instrumentationFilePath = options.instrumentation || './src/instrument.server.ts';
const router = (config as UserConfig & { router: { target: string; name: string; root: string } }).router;
Expand Down Expand Up @@ -42,7 +54,8 @@ export function makeBuildInstrumentationFilePlugin(options: SentrySolidStartPlug
return config;
}

input.push(path.resolve(router.root, instrumentationFilePath));
instrumentationFile = path.resolve(router.root, instrumentationFilePath);
input.push(instrumentationFile);

return {
...config,
Expand Down
2 changes: 1 addition & 1 deletion packages/solidstart/src/vite/sentrySolidStartVite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export const sentrySolidStartVite = (
];

if (options.autoInjectServerSentry !== 'experimental_dynamic-import') {
sentryPlugins.push(makeBuildInstrumentationFilePlugin(options));
sentryPlugins.push(makeBuildInstrumentationFilePlugin(options, tunnelBasePath));
}

if (process.env.NODE_ENV !== 'development') {
Expand Down
Loading
Loading