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
3 changes: 2 additions & 1 deletion .oxlintrc.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@
"files": ["**/src/**/*.ts", "**/src/**/*.tsx", "**/addon/**/*.ts"],
"rules": {
"sdk/no-unguarded-span-apis": "error",
"sdk/no-unguarded-debug-logs": "error"
"sdk/no-unguarded-debug-logs": "error",
"sdk/require-define-integration": "error"
}
},
{
Expand Down
29 changes: 29 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,35 @@

- "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott

## 11.20.0

### Important Changes

- **feat(nestjs): Trace WebSocket messages on Nest 12 ([#26768](https://github.com/getsentry/sentry-javascript/pull/26768))**

On Nest 12 and newer, the SDK now creates a `websocket` span for each WebSocket message a gateway handles, named `WS <namespace> <pattern>`. Each message starts its own trace.

### Other Changes

- feat(bundler-plugins): Add the call-site rewriter core ([#26101](https://github.com/getsentry/sentry-javascript/pull/26101))
- feat(core): Add experimental minification-independent function fingerprint ([#26840](https://github.com/getsentry/sentry-javascript/pull/26840))
- feat(core): Report library functions in integration options without a fingerprint ([#26898](https://github.com/getsentry/sentry-javascript/pull/26898))
- fix(core): Clear pending idle span timers when the span ends ([#26938](https://github.com/getsentry/sentry-javascript/pull/26938))
- fix(nestjs): Register SentryTracingInterceptor only once ([#26775](https://github.com/getsentry/sentry-javascript/pull/26775))
- fix(nuxt): Avoid duplicate spans when Nitro tracing channels are on ([#26928](https://github.com/getsentry/sentry-javascript/pull/26928))
- fix(server-utils): Sum Vercel AI reasoning tokens onto invoke_agent spans ([#26904](https://github.com/getsentry/sentry-javascript/pull/26904))
- fix(tanstackstart-react): Report the TanStack Start SDK name with the Cloudflare Vite plugin ([#26925](https://github.com/getsentry/sentry-javascript/pull/26925))

<details>
<summary><strong>Internal Changes</strong></summary>

- chore(lint): Require integrations to be created with `defineIntegration` ([#26937](https://github.com/getsentry/sentry-javascript/pull/26937))
- docs: Add a checklist for new major releases ([#26926](https://github.com/getsentry/sentry-javascript/pull/26926))

</details>

Work in this release was contributed by @faizansaiyed123. Thank you for your contribution!

## 11.19.0

- docs(aws-lambda): Fix the Lambda layer link in the v11 migration guide ([#26912](https://github.com/getsentry/sentry-javascript/pull/26912))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,30 @@
"name": "nestjs-websockets",
"version": "0.0.1",
"private": true,
"type": "module",
"scripts": {
"build": "nest build",
"start": "nest start",
"start": "node --import ./dist/instrument.js dist/main.js",
"test": "playwright test",
"test:build": "pnpm install && pnpm build",
"test:assert": "pnpm test"
},
"dependencies": {
"@nestjs/common": "^11.0.0",
"@nestjs/core": "^11.0.0",
"@nestjs/platform-express": "^11.0.0",
"@nestjs/websockets": "^11.0.0",
"@nestjs/platform-socket.io": "^11.0.0",
"@nestjs/common": "12.5.1",
"@nestjs/core": "12.5.1",
"@nestjs/platform-express": "12.5.1",
"@nestjs/websockets": "12.5.1",
"@nestjs/platform-socket.io": "12.5.1",
"@sentry/nestjs": "file:../../packed/sentry-nestjs-packed.tgz",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
},
"devDependencies": {
"@playwright/test": "1.64.1",
"@sentry-internal/test-utils": "file:../../packed/sentry-internal-test-utils-packed.tgz",
"@nestjs/cli": "^11.0.0",
"@types/node": "^18.19.1",
"@nestjs/cli": "^12.0.0",
"@types/node": "^22.0.0",
"socket.io-client": "^4.0.0",
"typescript": "~5.0.0"
"typescript": "~5.9.0"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,16 @@ export class AppGateway {
return { event: 'capture-response', data: { success: true } };
}
}

@WebSocketGateway({ namespace: '/events' })
export class EventsGateway {
@SubscribeMessage('test-transaction')
handleTestTransaction() {
return { event: 'test-transaction-response', data: { success: true } };
}

@SubscribeMessage('test-transaction-error')
handleTestTransactionError() {
throw new Error('WebSocket handler failed');
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { SentryGlobalFilter, SentryModule } from '@sentry/nestjs/setup';
import { AppController } from './app.controller';
import { AppGateway } from './app.gateway';
import { AppController } from './app.controller.js';
import { AppGateway, EventsGateway } from './app.gateway.js';

@Module({
imports: [SentryModule.forRoot()],
Expand All @@ -13,6 +13,7 @@ import { AppGateway } from './app.gateway';
useClass: SentryGlobalFilter,
},
AppGateway,
EventsGateway,
],
})
export class AppModule {}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// Import this first
import './instrument';
// Loaded via `node --import ./dist/instrument.js` so Sentry's ESM instrumentation
// hooks register before any application module is linked. Kept here too so the
// file is part of the build output (ESM caches it, so it is not re-executed).
import './instrument.js';

// Import other modules
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AppModule } from './app.module.js';

const PORT = 3030;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect, test } from '@playwright/test';
import { getSpanOp, waitForStreamedSpan } from '@sentry-internal/test-utils';
import { io } from 'socket.io-client';

test('Sends an HTTP segment span', async ({ baseURL }) => {
const spanPromise = waitForStreamedSpan('nestjs-websockets', span => {
Expand All @@ -13,3 +14,89 @@ test('Sends an HTTP segment span', async ({ baseURL }) => {
expect(getSpanOp(span)).toBe('http.server');
expect(span.status).toBe('ok');
});

test('Marks WebSocket segment spans as failed when the handler errors', async ({ baseURL }) => {
const socket = io(`${baseURL}/events`);

try {
await new Promise<void>((resolve, reject) => {
socket.once('connect', resolve);
socket.once('connect_error', reject);
});

const spanPromise = waitForStreamedSpan('nestjs-websockets', span => {
return span.is_segment && span.name === 'WS /events test-transaction-error';
});
const exceptionPromise = new Promise<void>(resolve => {
socket.once('exception', () => resolve());
});

socket.emit('test-transaction-error', {});

const [span] = await Promise.all([spanPromise, exceptionPromise]);

expect(span.is_segment).toBe(true);
expect(getSpanOp(span)).toBe('websocket');
expect(span.name).toBe('WS /events test-transaction-error');
expect(span.status).toBe('error');
} finally {
socket.disconnect();
}
});

test('Names WebSocket segment spans with the Socket.IO namespace and message pattern', async ({ baseURL }) => {
const socket = io(`${baseURL}/events`);

try {
await new Promise<void>((resolve, reject) => {
socket.once('connect', resolve);
socket.once('connect_error', reject);
});

const spanPromise = waitForStreamedSpan('nestjs-websockets', span => {
return span.is_segment && span.name === 'WS /events test-transaction';
});
const responsePromise = new Promise<void>(resolve => {
socket.once('test-transaction-response', () => resolve());
});

socket.emit('test-transaction', {});

const [span] = await Promise.all([spanPromise, responsePromise]);

expect(span.is_segment).toBe(true);
expect(getSpanOp(span)).toBe('websocket');
expect(span.name).toBe('WS /events test-transaction');
expect(span.attributes['websocket.event.name']).toEqual({ type: 'string', value: 'test-transaction' });
expect(span.attributes['websocket.namespace']).toEqual({ type: 'string', value: '/events' });
} finally {
socket.disconnect();
}
});

test('Starts a new trace for each WebSocket message on the same connection', async ({ baseURL }) => {
const socket = io(`${baseURL}/events`);

try {
await new Promise<void>((resolve, reject) => {
socket.once('connect', resolve);
socket.once('connect_error', reject);
});

const firstSpanPromise = waitForStreamedSpan('nestjs-websockets', span => {
return span.is_segment && span.name === 'WS /events test-transaction';
});
socket.emit('test-transaction', {});
const firstSpan = await firstSpanPromise;

const secondSpanPromise = waitForStreamedSpan('nestjs-websockets', span => {
return span.is_segment && span.name === 'WS /events test-transaction' && span.trace_id !== firstSpan.trace_id;
});
socket.emit('test-transaction', {});
const secondSpan = await secondSpanPromise;

expect(secondSpan.trace_id).not.toBe(firstSpan.trace_id);
} finally {
socket.disconnect();
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "tests", "dist"]
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"module": "commonjs",
"module": "NodeNext",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
Expand All @@ -17,6 +17,6 @@
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
"moduleResolution": "Node16"
"moduleResolution": "NodeNext"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import * as Sentry from '@sentry/node';
import { generateText, simulateReadableStream, stepCountIs, streamText, tool } from 'ai';
import { MockLanguageModelV2 } from 'ai/test';
import { z } from 'zod';

// `@ai-sdk/google` 2.x reports candidate-only `outputTokens` and a separate `reasoningTokens`, with the
// raw counts in `providerMetadata`. Two steps reason 80 and 100 tokens.
const STEPS = [
{ candidates: 20, thoughts: 80, finishReason: 'tool-calls' },
{ candidates: 20, thoughts: 100, finishReason: 'stop' },
];

function usage({ candidates, thoughts }) {
return {
inputTokens: 10,
outputTokens: candidates,
totalTokens: 10 + candidates + thoughts,
reasoningTokens: thoughts,
};
}

function providerMetadata({ candidates, thoughts }) {
return {
google: {
usageMetadata: {
promptTokenCount: 10,
candidatesTokenCount: candidates,
thoughtsTokenCount: thoughts,
totalTokenCount: 10 + candidates + thoughts,
},
},
};
}

const tools = {
getWeather: tool({
description: 'Get the current weather for a location',
inputSchema: z.object({ location: z.string() }),
execute: async ({ location }) => `Weather in ${location}: Sunny, 72°F`,
}),
};

const toolCall = {
type: 'tool-call',
toolCallId: 'call-1',
toolName: 'getWeather',
input: JSON.stringify({ location: 'San Francisco' }),
};

async function run() {
await Sentry.startSpan({ op: 'function', name: 'main' }, async () => {
let generateCalls = 0;
await generateText({
model: new MockLanguageModelV2({
doGenerate: async () => {
const step = STEPS[generateCalls++];
return {
finishReason: step.finishReason,
usage: usage(step),
content: generateCalls === 1 ? [toolCall] : [{ type: 'text', text: 'Sunny, 72°F.' }],
warnings: [],
providerMetadata: providerMetadata(step),
};
},
}),
tools,
stopWhen: stepCountIs(5),
prompt: 'What is the weather in San Francisco?',
});

let streamCalls = 0;
const result = streamText({
model: new MockLanguageModelV2({
doStream: async () => {
const step = STEPS[streamCalls++];
const content =
streamCalls === 1
? [toolCall]
: [
{ type: 'text-start', id: '0' },
{ type: 'text-delta', id: '0', delta: 'Sunny, 72°F.' },
{ type: 'text-end', id: '0' },
];
return {
stream: simulateReadableStream({
chunks: [
{ type: 'stream-start', warnings: [] },
...content,
{
type: 'finish',
finishReason: step.finishReason,
usage: usage(step),
providerMetadata: providerMetadata(step),
},
],
}),
};
},
}),
tools,
stopWhen: stepCountIs(5),
prompt: 'What is the weather in San Francisco?',
});
for await (const _part of result.fullStream) {
void _part;
}

// `@ai-sdk/openai` 2.x reports reasoning only in the usage, inside an output that includes it.
await generateText({
model: new MockLanguageModelV2({
doGenerate: async () => ({
finishReason: 'stop',
usage: { inputTokens: 10, outputTokens: 50, totalTokens: 60, reasoningTokens: 30 },
content: [{ type: 'text', text: 'Sunny.' }],
warnings: [],
providerMetadata: { openai: {} },
}),
}),
prompt: 'What is the weather in San Francisco?',
});
});
}

run();
Loading
Loading