Skip to content

feat(node): Add connect instrumentation #11651

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 2 commits into from
Apr 17, 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
1 change: 1 addition & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1051,6 +1051,7 @@ jobs:
'node-nestjs-app',
'node-exports-test-app',
'node-koa-app',
'node-connect-app',
'vue-3',
'webpack-4',
'webpack-5'
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,31 @@
{
"name": "node-connect-app",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "ts-node src/app.ts",
"test": "playwright test",
"clean": "npx rimraf node_modules pnpm-lock.yaml",
"typecheck": "tsc",
"test:build": "pnpm install && pnpm run typecheck",
"test:assert": "pnpm test"
},
"dependencies": {
"@sentry/node": "latest || *",
"@sentry/types": "latest || *",
"@sentry/core": "latest || *",
"@sentry/utils": "latest || *",
"@sentry/opentelemetry": "latest || *",
"@types/node": "18.15.1",
"connect": "3.7.0",
"typescript": "4.9.5",
"ts-node": "10.9.1"
},
"devDependencies": {
"@sentry-internal/event-proxy-server": "link:../../../event-proxy-server",
"@playwright/test": "^1.38.1"
},
"volta": {
"extends": "../../package.json"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import type { PlaywrightTestConfig } from '@playwright/test';
import { devices } from '@playwright/test';

const connectPort = 3030;
const eventProxyPort = 3031;

/**
* See https://playwright.dev/docs/test-configuration.
*/
const config: PlaywrightTestConfig = {
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: 10000,
},
/* 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,
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:${connectPort}`,

/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
},

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

/* Run your local dev server before starting the tests */
webServer: [
{
command: 'pnpm ts-node-script start-event-proxy.ts',
port: eventProxyPort,
},
{
command: 'pnpm start',
port: connectPort,
},
],
};

export default config;
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type * as S from '@sentry/node';
const Sentry = require('@sentry/node') as typeof S;

Sentry.init({
environment: 'qa', // dynamic sampling bias to keep transactions
dsn: process.env.E2E_TEST_DSN,
integrations: [],
tracesSampleRate: 1,
tunnel: 'http://localhost:3031/', // proxy server
tracePropagationTargets: ['http://localhost:3030', '/external-allowed'],
});

import type * as H from 'http';
import type C from 'connect';

const connect = require('connect') as typeof C;
const http = require('http') as typeof H;

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

app.use('/test-success', (req, res, next) => {
res.end(
JSON.stringify({
version: 'v1',
}),
);
});

app.use('/test-error', async (req, res, next) => {
const exceptionId = Sentry.captureException(new Error('Sentry Test Error'));

await Sentry.flush();

res.end(JSON.stringify({ exceptionId }));
next();
});

app.use('/test-exception', () => {
throw new Error('This is an exception');
});

app.use('/test-transaction', (req, res, next) => {
Sentry.startSpan({ name: 'test-span' }, () => {});

res.end(
JSON.stringify({
version: 'v1',
}),
);

next();
});

Sentry.setupConnectErrorHandler(app);

const server = http.createServer(app);

server.listen(port);
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-connect-app',
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { expect, test } from '@playwright/test';
import { waitForError } from '@sentry-internal/event-proxy-server';
import axios, { AxiosError } from 'axios';

const authToken = process.env.E2E_TEST_AUTH_TOKEN;
const sentryTestOrgSlug = process.env.E2E_TEST_SENTRY_ORG_SLUG;
const sentryTestProject = process.env.E2E_TEST_SENTRY_TEST_PROJECT;
const EVENT_POLLING_TIMEOUT = 90_000;

test('Sends exception to Sentry', async ({ baseURL }) => {
const { data } = await axios.get(`${baseURL}/test-error`);
const { exceptionId } = data;

const url = `https://sentry.io/api/0/projects/${sentryTestOrgSlug}/${sentryTestProject}/events/${exceptionId}/`;

console.log(`Polling for error eventId: ${exceptionId}`);

await expect
.poll(
async () => {
try {
const response = await axios.get(url, { headers: { Authorization: `Bearer ${authToken}` } });

return response.status;
} catch (e) {
if (e instanceof AxiosError && e.response) {
if (e.response.status !== 404) {
throw e;
} else {
return e.response.status;
}
} else {
throw e;
}
}
},
{ timeout: EVENT_POLLING_TIMEOUT },
)
.toBe(200);
});

test('Sends correct error event', async ({ baseURL }) => {
const errorEventPromise = waitForError('node-connect-app', event => {
return !event.type && event.exception?.values?.[0]?.value === 'This is an exception';
});

try {
await axios.get(`${baseURL}/test-exception`);
} catch {
// this results in an error, but we don't care - we want to check the error event
}

const errorEvent = await errorEventPromise;

expect(errorEvent.exception?.values).toHaveLength(1);
expect(errorEvent.exception?.values?.[0]?.value).toBe('This is an exception');

expect(errorEvent.request).toEqual({
method: 'GET',
cookies: {},
headers: expect.any(Object),
url: 'http://localhost:3030/test-exception',
});

expect(errorEvent.transaction).toEqual('GET /test-exception');

expect(errorEvent.contexts?.trace).toEqual({
trace_id: expect.any(String),
span_id: expect.any(String),
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { expect, test } from '@playwright/test';
import { waitForTransaction } from '@sentry-internal/event-proxy-server';
import axios, { AxiosError } from 'axios';

const authToken = process.env.E2E_TEST_AUTH_TOKEN;
const sentryTestOrgSlug = process.env.E2E_TEST_SENTRY_ORG_SLUG;
const sentryTestProject = process.env.E2E_TEST_SENTRY_TEST_PROJECT;
const EVENT_POLLING_TIMEOUT = 90_000;

test('Sends an API route transaction', async ({ baseURL }) => {
const pageloadTransactionEventPromise = waitForTransaction('node-connect-app', transactionEvent => {
return (
transactionEvent?.contexts?.trace?.op === 'http.server' &&
transactionEvent?.transaction === 'GET /test-transaction'
);
});

await axios.get(`${baseURL}/test-transaction`);

const transactionEvent = await pageloadTransactionEventPromise;
const transactionEventId = transactionEvent.event_id;

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

expect(transactionEvent).toEqual(
expect.objectContaining({
spans: [
{
data: {
'sentry.origin': 'manual',
'otel.kind': 'INTERNAL',
},
description: 'test-span',
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),
origin: 'manual',
},
{
data: {
'sentry.origin': 'manual',
'http.route': '/test-transaction',
'connect.type': 'request_handler',
'connect.name': '/test-transaction',
'otel.kind': 'INTERNAL',
},
description: 'request handler - /test-transaction',
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),
origin: 'manual',
},
],
transaction: 'GET /test-transaction',
type: 'transaction',
transaction_info: {
source: 'route',
},
}),
);

await expect
.poll(
async () => {
try {
const response = await axios.get(
`https://sentry.io/api/0/projects/${sentryTestOrgSlug}/${sentryTestProject}/events/${transactionEventId}/`,
{ headers: { Authorization: `Bearer ${authToken}` } },
);

return response.status;
} catch (e) {
if (e instanceof AxiosError && e.response) {
if (e.response.status !== 404) {
throw e;
} else {
return e.response.status;
}
} else {
throw e;
}
}
},
{
timeout: EVENT_POLLING_TIMEOUT,
},
)
.toBe(200);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
Copy link
Contributor

Choose a reason for hiding this comment

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

Since we are only typescript to run the app with ts-node and to check types we can probably configure this to not emit any files and then we can also get rid of the gitignore.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Updated 👍

"types": ["node"],
"esModuleInterop": true,
"lib": ["dom", "dom.iterable", "esnext"],
"strict": true,
"noEmit": true
},
"include": ["*.ts"]
}
1 change: 1 addition & 0 deletions dev-packages/node-integration-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"@types/pg": "^8.6.5",
"apollo-server": "^3.11.1",
"axios": "^1.6.7",
"connect": "^3.7.0",
"cors": "^2.8.5",
"cron": "^3.1.6",
"express": "^4.17.3",
Expand Down
Loading