Skip to content

feat(node): Add @sentry/node/preload hook #12213

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

Merged
merged 4 commits into from
May 27, 2024
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
2 changes: 2 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1003,7 +1003,9 @@ jobs:
'create-remix-app-express-vite-dev',
'debug-id-sourcemaps',
'node-express-esm-loader',
'node-express-esm-preload',
'node-express-esm-without-loader',
'node-express-cjs-preload',
'nextjs-app-dir',
'nextjs-14',
'nextjs-15',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const NODE_EXPORTS_IGNORE = [
'initWithoutDefaultIntegrations',
'SentryContextManager',
'validateOpenTelemetrySetup',
'preloadOpenTelemetry',
];

const nodeExports = Object.keys(SentryNode).filter(e => !NODE_EXPORTS_IGNORE.includes(e));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@sentry:registry=http://127.0.0.1:4873
@sentry-internal:registry=http://127.0.0.1:4873
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "node-express-cjs-preload",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "node --require @sentry/node/preload src/app.js",
"clean": "npx rimraf node_modules pnpm-lock.yaml",
"test:build": "pnpm install",
"test:assert": "playwright test"
},
"dependencies": {
"@sentry/node": "latest || *",
"@sentry/opentelemetry": "latest || *",
"express": "4.19.2"
},
"devDependencies": {
"@sentry-internal/event-proxy-server": "link:../../../event-proxy-server",
"@playwright/test": "^1.27.1"
},
"volta": {
"extends": "../../package.json",
"node": "18.19.1"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { devices } from '@playwright/test';

// Fix urls not resolving to localhost on Node v17+
// See: https://github.com/axios/axios/issues/3821#issuecomment-1413727575
import { setDefaultResultOrder } from 'dns';
setDefaultResultOrder('ipv4first');

const eventProxyPort = 3031;
const expressPort = 3030;

/**
* See https://playwright.dev/docs/test-configuration.
*/
const config = {
testDir: './tests',
/* Maximum time one test can run for. */
timeout: 150_000,
expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000,
},
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: 0,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'list',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,

/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: `http://localhost:${expressPort}`,
},

/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
},
},
],

/* Run your local dev server before starting the tests */
webServer: [
{
command: 'node start-event-proxy.mjs',
port: eventProxyPort,
stdout: 'pipe',
stderr: 'pipe',
},
{
command: 'pnpm start',
port: expressPort,
stdout: 'pipe',
stderr: 'pipe',
},
],
};

export default config;
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const Sentry = require('@sentry/node');
const express = require('express');

const app = express();
const port = 3030;

app.get('/test-success', function (req, res) {
setTimeout(() => {
res.status(200).end();
}, 100);
});

app.get('/test-transaction/:param', function (req, res) {
setTimeout(() => {
res.status(200).end();
}, 100);
});

app.get('/test-error', function (req, res) {
Sentry.captureException(new Error('This is an error'));
setTimeout(() => {
Sentry.flush(2000).then(() => {
res.status(200).end();
});
}, 100);
});

Sentry.setupExpressErrorHandler(app);

app.use(function onError(err, req, res, next) {
// The error id is attached to `res.sentry` to be returned
// and optionally displayed to the user for support.
res.statusCode = 500;
res.end(res.sentry + '\n');
});

async function run() {
await new Promise(resolve => setTimeout(resolve, 1000));

Sentry.init({
environment: 'qa', // dynamic sampling bias to keep transactions
dsn: process.env.E2E_TEST_DSN,
tunnel: `http://localhost:3031/`, // proxy server
tracesSampleRate: 1,
});

app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
}

run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { startEventProxyServer } from '@sentry-internal/event-proxy-server';

startEventProxyServer({
port: 3031,
proxyServerName: 'node-express-cjs-preload',
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { expect, test } from '@playwright/test';
import { waitForError, waitForTransaction } from '@sentry-internal/event-proxy-server';

test('Should record exceptions captured inside handlers', async ({ request }) => {
const errorEventPromise = waitForError('node-express-cjs-preload', errorEvent => {
return !!errorEvent?.exception?.values?.[0]?.value?.includes('This is an error');
});

await request.get('/test-error');

await expect(errorEventPromise).resolves.toBeDefined();
});

test('Should record a transaction for a parameterless route', async ({ request }) => {
const transactionEventPromise = waitForTransaction('node-express-cjs-preload', transactionEvent => {
return transactionEvent?.transaction === 'GET /test-success';
});

await request.get('/test-success');

await expect(transactionEventPromise).resolves.toBeDefined();
});

test('Should record a transaction for route with parameters', async ({ request }) => {
const transactionEventPromise = waitForTransaction('node-express-cjs-preload', transactionEvent => {
return transactionEvent.contexts?.trace?.data?.['http.target'] === '/test-transaction/1';
});

await request.get('/test-transaction/1');

const transactionEvent = await transactionEventPromise;

expect(transactionEvent).toBeDefined();
expect(transactionEvent.transaction).toEqual('GET /test-transaction/:param');
expect(transactionEvent.contexts?.trace?.data).toEqual(
expect.objectContaining({
'http.flavor': '1.1',
'http.host': 'localhost:3030',
'http.method': 'GET',
'http.response.status_code': 200,
'http.route': '/test-transaction/:param',
'http.scheme': 'http',
'http.status_code': 200,
'http.status_text': 'OK',
'http.target': '/test-transaction/1',
'http.url': 'http://localhost:3030/test-transaction/1',
'http.user_agent': expect.any(String),
'net.host.ip': expect.any(String),
'net.host.name': 'localhost',
'net.host.port': 3030,
'net.peer.ip': expect.any(String),
'net.peer.port': expect.any(Number),
'net.transport': 'ip_tcp',
'otel.kind': 'SERVER',
'sentry.op': 'http.server',
'sentry.origin': 'auto.http.otel.http',
'sentry.sample_rate': 1,
'sentry.source': 'route',
url: 'http://localhost:3030/test-transaction/1',
}),
);

const spans = transactionEvent.spans || [];
expect(spans).toContainEqual({
data: {
'express.name': 'query',
'express.type': 'middleware',
'http.route': '/',
'otel.kind': 'INTERNAL',
'sentry.origin': 'auto.http.otel.express',
'sentry.op': 'middleware.express',
},
op: 'middleware.express',
description: 'query',
origin: 'auto.http.otel.express',
parent_span_id: expect.any(String),
span_id: expect.any(String),
start_timestamp: expect.any(Number),
status: 'ok',
timestamp: expect.any(Number),
trace_id: expect.any(String),
});

expect(spans).toContainEqual({
data: {
'express.name': 'expressInit',
'express.type': 'middleware',
'http.route': '/',
'otel.kind': 'INTERNAL',
'sentry.origin': 'auto.http.otel.express',
'sentry.op': 'middleware.express',
},
op: 'middleware.express',
description: 'expressInit',
origin: 'auto.http.otel.express',
parent_span_id: expect.any(String),
span_id: expect.any(String),
start_timestamp: expect.any(Number),
status: 'ok',
timestamp: expect.any(Number),
trace_id: expect.any(String),
});

expect(spans).toContainEqual({
data: {
'express.name': '/test-transaction/:param',
'express.type': 'request_handler',
'http.route': '/test-transaction/:param',
'otel.kind': 'INTERNAL',
'sentry.origin': 'auto.http.otel.express',
'sentry.op': 'request_handler.express',
},
op: 'request_handler.express',
description: '/test-transaction/:param',
origin: 'auto.http.otel.express',
parent_span_id: expect.any(String),
span_id: expect.any(String),
start_timestamp: expect.any(Number),
status: 'ok',
timestamp: expect.any(Number),
trace_id: expect.any(String),
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@sentry:registry=http://127.0.0.1:4873
@sentry-internal:registry=http://127.0.0.1:4873
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "node-express-esm-preload",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "node --import @sentry/node/preload src/app.mjs",
"clean": "npx rimraf node_modules pnpm-lock.yaml",
"test:build": "pnpm install",
"test:assert": "playwright test"
},
"dependencies": {
"@sentry/node": "latest || *",
"@sentry/opentelemetry": "latest || *",
"express": "4.19.2"
},
"devDependencies": {
"@sentry-internal/event-proxy-server": "link:../../../event-proxy-server",
"@playwright/test": "^1.27.1"
},
"volta": {
"extends": "../../package.json",
"node": "18.19.1"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { devices } from '@playwright/test';

// Fix urls not resolving to localhost on Node v17+
// See: https://github.com/axios/axios/issues/3821#issuecomment-1413727575
import { setDefaultResultOrder } from 'dns';
setDefaultResultOrder('ipv4first');

const eventProxyPort = 3031;
const expressPort = 3030;

/**
* See https://playwright.dev/docs/test-configuration.
*/
const config = {
testDir: './tests',
/* Maximum time one test can run for. */
timeout: 150_000,
expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000,
},
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: 0,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'list',
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,

/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: `http://localhost:${expressPort}`,
},

/* Configure projects for major browsers */
projects: [
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
},
},
],

/* Run your local dev server before starting the tests */
webServer: [
{
command: 'node start-event-proxy.mjs',
port: eventProxyPort,
stdout: 'pipe',
stderr: 'pipe',
},
{
command: 'pnpm start',
port: expressPort,
stdout: 'pipe',
stderr: 'pipe',
},
],
};

export default config;
Loading
Loading