Skip to content

Introduce @sentry/serverless with AWSLambda support #2886

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 13 commits into from
Sep 9, 2020
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# dependencies
node_modules/
packages/*/package-lock.json
package-lock.json

# build and test
build/
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"packages/minimal",
"packages/node",
"packages/react",
"packages/serverless",
"packages/tracing",
"packages/types",
"packages/typescript",
Expand Down
24 changes: 24 additions & 0 deletions packages/serverless/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
parserOptions: {
ecmaVersion: 2018,
},
extends: ['@sentry-internal/sdk'],
ignorePatterns: ['dist/**', 'esm/**'],
overrides: [
{
files: ['*.ts', '*.d.ts'],
parserOptions: {
project: './tsconfig.json',
},
},
],
rules: {
'@typescript-eslint/no-var-requires': 'off',
'@sentry-internal/sdk/no-async-await': 'off',
},
};
4 changes: 4 additions & 0 deletions packages/serverless/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*
!/dist/**/*
!/esm/**/*
*.tsbuildinfo
9 changes: 9 additions & 0 deletions packages/serverless/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2020, Sentry

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
43 changes: 43 additions & 0 deletions packages/serverless/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<p align="center">
<a href="https://sentry.io" target="_blank" align="center">
<img src="https://sentry-brand.storage.googleapis.com/sentry-logo-black.png" width="280">
</a>
<br />
</p>

# Official Sentry SDK for Serverless environments

## Links

- [Official SDK Docs](https://docs.sentry.io/)
- [TypeDoc](http://getsentry.github.io/sentry-javascript/)

## General

This package is a wrapper around `@sentry/node`, with added functionality related to various Serverless solutions. All
methods available in `@sentry/node` can be imported from `@sentry/serverless`.

Currently supported environment:

*AWS Lambda*

To use this SDK, call `Sentry.init(options)` at the very beginning of your JavaScript file.

```javascript
import * as Sentry from '@sentry/serverless';

Sentry.init({
dsn: '__DSN__',
// ...
});

// async (recommended)
exports.handler = Sentry.AWSLambda.wrapHandler(async (event, context) => {
throw new Error('oh, hello there!');
});

// sync
exports.handler = Sentry.AWSLambda.wrapHandler((event, context, callback) => {
throw new Error('oh, hello there!');
});
```
55 changes: 55 additions & 0 deletions packages/serverless/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"name": "@sentry/serverless",
"version": "5.22.3",
"description": "Offical Sentry SDK for various serverless solutions",
"repository": "git://github.com/getsentry/sentry-javascript.git",
"homepage": "https://github.com/getsentry/sentry-javascript/tree/master/packages/serverless",
"author": "Sentry",
"license": "MIT",
"engines": {
"node": ">=10"
},
"main": "dist/index.js",
"module": "esm/index.js",
"types": "dist/index.d.ts",
"publishConfig": {
"access": "public"
},
"dependencies": {
"@sentry/minimal": "5.22.3",
"@sentry/node": "5.22.3",
"@sentry/types": "5.22.3",
"@sentry/utils": "5.22.3",
"@types/aws-lambda": "^8.10.62",
"@types/node": "^14.6.4",
"tslib": "^1.9.3"
},
"devDependencies": {
"@sentry-internal/eslint-config-sdk": "5.22.3",
"eslint": "7.6.0",
"npm-run-all": "^4.1.2",
"prettier": "1.19.0",
"rimraf": "^2.6.3",
"typescript": "3.7.5"
},
"scripts": {
"build": "run-p build:es5 build:esm",
"build:es5": "tsc -p tsconfig.build.json",
"build:esm": "tsc -p tsconfig.esm.json",
"build:watch": "run-p build:watch:es5 build:watch:esm",
"build:watch:es5": "tsc -p tsconfig.build.json -w --preserveWatchOutput",
"build:watch:esm": "tsc -p tsconfig.esm.json -w --preserveWatchOutput",
"clean": "rimraf dist coverage build esm",
"link:yarn": "yarn link",
"lint": "run-s lint:prettier lint:eslint",
"lint:prettier": "prettier --check \"{src,test}/**/*.ts\"",
"lint:eslint": "eslint . --cache --cache-location '../../eslintcache/' --format stylish",
"fix": "run-s fix:eslint fix:prettier",
"fix:prettier": "prettier --write \"{src,test}/**/*.ts\"",
"fix:eslint": "eslint . --format stylish --fix",
"test": "jest --passWithNoTests",
"test:watch": "jest --watch --passWithNoTests",
"pack": "npm pack"
},
"sideEffects": false
}
207 changes: 207 additions & 0 deletions packages/serverless/src/awslambda.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
import { captureException, captureMessage, flush, Scope, SDK_VERSION, Severity, withScope } from '@sentry/node';
import { addExceptionMechanism } 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
// eslint-disable-next-line import/no-unresolved
import { Callback, Context, Handler } from 'aws-lambda';
import { hostname } from 'os';
import { performance } from 'perf_hooks';
import { types } from 'util';

const { isPromise } = types;

// https://www.npmjs.com/package/aws-lambda-consumer
type SyncHandler<T extends Handler> = (
event: Parameters<T>[0],
context: Parameters<T>[1],
callback: Parameters<T>[2],
) => void;

export type AsyncHandler<T extends Handler> = (
event: Parameters<T>[0],
context: Parameters<T>[1],
) => Promise<NonNullable<Parameters<Parameters<T>[2]>[1]>>;

interface WrapperOptions {
flushTimeout: number;
rethrowAfterCapture: boolean;
callbackWaitsForEmptyEventLoop: boolean;
captureTimeoutWarning: boolean;
timeoutWarning: number;
}

/**
* Add event processor that will override SDK details to point to the serverless SDK instead of Node,
* as well as set correct mechanism type, which should be set to `handled: false`.
* We do it like this, so that we don't introduce any side-effects in this module, which makes it tree-shakeable.
* @param scope Scope that processor should be added to
*/
function addServerlessEventProcessor(scope: Scope): void {
scope.addEventProcessor(event => {
event.sdk = {
...event.sdk,
name: 'sentry.javascript.serverless',
integrations: [...((event.sdk && event.sdk.integrations) || []), 'AWSLambda'],
packages: [
...((event.sdk && event.sdk.packages) || []),
{
name: 'npm:@sentry/serverless',
version: SDK_VERSION,
},
],
version: SDK_VERSION,
};

addExceptionMechanism(event, {
handled: false,
});

return event;
});
}

/**
* Adds additional information from the environment and AWS Context to the Sentry Scope.
*
* @param scope Scope that should be enhanced
* @param context AWS Lambda context that will be used to extract some part of the data
*/
function enhanceScopeWithEnvironmentData(scope: Scope, context: Context): void {
scope.setTransactionName(context.functionName);

scope.setTag('server_name', process.env._AWS_XRAY_DAEMON_ADDRESS || process.env.SENTRY_NAME || hostname());
scope.setTag('url', `awslambda:///${context.functionName}`);

scope.setContext('runtime', {
name: 'node',
version: global.process.version,
});

scope.setContext('aws.lambda', {
aws_request_id: context.awsRequestId,
function_name: context.functionName,
function_version: context.functionVersion,
invoked_function_arn: context.invokedFunctionArn,
execution_duration_in_millis: performance.now(),
remaining_time_in_millis: context.getRemainingTimeInMillis(),
'sys.argv': process.argv,
});

scope.setContext('aws.cloudwatch.logs', {
log_group: context.logGroupName,
log_stream: context.logStreamName,
url: `https://console.aws.amazon.com/cloudwatch/home?region=${
process.env.AWS_REGION
}#logsV2:log-groups/log-group/${encodeURIComponent(context.logGroupName)}/log-events/${encodeURIComponent(
context.logStreamName,
)}`,
});
}

/**
* Capture, flush the result down the network stream and await the response.
*
* @param e exception to be captured
* @param options WrapperOptions
*/
function captureExceptionAsync(e: unknown, context: Context, options: Partial<WrapperOptions>): Promise<boolean> {
withScope(scope => {
addServerlessEventProcessor(scope);
enhanceScopeWithEnvironmentData(scope, context);
captureException(e);
});
return flush(options.flushTimeout);
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const wrapHandler = <TEvent = any, TResult = any>(
handler: Handler,
handlerOptions: Partial<WrapperOptions> = {},
): Handler => {
const options = {
flushTimeout: 2000,
rethrowAfterCapture: true,
callbackWaitsForEmptyEventLoop: false,
captureTimeoutWarning: true,
timeoutWarningLimit: 500,
...handlerOptions,
};
let timeoutWarningTimer: NodeJS.Timeout;

return async (event: TEvent, context: Context, callback: Callback<TResult>) => {
context.callbackWaitsForEmptyEventLoop = options.callbackWaitsForEmptyEventLoop;

// In seconds. You cannot go any more granular than this in AWS Lambda.
const configuredTimeout = Math.ceil(context.getRemainingTimeInMillis() / 1000);
const configuredTimeoutMinutes = Math.floor(configuredTimeout / 60);
const configuredTimeoutSeconds = configuredTimeout % 60;

const humanReadableTimeout =
configuredTimeoutMinutes > 0
? `${configuredTimeoutMinutes}m${configuredTimeoutSeconds}s`
: `${configuredTimeoutSeconds}s`;

// When `callbackWaitsForEmptyEventLoop` is set to false, which it should when using `captureTimeoutWarning`,
// we don't have a guarantee that this message will be delivered. Because of that, we don't flush it.
if (options.captureTimeoutWarning) {
const timeoutWarningDelay = context.getRemainingTimeInMillis() - options.timeoutWarningLimit;

timeoutWarningTimer = setTimeout(() => {
withScope(scope => {
addServerlessEventProcessor(scope);
enhanceScopeWithEnvironmentData(scope, context);
scope.setTag('timeout', humanReadableTimeout);
captureMessage(`Possible function timeout: ${context.functionName}`, Severity.Warning);
});
}, timeoutWarningDelay);
}

const callbackWrapper = <TResult>(
callback: Callback<TResult>,
resolve: (value?: unknown) => void,
reject: (reason?: unknown) => void,
): Callback<TResult> => {
return (...args) => {
clearTimeout(timeoutWarningTimer);
if (args[0] === null || args[0] === undefined) {
resolve(callback(...args));
} else {
captureExceptionAsync(args[0], context, options).then(
() => reject(callback(...args)),
() => reject(callback(...args)),
);
}
};
};

try {
// AWSLambda is like Express. It makes a distinction about handlers based on it's last argument
// async (event) => async handler
// async (event, context) => async handler
// (event, context, callback) => sync handler
const isSyncHandler = handler.length === 3;
const handlerRv = isSyncHandler
? await new Promise((resolve, reject) => {
const rv = (handler as SyncHandler<Handler<TEvent, TResult>>)(
event,
context,
callbackWrapper(callback, resolve, reject),
);

// This should never happen, but still can if someone writes a handler as
// `async (event, context, callback) => {}`
if (isPromise(rv)) {
((rv as unknown) as Promise<TResult>).then(resolve, reject);
}
})
: await (handler as AsyncHandler<Handler<TEvent, TResult>>)(event, context);
clearTimeout(timeoutWarningTimer);
return handlerRv;
} catch (e) {
clearTimeout(timeoutWarningTimer);
await captureExceptionAsync(e, context, options);
if (options.rethrowAfterCapture) {
throw e;
}
}
};
};
5 changes: 5 additions & 0 deletions packages/serverless/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// https://medium.com/unsplash/named-namespace-imports-7345212bbffb
import * as AWSLambda from './awslambda';
export { AWSLambda };

export * from '@sentry/node';
Empty file.
9 changes: 9 additions & 0 deletions packages/serverless/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"include": ["src/**/*"],
"compilerOptions": {
"baseUrl": ".",
"outDir": "dist",
"target": "ES2018"
}
}
9 changes: 9 additions & 0 deletions packages/serverless/tsconfig.esm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.esm.json",
"include": ["src/**/*"],
"compilerOptions": {
"baseUrl": ".",
"outDir": "esm",
"target": "ES2018"
}
}
4 changes: 4 additions & 0 deletions packages/serverless/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.build.json",
"include": ["src/**/*.ts", "test/**/*.ts"]
}
Loading