Refactor telemetry usage flow (#7522)

This commit is contained in:
Bjorn Lu 2023-06-30 17:28:17 +08:00 committed by GitHub
parent 5b1745bf31
commit fcba0f0199
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 18 additions and 49 deletions

View file

@ -1375,7 +1375,6 @@ export interface AstroSettings {
tsConfig: TsConfigJson | undefined; tsConfig: TsConfigJson | undefined;
tsConfigPath: string | undefined; tsConfigPath: string | undefined;
watchFiles: string[]; watchFiles: string[];
forceDisableTelemetry: boolean;
timer: AstroTimer; timer: AstroTimer;
} }

View file

@ -148,7 +148,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
telemetry.record(event.eventCliSession(cmd)); telemetry.record(event.eventCliSession(cmd));
const packages = flags._.slice(3) as string[]; const packages = flags._.slice(3) as string[];
return await add(packages, { cwd: root, flags, logging, telemetry }); return await add(packages, { cwd: root, flags, logging });
} }
case 'docs': { case 'docs': {
telemetry.record(event.eventCliSession(cmd)); telemetry.record(event.eventCliSession(cmd));
@ -170,7 +170,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
// Do not track session start, since the user may be trying to enable, // Do not track session start, since the user may be trying to enable,
// disable, or modify telemetry settings. // disable, or modify telemetry settings.
const subcommand = flags._[3]?.toString(); const subcommand = flags._[3]?.toString();
return await telemetryHandler.update(subcommand, { flags, telemetry }); return await telemetryHandler.update(subcommand, { flags });
} }
} }
@ -209,7 +209,6 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
configFlagPath, configFlagPath,
flags, flags,
logging, logging,
telemetry,
handleConfigError(e) { handleConfigError(e) {
handleConfigError(e, { cmd, cwd: root, flags, logging }); handleConfigError(e, { cmd, cwd: root, flags, logging });
info(logging, 'astro', 'Continuing with previous valid configuration\n'); info(logging, 'astro', 'Continuing with previous valid configuration\n');
@ -224,7 +223,6 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
return await build(settings, { return await build(settings, {
flags, flags,
logging, logging,
telemetry,
teardownCompiler: true, teardownCompiler: true,
mode: flags.mode, mode: flags.mode,
}); });
@ -256,7 +254,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
case 'preview': { case 'preview': {
const { default: preview } = await import('../core/preview/index.js'); const { default: preview } = await import('../core/preview/index.js');
const server = await preview(settings, { logging, telemetry, flags }); const server = await preview(settings, { logging, flags });
if (server) { if (server) {
return await server.closed(); // keep alive until the server is closed return await server.closed(); // keep alive until the server is closed
} }

View file

@ -1,13 +1,13 @@
/* eslint-disable no-console */ /* eslint-disable no-console */
import type { AstroTelemetry } from '@astrojs/telemetry';
import type yargs from 'yargs-parser'; import type yargs from 'yargs-parser';
import * as msg from '../core/messages.js'; import * as msg from '../core/messages.js';
import { telemetry } from '../events/index.js';
export interface TelemetryOptions { export interface TelemetryOptions {
flags: yargs.Arguments; flags: yargs.Arguments;
telemetry: AstroTelemetry;
} }
export async function update(subcommand: string, { flags, telemetry }: TelemetryOptions) { export async function update(subcommand: string, { flags }: TelemetryOptions) {
const isValid = ['enable', 'disable', 'reset'].includes(subcommand); const isValid = ['enable', 'disable', 'reset'].includes(subcommand);
if (flags.help || flags.h || !isValid) { if (flags.help || flags.h || !isValid) {

View file

@ -1,4 +1,3 @@
import type { AstroTelemetry } from '@astrojs/telemetry';
import boxen from 'boxen'; import boxen from 'boxen';
import { diffWords } from 'diff'; import { diffWords } from 'diff';
import { execa } from 'execa'; import { execa } from 'execa';
@ -30,7 +29,6 @@ import { wrapDefaultExport } from './wrapper.js';
export interface AddOptions { export interface AddOptions {
logging: LogOptions; logging: LogOptions;
flags: yargs.Arguments; flags: yargs.Arguments;
telemetry: AstroTelemetry;
cwd?: string; cwd?: string;
} }
@ -83,7 +81,7 @@ async function getRegistry(): Promise<string> {
return stdout || 'https://registry.npmjs.org'; return stdout || 'https://registry.npmjs.org';
} }
export default async function add(names: string[], { cwd, flags, logging, telemetry }: AddOptions) { export default async function add(names: string[], { cwd, flags, logging }: AddOptions) {
applyPolyfill(); applyPolyfill();
if (flags.help || names.length === 0) { if (flags.help || names.length === 0) {
printHelp({ printHelp({

View file

@ -1,4 +1,3 @@
import type { AstroTelemetry } from '@astrojs/telemetry';
import type { AstroConfig, AstroSettings, ManifestData, RuntimeMode } from '../../@types/astro'; import type { AstroConfig, AstroSettings, ManifestData, RuntimeMode } from '../../@types/astro';
import fs from 'fs'; import fs from 'fs';
@ -26,7 +25,6 @@ import { getTimeStat } from './util.js';
export interface BuildOptions { export interface BuildOptions {
mode?: RuntimeMode; mode?: RuntimeMode;
logging: LogOptions; logging: LogOptions;
telemetry: AstroTelemetry;
/** /**
* Teardown the compiler WASM instance after build. This can improve performance when * Teardown the compiler WASM instance after build. This can improve performance when
* building once, but may cause a performance hit if building multiple times in a row. * building once, but may cause a performance hit if building multiple times in a row.

View file

@ -104,7 +104,6 @@ export function createBaseSettings(config: AstroConfig): AstroSettings {
scripts: [], scripts: [],
clientDirectives: getDefaultClientDirectives(), clientDirectives: getDefaultClientDirectives(),
watchFiles: [], watchFiles: [],
forceDisableTelemetry: false,
timer: new AstroTimer(), timer: new AstroTimer(),
}; };
} }

View file

@ -46,7 +46,6 @@ export interface CreateContainerParams {
// The string passed to --config and the resolved path // The string passed to --config and the resolved path
configFlag?: string; configFlag?: string;
configFlagPath?: string; configFlagPath?: string;
disableTelemetry?: boolean;
} }
export async function createContainer(params: CreateContainerParams = {}): Promise<Container> { export async function createContainer(params: CreateContainerParams = {}): Promise<Container> {
@ -55,13 +54,8 @@ export async function createContainer(params: CreateContainerParams = {}): Promi
logging = defaultLogging, logging = defaultLogging,
settings = await createDefaultDevSettings(params.userConfig, params.root), settings = await createDefaultDevSettings(params.userConfig, params.root),
fs = nodeFs, fs = nodeFs,
disableTelemetry,
} = params; } = params;
if (disableTelemetry) {
settings.forceDisableTelemetry = true;
}
// Initialize // Initialize
applyPolyfill(); applyPolyfill();
settings = await runHookConfigSetup({ settings = await runHookConfigSetup({
@ -149,7 +143,7 @@ export async function runInContainer(
params: CreateContainerParams, params: CreateContainerParams,
callback: (container: Container) => Promise<void> | void callback: (container: Container) => Promise<void> | void
) { ) {
const container = await createContainer({ ...params, disableTelemetry: true }); const container = await createContainer(params);
try { try {
await callback(container); await callback(container);
} finally { } finally {

View file

@ -1,4 +1,3 @@
import type { AstroTelemetry } from '@astrojs/telemetry';
import type http from 'http'; import type http from 'http';
import { cyan } from 'kleur/colors'; import { cyan } from 'kleur/colors';
import type { AddressInfo } from 'net'; import type { AddressInfo } from 'net';
@ -7,6 +6,7 @@ import type * as vite from 'vite';
import type yargs from 'yargs-parser'; import type yargs from 'yargs-parser';
import type { AstroSettings } from '../../@types/astro'; import type { AstroSettings } from '../../@types/astro';
import { attachContentServerListeners } from '../../content/index.js'; import { attachContentServerListeners } from '../../content/index.js';
import { telemetry } from '../../events/index.js';
import { info, warn, type LogOptions } from '../logger/core.js'; import { info, warn, type LogOptions } from '../logger/core.js';
import * as msg from '../messages.js'; import * as msg from '../messages.js';
import { printHelp } from '../messages.js'; import { printHelp } from '../messages.js';
@ -18,7 +18,6 @@ export interface DevOptions {
configFlagPath: string | undefined; configFlagPath: string | undefined;
flags?: yargs.Arguments; flags?: yargs.Arguments;
logging: LogOptions; logging: LogOptions;
telemetry: AstroTelemetry;
handleConfigError: (error: Error) => void; handleConfigError: (error: Error) => void;
isRestart?: boolean; isRestart?: boolean;
} }
@ -56,7 +55,7 @@ export default async function dev(
} }
const devStart = performance.now(); const devStart = performance.now();
await options.telemetry.record([]); await telemetry.record([]);
// Create a container which sets up the Vite server. // Create a container which sets up the Vite server.
const restart = await createContainerWithAutomaticRestart({ const restart = await createContainerWithAutomaticRestart({

View file

@ -1,4 +1,3 @@
import type { AstroTelemetry } from '@astrojs/telemetry';
import { cyan } from 'kleur/colors'; import { cyan } from 'kleur/colors';
import { createRequire } from 'module'; import { createRequire } from 'module';
import { pathToFileURL } from 'url'; import { pathToFileURL } from 'url';
@ -12,7 +11,6 @@ import { getResolvedHostForHttpServer } from './util.js';
interface PreviewOptions { interface PreviewOptions {
logging: LogOptions; logging: LogOptions;
telemetry: AstroTelemetry;
flags?: Arguments; flags?: Arguments;
} }

View file

@ -32,7 +32,6 @@ export function createDevelopmentEnvironment(
site: settings.config.site, site: settings.config.site,
ssr: isServerLikeOutput(settings.config), ssr: isServerLikeOutput(settings.config),
streaming: true, streaming: true,
telemetry: Boolean(settings.forceDisableTelemetry),
}); });
return { return {

View file

@ -23,7 +23,6 @@ export interface Environment {
site?: string; site?: string;
ssr: boolean; ssr: boolean;
streaming: boolean; streaming: boolean;
telemetry?: boolean;
} }
export type CreateEnvironmentArgs = Environment; export type CreateEnvironmentArgs = Environment;
@ -53,6 +52,5 @@ export function createBasicEnvironment(options: CreateBasicEnvironmentArgs): Env
routeCache: new RouteCache(options.logging, mode), routeCache: new RouteCache(options.logging, mode),
ssr: options.ssr ?? true, ssr: options.ssr ?? true,
streaming: options.streaming ?? true, streaming: options.streaming ?? true,
telemetry: false,
}); });
} }

View file

@ -91,9 +91,7 @@ export async function handleRequest(
// Our error should already be complete, but let's try to add a bit more through some guesswork // Our error should already be complete, but let's try to add a bit more through some guesswork
const errorWithMetadata = collectErrorMetadata(err, config.root); const errorWithMetadata = collectErrorMetadata(err, config.root);
if (env.telemetry !== false) { telemetry.record(eventError({ cmd: 'dev', err: errorWithMetadata, isFatal: false }));
telemetry.record(eventError({ cmd: 'dev', err: errorWithMetadata, isFatal: false }));
}
error(env.logging, null, msg.formatErrorMessage(errorWithMetadata)); error(env.logging, null, msg.formatErrorMessage(errorWithMetadata));
handle500Response(moduleLoader, res, errorWithMetadata); handle500Response(moduleLoader, res, errorWithMetadata);

View file

@ -22,6 +22,9 @@ polyfill(globalThis, {
exclude: 'window document', exclude: 'window document',
}); });
// Disable telemetry when running tests
process.env.ASTRO_TELEMETRY_DISABLED = true;
/** /**
* @typedef {import('undici').Response} Response * @typedef {import('undici').Response} Response
* @typedef {import('../src/core/dev/dev').DedvServer} DevServer * @typedef {import('../src/core/dev/dev').DedvServer} DevServer
@ -146,13 +149,6 @@ export async function loadFixture(inlineConfig) {
return settings; return settings;
}; };
/** @type {import('@astrojs/telemetry').AstroTelemetry} */
const telemetry = {
record() {
return Promise.resolve();
},
};
const resolveUrl = (url) => const resolveUrl = (url) =>
`http://${config.server.host || 'localhost'}:${config.server.port}${url.replace(/^\/?/, '/')}`; `http://${config.server.host || 'localhost'}:${config.server.port}${url.replace(/^\/?/, '/')}`;
@ -184,7 +180,7 @@ export async function loadFixture(inlineConfig) {
return { return {
build: async (opts = {}) => { build: async (opts = {}) => {
process.env.NODE_ENV = 'production'; process.env.NODE_ENV = 'production';
return build(await getSettings(), { logging, telemetry, ...opts }); return build(await getSettings(), { logging, ...opts });
}, },
sync: async (opts) => sync(await getSettings(), { logging, fs, ...opts }), sync: async (opts) => sync(await getSettings(), { logging, fs, ...opts }),
check: async (opts) => { check: async (opts) => {
@ -192,7 +188,7 @@ export async function loadFixture(inlineConfig) {
}, },
startDevServer: async (opts = {}) => { startDevServer: async (opts = {}) => {
process.env.NODE_ENV = 'development'; process.env.NODE_ENV = 'development';
devServer = await dev(await getSettings(), { logging, telemetry, ...opts }); devServer = await dev(await getSettings(), { logging, ...opts });
config.server.host = parseAddressToHost(devServer.address.address); // update host config.server.host = parseAddressToHost(devServer.address.address); // update host
config.server.port = devServer.address.port; // update port config.server.port = devServer.address.port; // update port
return devServer; return devServer;
@ -214,11 +210,7 @@ export async function loadFixture(inlineConfig) {
}, },
preview: async (opts = {}) => { preview: async (opts = {}) => {
process.env.NODE_ENV = 'production'; process.env.NODE_ENV = 'production';
const previewServer = await preview(await getSettings(), { const previewServer = await preview(await getSettings(), { logging, ...opts });
logging,
telemetry,
...opts,
});
config.server.host = parseAddressToHost(previewServer.host); // update host config.server.host = parseAddressToHost(previewServer.host); // update host
config.server.port = previewServer.port; // update port config.server.port = previewServer.port; // update port
return previewServer; return previewServer;

View file

@ -135,7 +135,6 @@ describe('Route matching', () => {
output: 'hybrid', output: 'hybrid',
adapter: testAdapter(), adapter: testAdapter(),
}, },
disableTelemetry: true,
}); });
settings = container.settings; settings = container.settings;

View file

@ -9,7 +9,7 @@ describe('<Code />', () => {
let container; let container;
let mod; let mod;
before(async () => { before(async () => {
container = await createContainer({ root, disableTelemetry: true }); container = await createContainer({ root });
const loader = createViteLoader(container.viteServer); const loader = createViteLoader(container.viteServer);
mod = await loader.import('astro/components/Shiki.js'); mod = await loader.import('astro/components/Shiki.js');
}); });