Skip to content

Commit

Permalink
respect metric enabled/disabled
Browse files Browse the repository at this point in the history
  • Loading branch information
emily-shen committed Nov 15, 2024
1 parent 28f234d commit 3c29a36
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 56 deletions.
71 changes: 43 additions & 28 deletions packages/wrangler/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,35 +55,13 @@ export function readConfig(
requirePagesConfig?: boolean,
hideWarnings: boolean = false
): Config {
const isJsonConfigEnabled =
getFlag("JSON_CONFIG_FILE") ?? args.experimentalJsonConfig;
let rawConfig: RawConfig = {};

if (!configPath) {
configPath = findWranglerToml(process.cwd(), isJsonConfigEnabled);
}
const {
rawConfig,
configPath: updateConfigPath,
isJsonConfigEnabled,
} = parseConfig(configPath, args, requirePagesConfig);

try {
// Load the configuration from disk if available
if (configPath?.endsWith("toml")) {
rawConfig = parseTOML(readFileSync(configPath), configPath);
} else if (configPath?.endsWith("json") || configPath?.endsWith("jsonc")) {
rawConfig = parseJSONC(readFileSync(configPath), configPath);
}
} catch (e) {
// Swallow parsing errors if we require a pages config file.
// At this point, we can't tell if the user intended to provide a Pages config file (and so should see the parsing error) or not (and so shouldn't).
// We err on the side of swallowing the error so as to not break existing projects
if (requirePagesConfig) {
logger.error(e);
throw new FatalError(
"Your wrangler.toml is not a valid Pages config file",
EXIT_CODE_INVALID_PAGES_CONFIG
);
} else {
throw e;
}
}
configPath = updateConfigPath;

/**
* Check if configuration file belongs to a Pages project.
Expand Down Expand Up @@ -154,6 +132,43 @@ export function readConfig(
return config;
}

export const parseConfig = (
configPath: string | undefined,
// Include command specific args as well as the wrangler global flags
args: ReadConfigCommandArgs,
requirePagesConfig?: boolean
) => {
const isJsonConfigEnabled =
getFlag("JSON_CONFIG_FILE") ?? args.experimentalJsonConfig;
let rawConfig: RawConfig = {};

if (!configPath) {
configPath = findWranglerToml(process.cwd(), isJsonConfigEnabled);
}

try {
// Load the configuration from disk if available
if (configPath?.endsWith("toml")) {
rawConfig = parseTOML(readFileSync(configPath), configPath);
} else if (configPath?.endsWith("json") || configPath?.endsWith("jsonc")) {
rawConfig = parseJSONC(readFileSync(configPath), configPath);
}
} catch (e) {
// Swallow parsing errors if we require a pages config file.
// At this point, we can't tell if the user intended to provide a Pages config file (and so should see the parsing error) or not (and so shouldn't).
// We err on the side of swallowing the error so as to not break existing projects
if (requirePagesConfig) {
logger.error(e);
throw new FatalError(
"Your wrangler.toml is not a valid Pages config file",
EXIT_CODE_INVALID_PAGES_CONFIG
);
} else {
throw e;
}
}
return { rawConfig, configPath, isJsonConfigEnabled };
};
/**
* Modifies the provided config to support python workers, if the entrypoint is a .py file
*/
Expand Down
14 changes: 8 additions & 6 deletions packages/wrangler/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import makeCLI from "yargs";
import { version as wranglerVersion } from "../package.json";
import { ai } from "./ai";
import { cloudchamber } from "./cloudchamber";
import { loadDotEnv } from "./config";
import { loadDotEnv, parseConfig } from "./config";
import { createCommandRegister } from "./core/register-commands";
import { d1 } from "./d1";
import { deleteHandler, deleteOptions } from "./delete";
Expand Down Expand Up @@ -52,7 +52,7 @@ import "./user/commands";
import "./metrics/commands";
import { demandSingleValue } from "./core";
import { logBuildFailure, logger, LOGGER_LEVELS } from "./logger";
import { sendNewMetricsEvent } from "./metrics/send-event";
import { getMetricsDispatcher } from "./metrics";
import { mTlsCertificateCommands } from "./mtls-certificate/cli";
import { writeOutput } from "./output";
import { pages } from "./pages";
Expand Down Expand Up @@ -686,7 +686,7 @@ export async function main(argv: string[]): Promise<void> {
const wrangler = createCLIParser(argv);
let command: string | undefined;
let metricsArgs: Record<string, unknown> | undefined;

let dispatcher: ReturnType<typeof getMetricsDispatcher> | undefined;
// Register Yargs middleware to record command as Sentry breadcrumb
let recordedCommand = false;
const wranglerWithMiddleware = wrangler.middleware((args) => {
Expand All @@ -698,10 +698,12 @@ export async function main(argv: string[]): Promise<void> {
// `args._` doesn't include any positional arguments (e.g. script name,
// key to fetch) or flags

const { rawConfig } = parseConfig(args.config, args, false);
dispatcher = getMetricsDispatcher({ sendMetrics: rawConfig.send_metrics });
command = `wrangler ${args._.join(" ")}`;
metricsArgs = args;
addBreadcrumb(command);
void sendNewMetricsEvent("wrangler command started", {
void dispatcher.sendNewEvent("wrangler command started", {
command,
args,
});
Expand All @@ -713,7 +715,7 @@ export async function main(argv: string[]): Promise<void> {

const durationMs = Date.now() - startTime;

void sendNewMetricsEvent("wrangler command completed", {
void dispatcher?.sendNewEvent("wrangler command completed", {
command,
args: metricsArgs,
durationMs,
Expand Down Expand Up @@ -829,7 +831,7 @@ export async function main(argv: string[]): Promise<void> {

const durationMs = Date.now() - startTime;

void sendNewMetricsEvent("wrangler command errored", {
void dispatcher?.sendNewEvent("wrangler command errored", {
command,
args: metricsArgs,
durationMs,
Expand Down
4 changes: 2 additions & 2 deletions packages/wrangler/src/metrics/metrics-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ export interface MetricsConfig {
* If the current process is not interactive then we will cannot prompt the user and just assume
* we cannot send metrics if there is no cached or project-level preference available.
*/
export async function getMetricsConfig({
export function getMetricsConfig({
sendMetrics,
}: MetricsConfigOptions): Promise<MetricsConfig> {
}: MetricsConfigOptions): MetricsConfig {
const config = readMetricsConfig();
const deviceId = getDeviceId(config);

Expand Down
16 changes: 12 additions & 4 deletions packages/wrangler/src/metrics/metrics-dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { version as wranglerVersion } from "../../package.json";
import { logger } from "../logger";
import { getMetricsConfig, readMetricsConfig } from "./metrics-config";
import type { MetricsConfigOptions } from "./metrics-config";
import type { CommonEventProperties } from "./send-event";
import type { CommonEventProperties, Events } from "./send-event";

// The SPARROW_SOURCE_KEY is provided at esbuild time as a `define` for production and beta
// releases. Otherwise it is left undefined, which automatically disables metrics requests.
Expand All @@ -26,7 +26,7 @@ function getPlatform() {
}
}

export async function getMetricsDispatcher(options: MetricsConfigOptions) {
export function getMetricsDispatcher(options: MetricsConfigOptions) {
const platform = getPlatform();
const packageManager = whichPmRuns()?.name;
const isFirstUsage = readMetricsConfig().permission === undefined;
Expand Down Expand Up @@ -54,15 +54,23 @@ export async function getMetricsDispatcher(options: MetricsConfigOptions) {
async identify(properties: Properties): Promise<void> {
await dispatch({ type: "identify", name: "identify", properties });
},
async sendNewEvent<EventName extends Events["name"]>(
name: EventName,
properties: Omit<
Extract<Events, { name: EventName }>["properties"],
keyof CommonEventProperties
>
): Promise<void> {
await dispatch({ type: "event", name, properties });
},
};

async function dispatch(event: {
type: "identify" | "event";
name: string;
properties: Properties;
}): Promise<void> {
// TODO: make not async
const metricsConfig = await getMetricsConfig(options);
const metricsConfig = getMetricsConfig(options);

const commonEventProperties: CommonEventProperties = {
amplitude_session_id,
Expand Down
16 changes: 0 additions & 16 deletions packages/wrangler/src/metrics/send-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,19 +170,3 @@ export type Events =
errorType: string | undefined;
};
};

export async function sendNewMetricsEvent<EventName extends Events["name"]>(
event: EventName,
properties: Omit<
Extract<Events, { name: EventName }>["properties"],
keyof CommonEventProperties
>,
options?: MetricsConfigOptions
): Promise<void> {
try {
const metricsDispatcher = await getMetricsDispatcher(options ?? {});
await metricsDispatcher.sendEvent(event, properties);
} catch (err) {
logger.debug("Error sending metrics event", err);
}
}

0 comments on commit 3c29a36

Please sign in to comment.