src/vs/platform/telemetry/common/telemetryService.ts

366 LOC · 272 covered · 94 uncovered · 26 ranges · 1484 concepts · 2 introducers · 685 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- agentHostTelemetryService.ts ×29
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { DisposableStore } from '../../../base/common/lifecycle.js';
7 > import { mixin } from '../../../base/common/objects.js';
8 > import { isWeb } from '../../../base/common/platform.js';
9 > import { PolicyCategory } from '../../../base/common/policy.js';
10 > import { escapeRegExpCharacters } from '../../../base/common/strings.js';
11 > import { localize } from '../../../nls.js';
12 > import { IConfigurationService } from '../../configuration/common/configuration.js';
13 > import { ConfigurationScope, Extensions, IConfigurationRegistry } from '../../configuration/common/configurationRegistry.js';
14 > import { IMeteredConnectionService } from '../../meteredConnection/common/meteredConnection.js';
15 > import product from '../../product/common/product.js';
16 > import { IProductService } from '../../product/common/productService.js';
17 > import { Registry } from '../../registry/common/platform.js';
18 > import { ClassifiedEvent, IGDPRProperty, OmitMetadata, StrictPropertyCheck } from './gdprTypings.js';
19 > import { ITelemetryData, ITelemetryService, TelemetryConfiguration, TelemetryLevel, TELEMETRY_CRASH_REPORTER_SETTING_ID, TELEMETRY_OLD_SETTING_ID, TELEMETRY_SECTION_ID, TELEMETRY_SETTING_ID, ICommonProperties } from './telemetry.js';
20 > import { cleanData, getTelemetryLevel, ITelemetryAppender, TelemetryTrustedValue } from './telemetryUtils.js';
21 >
22 > export interface ITelemetryServiceConfig {
23 > appenders: ITelemetryAppender[];
24 > sendErrorTelemetry?: boolean;
25 > commonProperties?: ICommonProperties;
26 > piiPaths?: string[];
27 > /**
28 > * If true, telemetry events will be buffered until setExperimentProperty is called
29 > * (up to 10 seconds) to ensure experiment context is attached to all events.
30 > */
31 > waitForExperimentProperties?: boolean;
32 > /**
33 > * If provided, telemetry events will be dropped when the connection is metered.
34 > */
35 > meteredConnectionService?: IMeteredConnectionService;
36 > }
37 >
38 > interface IPendingEvent {
39 > eventName: string;
40 > eventLevel: TelemetryLevel;
41 > data: ITelemetryData | undefined;
42 > }
43 >
44 > export class TelemetryService implements ITelemetryService {
45 >
46 > static readonly IDLE_START_EVENT_NAME = 'UserIdleStart';
47 > static readonly IDLE_STOP_EVENT_NAME = 'UserIdleStop';
48 >
49 > private static readonly BUFFER_FLUSH_TIMEOUT = 10000; // 10 seconds
50 > private static readonly MAX_BUFFER_SIZE = 1000;
51 >
52 > declare readonly _serviceBrand: undefined;
53 >
54 > readonly sessionId: string;
55 > readonly machineId: string;
56 > readonly sqmId: string;
57 > readonly devDeviceId: string;
58 > readonly firstSessionDate: string;
59 > readonly msftInternal: boolean | undefined;
60 >
61 > private _appenders: ITelemetryAppender[];
62 > private _commonProperties: ICommonProperties;
63 > private _experimentProperties: { [name: string]: string | TelemetryTrustedValue<string> } = {};
64 > private _piiPaths: string[];
65 > private _telemetryLevel: TelemetryLevel;
66 > private _sendErrorTelemetry: boolean;
67 >
68 > private readonly _meteredConnectionService: IMeteredConnectionService | undefined;
69 >
70 > private _pendingEvents: IPendingEvent[] = [];
71 > private _isExperimentPropertySet = false;
72 > private _flushTimeout: ReturnType<typeof setTimeout> | undefined;
73 >
74 > private readonly _disposables = new DisposableStore();
75 > private _cleanupPatterns: RegExp[] = [];
76 >
77 > constructor(
78 > config: ITelemetryServiceConfig, telemetryService.ts ×9
79 > @IConfigurationService private _configurationService: IConfigurationService,
80 > @IProductService private _productService: IProductService
81 > ) {
82 > this._appenders = config.appenders;
83 > this._commonProperties = config.commonProperties ?? Object.create(null);
84 >
85 > this.sessionId = this._commonProperties['sessionID'] as string;
86 > this.machineId = this._commonProperties['common.machineId'] as string;
87 > this.sqmId = this._commonProperties['common.sqmId'] as string;
88 > this.devDeviceId = this._commonProperties['common.devDeviceId'] as string;
89 > this.firstSessionDate = this._commonProperties['common.firstSessionDate'] as string;
90 > this.msftInternal = this._commonProperties['common.msftInternal'] as boolean | undefined;
91 >
92 > this._piiPaths = config.piiPaths || [];
93 > this._telemetryLevel = TelemetryLevel.USAGE;
94 > this._sendErrorTelemetry = !!config.sendErrorTelemetry;
95 > this._meteredConnectionService = config.meteredConnectionService;
96 >
97 > // static cleanup pattern for: `vscode-file:///DANGEROUS/PATH/resources/app/Useful/Information`
98 > this._cleanupPatterns = [/(vscode-)?file:\/\/.*?\/resources\/app\//gi];
99 >
100 > for (const piiPath of this._piiPaths) {
101 > this._cleanupPatterns.push(new RegExp(escapeRegExpCharacters(piiPath), 'gi'));
102 >
103 > if (piiPath.indexOf('\\') >= 0) {
104 this._cleanupPatterns.push(new RegExp(escapeRegExpCharacters(piiPath.replace(/\\/g, '/')), 'gi'));
105 }
107 >
108 > this._updateTelemetryLevel();
109 > this._disposables.add(this._configurationService.onDidChangeConfiguration(e => {
110 // Check on the telemetry settings and update the state if changed
111 const affectsTelemetryConfig =
112 e.affectsConfiguration(TELEMETRY_SETTING_ID)
113 || e.affectsConfiguration(TELEMETRY_OLD_SETTING_ID)
114 || e.affectsConfiguration(TELEMETRY_CRASH_REPORTER_SETTING_ID);
115 if (affectsTelemetryConfig) {
116 this._updateTelemetryLevel();
117 }
119 >
120 > // Buffer events until experiment properties are set (or timeout expires).
121 > // This ensures early events include experiment context when available.
122 > if (config.waitForExperimentProperties) {
123 this._flushTimeout = setTimeout(() => this._flushPendingEvents(), TelemetryService.BUFFER_FLUSH_TIMEOUT);
124 > } else { telemetryService.ts ×9
125 > this._isExperimentPropertySet = true;
126 > }
127 > }
129 > setExperimentProperty(name: string, value: string): void {
130 this._experimentProperties[name] = new TelemetryTrustedValue(value);
131
132 // On first call, flush all pending events that were buffered waiting for experiment properties
133 if (!this._isExperimentPropertySet) {
134 this._flushPendingEvents();
135 }
136 }
138 > setCommonProperty(name: string, value: string | boolean): void {
139 this._commonProperties[name] = value;
140 }
142 > private _flushPendingEvents(): void {
143 > if (this._isExperimentPropertySet) { telemetryService.ts ×9
144 > return;
145 > }
146
147 this._isExperimentPropertySet = true;
148
149 if (this._flushTimeout !== undefined) {
150 clearTimeout(this._flushTimeout);
151 this._flushTimeout = undefined;
152 }
153
154 // Send all buffered events now that experiment properties are available
155 for (const event of this._pendingEvents) {
156 this._doLog(event.eventName, event.eventLevel, event.data);
157 }
158 this._pendingEvents = [];
161 > private _updateTelemetryLevel(): void {
162 > let level = getTelemetryLevel(this._configurationService); telemetryService.ts ×9
163 > const collectableTelemetry = this._productService.enabledTelemetryLevels;
164 > // Also ensure that error telemetry is respecting the product configuration for collectable telemetry
165 > if (collectableTelemetry) {
166 this._sendErrorTelemetry = this.sendErrorTelemetry ? collectableTelemetry.error : false;
167 // Make sure the telemetry level from the service is the minimum of the config and product
168 const maxCollectableTelemetryLevel = collectableTelemetry.usage ? TelemetryLevel.USAGE : collectableTelemetry.error ? TelemetryLevel.ERROR : TelemetryLevel.NONE;
169 level = Math.min(level, maxCollectableTelemetryLevel);
170 }
172 > this._telemetryLevel = level;
173 > }
175 > get sendErrorTelemetry(): boolean {
176 return this._sendErrorTelemetry;
177 }
179 > get telemetryLevel(): TelemetryLevel {
180 return this._telemetryLevel;
181 }
183 > dispose(): void {
184 > // Flush any remaining pending events before disposing telemetryService.ts ×9
185 > this._flushPendingEvents();
186 > this._disposables.dispose();
187 > }
189 > private _log(eventName: string, eventLevel: TelemetryLevel, data?: ITelemetryData) {
190 // don't send events when the user is optout
191 if (this._telemetryLevel < eventLevel) {
192 return;
193 }
194
195 // Don't send events when the connection is metered
196 if (this._meteredConnectionService?.isConnectionMetered) {
197 return;
198 }
199
200 // Buffer events until experiment properties are set (or timeout expires)
201 if (!this._isExperimentPropertySet) {
202 if (this._pendingEvents.length < TelemetryService.MAX_BUFFER_SIZE) {
203 this._pendingEvents.push({ eventName, eventLevel, data });
204 }
205 return;
206 }
207
208 this._doLog(eventName, eventLevel, data);
209 }
211 > private _doLog(eventName: string, eventLevel: TelemetryLevel, data?: ITelemetryData) {
212 // add experiment properties
213 data = mixin(data, this._experimentProperties);
214
215 // remove all PII from data
216 data = cleanData(data, this._cleanupPatterns);
217
218 // add common properties
219 data = mixin(data, this._commonProperties);
220
221 // tag error-level events so the backend can identify them generically
222 if (eventLevel === TelemetryLevel.ERROR) {
223 data = { ...data, 'isError': true };
224 }
225
226 // Log to the appenders of sufficient level
227 this._appenders.forEach(a => a.log(eventName, data ?? {}));
228 }
230 > publicLog(eventName: string, data?: ITelemetryData) {
231 this._log(eventName, TelemetryLevel.USAGE, data);
232 }
234 > publicLog2<E extends ClassifiedEvent<OmitMetadata<T>> = never, T extends IGDPRProperty = never>(eventName: string, data?: StrictPropertyCheck<T, E>) {
235 this.publicLog(eventName, data as ITelemetryData);
236 }
238 > publicLogError(errorEventName: string, data?: ITelemetryData) {
239 if (!this._sendErrorTelemetry) {
240 return;
241 }
242
243 // Send error event and anonymize paths
244 this._log(errorEventName, TelemetryLevel.ERROR, data);
245 }
247 > publicLogError2<E extends ClassifiedEvent<OmitMetadata<T>> = never, T extends IGDPRProperty = never>(eventName: string, data?: StrictPropertyCheck<T, E>) {
248 this.publicLogError(eventName, data as ITelemetryData);
249 }
251 >
252 > function getTelemetryLevelSettingDescription(): string {
253 > const telemetryText = localize('telemetry.telemetryLevelMd', "Controls {0} telemetry, first-party extension telemetry, and participating third-party extension telemetry. Some third party extensions might not respect this setting. Consult the specific extension's documentation to be sure. Telemetry helps us better understand how {0} is performing, where improvements need to be made, and how features are being used.", product.nameLong);
254 > const externalLinksStatement = !product.privacyStatementUrl ?
255 > localize("telemetry.docsStatement", "Read more about the [data we collect]({0}).", 'https://aka.ms/vscode-telemetry') :
256 localize("telemetry.docsAndPrivacyStatement", "Read more about the [data we collect]({0}) and our [privacy statement]({1}).", 'https://aka.ms/vscode-telemetry', product.privacyStatementUrl);
257 > const restartString = !isWeb ? localize('telemetry.restart', 'A full restart of the application is necessary for crash reporting changes to take effect.') : ''; agentHostTelemetryService.ts ×29
258 >
259 > const crashReportsHeader = localize('telemetry.crashReports', "Crash Reports");
260 > const errorsHeader = localize('telemetry.errors', "Error Telemetry");
261 > const usageHeader = localize('telemetry.usage', "Usage Data");
262 >
263 > const telemetryTableDescription = localize('telemetry.telemetryLevel.tableDescription', "The following table outlines the data sent with each setting:");
264 > const telemetryTable = `
265 > | | ${crashReportsHeader} | ${errorsHeader} | ${usageHeader} |
266 > |:------|:-------------:|:---------------:|:----------:|
267 > | all | ✓ | ✓ | ✓ |
268 > | error | ✓ | ✓ | - |
269 > | crash | ✓ | - | - |
270 > | off | - | - | - |
271 > `;
272 >
273 > const deprecatedSettingNote = localize('telemetry.telemetryLevel.deprecated', "****Note:*** If this setting is 'off', no telemetry will be sent regardless of other telemetry settings. If this setting is set to anything except 'off' and telemetry is disabled with deprecated settings, no telemetry will be sent.*");
274 > const telemetryDescription = `
275 > ${telemetryText} ${externalLinksStatement} ${restartString}
276 >
277 > &nbsp;
278 >
279 > ${telemetryTableDescription}
280 > ${telemetryTable}
281 >
282 > &nbsp;
283 >
284 > ${deprecatedSettingNote}
285 > `;
286 >
287 > return telemetryDescription;
288 > }
289 >
290 > const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration);
291 > configurationRegistry.registerConfiguration({
292 > 'id': TELEMETRY_SECTION_ID,
293 > 'order': 1,
294 > 'type': 'object',
295 > 'title': localize('telemetryConfigurationTitle', "Telemetry"),
296 > 'properties': {
297 > [TELEMETRY_SETTING_ID]: {
298 > 'type': 'string',
299 > 'enum': [TelemetryConfiguration.ON, TelemetryConfiguration.ERROR, TelemetryConfiguration.CRASH, TelemetryConfiguration.OFF],
300 > 'enumDescriptions': [
301 > localize('telemetry.telemetryLevel.default', "Sends usage data, errors, and crash reports."),
302 > localize('telemetry.telemetryLevel.error', "Sends general error telemetry and crash reports."),
303 > localize('telemetry.telemetryLevel.crash', "Sends OS level crash reports."),
304 > localize('telemetry.telemetryLevel.off', "Disables all product telemetry.")
305 > ],
306 > 'markdownDescription': getTelemetryLevelSettingDescription(),
307 > 'default': TelemetryConfiguration.ON,
308 > 'restricted': true,
309 > 'scope': ConfigurationScope.APPLICATION,
310 > 'tags': ['usesOnlineServices', 'telemetry'],
311 > 'policy': {
312 > name: 'TelemetryLevel',
313 > category: PolicyCategory.Telemetry,
314 > minimumVersion: '1.99',
315 > localization: {
316 > description: {
317 > key: 'telemetry.telemetryLevel.policyDescription',
318 > value: localize('telemetry.telemetryLevel.policyDescription', "Controls the level of telemetry."),
319 > },
320 > enumDescriptions: [
321 > {
322 > key: 'telemetry.telemetryLevel.default',
323 > value: localize('telemetry.telemetryLevel.default', "Sends usage data, errors, and crash reports."),
324 > },
325 > {
326 > key: 'telemetry.telemetryLevel.error',
327 > value: localize('telemetry.telemetryLevel.error', "Sends general error telemetry and crash reports."),
328 > },
329 > {
330 > key: 'telemetry.telemetryLevel.crash',
331 > value: localize('telemetry.telemetryLevel.crash', "Sends OS level crash reports."),
332 > },
333 > {
334 > key: 'telemetry.telemetryLevel.off',
335 > value: localize('telemetry.telemetryLevel.off', "Disables all product telemetry."),
336 > }
337 > ]
338 > }
339 > }
340 > },
341 > 'telemetry.feedback.enabled': {
342 > type: 'boolean',
343 > default: true,
344 > description: localize('telemetry.feedback.enabled', "Enable feedback mechanisms such as the issue reporter, surveys, and other feedback options."),
345 > policy: {
346 > name: 'EnableFeedback',
347 > category: PolicyCategory.Telemetry,
348 > minimumVersion: '1.99',
349 > localization: { description: { key: 'telemetry.feedback.enabled', value: localize('telemetry.feedback.enabled', "Enable feedback mechanisms such as the issue reporter, surveys, and other feedback options.") } },
350 > }
351 > },
352 > // Deprecated telemetry setting
353 > [TELEMETRY_OLD_SETTING_ID]: {
354 > 'type': 'boolean',
355 > 'markdownDescription':
356 > !product.privacyStatementUrl ?
357 > localize('telemetry.enableTelemetry', "Enable diagnostic data to be collected. This helps us to better understand how {0} is performing and where improvements need to be made.", product.nameLong) :
358 localize('telemetry.enableTelemetryMd', "Enable diagnostic data to be collected. This helps us to better understand how {0} is performing and where improvements need to be made. [Read more]({1}) about what we collect and our privacy statement.", product.nameLong, product.privacyStatementUrl),
359 > 'default': true, agentHostTelemetryService.ts ×29
360 > 'restricted': true,
361 > 'markdownDeprecationMessage': localize('enableTelemetryDeprecated', "If this setting is false, no telemetry will be sent regardless of the new setting's value. Deprecated in favor of the {0} setting.", `\`#${TELEMETRY_SETTING_ID}#\``),
362 > 'scope': ConfigurationScope.APPLICATION,
363 > 'tags': ['usesOnlineServices', 'telemetry']
364 > }
365 > },
366 > });