|
| 1 | +import { captureException, captureMessage, flush, Scope, SDK_VERSION, Severity, withScope } from '@sentry/node'; |
| 2 | +import { addExceptionMechanism } from '@sentry/utils'; |
| 3 | +// 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 |
| 4 | +// eslint-disable-next-line import/no-unresolved |
| 5 | +import { Callback, Context, Handler } from 'aws-lambda'; |
| 6 | +import { hostname } from 'os'; |
| 7 | +import { performance } from 'perf_hooks'; |
| 8 | +import { types } from 'util'; |
| 9 | + |
| 10 | +const { isPromise } = types; |
| 11 | + |
| 12 | +// https://www.npmjs.com/package/aws-lambda-consumer |
| 13 | +type SyncHandler<T extends Handler> = ( |
| 14 | + event: Parameters<T>[0], |
| 15 | + context: Parameters<T>[1], |
| 16 | + callback: Parameters<T>[2], |
| 17 | +) => void; |
| 18 | + |
| 19 | +export type AsyncHandler<T extends Handler> = ( |
| 20 | + event: Parameters<T>[0], |
| 21 | + context: Parameters<T>[1], |
| 22 | +) => Promise<NonNullable<Parameters<Parameters<T>[2]>[1]>>; |
| 23 | + |
| 24 | +interface WrapperOptions { |
| 25 | + flushTimeout: number; |
| 26 | + rethrowAfterCapture: boolean; |
| 27 | + callbackWaitsForEmptyEventLoop: boolean; |
| 28 | + captureTimeoutWarning: boolean; |
| 29 | + timeoutWarning: number; |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Add event processor that will override SDK details to point to the serverless SDK instead of Node, |
| 34 | + * as well as set correct mechanism type, which should be set to `handled: false`. |
| 35 | + * We do it like this, so that we don't introduce any side-effects in this module, which makes it tree-shakeable. |
| 36 | + * @param scope Scope that processor should be added to |
| 37 | + */ |
| 38 | +function addServerlessEventProcessor(scope: Scope): void { |
| 39 | + scope.addEventProcessor(event => { |
| 40 | + event.sdk = { |
| 41 | + ...event.sdk, |
| 42 | + name: 'sentry.javascript.serverless', |
| 43 | + integrations: [...((event.sdk && event.sdk.integrations) || []), 'AWSLambda'], |
| 44 | + packages: [ |
| 45 | + ...((event.sdk && event.sdk.packages) || []), |
| 46 | + { |
| 47 | + name: 'npm:@sentry/serverless', |
| 48 | + version: SDK_VERSION, |
| 49 | + }, |
| 50 | + ], |
| 51 | + version: SDK_VERSION, |
| 52 | + }; |
| 53 | + |
| 54 | + addExceptionMechanism(event, { |
| 55 | + handled: false, |
| 56 | + }); |
| 57 | + |
| 58 | + return event; |
| 59 | + }); |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Adds additional information from the environment and AWS Context to the Sentry Scope. |
| 64 | + * |
| 65 | + * @param scope Scope that should be enhanced |
| 66 | + * @param context AWS Lambda context that will be used to extract some part of the data |
| 67 | + */ |
| 68 | +function enhanceScopeWithEnvironmentData(scope: Scope, context: Context): void { |
| 69 | + scope.setTransactionName(context.functionName); |
| 70 | + |
| 71 | + scope.setTag('server_name', process.env._AWS_XRAY_DAEMON_ADDRESS || process.env.SENTRY_NAME || hostname()); |
| 72 | + scope.setTag('url', `awslambda:///${context.functionName}`); |
| 73 | + |
| 74 | + scope.setContext('runtime', { |
| 75 | + name: 'node', |
| 76 | + version: global.process.version, |
| 77 | + }); |
| 78 | + |
| 79 | + scope.setContext('aws.lambda', { |
| 80 | + aws_request_id: context.awsRequestId, |
| 81 | + function_name: context.functionName, |
| 82 | + function_version: context.functionVersion, |
| 83 | + invoked_function_arn: context.invokedFunctionArn, |
| 84 | + execution_duration_in_millis: performance.now(), |
| 85 | + remaining_time_in_millis: context.getRemainingTimeInMillis(), |
| 86 | + 'sys.argv': process.argv, |
| 87 | + }); |
| 88 | + |
| 89 | + scope.setContext('aws.cloudwatch.logs', { |
| 90 | + log_group: context.logGroupName, |
| 91 | + log_stream: context.logStreamName, |
| 92 | + url: `https://console.aws.amazon.com/cloudwatch/home?region=${ |
| 93 | + process.env.AWS_REGION |
| 94 | + }#logsV2:log-groups/log-group/${encodeURIComponent(context.logGroupName)}/log-events/${encodeURIComponent( |
| 95 | + context.logStreamName, |
| 96 | + )}`, |
| 97 | + }); |
| 98 | +} |
| 99 | + |
| 100 | +/** |
| 101 | + * Capture, flush the result down the network stream and await the response. |
| 102 | + * |
| 103 | + * @param e exception to be captured |
| 104 | + * @param options WrapperOptions |
| 105 | + */ |
| 106 | +function captureExceptionAsync(e: unknown, context: Context, options: Partial<WrapperOptions>): Promise<boolean> { |
| 107 | + withScope(scope => { |
| 108 | + addServerlessEventProcessor(scope); |
| 109 | + enhanceScopeWithEnvironmentData(scope, context); |
| 110 | + captureException(e); |
| 111 | + }); |
| 112 | + return flush(options.flushTimeout); |
| 113 | +} |
| 114 | + |
| 115 | +// eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 116 | +export const wrapHandler = <TEvent = any, TResult = any>( |
| 117 | + handler: Handler, |
| 118 | + handlerOptions: Partial<WrapperOptions> = {}, |
| 119 | +): Handler => { |
| 120 | + const options = { |
| 121 | + flushTimeout: 2000, |
| 122 | + rethrowAfterCapture: true, |
| 123 | + callbackWaitsForEmptyEventLoop: false, |
| 124 | + captureTimeoutWarning: true, |
| 125 | + timeoutWarningLimit: 500, |
| 126 | + ...handlerOptions, |
| 127 | + }; |
| 128 | + let timeoutWarningTimer: NodeJS.Timeout; |
| 129 | + |
| 130 | + return async (event: TEvent, context: Context, callback: Callback<TResult>) => { |
| 131 | + context.callbackWaitsForEmptyEventLoop = options.callbackWaitsForEmptyEventLoop; |
| 132 | + |
| 133 | + // In seconds. You cannot go any more granular than this in AWS Lambda. |
| 134 | + const configuredTimeout = Math.ceil(context.getRemainingTimeInMillis() / 1000); |
| 135 | + const configuredTimeoutMinutes = Math.floor(configuredTimeout / 60); |
| 136 | + const configuredTimeoutSeconds = configuredTimeout % 60; |
| 137 | + |
| 138 | + const humanReadableTimeout = |
| 139 | + configuredTimeoutMinutes > 0 |
| 140 | + ? `${configuredTimeoutMinutes}m${configuredTimeoutSeconds}s` |
| 141 | + : `${configuredTimeoutSeconds}s`; |
| 142 | + |
| 143 | + // When `callbackWaitsForEmptyEventLoop` is set to false, which it should when using `captureTimeoutWarning`, |
| 144 | + // we don't have a guarantee that this message will be delivered. Because of that, we don't flush it. |
| 145 | + if (options.captureTimeoutWarning) { |
| 146 | + const timeoutWarningDelay = context.getRemainingTimeInMillis() - options.timeoutWarningLimit; |
| 147 | + |
| 148 | + timeoutWarningTimer = setTimeout(() => { |
| 149 | + withScope(scope => { |
| 150 | + addServerlessEventProcessor(scope); |
| 151 | + enhanceScopeWithEnvironmentData(scope, context); |
| 152 | + scope.setTag('timeout', humanReadableTimeout); |
| 153 | + captureMessage(`Possible function timeout: ${context.functionName}`, Severity.Warning); |
| 154 | + }); |
| 155 | + }, timeoutWarningDelay); |
| 156 | + } |
| 157 | + |
| 158 | + const callbackWrapper = <TResult>( |
| 159 | + callback: Callback<TResult>, |
| 160 | + resolve: (value?: unknown) => void, |
| 161 | + reject: (reason?: unknown) => void, |
| 162 | + ): Callback<TResult> => { |
| 163 | + return (...args) => { |
| 164 | + clearTimeout(timeoutWarningTimer); |
| 165 | + if (args[0] === null || args[0] === undefined) { |
| 166 | + resolve(callback(...args)); |
| 167 | + } else { |
| 168 | + captureExceptionAsync(args[0], context, options).then( |
| 169 | + () => reject(callback(...args)), |
| 170 | + () => reject(callback(...args)), |
| 171 | + ); |
| 172 | + } |
| 173 | + }; |
| 174 | + }; |
| 175 | + |
| 176 | + try { |
| 177 | + // AWSLambda is like Express. It makes a distinction about handlers based on it's last argument |
| 178 | + // async (event) => async handler |
| 179 | + // async (event, context) => async handler |
| 180 | + // (event, context, callback) => sync handler |
| 181 | + const isSyncHandler = handler.length === 3; |
| 182 | + const handlerRv = isSyncHandler |
| 183 | + ? await new Promise((resolve, reject) => { |
| 184 | + const rv = (handler as SyncHandler<Handler<TEvent, TResult>>)( |
| 185 | + event, |
| 186 | + context, |
| 187 | + callbackWrapper(callback, resolve, reject), |
| 188 | + ); |
| 189 | + |
| 190 | + // This should never happen, but still can if someone writes a handler as |
| 191 | + // `async (event, context, callback) => {}` |
| 192 | + if (isPromise(rv)) { |
| 193 | + ((rv as unknown) as Promise<TResult>).then(resolve, reject); |
| 194 | + } |
| 195 | + }) |
| 196 | + : await (handler as AsyncHandler<Handler<TEvent, TResult>>)(event, context); |
| 197 | + clearTimeout(timeoutWarningTimer); |
| 198 | + return handlerRv; |
| 199 | + } catch (e) { |
| 200 | + clearTimeout(timeoutWarningTimer); |
| 201 | + await captureExceptionAsync(e, context, options); |
| 202 | + if (options.rethrowAfterCapture) { |
| 203 | + throw e; |
| 204 | + } |
| 205 | + } |
| 206 | + }; |
| 207 | +}; |
0 commit comments