Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
SETTINGS_VIEW_NAME,
getActiveDebugSessionId,
getJsDebugCDPProxyWebsocketUrl,
reportFileExtensionTypes,
trackOpenedFileTypes,
reportChangedExtensionSetting,
reportExtensionSettings,
reportUrlType,
Expand All @@ -41,6 +41,7 @@ import { ErrorReporter } from './errorReporter';
import { ErrorCodes } from './common/errorCodes';

let telemetryReporter: Readonly<TelemetryReporter>;
let openedFileTypesTracker: vscode.Disposable | undefined;
let browserInstance: Browser;
let cdpTargetsProvider: CDPTargetsProvider;

Expand Down Expand Up @@ -233,11 +234,19 @@ export function activate(context: vscode.ExtensionContext): void {
}));

void vscode.commands.executeCommand('setContext', 'titleCommandsRegistered', true);
void reportFileExtensionTypes(telemetryReporter);
openedFileTypesTracker = trackOpenedFileTypes(telemetryReporter);
context.subscriptions.push(openedFileTypesTracker);
reportExtensionSettings(telemetryReporter);
vscode.workspace.onDidChangeConfiguration(event => reportChangedExtensionSetting(event, telemetryReporter));
}

export async function deactivate(): Promise<void> {
// Report pending opened-file counts, then flush the reporter so they aren't lost on shutdown.
openedFileTypesTracker?.dispose();
openedFileTypesTracker = undefined;
await telemetryReporter?.dispose();
}

function ensureWorkspaceTrusted(): boolean {
if (vscode.workspace.isTrusted) {
return true;
Expand Down
85 changes: 52 additions & 33 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -775,41 +775,60 @@ export function reportUrlType(url: string, telemetryReporter: Readonly<Telemetry
sendTaxonomyEvent(telemetryReporter, { area: 'user', feature: 'browser', action: 'navigate' }, { 'urlType': urlType });
}

export async function reportFileExtensionTypes(telemetryReporter: Readonly<TelemetryReporter>): Promise<void> {
const files = await vscode.workspace.findFiles('**/*.*', '**/node_modules/**');
const extensionMap: Map<string, number> = new Map<string, number>([
['html', 0],
['css', 0],
['js', 0],
['ts', 0],
['jsx', 0],
['scss', 0],
['json', 0],
['mjs', 0],
['other', 0],
]);
for (const file of files) {
const extension: string | undefined = file.path.split('.').pop();
if (extension) {
if (extensionMap.has(extension)) {
const currentValue = extensionMap.get(extension);
if (currentValue !== undefined) {
extensionMap.set(extension, currentValue + 1);
}
} else {
const otherCount = extensionMap.get('other');
if (otherCount !== undefined) {
extensionMap.set('other', otherCount + 1);
}
}
const TRACKED_FILE_EXTENSIONS = ['html', 'css', 'js', 'ts', 'jsx', 'scss', 'json', 'mjs'];
const TRACKED_URI_SCHEMES = ['file', 'vscode-remote'];
export const OPENED_FILE_TYPES_REPORT_DELAY_MS = 30000;

/**
* Tracks the types of files the user opens and reports them as batched telemetry.
*/
export function trackOpenedFileTypes(telemetryReporter: Readonly<TelemetryReporter>): vscode.Disposable {
const seenFiles = new Set<string>();
let pendingCounts = new Map<string, number>();
let reportTimer: NodeJS.Timeout | undefined;

const report = (): void => {
if (reportTimer) {
clearTimeout(reportTimer);
reportTimer = undefined;
}
}
extensionMap.set('total', files.length);
if (pendingCounts.size === 0) {
return;
}
const fileTypes: {[key: string]: number} = { total: 0 };
for (const extension of [...TRACKED_FILE_EXTENSIONS, 'other']) {
fileTypes[extension] = pendingCounts.get(extension) ?? 0;
fileTypes.total += fileTypes[extension];
}
pendingCounts = new Map<string, number>();
sendTaxonomyEvent(telemetryReporter, { area: 'workspace', feature: 'metadata', action: 'fileOpened' }, undefined, fileTypes);
};

const listener = vscode.workspace.onDidOpenTextDocument(document => {
Comment thread
vidorteg marked this conversation as resolved.
Resolved
Comment thread
vidorteg marked this conversation as resolved.
Resolved
const uri = document.uri;
if (!TRACKED_URI_SCHEMES.includes(uri.scheme) || uri.path.includes('/.git/')) {
return;
}
const key = uri.toString();
if (seenFiles.has(key)) {
return;
}
seenFiles.add(key);

const extension = path.posix.extname(uri.path).slice(1).toLowerCase();
const bucket = TRACKED_FILE_EXTENSIONS.includes(extension) ? extension : 'other';
pendingCounts.set(bucket, (pendingCounts.get(bucket) ?? 0) + 1);

// Creates Object from map
const fileTypes: {[key: string]: number} = {};
Object.assign(fileTypes, ...[...extensionMap.entries()].map(([k, v]) => ({[k]: v})));
sendTaxonomyEvent(telemetryReporter, { area: 'workspace', feature: 'metadata', action: 'scan' }, undefined, fileTypes);
if (reportTimer) {
clearTimeout(reportTimer);
}
reportTimer = setTimeout(report, OPENED_FILE_TYPES_REPORT_DELAY_MS);
});

return new vscode.Disposable(() => {
Comment thread
vidorteg marked this conversation as resolved.
Resolved
listener.dispose();
report();
Comment thread
vidorteg marked this conversation as resolved.
Resolved
});
}

(function initialize() {
Expand Down
20 changes: 17 additions & 3 deletions test/extension.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ describe("extension", () => {
removeTrailingSlash: jest.fn(removeTrailingSlash),
getJsDebugCDPProxyWebsocketUrl: jest.fn(),
getActiveDebugSessionId: jest.fn(),
reportFileExtensionTypes: jest.fn(),
trackOpenedFileTypes: jest.fn(),
reportChangedExtensionSetting: jest.fn(),
reportExtensionSettings: jest.fn(),
};
Expand Down Expand Up @@ -76,13 +76,27 @@ describe("extension", () => {
expect(mockUtils.createTelemetryReporter).toHaveBeenCalled();
});

it("reports pending opened file types and flushes telemetry on deactivate", async () => {
const calls: string[] = [];
const reporter = createFakeTelemetryReporter();
reporter.dispose.mockImplementation(async () => { calls.push('reporter'); });
mockUtils.createTelemetryReporter!.mockReturnValue(reporter);
mockUtils.trackOpenedFileTypes!.mockReturnValue({ dispose: jest.fn(() => calls.push('tracker')) });
const newExtension = await import("../src/extension");

newExtension.activate(context);
await newExtension.deactivate();

expect(calls).toEqual(['tracker', 'reporter']);
});

it("registers commands correctly", async () => {
const newExtension = await import("../src/extension");

// Activation should add the commands as subscriptions on the context
newExtension.activate(context);

expect(context.subscriptions.length).toBe(19);
expect(context.subscriptions.length).toBe(20);
expect(commandMock).toHaveBeenCalledTimes(18);
expect(commandMock)
.toHaveBeenNthCalledWith(1, `${SETTINGS_STORE_NAME}.attach`, expect.any(Function));
Expand Down Expand Up @@ -421,7 +435,7 @@ describe("extension", () => {
reportChangedExtensionSetting: jest.fn(),
reportExtensionSettings: jest.fn(),
reportUrlType: jest.fn(),
reportFileExtensionTypes: jest.fn(),
trackOpenedFileTypes: jest.fn(),
};

mockPanel = {
Expand Down
11 changes: 2 additions & 9 deletions test/helpers/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export function createFakeVSCode() {
Diagnostic: jest.fn(),
CallHierarchyItem: jest.fn(),
CodeActionKind: jest.fn(),
Disposable: jest.fn(),
Disposable: jest.fn().mockImplementation((callOnDispose: () => void) => ({ dispose: callOnDispose })),
ExtensionMode: {
Production: 1
},
Expand Down Expand Up @@ -110,14 +110,7 @@ export function createFakeVSCode() {
workspace: {
isTrusted: true,
createFileSystemWatcher: jest.fn(),
findFiles: jest.fn(() => {
return [
{path: '/c:/test/main.js'},
{path: '/c:/test/styles.css'},
{path: '/c:/test/react/test.jsx'},
{path: '/c:/.vscode/launch.json'}
];
}),
onDidOpenTextDocument: jest.fn(() => ({ dispose: jest.fn() })),
getConfiguration: jest.fn(() => {
return {
get: (name: string) => {
Expand Down
74 changes: 70 additions & 4 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1037,11 +1037,77 @@ describe("utils", () => {
});
});

describe('reportFileExtensionTypes', () => {
it('correctly lists extension types in the workspace', async () => {
describe('trackOpenedFileTypes', () => {
const openDocument = (uri: string): void => {
const vscodeMock = jest.requireMock("vscode");
const listener = vscodeMock.workspace.onDidOpenTextDocument.mock.calls[0][0];
const [, scheme, filePath = ''] = /^([a-z-]+):\/\/[^/]*(\/.*)?$/.exec(uri) as RegExpExecArray;
listener({ uri: { scheme, path: filePath, toString: () => uri } });
};

beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
});

it('reports batched counts of unique opened files after a quiet period', () => {
const reporter = createFakeTelemetryReporter();
utils.trackOpenedFileTypes(reporter);

openDocument('file:///c:/test/main.js');
openDocument('file:///c:/test/main.js');
openDocument('file:///c:/test/styles.CSS');
openDocument('vscode-remote://ssh-remote+host/home/test/react/test.jsx');
openDocument('file:///c:/.vscode/launch.json');
openDocument('file:///c:/test/Makefile');
openDocument('file:///c:/test/.git/COMMIT_EDITMSG');
openDocument('git:///c:/test/main.js');
openDocument('output://extension-output');

expect(reporter.sendTelemetryEvent).not.toHaveBeenCalled();
jest.advanceTimersByTime(utils.OPENED_FILE_TYPES_REPORT_DELAY_MS);

expect(reporter.sendTelemetryEvent).toHaveBeenCalledTimes(1);
expect(reporter.sendTelemetryEvent).toHaveBeenCalledWith('workspace', { area: 'workspace', feature: 'metadata', action: 'fileOpened', outcome: 'success' }, {"css": 1, "html": 0, "js": 1, "json": 1, "jsx": 1, "mjs": 0, "other": 1, "scss": 0, "total": 5, "ts": 0});
});

it('reports only newly opened files in subsequent batches', () => {
const reporter = createFakeTelemetryReporter();
utils.trackOpenedFileTypes(reporter);

openDocument('file:///c:/test/main.js');
jest.advanceTimersByTime(utils.OPENED_FILE_TYPES_REPORT_DELAY_MS);
openDocument('file:///c:/test/main.js');
openDocument('file:///c:/test/index.html');
jest.advanceTimersByTime(utils.OPENED_FILE_TYPES_REPORT_DELAY_MS);

expect(reporter.sendTelemetryEvent).toHaveBeenCalledTimes(2);
expect(reporter.sendTelemetryEvent).toHaveBeenLastCalledWith('workspace', expect.anything(), expect.objectContaining({ "html": 1, "js": 0, "total": 1 }));
});

it('flushes pending counts and stops listening on dispose', () => {
const reporter = createFakeTelemetryReporter();
const disposable = utils.trackOpenedFileTypes(reporter);
const listenerDisposable = jest.requireMock("vscode").workspace.onDidOpenTextDocument.mock.results[0].value;

openDocument('file:///c:/test/app.ts');
disposable.dispose();

expect(listenerDisposable.dispose).toHaveBeenCalled();
expect(reporter.sendTelemetryEvent).toHaveBeenCalledTimes(1);
expect(reporter.sendTelemetryEvent).toHaveBeenCalledWith('workspace', expect.anything(), expect.objectContaining({ "ts": 1, "total": 1 }));

jest.advanceTimersByTime(utils.OPENED_FILE_TYPES_REPORT_DELAY_MS);
expect(reporter.sendTelemetryEvent).toHaveBeenCalledTimes(1);
});

it('does not report when no files were opened', () => {
const reporter = createFakeTelemetryReporter();
await utils.reportFileExtensionTypes(reporter);
expect(reporter.sendTelemetryEvent).toHaveBeenCalledWith('workspace', { area: 'workspace', feature: 'metadata', action: 'scan', outcome: 'success' }, {"css": 1, "html": 0, "js": 1, "json": 1, "jsx": 1, "mjs": 0, "other": 0, "scss": 0, "total": 4, "ts": 0});
utils.trackOpenedFileTypes(reporter).dispose();
expect(reporter.sendTelemetryEvent).not.toHaveBeenCalled();
});
});

Expand Down
Loading