-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
Changes from 5 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
80f49fd
feat: Introduce @sentry/serverless package with AWS Lambda support
kamilogorek fd4a5b8
ref: Provide more direct CloudWatch Logs url
kamilogorek 585d8c8
fix: Set mechanism.handled to false
kamilogorek f8b1ab5
feat: Add AWSLambda to integrations table in SDK info field
kamilogorek f4eda6e
feat: Intercept callback(err) calls as exceptions
kamilogorek d8c624a
ref: Target ES2018 as Node10+ already supports all its features
kamilogorek 5785af5
ref: Always return async function from handler and handle sync resolu…
kamilogorek 8c6dc7d
misc: Remove package-lock.json from root and add it to gitignore
kamilogorek a0ab3e2
misc: Readme codereview updates
kamilogorek 4d6a7d6
ref: Clean up eslint and typescript configs
kamilogorek cd1ed44
misc: Ignore serverless on Travis with Node <10
kamilogorek d2b26e4
fix: Handle edgecase where someone writes async handler with callback…
kamilogorek 6986e9c
misc: Ignore serverless builds on pre v10 node
kamilogorek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
module.exports = { | ||
root: true, | ||
env: { | ||
es6: true, | ||
node: true, | ||
}, | ||
parserOptions: { | ||
ecmaVersion: 2018, | ||
}, | ||
extends: ['@sentry-internal/sdk'], | ||
ignorePatterns: ['build/**', 'dist/**', 'esm/**', 'examples/**', 'scripts/**', 'test/manual/**'], | ||
overrides: [ | ||
{ | ||
files: ['*.ts', '*.tsx', '*.d.ts'], | ||
parserOptions: { | ||
project: './tsconfig.json', | ||
}, | ||
}, | ||
{ | ||
files: ['test/**'], | ||
rules: { | ||
'@typescript-eslint/no-explicit-any': 'off', | ||
'@typescript-eslint/no-non-null-assertion': 'off', | ||
}, | ||
}, | ||
{ | ||
files: ['test/**/*.js'], | ||
rules: { | ||
'import/order': 'off', | ||
}, | ||
}, | ||
], | ||
rules: { | ||
'prefer-rest-params': 'off', | ||
'@typescript-eslint/no-var-requires': 'off', | ||
'@sentry-internal/sdk/no-async-await': 'off', | ||
}, | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
* | ||
!/dist/**/* | ||
!/esm/**/* | ||
*.tsbuildinfo |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/quickstart/) | ||
- [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 | ||
kamilogorek marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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!'); | ||
}); | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
"test:watch": "jest --watch", | ||
"pack": "npm pack" | ||
}, | ||
"sideEffects": false | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,182 @@ | ||
import { captureException, captureMessage, flush, Scope, SDK_VERSION, Severity, withScope } from '@sentry/node'; | ||
import { addExceptionMechanism } from '@sentry/utils'; | ||
import { Callback, Context, Handler } from 'aws-lambda'; | ||
import { hostname } from 'os'; | ||
import { performance } from 'perf_hooks'; | ||
import { types } from 'util'; | ||
|
||
const { isPromise } = types; | ||
|
||
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 (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); | ||
} | ||
|
||
try { | ||
const callbackWrapper: Callback<TResult> = (...args) => { | ||
clearTimeout(timeoutWarningTimer); | ||
|
||
if (args[0] === null || args[0] === undefined) { | ||
return callback(...args); | ||
} else { | ||
return captureExceptionAsync(args[0], context, options).then( | ||
() => callback(...args), | ||
() => callback(...args), | ||
); | ||
} | ||
}; | ||
|
||
let handlerRv = handler(event, context, callbackWrapper); | ||
|
||
if (isPromise(handlerRv)) { | ||
handlerRv = handlerRv as Promise<TResult>; | ||
return handlerRv.catch(e => { | ||
clearTimeout(timeoutWarningTimer); | ||
return captureExceptionAsync(e, context, options).then(() => { | ||
if (options.rethrowAfterCapture) { | ||
throw e; | ||
} | ||
}); | ||
}); | ||
} else { | ||
return handlerRv; | ||
} | ||
} catch (e) { | ||
clearTimeout(timeoutWarningTimer); | ||
return captureExceptionAsync(e, context, options).then(() => { | ||
if (options.rethrowAfterCapture) { | ||
throw e; | ||
} | ||
}); | ||
} | ||
}; | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
{ | ||
"extends": "../../tsconfig.json", | ||
"compilerOptions": { | ||
"esModuleInterop": true, | ||
"baseUrl": ".", | ||
"outDir": "dist", | ||
"jsx": "react" | ||
}, | ||
"include": ["src/**/*"] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
{ | ||
"extends": "../../tsconfig.esm.json", | ||
"compilerOptions": { | ||
"esModuleInterop": true, | ||
"baseUrl": ".", | ||
"outDir": "esm", | ||
"jsx": "react" | ||
}, | ||
"include": ["src/**/*"] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
{ | ||
"extends": "./tsconfig.build.json", | ||
"include": ["src/**/*.ts", "test/**/*.ts", "src/**/*.tsx", "test/**/*.tsx"], | ||
"exclude": ["dist"], | ||
"compilerOptions": { | ||
"rootDir": ".", | ||
"types": ["node"] | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.