Skip to content

Nestjs WS Trace Interceptor #13810

Open
@CSenshi

Description

@CSenshi

Problem Statement

Nestjs supports websocket gateway. It would be nice to have built in tracing interceptor like sentry has for http requests

Solution Brainstorm

This is implementation which we wrote in our project

import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
import * as Sentry from '@sentry/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs';

export class SentryWsTracingInterceptor implements NestInterceptor {
  /**
   * Intercepts WS requests to set the transaction name for Sentry tracing.
   */
  public intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<unknown> {
    if (context.getType() === 'ws') {
      const client = context.switchToWs().getClient();
      const pattern = context.switchToWs().getPattern();
      Sentry.getIsolationScope().setTransactionName(
        `WS ${client.nsp.name} ${pattern}`,
      );

      return Sentry.startSpanManual(
        {
          op: 'ws',
          name: `WS ${client.nsp.name} ${pattern}`,
        },
        (span) => {
          return next.handle().pipe(
            tap({
              finalize: () => span.end(),
            }),
          );
        },
      );
    }

    return next.handle();
  }
}

Product Area

Profiling

Metadata

Metadata

Assignees

No one assigned

    Projects

    Status

    Waiting for: Product Owner

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions