-
Notifications
You must be signed in to change notification settings - Fork 481
Expand file tree
/
Copy pathbrowser-connection.ts
More file actions
356 lines (316 loc) · 13 KB
/
Copy pathbrowser-connection.ts
File metadata and controls
356 lines (316 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { oneLine } from 'common-tags';
import {
getProfileViaWebChannel,
getExternalMarkersViaWebChannel,
getExternalPowerTracksViaWebChannel,
getSymbolTableViaWebChannel,
queryWebChannelVersionViaWebChannel,
querySymbolicationApiViaWebChannel,
getPageFaviconsViaWebChannel,
showFunctionInDevtoolsViaWebChannel,
getJSSourcesViaWebChannelV6,
getJSSourcesViaWebChannelV7,
getSourceMapViaWebChannel,
} from './web-channel';
import type { RawSourceMap } from 'source-map';
import type {
Milliseconds,
FaviconData,
MixedObject,
SymbolTableAsTuple,
} from 'firefox-profiler/types';
/**
* This file manages the communication between the profiler and the browser.
*/
export type BrowserConnectionStatus =
// The initial state.
| { status: 'NO_ATTEMPT' }
// In non-Firefox browsers we don't attempt to establish a connection.
// This is determined via the userAgent.
| { status: 'NOT_FIREFOX' }
// We are in Firefox, and have sent the initial WebChannel event.
| { status: 'WAITING' }
// We are in Firefox but the WebChannel connection has been denied.
// This usually means that this profiler instance is running on a
// different host than the one that's specified in the
// preference `devtools.performance.recording.ui-base-url`.
| { status: 'DENIED'; error: Error }
// We are in Firefox but the WebChannel did not respond within 5 seconds.
// This is unexpected. It could mean that we are running in an old Firefox
// (older than Firefox 76) which did not have a profiler WebChannel.
| { status: 'TIMED_OUT' }
// The WebChannel connection has been established.
| { status: 'ESTABLISHED'; browserConnection: BrowserConnection };
/**
* The interface of communication with the browser. Can be backed by a WebChannel
* or by the frame script API.
* Only exists if at least an old version of the WebChannel is available in this browser.
*/
export interface BrowserConnection {
// Get the profile for this tab from the browser.
getProfile(options: {
onThirtySecondTimeout: () => void;
}): Promise<ArrayBuffer | MixedObject>;
getExternalMarkers(
startTime: Milliseconds,
endTime: Milliseconds
): Promise<MixedObject>;
getExternalPowerTracks(
startTime: Milliseconds,
endTime: Milliseconds
): Promise<MixedObject[]>;
// Query the browser-internal symbolication API. This provides richer
// information than getSymbolTable.
querySymbolicationApi(path: string, requestJson: string): Promise<string>;
// Get a symbol table from the browser.
getSymbolTable(
debugName: string,
breakpadId: string
): Promise<SymbolTableAsTuple>;
getPageFavicons(pageUrls: Array<string>): Promise<Array<FaviconData | null>>;
showFunctionInDevtools(
tabID: number,
scriptUrl: string,
line: number | null,
column: number | null
): Promise<void>;
getJSSource(sourceUuid: string): Promise<string>;
// Get source map of the given source directly from the browser.
// Requires WebChannel version 7+.
getSourceMap(sourceId: string): Promise<RawSourceMap>;
// True when the browser exposes GET_SOURCE_MAP (WebChannel version 7+).
// Callers use this to gate source-map-based features.
readonly supportsGetSourceMap: boolean;
}
/**
* The regular implementation of the BrowserConnection interface.
*
* Only created when a WebChannel exists. But it could be an old WebChannel
* (from a pre-bug 1625309 Firefox version) which does not support obtaining
* the profile or symbols. So this class also supports the frame script.
*/
class BrowserConnectionImpl implements BrowserConnection {
_webChannelVersion: number;
_webChannelSupportsGetProfileAndSymbolication: boolean;
_webChannelSupportsGetExternalPowerTracks: boolean;
_webChannelSupportsGetExternalMarkers: boolean;
_webChannelSupportsGetPageFavicons: boolean;
_webChannelSupportsOpenDebuggerInTab: boolean;
_webChannelSupportsGetJSSource: boolean;
readonly supportsGetSourceMap: boolean;
_geckoProfiler: $GeckoProfiler | undefined;
constructor(webChannelVersion: number) {
this._webChannelVersion = webChannelVersion;
this._webChannelSupportsGetProfileAndSymbolication = webChannelVersion >= 1;
this._webChannelSupportsGetExternalPowerTracks = webChannelVersion >= 2;
this._webChannelSupportsGetExternalMarkers = webChannelVersion >= 3;
this._webChannelSupportsGetPageFavicons = webChannelVersion >= 4;
this._webChannelSupportsOpenDebuggerInTab = webChannelVersion >= 5;
this._webChannelSupportsGetJSSource = webChannelVersion >= 6;
this.supportsGetSourceMap = webChannelVersion >= 7;
}
// Only called when we must obtain the profile from the browser, i.e. if we
// cannot proceed without a connection to the browser. This method falls back
// to the frame script API (window.geckoProfilerPromise) if this browser has
// an old version of the WebChannel.
async _getConnectionViaFrameScript(): Promise<$GeckoProfiler> {
if (!this._geckoProfiler) {
this._geckoProfiler = await window.geckoProfilerPromise;
}
return this._geckoProfiler;
}
async getProfile(options: {
onThirtySecondTimeout: () => void;
}): Promise<ArrayBuffer | MixedObject> {
const timeoutId = setTimeout(options.onThirtySecondTimeout, 30000);
// On Firefox 96 and above, we can get the profile from the WebChannel.
if (this._webChannelSupportsGetProfileAndSymbolication) {
const profile = await getProfileViaWebChannel();
clearTimeout(timeoutId);
return profile;
}
// For older versions, fall back to the geckoProfiler frame script API.
// This fallback can be removed once the oldest supported Firefox ESR version is 96 or newer.
const geckoProfiler = await this._getConnectionViaFrameScript();
const profile = await geckoProfiler.getProfile();
clearTimeout(timeoutId);
return profile as MixedObject;
}
async getExternalMarkers(
startTime: Milliseconds,
endTime: Milliseconds
): Promise<MixedObject> {
// On Firefox 125 and above, we can get additional global markers recorded outside the browser.
if (this._webChannelSupportsGetExternalMarkers) {
return getExternalMarkersViaWebChannel(startTime, endTime);
}
return [] as unknown as MixedObject;
}
async getExternalPowerTracks(
startTime: Milliseconds,
endTime: Milliseconds
): Promise<MixedObject[]> {
// On Firefox 121 and above, we can get additional power tracks recorded outside the browser.
if (this._webChannelSupportsGetExternalPowerTracks) {
return getExternalPowerTracksViaWebChannel(startTime, endTime);
}
return [];
}
async querySymbolicationApi(
path: string,
requestJson: string
): Promise<string> {
// This only works on Firefox 96 and above.
if (!this._webChannelSupportsGetProfileAndSymbolication) {
throw new Error(
"Can't use querySymbolicationApi in Firefox versions with the old WebChannel."
);
}
return querySymbolicationApiViaWebChannel(path, requestJson);
}
async showFunctionInDevtools(
tabID: number,
scriptUrl: string,
line: number | null,
column: number | null
): Promise<void> {
if (!this._webChannelSupportsOpenDebuggerInTab) {
throw new Error(
"Can't use showFunctionInDevtools in Firefox versions with the old WebChannel."
);
}
return showFunctionInDevtoolsViaWebChannel(tabID, scriptUrl, line, column);
}
async getSymbolTable(
debugName: string,
breakpadId: string
): Promise<SymbolTableAsTuple> {
// On Firefox 96 and above, we can get the symbol table from the WebChannel.
if (this._webChannelSupportsGetProfileAndSymbolication) {
return getSymbolTableViaWebChannel(debugName, breakpadId);
}
// For older versions, fall back to the geckoProfiler frame script API.
// This fallback can be removed once the oldest supported Firefox ESR version is 96 or newer.
// Note that we use this._geckoProfiler directly instead of
// _getConnectionViaFrameScript so that we're not waiting forever when the
// user opens an unsymbolicated profile with a Firefox that doesn't support
// the WebChannel.
if (this._geckoProfiler) {
return this._geckoProfiler.getSymbolTable(debugName, breakpadId);
}
throw new Error(
'Cannot obtain a symbol table: have neither WebChannel nor a GeckoProfiler object'
);
}
async getPageFavicons(
pageUrls: Array<string>
): Promise<Array<FaviconData | null>> {
// This is added in Firefox 134.
if (this._webChannelSupportsGetPageFavicons) {
return getPageFaviconsViaWebChannel(pageUrls);
}
return [];
}
async getSourceMap(sourceId: string): Promise<RawSourceMap> {
if (!this.supportsGetSourceMap) {
throw new Error(
"Can't use getSourceMap in Firefox versions with the old WebChannel."
);
}
return getSourceMapViaWebChannel(sourceId);
}
/**
* Fetches JavaScript source code from the browser using the source UUID.
* This method requires WebChannel version 6 or higher (Firefox 145+).
*/
async getJSSource(sourceUuid: string): Promise<string> {
if (!this._webChannelSupportsGetJSSource) {
throw new Error(
"Can't use getJSSource in Firefox versions with the old WebChannel."
);
}
// Even though the WebChannel request for fetching JS sources supports
// fetching multiple sources, we only fetch one at a time currently.
// TODO: Change this to fetch multiple JS sources at the load time or while
// we share the profile.
const sourcesPromise =
this._webChannelVersion >= 7
? getJSSourcesViaWebChannelV7([sourceUuid])
: getJSSourcesViaWebChannelV6([sourceUuid]);
return sourcesPromise.then((sources) => {
const source = sources[0];
if ('error' in source) {
throw new Error(source.error);
}
return source.sourceText;
});
}
}
// Should work with:
// Firefox Desktop: "Mozilla/5.0 (X11; Linux x86_64; rv:132.0) Gecko/20100101 Firefox/132.0"
// Thunderbird: "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Thunderbird/128.2.3"
// Firefox Android: "Mozilla/5.0 (Android 12; Mobile; rv:132.0) Gecko/132.0 Firefox/132.0"
// Should not work with:
// Chrome: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'
// Safari: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1'
//
// We could match for Gecko/ but do all Gecko-based browsers support the
// WebChannel? Probably not. Therefore specifically Firefox and Thunderbird are
// looked for, until we find that we need a broader net.
function _isFirefox(userAgent: string): boolean {
return userAgent.includes('Firefox/') || userAgent.includes('Thunderbird/');
}
class TimeoutError extends Error {
override name = 'TimeoutError';
}
function makeTimeoutRejectionPromise(durationInMs: number) {
return new Promise((_resolve, reject) => {
setTimeout(() => {
reject(new TimeoutError(`Timed out after ${durationInMs}ms`));
}, durationInMs);
});
}
export async function createBrowserConnection(
userAgent: string = navigator.userAgent
): Promise<BrowserConnectionStatus> {
if (!_isFirefox(userAgent)) {
return { status: 'NOT_FIREFOX' };
}
try {
const webChannelVersion = (await Promise.race([
queryWebChannelVersionViaWebChannel(),
makeTimeoutRejectionPromise(5000),
])) as number;
// If we get here, it means queryWebChannelVersionViaWebChannel()
// did not throw an exception. This means that a WebChannel exists.
const browserConnection = new BrowserConnectionImpl(webChannelVersion);
return {
status: 'ESTABLISHED',
browserConnection,
};
} catch (e) {
if (e instanceof TimeoutError) {
// The browser never reacted to our WebChannelMessageToChrome event.
// This can happen if we're running on a browser that's not Firefox, or if we're running
// on an old version of Firefox which does not have support for any WebChannels.
return { status: 'TIMED_OUT' };
}
// The WebChannel responded with an error. This usually means that this profiler
// instance is running on a different host than the one that's specified in the
// preference `devtools.performance.recording.ui-base-url`.
// Or it means we're running in a test environment where no WebChannel simulation
// has been set up.
const error = new Error(oneLine`
This profiler instance was unable to connect to the
WebChannel. This usually means that it’s running on a
different host from the one that is specified in the
preference devtools.performance.recording.ui-base-url. If
you would like to capture new profiles with this instance, you can go to about:config
and change the preference. Error: ${e.name}: ${e.message}
`);
return { status: 'DENIED', error };
}
}