-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBacktraceClient.ts
More file actions
336 lines (293 loc) · 13 KB
/
BacktraceClient.ts
File metadata and controls
336 lines (293 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import {
BacktraceCoreClient,
BacktraceReport,
BreadcrumbsManager,
DebugIdContainer,
FileAttributeManager,
SessionFiles,
VariableDebugIdMapProvider,
} from '@backtrace/sdk-core';
import path from 'path';
import { AGENT } from './agentDefinition';
import { transformAttachment } from './attachment/transformAttachments';
import { BacktraceConfiguration, BacktraceSetupConfiguration } from './BacktraceConfiguration';
import { BacktraceNodeRequestHandler } from './BacktraceNodeRequestHandler';
import { FileBreadcrumbsStorage } from './breadcrumbs/FileBreadcrumbsStorage';
import { BacktraceClientBuilder } from './builder/BacktraceClientBuilder';
import { BacktraceNodeClientSetup } from './builder/BacktraceClientSetup';
import { NodeOptionReader } from './common/NodeOptionReader';
import { NodeDiagnosticReportConverter } from './converter/NodeDiagnosticReportConverter';
import { LocalVariableProvider } from './LocalVariableProvider';
import { FsNodeFileSystem } from './storage/FsNodeFileSystem';
import { NodeFileSystem } from './storage/interfaces/NodeFileSystem';
export class BacktraceClient extends BacktraceCoreClient<BacktraceConfiguration> {
private _listeners: Record<string, NodeJS.UnhandledRejectionListener | NodeJS.UncaughtExceptionListener> = {};
protected get nodeFileSystem() {
return this.fileSystem as NodeFileSystem | undefined;
}
constructor(clientSetup: BacktraceNodeClientSetup) {
const fileSystem = clientSetup.fileSystem ?? new FsNodeFileSystem();
super({
sdkOptions: AGENT,
requestHandler: new BacktraceNodeRequestHandler(clientSetup.options),
debugIdMapProvider: new VariableDebugIdMapProvider(global as DebugIdContainer),
...clientSetup,
fileSystem,
options: {
...clientSetup.options,
attachments: clientSetup.options.attachments?.map(transformAttachment),
},
});
const breadcrumbsManager = this.modules.get(BreadcrumbsManager);
if (breadcrumbsManager && this.sessionFiles) {
breadcrumbsManager.setStorage(
FileBreadcrumbsStorage.create(
this.sessionFiles,
fileSystem,
clientSetup.options.breadcrumbs?.maximumBreadcrumbs ?? 100,
),
);
}
if (this.sessionFiles && clientSetup.options.database?.captureNativeCrashes) {
this.addModule(FileAttributeManager, FileAttributeManager.create(fileSystem));
}
if (clientSetup.options.localVariable) {
this.addModule(LocalVariableProvider, new LocalVariableProvider());
}
}
public initialize(): void {
const lockId = this.sessionFiles?.lockPreviousSessions();
try {
super.initialize();
this.captureUnhandledErrors(
this.options.captureUnhandledErrors,
this.options.captureUnhandledPromiseRejections,
);
this.captureNodeCrashes();
} catch (err) {
lockId && this.sessionFiles?.unlockPreviousSessions(lockId);
throw err;
}
this.loadNodeCrashes().finally(() => lockId && this.sessionFiles?.unlockPreviousSessions(lockId));
}
public static builder(options: BacktraceSetupConfiguration): BacktraceClientBuilder {
return new BacktraceClientBuilder({ options });
}
/**
* Initializes the client. If the client already exists, the available instance
* will be returned and all other options will be ignored.
* @param options client configuration
* @param build builder
* @returns backtrace client
*/
public static initialize(
options: BacktraceSetupConfiguration,
build?: (builder: BacktraceClientBuilder) => void,
): BacktraceClient {
if (this.instance) {
return this.instance;
}
const builder = this.builder(options);
build && build(builder);
this._instance = builder.build();
return this._instance as BacktraceClient;
}
/**
* Returns created BacktraceClient instance if the instance exists.
* Otherwise undefined.
*/
public static get instance(): BacktraceClient | undefined {
return this._instance as BacktraceClient;
}
/**
* Disposes the client and all client callbacks
*/
public dispose(): void {
for (const [name, listener] of Object.entries(this._listeners)) {
process.removeListener(name, listener);
}
super.dispose();
BacktraceClient._instance = undefined;
}
private captureUnhandledErrors(captureUnhandledExceptions = true, captureUnhandledRejections = true) {
if (!captureUnhandledExceptions && !captureUnhandledRejections) {
return;
}
const captureUncaughtException = async (error: Error, origin?: 'uncaughtException' | 'unhandledRejection') => {
if (origin === 'unhandledRejection' && !captureUnhandledRejections) {
return;
}
if (origin === 'uncaughtException' && !captureUnhandledExceptions) {
return;
}
await this.send(
new BacktraceReport(error, { 'error.type': 'Unhandled exception', errorOrigin: origin }, [], {
classifiers: origin === 'unhandledRejection' ? ['UnhandledPromiseRejection'] : undefined,
}),
);
};
process.prependListener('uncaughtExceptionMonitor', captureUncaughtException);
this._listeners['uncaughtExceptionMonitor'] = captureUncaughtException;
if (!captureUnhandledRejections) {
return;
}
// Node 15+ has changed the default unhandled promise rejection behavior.
// In node 14 - the default behavior is to warn about unhandled promise rejections. In newer version
// the default mode is throw.
const nodeMajorVersion = process.version.split('.')[0];
const unhandledRejectionMode = NodeOptionReader.read('unhandled-rejections');
const traceWarnings = NodeOptionReader.read('trace-warnings');
/**
* Node JS allows to use only uncaughtExceptionMonitor only when:
* - we're in the throw/strict error mode
* - the node version 15+
*
* In other scenarios we need to capture unhandledRejections via other event.
*/
const ignoreUnhandledRejectionHandler =
unhandledRejectionMode === 'strict' ||
unhandledRejectionMode === 'throw' ||
(nodeMajorVersion !== 'v14' && !unhandledRejectionMode);
if (ignoreUnhandledRejectionHandler) {
return;
}
const captureUnhandledRejectionsCallback = async (reason: unknown) => {
const isErrorTypeReason = reason instanceof Error;
await this.send(
new BacktraceReport(
isErrorTypeReason ? reason : reason?.toString() ?? 'Unhandled rejection',
{
'error.type': 'Unhandled exception',
},
[],
{
classifiers: ['UnhandledPromiseRejection'],
skipFrames: isErrorTypeReason ? 0 : 1,
},
),
);
const error = isErrorTypeReason ? reason : new Error(reason?.toString() ?? 'Unhandled rejection');
// if there is any other unhandled rejection handler, reproduce default node behavior
// and let other handlers to capture the event
if (process.listenerCount('unhandledRejection') !== 1) {
return;
}
// everything else will be handled by node
if (unhandledRejectionMode === 'none' || unhandledRejectionMode === 'warn') {
return;
}
// handle last status: warn-with-error-code
process.exitCode = 1;
const unhandledRejectionErrName = 'UnhandledPromiseRejectionWarning';
process.emitWarning(
(isErrorTypeReason ? error.stack : reason?.toString()) ?? '',
unhandledRejectionErrName,
);
const warning = new Error(
`Unhandled promise rejection. This error originated either by ` +
`throwing inside of an async function without a catch block, ` +
`or by rejecting a promise which was not handled with .catch(). ` +
`To terminate the node process on unhandled promise ` +
'rejection, use the CLI flag `--unhandled-rejections=strict` (see ' +
'https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). ',
);
Object.defineProperty(warning, 'name', {
value: 'UnhandledPromiseRejectionWarning',
enumerable: false,
writable: true,
configurable: true,
});
warning.stack = traceWarnings && isErrorTypeReason ? error.stack ?? '' : '';
process.emitWarning(warning);
};
process.prependListener('unhandledRejection', captureUnhandledRejectionsCallback);
this._listeners['unhandledRejection'] = captureUnhandledRejectionsCallback;
}
private captureNodeCrashes() {
if (!process.report) {
return;
}
if (!this.options.database?.enable) {
return;
}
if (!this.options.database?.captureNativeCrashes) {
return;
}
process.report.reportOnFatalError = true;
if (!process.report.directory) {
process.report.directory = this.options.database.path;
}
}
private async loadNodeCrashes() {
if (!this.database || !this.nodeFileSystem || !this.options.database?.captureNativeCrashes) {
return;
}
const reportName = process.report?.filename;
const databasePath = process.report?.directory
? process.report.directory
: this.options.database?.path ?? process.cwd();
let databaseFiles: string[];
try {
databaseFiles = await this.nodeFileSystem.readDir(databasePath);
} catch {
return;
}
const converter = new NodeDiagnosticReportConverter();
const recordNames = databaseFiles.filter((file) =>
// If the user specifies a preset name for reports, we should compare it directly
// Otherwise, match the default name
reportName ? file === reportName : file.startsWith('report.') && file.endsWith('.json'),
);
if (!recordNames.length) {
return;
}
const reports: [path: string, report: BacktraceReport, sessionFiles?: SessionFiles][] = [];
for (const recordName of recordNames) {
const recordPath = path.join(databasePath, recordName);
try {
const recordJson = await this.nodeFileSystem.readFile(recordPath);
const report = converter.convert(JSON.parse(recordJson));
reports.push([recordPath, report]);
} catch {
// Do nothing, skip the report
}
}
// Sort reports by timestamp descending
reports.sort((a, b) => b[1].timestamp - a[1].timestamp);
// Map reports to sessions
// When the sessions are sorted by timestamp, we can assume that each previous session maps to the next report
let currentSession = this.sessionFiles?.getPreviousSession();
for (const tuple of reports) {
tuple[2] = currentSession;
currentSession = currentSession?.getPreviousSession();
}
for (const [recordPath, report, session] of reports) {
try {
if (session) {
const breadcrumbsStorage = FileBreadcrumbsStorage.createFromSession(session, this.nodeFileSystem);
if (breadcrumbsStorage) {
report.attachments.push(...breadcrumbsStorage.getAttachments());
}
const fileAttributes = FileAttributeManager.createFromSession(session, this.nodeFileSystem);
Object.assign(report.attributes, await fileAttributes.get());
report.attributes['application.session'] = session.sessionId;
} else {
report.attributes['application.session'] = null;
}
const data = this.generateSubmissionData(report);
if (data) {
this.database.add(data, report.attachments);
}
} catch {
// Do nothing, skip the report
} finally {
try {
await this.nodeFileSystem.unlink(recordPath);
} catch {
// Do nothing
}
}
}
await this.database.send();
}
}