-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBacktraceMainElectronModule.ts
More file actions
214 lines (178 loc) · 7.96 KB
/
BacktraceMainElectronModule.ts
File metadata and controls
214 lines (178 loc) · 7.96 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
import { FileAttachmentsManager, FileBreadcrumbsStorage, NodeFileSystem } from '@backtrace/node';
import type { BacktraceDatabase } from '@backtrace/sdk-core';
import {
BacktraceData,
BacktraceModule,
BacktraceModuleBindData,
RawBreadcrumb,
SessionFiles,
SubmissionUrlInformation,
SummedEvent,
} from '@backtrace/sdk-core';
import { app, crashReporter } from 'electron';
import { IpcAttachmentReference } from '../../common/ipc/IpcAttachmentReference.js';
import { IpcEvents } from '../../common/ipc/IpcEvents.js';
import { SyncData } from '../../common/models/SyncData.js';
import { MainIpcRpcHandler } from '../ipc/MainIpcRpcHandler.js';
import { MainIpcTransportHandler } from '../ipc/MainIpcTransportHandler.js';
import { WindowIpcTransport } from '../ipc/WindowIpcTransport.js';
import { IpcAttachment } from './IpcAttachment.js';
export class BacktraceMainElectronModule implements BacktraceModule {
private _bindData?: BacktraceModuleBindData;
public bind(bindData: BacktraceModuleBindData): void {
const { requestHandler, reportSubmission, client, attributeManager } = bindData;
const getSyncData = (): SyncData => ({
sessionId: client.sessionId,
});
const rpc = new MainIpcRpcHandler();
const ipcTransport = new MainIpcTransportHandler();
rpc.on(IpcEvents.post, async (_: unknown, url: string, dataJson: string) => {
return requestHandler.post(url, dataJson);
});
rpc.on(IpcEvents.sendReport, async (event, data: BacktraceData, attachmentRefs: IpcAttachmentReference[]) => {
const { attributes, annotations } = attributeManager.get();
data.attributes = {
...attributes,
...this.getEventAttributes(event),
...data.attributes,
};
data.annotations = {
...annotations,
...data.annotations,
};
const attachments = attachmentRefs.map(
(v) => new IpcAttachment(v.name, v.id, new WindowIpcTransport(event.sender)),
);
return await reportSubmission.send(data, [...attachments, ...client.attachments]);
});
rpc.on(IpcEvents.sendAttachment, async (event, rxid: string, attachmentRef: IpcAttachmentReference) => {
const attachment = new IpcAttachment(
attachmentRef.name,
attachmentRef.id,
new WindowIpcTransport(event.sender),
);
return await reportSubmission.sendAttachment(rxid, attachment);
});
rpc.on(IpcEvents.sendMetrics, async () => client.metrics?.send());
rpc.on(IpcEvents.ping, () => Promise.resolve('pong'));
rpc.on(IpcEvents.sync, () => Promise.resolve(getSyncData()));
rpc.onSync(IpcEvents.sync, (event: Electron.IpcMainEvent) => {
event.returnValue = getSyncData();
});
ipcTransport.on(IpcEvents.sync, (event) => {
const transport = new WindowIpcTransport(event.sender);
transport.emit(IpcEvents.sync, getSyncData());
});
ipcTransport.on(IpcEvents.addBreadcrumb, (event: Electron.IpcMainInvokeEvent, breadcrumb: RawBreadcrumb) => {
client.breadcrumbs?.addBreadcrumb(breadcrumb.message, breadcrumb.level, breadcrumb.type, {
...this.getEventAttributes(event),
...breadcrumb.attributes,
});
});
ipcTransport.on(IpcEvents.addSummedMetric, (event: Electron.IpcMainInvokeEvent, metric: SummedEvent) => {
client.metrics?.addSummedEvent(metric.metricGroupValue, {
...this.getEventAttributes(event),
...metric.attributes,
});
});
this._bindData = bindData;
}
public initialize(): void {
if (!this._bindData) {
return;
}
const { options, attributeManager, sessionFiles, fileSystem, database } = this._bindData;
if (options.database?.captureNativeCrashes) {
if (options.database.path) {
app.setPath('crashDumps', options.database.path);
}
crashReporter.start({
submitURL: SubmissionUrlInformation.toMinidumpSubmissionUrl(options.url),
uploadToServer: true,
extra: {
...toStringDictionary(attributeManager.get('scoped').attributes),
'error.type': 'Crash',
},
});
attributeManager.attributeEvents.on('scoped-attributes-updated', ({ attributes }) => {
const dict = toStringDictionary(attributes);
for (const key in dict) {
crashReporter.addExtraParameter(key, dict[key]);
}
});
if (sessionFiles && database && fileSystem) {
const lockId = sessionFiles.lockPreviousSessions();
this.sendPreviousCrashAttachments(database, sessionFiles, fileSystem as NodeFileSystem).finally(
() => lockId && sessionFiles.unlockPreviousSessions(lockId),
);
}
}
}
private getEventAttributes(event: Electron.IpcMainInvokeEvent) {
return {
'electron.frameId': event.frameId,
'electron.processId': event.processId,
'electron.process': 'renderer',
};
}
private async sendPreviousCrashAttachments(
database: BacktraceDatabase,
session: SessionFiles,
fileSystem: NodeFileSystem,
) {
// Sort crashes and sessions by timestamp descending
const crashes = crashReporter.getUploadedReports().sort((a, b) => b.date.getTime() - a.date.getTime());
const previousSessions = session
.getPreviousSessions()
.sort((a, b) => b.sessionId.timestamp - a.sessionId.timestamp);
for (const crash of crashes) {
const rxid = this.getCrashRxid(crash.id);
if (!rxid) {
continue;
}
try {
// Get first session that happened before the crash
const session = previousSessions.find((p) => p.sessionId.timestamp < crash.date.getTime());
// If there is no such session, there won't be any other sessions
if (!session) {
break;
}
const crashLock = session.getFileName(`electron-crash-lock-${rxid}`);
// If crash lock exists, do not attempt to add attachments twice
if (await fileSystem.exists(crashLock)) {
continue;
}
const fileAttachmentsManager = FileAttachmentsManager.createFromSession(session, fileSystem);
const sessionAttachments = [
...FileBreadcrumbsStorage.getSessionAttachments(session, fileSystem),
...(await fileAttachmentsManager.get()),
];
for (const attachment of sessionAttachments) {
database.addAttachment(rxid, attachment, session.sessionId);
}
// Write an empty crash lock, so we know that this crash is already taken care of
await fileSystem.writeFile(crashLock, '');
} catch {
// Do nothing, skip the report
}
}
await database.send();
}
private getCrashRxid(crashId: string): string | undefined {
try {
return JSON.parse(crashId)._rxid;
} catch {
const rxidRegex = /"_rxid":\s*"([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})"/i;
return crashId.match(rxidRegex)?.[1];
}
}
}
function toStringDictionary(record: Record<string, unknown>): Record<string, string> {
return Object.keys(record).reduce(
(obj, key) => {
obj[key] = record[key]?.toString() ?? '';
return obj;
},
{} as Record<string, string>,
);
}