Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2047646
fix(nestjs): trace WebSocket interceptor contexts
faizansaiyed123 Oct 6, 2026
0eda62c
fix(nestjs): instrument existing WebSocket observable
faizansaiyed123 Oct 27, 2026
b594d1e
fix(nestjs): remove unnecessary rxjs peer dependency
faizansaiyed123 Oct 27, 2026
4743b1e
test(nestjs): assert scope during WebSocket subscription
faizansaiyed123 Oct 27, 2026
7b231d6
test(nestjs): add namespaced WebSocket tracing endpoint
faizansaiyed123 Oct 27, 2026
d7723f4
test(nestjs): register namespaced WebSocket gateway
faizansaiyed123 Oct 27, 2026
8fd27de
test(nestjs): assert WebSocket transaction naming in e2e
faizansaiyed123 Oct 27, 2026
92bf3e3
fix(nestjs): create spans for WebSocket handlers
faizansaiyed123 Oct 27, 2026
f9f2b5d
test(nestjs): assert WebSocket spans are created and ended
faizansaiyed123 Oct 27, 2026
83300b5
test(nestjs): assert WebSocket span operation in e2e
faizansaiyed123 Oct 27, 2026
c92d2dc
style(nestjs): format WebSocket tracing imports
faizansaiyed123 Oct 27, 2026
f71a621
test(nestjs): assert isolation scope during handler execution
faizansaiyed123 Oct 27, 2026
3b8dd59
fix(nestjs): use conventional websocket span attributes
faizansaiyed123 Oct 27, 2026
0dad26b
test(nestjs): cover websocket span cleanup
faizansaiyed123 Oct 27, 2026
eab54dc
test(nestjs): assert conventional websocket span op
faizansaiyed123 Oct 27, 2026
17161e1
fix(nestjs): mark failed websocket spans as errors
faizansaiyed123 Nov 4, 2026
a15f423
test(nestjs): cover asynchronous websocket observable errors
faizansaiyed123 Nov 4, 2026
fab6e95
test(nestjs): keep Observable subscribe overloads typed
faizansaiyed123 Nov 4, 2026
dff228a
fix(nestjs): preserve observable observer callback context
faizansaiyed123 Nov 4, 2026
62094d6
fix(nestjs): Harden WebSocket tracing interceptor
chargome Nov 23, 2026
3a4623f
fix(nestjs): Start a new trace per WebSocket message
chargome Nov 23, 2026
76d7a32
test(nestjs): Run WebSocket tracing e2e tests on Nest 12
chargome Nov 23, 2026
fa826fa
test(nestjs): Exclude tests from the WebSocket e2e app build
chargome Nov 24, 2026
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 @@ -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,87 @@ 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');
} 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"
}
}
2 changes: 1 addition & 1 deletion packages/nestjs/src/decorators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { startSpan } from '@sentry/node';
import { _INTERNAL_cronExpressionToMonitorConfig as cronExpressionToMonitorConfig } from '@sentry/server-utils';
import { DEBUG_BUILD } from './debug-build';
import { isExpectedError } from './helpers';
import type { ReflectWithMetadata } from './integrations/helpers';
import type { ReflectWithMetadata } from './helpers';
import { copyReflectMetadata, getNestScheduleVersion, markSentryCronMethod } from './integrations/helpers';

/**
Expand Down
88 changes: 87 additions & 1 deletion packages/nestjs/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { isObjectLike } from '@sentry/core';
import type { Span } from '@sentry/core';
import { isObjectLike, withActiveSpan } from '@sentry/core';

/**
* Determines if the exception is an expected NestJS control flow error.
Expand Down Expand Up @@ -45,3 +46,88 @@ export function isWsOrRpcException(exception: unknown): boolean {

return typeof exception.getError === 'function' && typeof exception.initMessage === 'function';
}

/**
* The subset of `reflect-metadata`'s `Reflect` augmentation that NestJS
* relies on. Methods are optional because `reflect-metadata` may not be
* loaded; guard each before use.
*/
export interface ReflectWithMetadata {
getMetadataKeys?: (target: object) => unknown[];
getMetadata?: (key: unknown, target: object) => unknown;
defineMetadata?: (key: unknown, value: unknown, target: object) => void;
}

export interface Subscription {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
add(...args: any[]): void;
}

/**
* A minimal interface for an Observable.
*/
export interface Observable<T> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
subscribe(next?: (value: T) => void, error?: (err: any) => void, complete?: () => void): Subscription;
}

/**
* Adds instrumentation to a js observable and attaches the span to an active
* parent span.
*/
export function instrumentObservable(
observable: Observable<unknown>,
activeSpan: Span | undefined,
onError?: (error: unknown) => void,
): void {
if (activeSpan) {
// eslint-disable-next-line @typescript-eslint/unbound-method
observable.subscribe = new Proxy(observable.subscribe, {
apply: (originalSubscribe, thisArgSubscribe, argsSubscribe) => {
return withActiveSpan(activeSpan, () => {
const subscribeArgs = [...argsSubscribe];

if (onError) {
const observer = argsSubscribe[0];
if (observer && typeof observer === 'object') {
subscribeArgs[0] = new Proxy(observer, {
get(target, property) {
if (property !== 'error') {
const value = Reflect.get(target, property, target);
if ((property === 'next' || property === 'complete') && typeof value === 'function') {
return (...args: unknown[]) => Reflect.apply(value, target, args);
}
return value;
}

const errorHandler = Reflect.get(target, property, target);
return function (this: unknown, error: unknown): unknown {
onError(error);
if (typeof errorHandler !== 'function') {
throw error;
}
return Reflect.apply(errorHandler, target, [error]);
};
},
});
} else {
// RxJS ignores positional callbacks when the first argument is an observer object.
const errorHandler = argsSubscribe[1];
subscribeArgs[1] = function (this: unknown, error: unknown): unknown {
onError(error);
if (typeof errorHandler !== 'function') {
throw error;
}
return Reflect.apply(errorHandler, this, [error]);
};
}
}

const subscription: Subscription = originalSubscribe.apply(thisArgSubscribe, subscribeArgs);
subscription.add(() => activeSpan.end());
return subscription;
});
},
});
}
}
33 changes: 2 additions & 31 deletions packages/nestjs/src/integrations/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import {
isObjectLike,
withActiveSpan,
} from '@sentry/core';
import type { CatchTarget, InjectableTarget, NextFunction, Observable, Subscription } from './types';
import type { ReflectWithMetadata } from '../helpers';
import type { CatchTarget, InjectableTarget, NextFunction } from './types';

/** A function of unknown signature, matching the methods/handlers we wrap. */
export type AnyFn = (this: unknown, ...args: unknown[]) => unknown;
Expand Down Expand Up @@ -95,17 +96,6 @@ export function getNestScheduleVersion(cronOptions: object): string | undefined
return NEST_SCHEDULE_VERSIONS.get(cronOptions);
}

/**
* The subset of `reflect-metadata`'s `Reflect` augmentation that NestJS
* relies on. Methods are optional because `reflect-metadata` may not be
* loaded; guard each before use.
*/
export interface ReflectWithMetadata {
getMetadataKeys?: (target: object) => unknown[];
getMetadata?: (key: unknown, target: object) => unknown;
defineMetadata?: (key: unknown, value: unknown, target: object) => void;
}

/**
* Copy NestJS reflect-metadata from one object onto another so decorators
* (param decorators, guards, `@EventPattern`, ...) that read it keep working
Expand Down Expand Up @@ -224,25 +214,6 @@ export function getBullMQProcessSpanOptions(queueName: string | undefined): {
};
}

/**
* Adds instrumentation to a js observable and attaches the span to an active
* parent span.
*/
export function instrumentObservable(observable: Observable<unknown>, activeSpan: Span | undefined): void {
if (activeSpan) {
// eslint-disable-next-line @typescript-eslint/unbound-method
observable.subscribe = new Proxy(observable.subscribe, {
apply: (originalSubscribe, thisArgSubscribe, argsSubscribe) => {
return withActiveSpan(activeSpan, () => {
const subscription: Subscription = originalSubscribe.apply(thisArgSubscribe, argsSubscribe);
subscription.add(() => activeSpan.end());
return subscription;
});
},
});
}
}

/**
* Proxies the next() call in a nestjs middleware to end the span when called
*/
Expand Down
15 changes: 4 additions & 11 deletions packages/nestjs/src/integrations/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Observable } from '../helpers';

export type { Observable, Subscription } from '../helpers';

// Partial extract of FastifyRequest interface
// https://github.com/fastify/fastify/blob/87f9f20687c938828f1138f91682d568d2a31e53/types/request.d.ts#L41
interface FastifyRequest {
Expand Down Expand Up @@ -41,17 +45,6 @@ export interface MinimalNestJsApp {
}) => void;
}

export interface Subscription {
add(...args: any[]): void;
}

/**
* A minimal interface for an Observable.
*/
export interface Observable<T> {
subscribe(next?: (value: T) => void, error?: (err: any) => void, complete?: () => void): Subscription;
}

/**
* A NestJS call handler. Used in interceptors to start the route execution.
*/
Expand Down
Loading
Loading