1 | import * as tslib_1 from "tslib";
|
2 | import { Span } from '@sentry/apm';
|
3 | import { captureException, getCurrentHub, withScope } from '@sentry/core';
|
4 | import { forget, isString, logger, normalize } from '@sentry/utils';
|
5 | import * as cookie from 'cookie';
|
6 | import * as domain from 'domain';
|
7 | import * as os from 'os';
|
8 | import * as url from 'url';
|
9 | import { flush } from './sdk';
|
10 | var DEFAULT_SHUTDOWN_TIMEOUT = 2000;
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | export function tracingHandler() {
|
16 | return function sentryTracingMiddleware(req, res, next) {
|
17 |
|
18 |
|
19 | var reqMethod = (req.method || '').toUpperCase();
|
20 | var reqUrl = req.url;
|
21 | var hub = getCurrentHub();
|
22 | var transaction = hub.startSpan({
|
23 | transaction: reqMethod + "|" + reqUrl,
|
24 | });
|
25 | hub.configureScope(function (scope) {
|
26 | scope.setSpan(transaction);
|
27 | });
|
28 | res.once('finish', function () {
|
29 | transaction.setHttpStatus(res.statusCode);
|
30 | transaction.finish();
|
31 | });
|
32 | next();
|
33 | };
|
34 | }
|
35 |
|
36 | function extractTransaction(req, type) {
|
37 | try {
|
38 |
|
39 | var request = req;
|
40 | switch (type) {
|
41 | case 'path': {
|
42 | return request.route.path;
|
43 | }
|
44 | case 'handler': {
|
45 | return request.route.stack[0].name;
|
46 | }
|
47 | case 'methodPath':
|
48 | default: {
|
49 | var method = request.method.toUpperCase();
|
50 | var path = request.route.path;
|
51 | return method + "|" + path;
|
52 | }
|
53 | }
|
54 | }
|
55 | catch (_oO) {
|
56 | return undefined;
|
57 | }
|
58 | }
|
59 |
|
60 | var DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url'];
|
61 |
|
62 | function extractRequestData(req, keys) {
|
63 | var request = {};
|
64 | var attributes = Array.isArray(keys) ? keys : DEFAULT_REQUEST_KEYS;
|
65 |
|
66 |
|
67 |
|
68 | var headers = (req.headers || req.header || {});
|
69 |
|
70 |
|
71 | var method = req.method;
|
72 |
|
73 |
|
74 |
|
75 |
|
76 | var host = req.hostname || req.host || headers.host || '<no host>';
|
77 |
|
78 |
|
79 |
|
80 | var protocol = req.protocol === 'https' || req.secure || (req.socket || {}).encrypted
|
81 | ? 'https'
|
82 | : 'http';
|
83 |
|
84 |
|
85 |
|
86 | var originalUrl = (req.originalUrl || req.url);
|
87 |
|
88 | var absoluteUrl = protocol + "://" + host + originalUrl;
|
89 | attributes.forEach(function (key) {
|
90 | switch (key) {
|
91 | case 'headers':
|
92 | request.headers = headers;
|
93 | break;
|
94 | case 'method':
|
95 | request.method = method;
|
96 | break;
|
97 | case 'url':
|
98 | request.url = absoluteUrl;
|
99 | break;
|
100 | case 'cookies':
|
101 |
|
102 |
|
103 | request.cookies = cookie.parse(headers.cookie || '');
|
104 | break;
|
105 | case 'query_string':
|
106 |
|
107 |
|
108 |
|
109 | request.query_string = url.parse(originalUrl || '', false).query;
|
110 | break;
|
111 | case 'data':
|
112 |
|
113 |
|
114 | var data = req.body;
|
115 | if (method === 'GET' || method === 'HEAD') {
|
116 | if (typeof data === 'undefined') {
|
117 | data = '<unavailable>';
|
118 | }
|
119 | }
|
120 | if (data && !isString(data)) {
|
121 |
|
122 | data = JSON.stringify(normalize(data));
|
123 | }
|
124 | request.data = data;
|
125 | break;
|
126 | default:
|
127 | if ({}.hasOwnProperty.call(req, key)) {
|
128 | request[key] = req[key];
|
129 | }
|
130 | }
|
131 | });
|
132 | return request;
|
133 | }
|
134 |
|
135 | var DEFAULT_USER_KEYS = ['id', 'username', 'email'];
|
136 |
|
137 | function extractUserData(req, keys) {
|
138 | var user = {};
|
139 | var attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS;
|
140 | attributes.forEach(function (key) {
|
141 | if (req.user && key in req.user) {
|
142 | user[key] = req.user[key];
|
143 | }
|
144 | });
|
145 |
|
146 |
|
147 |
|
148 | var ip = req.ip || (req.connection && req.connection.remoteAddress);
|
149 | if (ip) {
|
150 | user.ip_address = ip;
|
151 | }
|
152 | return user;
|
153 | }
|
154 |
|
155 |
|
156 |
|
157 |
|
158 |
|
159 |
|
160 |
|
161 |
|
162 |
|
163 | export function parseRequest(event, req, options) {
|
164 |
|
165 | options = tslib_1.__assign({ request: true, serverName: true, transaction: true, user: true, version: true }, options);
|
166 | if (options.version) {
|
167 | event.extra = tslib_1.__assign({}, event.extra, { node: global.process.version });
|
168 | }
|
169 | if (options.request) {
|
170 | event.request = tslib_1.__assign({}, event.request, extractRequestData(req, options.request));
|
171 | }
|
172 | if (options.serverName) {
|
173 | event.server_name = global.process.env.SENTRY_NAME || os.hostname();
|
174 | }
|
175 | if (options.user && req.user) {
|
176 | event.user = tslib_1.__assign({}, event.user, extractUserData(req, options.user));
|
177 | }
|
178 | if (options.transaction && !event.transaction) {
|
179 | var transaction = extractTransaction(req, options.transaction);
|
180 | if (transaction) {
|
181 | event.transaction = transaction;
|
182 | }
|
183 | }
|
184 | return event;
|
185 | }
|
186 |
|
187 |
|
188 |
|
189 |
|
190 | export function requestHandler(options) {
|
191 | return function sentryRequestMiddleware(req, res, next) {
|
192 | if (options && options.flushTimeout && options.flushTimeout > 0) {
|
193 |
|
194 | var _end_1 = res.end;
|
195 | res.end = function (chunk, encoding, cb) {
|
196 | var _this = this;
|
197 | flush(options.flushTimeout)
|
198 | .then(function () {
|
199 | _end_1.call(_this, chunk, encoding, cb);
|
200 | })
|
201 | .then(null, function (e) {
|
202 | logger.error(e);
|
203 | });
|
204 | };
|
205 | }
|
206 | var local = domain.create();
|
207 | local.add(req);
|
208 | local.add(res);
|
209 | local.on('error', next);
|
210 | local.run(function () {
|
211 | getCurrentHub().configureScope(function (scope) {
|
212 | return scope.addEventProcessor(function (event) { return parseRequest(event, req, options); });
|
213 | });
|
214 | next();
|
215 | });
|
216 | };
|
217 | }
|
218 |
|
219 | function getStatusCodeFromResponse(error) {
|
220 | var statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode);
|
221 | return statusCode ? parseInt(statusCode, 10) : 500;
|
222 | }
|
223 |
|
224 | function defaultShouldHandleError(error) {
|
225 | var status = getStatusCodeFromResponse(error);
|
226 | return status >= 500;
|
227 | }
|
228 |
|
229 |
|
230 |
|
231 |
|
232 | export function errorHandler(options) {
|
233 | return function sentryErrorMiddleware(error, req, res, next) {
|
234 | var shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError;
|
235 | if (shouldHandleError(error)) {
|
236 | withScope(function (scope) {
|
237 | if (req.headers && isString(req.headers['sentry-trace'])) {
|
238 | var span = Span.fromTraceparent(req.headers['sentry-trace']);
|
239 | scope.setSpan(span);
|
240 | }
|
241 | var eventId = captureException(error);
|
242 | res.sentry = eventId;
|
243 | next(error);
|
244 | });
|
245 | return;
|
246 | }
|
247 | next(error);
|
248 | };
|
249 | }
|
250 |
|
251 |
|
252 |
|
253 | export function logAndExitProcess(error) {
|
254 | console.error(error && error.stack ? error.stack : error);
|
255 | var client = getCurrentHub().getClient();
|
256 | if (client === undefined) {
|
257 | logger.warn('No NodeClient was defined, we are exiting the process now.');
|
258 | global.process.exit(1);
|
259 | return;
|
260 | }
|
261 | var options = client.getOptions();
|
262 | var timeout = (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) ||
|
263 | DEFAULT_SHUTDOWN_TIMEOUT;
|
264 | forget(client.close(timeout).then(function (result) {
|
265 | if (!result) {
|
266 | logger.warn('We reached the timeout for emptying the request buffer, still exiting now!');
|
267 | }
|
268 | global.process.exit(1);
|
269 | }));
|
270 | }
|
271 |
|
\ | No newline at end of file |