Skip to content

ref(serverless): Convert integrations to functional approach #10329

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 7 commits into from
Jan 29, 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
9 changes: 4 additions & 5 deletions packages/serverless/src/awslambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { existsSync } from 'fs';
import { hostname } from 'os';
import { basename, resolve } from 'path';
import { types } from 'util';
/* eslint-disable max-lines */
import type { NodeOptions, Scope } from '@sentry/node';
import { SDK_VERSION } from '@sentry/node';
import {
Expand All @@ -19,12 +18,12 @@ import {
} from '@sentry/node';
import type { Integration, Options, SdkMetadata, Span } from '@sentry/types';
import { isString, logger } from '@sentry/utils';
// NOTE: I have no idea how to fix this right now, and don't want to waste more time, as it builds just fine — Kamil
import type { Context, Handler } from 'aws-lambda';
import { performance } from 'perf_hooks';

import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '@sentry/core';
import { AWSServices } from './awsservices';
import { awsServicesIntegration } from './awsservices';

import { DEBUG_BUILD } from './debug-build';
import { markEventUnhandled } from './utils';

Expand Down Expand Up @@ -71,12 +70,12 @@ export interface WrapperOptions {
export const defaultIntegrations: Integration[] = [
// eslint-disable-next-line deprecation/deprecation
...nodeDefaultIntegrations,
new AWSServices({ optional: true }),
awsServicesIntegration({ optional: true }),
];

/** Get the default integrations for the AWSLambda SDK. */
export function getDefaultIntegrations(options: Options): Integration[] {
return [...getNodeDefaultIntegrations(options), new AWSServices({ optional: true })];
return [...getNodeDefaultIntegrations(options), awsServicesIntegration({ optional: true })];
}

interface AWSLambdaOptions extends NodeOptions {
Expand Down
104 changes: 57 additions & 47 deletions packages/serverless/src/awsservices.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
import { startInactiveSpan } from '@sentry/node';
import type { Integration, Span } from '@sentry/types';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, convertIntegrationFnToClass, defineIntegration } from '@sentry/core';
import { getClient, startInactiveSpan } from '@sentry/node';
import type { Client, Integration, IntegrationClass, IntegrationFn, Span } from '@sentry/types';
import { fill } from '@sentry/utils';
// 'aws-sdk/global' import is expected to be type-only so it's erased in the final .js file.
// When TypeScript compiler is upgraded, use `import type` syntax to explicitly assert that we don't want to load a module here.
Expand All @@ -16,63 +16,73 @@ interface AWSService {
serviceIdentifier: string;
}

/** AWS service requests tracking */
export class AWSServices implements Integration {
/**
* @inheritDoc
*/
public static id: string = 'AWSServices';
const INTEGRATION_NAME = 'AWSServices';

/**
* @inheritDoc
*/
public name: string;
const SETUP_CLIENTS = new WeakMap<Client, boolean>();

private readonly _optional: boolean;
const _awsServicesIntegration = ((options: { optional?: boolean } = {}) => {
const optional = options.optional || false;
return {
name: INTEGRATION_NAME,
setupOnce() {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const awsModule = require('aws-sdk/global') as typeof AWS;
fill(awsModule.Service.prototype, 'makeRequest', wrapMakeRequest);
} catch (e) {
if (!optional) {
throw e;
}
}
},
setup(client) {
SETUP_CLIENTS.set(client, true);
},
};
}) satisfies IntegrationFn;

public constructor(options: { optional?: boolean } = {}) {
this.name = AWSServices.id;
export const awsServicesIntegration = defineIntegration(_awsServicesIntegration);

this._optional = options.optional || false;
}
/**
* AWS Service Request Tracking.
*
* @deprecated Use `awsServicesIntegration()` instead.
*/
// eslint-disable-next-line deprecation/deprecation
export const AWSServices = convertIntegrationFnToClass(
INTEGRATION_NAME,
awsServicesIntegration,
) as IntegrationClass<Integration>;
Copy link
Member

Choose a reason for hiding this comment

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

let's also add:

export type AWSServices = typeof AWSServices;

right away here (same for the gcp stuff)!

Copy link
Member Author

Choose a reason for hiding this comment

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

do we have to also export the type from the index?

Copy link
Member

Choose a reason for hiding this comment

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

otherwise this does not work anymore (it does not work with the stuff I migrated):

import {AWSServices} from '@sentry/serverless';

let a: AWSServices | undefined;
// instead you need to do this:
let b: typeof AWSServices | undefined;

This is very unlikely to affect somebody, but for consistency we should do that (and also for all other integrations, just didn't get to it yet...)


/**
* @inheritDoc
*/
public setupOnce(): void {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const awsModule = require('aws-sdk/global') as typeof AWS;
fill(awsModule.Service.prototype, 'makeRequest', wrapMakeRequest);
} catch (e) {
if (!this._optional) {
throw e;
}
}
}
}
// eslint-disable-next-line deprecation/deprecation
export type AWSServices = typeof AWSServices;

/** */
/**
* Patches AWS SDK request to create `http.client` spans.
*/
function wrapMakeRequest<TService extends AWSService, TResult>(
orig: MakeRequestFunction<GenericParams, TResult>,
): MakeRequestFunction<GenericParams, TResult> {
return function (this: TService, operation: string, params?: GenericParams, callback?: MakeRequestCallback<TResult>) {
let span: Span | undefined;
const req = orig.call(this, operation, params);
req.on('afterBuild', () => {
span = startInactiveSpan({
name: describe(this, operation, params),
op: 'http.client',
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.serverless',
},

if (SETUP_CLIENTS.has(getClient() as Client)) {
req.on('afterBuild', () => {
span = startInactiveSpan({
name: describe(this, operation, params),
op: 'http.client',
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.serverless',
},
});
});
});
req.on('complete', () => {
if (span) {
span.end();
}
});
req.on('complete', () => {
if (span) {
span.end();
}
});
}

if (callback) {
req.send(callback);
Expand Down
12 changes: 6 additions & 6 deletions packages/serverless/src/gcpfunction/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import {
} from '@sentry/node';
import type { Integration, Options, SdkMetadata } from '@sentry/types';

import { GoogleCloudGrpc } from '../google-cloud-grpc';
import { GoogleCloudHttp } from '../google-cloud-http';
import { googleCloudGrpcIntegration } from '../google-cloud-grpc';
import { googleCloudHttpIntegration } from '../google-cloud-http';

export * from './http';
export * from './events';
Expand All @@ -18,16 +18,16 @@ export * from './cloud_events';
export const defaultIntegrations: Integration[] = [
// eslint-disable-next-line deprecation/deprecation
...defaultNodeIntegrations,
new GoogleCloudHttp({ optional: true }), // We mark this integration optional since '@google-cloud/common' module could be missing.
new GoogleCloudGrpc({ optional: true }), // We mark this integration optional since 'google-gax' module could be missing.
googleCloudHttpIntegration({ optional: true }), // We mark this integration optional since '@google-cloud/common' module could be missing.
googleCloudGrpcIntegration({ optional: true }), // We mark this integration optional since 'google-gax' module could be missing.
];

/** Get the default integrations for the GCP SDK. */
export function getDefaultIntegrations(options: Options): Integration[] {
return [
...getDefaultNodeIntegrations(options),
new GoogleCloudHttp({ optional: true }), // We mark this integration optional since '@google-cloud/common' module could be missing.
new GoogleCloudGrpc({ optional: true }), // We mark this integration optional since 'google-gax' module could be missing.
googleCloudHttpIntegration({ optional: true }), // We mark this integration optional since '@google-cloud/common' module could be missing.
googleCloudGrpcIntegration({ optional: true }), // We mark this integration optional since 'google-gax' module could be missing.
];
}

Expand Down
88 changes: 50 additions & 38 deletions packages/serverless/src/google-cloud-grpc.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { EventEmitter } from 'events';
import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
convertIntegrationFnToClass,
defineIntegration,
getClient,
} from '@sentry/core';
import { startInactiveSpan } from '@sentry/node';
import type { Integration } from '@sentry/types';
import type { Client, Integration, IntegrationClass, IntegrationFn } from '@sentry/types';
import { fill } from '@sentry/utils';

interface GrpcFunction extends CallableFunction {
Expand All @@ -26,45 +31,52 @@ interface Stub {
[key: string]: GrpcFunctionObject;
}

/** Google Cloud Platform service requests tracking for GRPC APIs */
export class GoogleCloudGrpc implements Integration {
/**
* @inheritDoc
*/
public static id: string = 'GoogleCloudGrpc';
const SERVICE_PATH_REGEX = /^(\w+)\.googleapis.com$/;

/**
* @inheritDoc
*/
public name: string;
const INTEGRATION_NAME = 'GoogleCloudGrpc';

private readonly _optional: boolean;
const SETUP_CLIENTS = new WeakMap<Client, boolean>();

public constructor(options: { optional?: boolean } = {}) {
this.name = GoogleCloudGrpc.id;
const _googleCloudGrpcIntegration = ((options: { optional?: boolean } = {}) => {
const optional = options.optional || false;
return {
name: INTEGRATION_NAME,
setupOnce() {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const gaxModule = require('google-gax');
fill(
gaxModule.GrpcClient.prototype, // eslint-disable-line @typescript-eslint/no-unsafe-member-access
'createStub',
wrapCreateStub,
);
} catch (e) {
if (!optional) {
throw e;
}
}
},
setup(client) {
SETUP_CLIENTS.set(client, true);
},
};
}) satisfies IntegrationFn;

this._optional = options.optional || false;
}
export const googleCloudGrpcIntegration = defineIntegration(_googleCloudGrpcIntegration);

/**
* @inheritDoc
*/
public setupOnce(): void {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const gaxModule = require('google-gax');
fill(
gaxModule.GrpcClient.prototype, // eslint-disable-line @typescript-eslint/no-unsafe-member-access
'createStub',
wrapCreateStub,
);
} catch (e) {
if (!this._optional) {
throw e;
}
}
}
}
/**
* Google Cloud Platform service requests tracking for GRPC APIs.
*
* @deprecated Use `googleCloudGrpcIntegration()` instead.
*/
// eslint-disable-next-line deprecation/deprecation
export const GoogleCloudGrpc = convertIntegrationFnToClass(
INTEGRATION_NAME,
googleCloudGrpcIntegration,
) as IntegrationClass<Integration>;

// eslint-disable-next-line deprecation/deprecation
export type GoogleCloudGrpc = typeof GoogleCloudGrpc;

/** Returns a wrapped function that returns a stub with tracing enabled */
function wrapCreateStub(origCreate: CreateStubFunc): CreateStubFunc {
Expand Down Expand Up @@ -105,7 +117,7 @@ function fillGrpcFunction(stub: Stub, serviceIdentifier: string, methodName: str
(orig: GrpcFunction): GrpcFunction =>
(...args) => {
const ret = orig.apply(stub, args);
if (typeof ret?.on !== 'function') {
if (typeof ret?.on !== 'function' || !SETUP_CLIENTS.has(getClient() as Client)) {
return ret;
}
const span = startInactiveSpan({
Expand All @@ -127,6 +139,6 @@ function fillGrpcFunction(stub: Stub, serviceIdentifier: string, methodName: str

/** Identifies service by its address */
function identifyService(servicePath: string): string {
const match = servicePath.match(/^(\w+)\.googleapis.com$/);
const match = servicePath.match(SERVICE_PATH_REGEX);
return match ? match[1] : servicePath;
}
Loading