telemetryUtils.ts 9.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

import { TPromise } from 'vs/base/common/winjs.base';
import { IDisposable } from 'vs/base/common/lifecycle';
import { guessMimeTypes } from 'vs/base/common/mime';
import paths = require('vs/base/common/paths');
import URI from 'vs/base/common/uri';
import { ConfigurationSource, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IKeybindingService, KeybindingSource } from 'vs/platform/keybinding/common/keybinding';
import { ILifecycleService, ShutdownReason } from 'vs/platform/lifecycle/common/lifecycle';
import { IStorageService } from 'vs/platform/storage/common/storage';
16
import { ITelemetryService, ITelemetryExperiments, ITelemetryInfo, ITelemetryData } from 'vs/platform/telemetry/common/telemetry';
C
Christof Marti 已提交
17
import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
18 19

export const defaultExperiments: ITelemetryExperiments = {
20
	mergeQuickLinks: false,
21 22 23 24 25
};

export const NullTelemetryService = {
	_serviceBrand: undefined,
	_experiments: defaultExperiments,
26
	publicLog(eventName: string, data?: ITelemetryData) {
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
		return TPromise.as<void>(null);
	},
	isOptedIn: true,
	getTelemetryInfo(): TPromise<ITelemetryInfo> {
		return TPromise.as({
			instanceId: 'someValue.instanceId',
			sessionId: 'someValue.sessionId',
			machineId: 'someValue.machineId'
		});
	},
	getExperiments(): ITelemetryExperiments {
		return this._experiments;
	}
};

C
Christof Marti 已提交
42 43 44
export function loadExperiments(accessor: ServicesAccessor): ITelemetryExperiments {
	const storageService = accessor.get(IStorageService);
	const configurationService = accessor.get(IConfigurationService);
45

46
	let {
47
		mergeQuickLinks,
48
	} = splitExperimentsRandomness(storageService);
49

50
	return applyOverrides({
51
		mergeQuickLinks,
52
	}, configurationService);
C
Christof Marti 已提交
53 54
}

55 56
function applyOverrides(experiments: ITelemetryExperiments, configurationService: IConfigurationService): ITelemetryExperiments {
	const experimentsConfig = getExperimentsOverrides(configurationService);
57 58 59 60 61 62 63 64
	Object.keys(experiments).forEach(key => {
		if (key in experimentsConfig) {
			experiments[key] = experimentsConfig[key];
		}
	});
	return experiments;
}

65 66
function splitExperimentsRandomness(storageService: IStorageService): ITelemetryExperiments {
	const random1 = getExperimentsRandomness(storageService);
67 68
	const [random2, /* showNewUserWatermark */] = splitRandom(random1);
	const [random3, /* openUntitledFile */] = splitRandom(random2);
69
	const [random4, mergeQuickLinks] = splitRandom(random3);
70 71
	// tslint:disable-next-line:no-unused-variable (https://github.com/Microsoft/TypeScript/issues/16628)
	const [random5, /* enableWelcomePage */] = splitRandom(random4);
72
	return {
73
		mergeQuickLinks,
74 75 76
	};
}

77
function getExperimentsRandomness(storageService: IStorageService) {
78
	const key = 'experiments.randomness';
79
	let valueString = storageService.get(key);
80 81
	if (!valueString) {
		valueString = Math.random().toString();
82
		storageService.store(key, valueString);
83 84 85 86 87
	}

	return parseFloat(valueString);
}

88 89 90 91 92 93
function splitRandom(random: number): [number, boolean] {
	const scaled = random * 2;
	const i = Math.floor(scaled);
	return [scaled - i, i === 1];
}

94
function getExperimentsOverrides(configurationService: IConfigurationService): ITelemetryExperiments {
95
	const config: any = configurationService.getConfiguration('telemetry');
96
	return config && config.experiments || {};
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
export interface ITelemetryAppender {
	log(eventName: string, data: any): void;
}

export function combinedAppender(...appenders: ITelemetryAppender[]): ITelemetryAppender {
	return { log: (e, d) => appenders.forEach(a => a.log(e, d)) };
}

export const NullAppender: ITelemetryAppender = { log: () => null };

// --- util

export function anonymize(input: string): string {
	if (!input) {
		return input;
	}

	let r = '';
	for (let i = 0; i < input.length; i++) {
		let ch = input[i];
		if (ch >= '0' && ch <= '9') {
			r += '0';
			continue;
		}
		if (ch >= 'a' && ch <= 'z') {
			r += 'a';
			continue;
		}
		if (ch >= 'A' && ch <= 'Z') {
			r += 'A';
			continue;
		}
		r += ch;
	}
	return r;
}

export interface URIDescriptor {
	mimeType?: string;
	ext?: string;
	path?: string;
}

export function telemetryURIDescriptor(uri: URI): URIDescriptor {
	const fsPath = uri && uri.fsPath;
	return fsPath ? { mimeType: guessMimeTypes(fsPath).join(', '), ext: paths.extname(fsPath), path: anonymize(fsPath) } : {};
}

C
Christof Marti 已提交
147 148 149
/**
 * Only add settings that cannot contain any personal/private information of users (PII).
 */
150
const configurationValueWhitelist = [
151
	'editor.tabCompletion',
152
	'editor.fontFamily',
153 154 155 156 157 158 159
	'editor.fontWeight',
	'editor.fontSize',
	'editor.lineHeight',
	'editor.letterSpacing',
	'editor.lineNumbers',
	'editor.rulers',
	'editor.wordSeparators',
160
	'editor.tabSize',
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
	'editor.insertSpaces',
	'editor.detectIndentation',
	'editor.roundedSelection',
	'editor.scrollBeyondLastLine',
	'editor.minimap.enabled',
	'editor.minimap.renderCharacters',
	'editor.minimap.maxColumn',
	'editor.find.seedSearchStringFromSelection',
	'editor.find.autoFindInSelection',
	'editor.wordWrap',
	'editor.wordWrapColumn',
	'editor.wrappingIndent',
	'editor.mouseWheelScrollSensitivity',
	'editor.multiCursorModifier',
	'editor.quickSuggestions',
	'editor.quickSuggestionsDelay',
	'editor.parameterHints',
	'editor.autoClosingBrackets',
179
	'editor.autoindent',
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
	'editor.formatOnType',
	'editor.formatOnPaste',
	'editor.suggestOnTriggerCharacters',
	'editor.acceptSuggestionOnEnter',
	'editor.acceptSuggestionOnCommitCharacter',
	'editor.snippetSuggestions',
	'editor.emptySelectionClipboard',
	'editor.wordBasedSuggestions',
	'editor.suggestFontSize',
	'editor.suggestLineHeight',
	'editor.selectionHighlight',
	'editor.occurrencesHighlight',
	'editor.overviewRulerLanes',
	'editor.overviewRulerBorder',
	'editor.cursorBlinking',
	'editor.cursorStyle',
	'editor.mouseWheelZoom',
	'editor.fontLigatures',
	'editor.hideCursorInOverviewRuler',
	'editor.renderWhitespace',
	'editor.renderControlCharacters',
	'editor.renderIndentGuides',
	'editor.renderLineHighlight',
	'editor.codeLens',
	'editor.folding',
	'editor.showFoldingControls',
	'editor.matchBrackets',
	'editor.glyphMargin',
	'editor.useTabStops',
	'editor.trimAutoWhitespace',
	'editor.stablePeek',
	'editor.dragAndDrop',
	'editor.formatOnSave',

	'window.zoomLevel',
215 216 217 218 219 220 221 222 223 224 225
	'files.autoSave',
	'files.hotExit',
	'typescript.check.tscVersion',
	'files.associations',
	'workbench.statusBar.visible',
	'files.trimTrailingWhitespace',
	'git.confirmSync',
	'workbench.sideBar.location',
	'window.openFilesInNewWindow',
	'javascript.validate.enable',
	'window.reopenFolders',
226
	'window.restoreWindows',
227 228 229 230 231 232 233
	'extensions.autoUpdate',
	'files.eol',
	'explorer.openEditors.visible',
	'workbench.editor.enablePreview',
	'files.autoSaveDelay',
	'workbench.editor.showTabs',
	'files.encoding',
234
	'files.autoGuessEncoding',
235 236 237 238
	'git.enabled',
	'http.proxyStrictSSL',
	'terminal.integrated.fontFamily',
	'workbench.editor.enablePreviewFromQuickOpen',
239
	'workbench.editor.swipeToNavigate',
240
	'php.builtInCompletions.enable',
241
	'php.validate.enable',
242
	'php.validate.run',
243
	'workbench.welcome.enabled',
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
];

export function configurationTelemetry(telemetryService: ITelemetryService, configurationService: IConfigurationService): IDisposable {
	return configurationService.onDidUpdateConfiguration(event => {
		if (event.source !== ConfigurationSource.Default) {
			telemetryService.publicLog('updateConfiguration', {
				configurationSource: ConfigurationSource[event.source],
				configurationKeys: flattenKeys(event.sourceConfig)
			});
			telemetryService.publicLog('updateConfigurationValues', {
				configurationSource: ConfigurationSource[event.source],
				configurationValues: flattenValues(event.sourceConfig, configurationValueWhitelist)
			});
		}
	});
}

export function lifecycleTelemetry(telemetryService: ITelemetryService, lifecycleService: ILifecycleService): IDisposable {
	return lifecycleService.onShutdown(event => {
		telemetryService.publicLog('shutdown', { reason: ShutdownReason[event] });
	});
}

export function keybindingsTelemetry(telemetryService: ITelemetryService, keybindingService: IKeybindingService): IDisposable {
	return keybindingService.onDidUpdateKeybindings(event => {
		if (event.source === KeybindingSource.User && event.keybindings) {
			telemetryService.publicLog('updateKeybindings', {
				bindings: event.keybindings.map(binding => ({
					key: binding.key,
					command: binding.command,
					when: binding.when,
					args: binding.args ? true : undefined
				}))
			});
		}
	});
}

function flattenKeys(value: Object): string[] {
	if (!value) {
		return [];
	}
	const result: string[] = [];
	flatKeys(result, '', value);
	return result;
}

function flatKeys(result: string[], prefix: string, value: Object): void {
	if (value && typeof value === 'object' && !Array.isArray(value)) {
		Object.keys(value)
			.forEach(key => flatKeys(result, prefix ? `${prefix}.${key}` : key, value[key]));
	} else {
		result.push(prefix);
	}
}

function flattenValues(value: Object, keys: string[]): { [key: string]: any }[] {
	if (!value) {
		return [];
	}

	return keys.reduce((array, key) => {
		const v = key.split('.')
			.reduce((tmp, k) => tmp && typeof tmp === 'object' ? tmp[k] : undefined, value);
		if (typeof v !== 'undefined') {
			array.push({ [key]: v });
		}
		return array;
	}, []);
}