|
| 1 | +import * as http from 'node:http'; |
| 2 | +import { buffer } from 'node:stream/consumers'; |
| 3 | +import { debug, dsnFromString, getEnvelopeEndpointWithUrlEncodedAuth } from '@sentry/core'; |
| 4 | +import { DEBUG_BUILD } from './debug-build'; |
| 5 | + |
| 6 | +/** |
| 7 | + * The Extension API Client. |
| 8 | + */ |
| 9 | +export class AwsLambdaExtension { |
| 10 | + private readonly _baseUrl: string; |
| 11 | + private _extensionId: string | null; |
| 12 | + |
| 13 | + public constructor() { |
| 14 | + this._baseUrl = `http://${process.env.AWS_LAMBDA_RUNTIME_API}/2020-01-01/extension`; |
| 15 | + this._extensionId = null; |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * Register this extension as an external extension with AWS. |
| 20 | + */ |
| 21 | + public async register(): Promise<void> { |
| 22 | + const res = await fetch(`${this._baseUrl}/register`, { |
| 23 | + method: 'POST', |
| 24 | + body: JSON.stringify({ |
| 25 | + events: ['INVOKE', 'SHUTDOWN'], |
| 26 | + }), |
| 27 | + headers: { |
| 28 | + 'Content-Type': 'application/json', |
| 29 | + 'Lambda-Extension-Name': 'sentry-extension', |
| 30 | + }, |
| 31 | + }); |
| 32 | + |
| 33 | + if (!res.ok) { |
| 34 | + throw new Error(`Failed to register with the extension API: ${await res.text()}`); |
| 35 | + } |
| 36 | + |
| 37 | + this._extensionId = res.headers.get('lambda-extension-identifier'); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Advances the extension to the next event. |
| 42 | + */ |
| 43 | + public async next(): Promise<void> { |
| 44 | + if (!this._extensionId) { |
| 45 | + throw new Error('Extension ID is not set'); |
| 46 | + } |
| 47 | + |
| 48 | + const res = await fetch(`${this._baseUrl}/event/next`, { |
| 49 | + headers: { |
| 50 | + 'Lambda-Extension-Identifier': this._extensionId, |
| 51 | + 'Content-Type': 'application/json', |
| 52 | + }, |
| 53 | + }); |
| 54 | + |
| 55 | + if (!res.ok) { |
| 56 | + throw new Error(`Failed to advance to next event: ${await res.text()}`); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Reports an error to the extension API. |
| 62 | + * @param phase The phase of the extension. |
| 63 | + * @param err The error to report. |
| 64 | + */ |
| 65 | + public async error(phase: 'init' | 'exit', err: Error): Promise<never> { |
| 66 | + if (!this._extensionId) { |
| 67 | + throw new Error('Extension ID is not set'); |
| 68 | + } |
| 69 | + |
| 70 | + const errorType = `Extension.${err.name || 'UnknownError'}`; |
| 71 | + |
| 72 | + const res = await fetch(`${this._baseUrl}/${phase}/error`, { |
| 73 | + method: 'POST', |
| 74 | + body: JSON.stringify({ |
| 75 | + errorMessage: err.message || err.toString(), |
| 76 | + errorType, |
| 77 | + stackTrace: [err.stack], |
| 78 | + }), |
| 79 | + headers: { |
| 80 | + 'Content-Type': 'application/json', |
| 81 | + 'Lambda-Extension-Identifier': this._extensionId, |
| 82 | + 'Lambda-Extension-Function-Error': errorType, |
| 83 | + }, |
| 84 | + }); |
| 85 | + |
| 86 | + if (!res.ok) { |
| 87 | + DEBUG_BUILD && debug.error(`Failed to report error: ${await res.text()}`); |
| 88 | + } |
| 89 | + |
| 90 | + throw err; |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Starts the Sentry tunnel. |
| 95 | + */ |
| 96 | + public startSentryTunnel(): void { |
| 97 | + const server = http.createServer(async (req, res) => { |
| 98 | + if (req.method === 'POST' && req.url?.startsWith('/envelope')) { |
| 99 | + try { |
| 100 | + const buf = await buffer(req); |
| 101 | + // Extract the actual bytes from the Buffer by slicing its underlying ArrayBuffer |
| 102 | + // This ensures we get only the data portion without any padding or offset |
| 103 | + const envelopeBytes = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); |
| 104 | + const envelope = new TextDecoder().decode(envelopeBytes); |
| 105 | + const piece = envelope.split('\n')[0]; |
| 106 | + const header = JSON.parse(piece || '{}') as { dsn?: string }; |
| 107 | + if (!header.dsn) { |
| 108 | + throw new Error('DSN is not set'); |
| 109 | + } |
| 110 | + const dsn = dsnFromString(header.dsn); |
| 111 | + if (!dsn) { |
| 112 | + throw new Error('Invalid DSN'); |
| 113 | + } |
| 114 | + const upstreamSentryUrl = getEnvelopeEndpointWithUrlEncodedAuth(dsn); |
| 115 | + |
| 116 | + fetch(upstreamSentryUrl, { |
| 117 | + method: 'POST', |
| 118 | + body: envelopeBytes, |
| 119 | + }).catch(err => { |
| 120 | + DEBUG_BUILD && debug.error('Error sending envelope to Sentry', err); |
| 121 | + }); |
| 122 | + |
| 123 | + res.writeHead(200, { 'Content-Type': 'application/json' }); |
| 124 | + res.end(JSON.stringify({})); |
| 125 | + } catch (e) { |
| 126 | + DEBUG_BUILD && debug.error('Error tunneling to Sentry', e); |
| 127 | + res.writeHead(500, { 'Content-Type': 'application/json' }); |
| 128 | + res.end(JSON.stringify({ error: 'Error tunneling to Sentry' })); |
| 129 | + } |
| 130 | + } else { |
| 131 | + res.writeHead(404, { 'Content-Type': 'application/json' }); |
| 132 | + res.end(JSON.stringify({ error: 'Not found' })); |
| 133 | + } |
| 134 | + }); |
| 135 | + |
| 136 | + server.listen(9000, () => { |
| 137 | + DEBUG_BUILD && debug.log('Sentry proxy listening on port 9000'); |
| 138 | + }); |
| 139 | + |
| 140 | + server.on('error', err => { |
| 141 | + DEBUG_BUILD && debug.error('Error starting Sentry proxy', err); |
| 142 | + process.exit(1); |
| 143 | + }); |
| 144 | + } |
| 145 | +} |
0 commit comments