Skip to content
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

feat(nestjs): Add function-level span decorator to nestjs #12721

Merged
merged 19 commits into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ export class AppController1 {
async testOutgoingHttpExternalDisallowed() {
return this.appService.testOutgoingHttpExternalDisallowed();
}

@Get('test-span-decorator')
async testSpanDecorator() {
return this.appService.testSpanDecorator();
}
}

@Controller()
Expand Down
10 changes: 10 additions & 0 deletions dev-packages/e2e-tests/test-applications/nestjs/src/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import * as Sentry from '@sentry/nestjs';
import { SentryTraced } from '@sentry/nestjs';
import { makeHttpRequest } from './utils';

@Injectable()
Expand Down Expand Up @@ -75,6 +76,15 @@ export class AppService1 {
async testOutgoingHttpExternalDisallowed() {
return makeHttpRequest('http://localhost:3040/external-disallowed');
}

@SentryTraced('wait function')
async wait() {
return new Promise(resolve => setTimeout(resolve, 500));
}
Copy link
Member

Choose a reason for hiding this comment

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

l: We could add a second method that is not async and assert on it in the test.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Do you mean a second non-async function and then check whether the transaction includes spans for both?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated


async testSpanDecorator() {
await this.wait();
}
}

@Injectable()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { expect, test } from '@playwright/test';
import { waitForTransaction } from '@sentry-internal/test-utils';

test('Transaction includes span for decorated function', async ({ baseURL }) => {
const transactionEventPromise = waitForTransaction('nestjs', transactionEvent => {
return (
transactionEvent?.contexts?.trace?.op === 'http.server' &&
transactionEvent?.transaction === 'GET /test-span-decorator'
);
});

await fetch(`${baseURL}/test-span-decorator`);

const transactionEvent = await transactionEventPromise;

expect(transactionEvent.spans).toEqual(
expect.arrayContaining([
expect.objectContaining({
span_id: expect.any(String),
trace_id: expect.any(String),
data: expect.any(Object),
Copy link
Member

Choose a reason for hiding this comment

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

m: Let's assert on the sentry.origin and sentry.source attibutes in the data object.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I explicitly assert the data object now, there is no sentry.source property though

description: 'wait',
parent_span_id: expect.any(String),
start_timestamp: expect.any(Number),
status: 'ok',
op: 'wait function',
origin: 'manual',
}),
]),
);
});
18 changes: 18 additions & 0 deletions packages/nestjs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,24 @@ Sentry.init({

Note that it is necessary to initialize Sentry **before you import any package that may be instrumented by us**.

## Span Decorator

Use the @SentryTraced() decorator to gain additional performance insights for any function within your NestJS
application.

```js
import { Injectable } from '@nestjs/common';
import { SentryTraced } from '@sentry/nestjs';

@Injectable()
export class ExampleService {
@SentryTraced('example function')
async performTask() {
// Your business logic here
}
}
```

## Links

- [Official SDK Docs](https://docs.sentry.io/platforms/javascript/guides/nestjs/)
2 changes: 2 additions & 0 deletions packages/nestjs/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export * from '@sentry/node';

export { init } from './sdk';

export * from './span-decorator';
Copy link
Member

Choose a reason for hiding this comment

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

h: In the index file, let's be specific about what we export. This is to avoid accidentally widening the API surface.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated

29 changes: 29 additions & 0 deletions packages/nestjs/src/span-decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { captureException, startSpan } from '@sentry/node';

/**
* A decorator usable to wrap arbitrary functions with spans.
*/
export function SentryTraced(op: string = 'function') {
return function (target: unknown, propertyKey: string, descriptor: PropertyDescriptor) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const originalMethod = descriptor.value as (...args: any[]) => Promise<any>;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
descriptor.value = async function (...args: any[]) {
Copy link
Member

Choose a reason for hiding this comment

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

h: We should not modify the return value. Currently we are wrapping all non-promise return values in a Promise. To fix this we can just remove all async and await keywords and everything will work perfectly fine.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fixed

await startSpan(
{
op: op,
name: propertyKey,
},
async () => {
try {
return await originalMethod.apply(this, args);
} catch (e) {
captureException(e);
}
Copy link
Member

Choose a reason for hiding this comment

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

h: We do not want to wrap this with a try-catch-captureException. We only want to capture errors when they bubble up to an unexpected place.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

updated

},
);
};
return descriptor;
};
}
Loading