Skip to content

Commit

Permalink
Prompt every time
Browse files Browse the repository at this point in the history
  • Loading branch information
penalosa committed Dec 8, 2023
1 parent fdc2486 commit 5cf6267
Show file tree
Hide file tree
Showing 7 changed files with 48 additions and 106 deletions.
1 change: 0 additions & 1 deletion packages/wrangler/src/api/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,6 @@ export async function unstable_dev(
logLevel: options?.logLevel ?? defaultLogLevel,
port: options?.port ?? 0,
updateCheck: options?.updateCheck ?? false,
metricsOptOut: undefined,
};

//due to Pages adoption of unstable_dev, we can't *just* disable rebuilds and watching. instead, we'll have two versions of startDev, which will converge.
Expand Down
9 changes: 5 additions & 4 deletions packages/wrangler/src/dialogs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,21 @@ export class NoDefaultValueProvided extends Error {

interface ConfirmOptions {
defaultValue?: boolean;
fallbackValue?: boolean;
}

export async function confirm(
text: string,
{ defaultValue = true }: ConfirmOptions = {}
{ defaultValue = true, fallbackValue = true }: ConfirmOptions = {}
): Promise<boolean> {
if (isNonInteractiveOrCI()) {
logger.log(`? ${text}`);
logger.log(
`🤖 ${chalk.dim(
"Using default value in non-interactive context:"
)} ${chalk.white.bold(defaultValue ? "yes" : "no")}`
"Using fallback value in non-interactive context:"
)} ${chalk.white.bold(fallbackValue ? "yes" : "no")}`
);
return defaultValue;
return fallbackValue;
}
const { value } = await prompts({
type: "confirm",
Expand Down
1 change: 0 additions & 1 deletion packages/wrangler/src/generate/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ export async function generateHandler(args: GenerateArgs) {
_: args._,
$0: args.$0,
experimentalJsonConfig: false,
metricsOptOut: undefined,
});
}

Expand Down
57 changes: 4 additions & 53 deletions packages/wrangler/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import module from "node:module";
import os from "node:os";
import path from "node:path";
import TOML from "@iarna/toml";
import chalk from "chalk";
import { ProxyAgent, setGlobalDispatcher } from "undici";
import makeCLI from "yargs";
import { version as wranglerVersion } from "../package.json";
Expand Down Expand Up @@ -41,11 +39,7 @@ import { initHandler, initOptions } from "./init";
import { kvNamespace, kvKey, kvBulk } from "./kv";
import { logBuildFailure, logger } from "./logger";
import * as metrics from "./metrics";
import {
CURRENT_METRICS_DATE,
getMetricsConfigPath,
writeMetricsConfig,
} from "./metrics/metrics-config";

import { mTlsCertificateCommands } from "./mtls-certificate/cli";
import { pages } from "./pages";
import { formatMessage, ParseError } from "./parse";
Expand All @@ -55,7 +49,7 @@ import { r2 } from "./r2";
import { secret, secretBulkHandler, secretBulkOptions } from "./secret";
import {
captureGlobalException,
captureWranglerCommand,
addBreadcrumb,
closeSentry,
setupSentry,
} from "./sentry";
Expand All @@ -67,7 +61,6 @@ import { vectorize } from "./vectorize/index";
import { whoami } from "./whoami";

import type { Config } from "./config";
import type { OnlyCamelCase } from "./config/config";
import type { CommonYargsArgv, CommonYargsOptions } from "./yargs-types";
import type Yargs from "yargs";

Expand Down Expand Up @@ -215,11 +208,6 @@ export function createCLIParser(argv: string[]) {
describe: `Experimental: Support wrangler.json`,
type: "boolean",
})
.option("metrics-opt-out", {
describe: `Opt out of crash reports & usage metrics, and remember the choice`,
type: "boolean",
hidden: true,
})
.check((args) => {
// Grab locally specified env params from `.env` file
const loaded = loadDotEnv(".env", args.env);
Expand Down Expand Up @@ -261,24 +249,6 @@ export function createCLIParser(argv: string[]) {
} else {
logger.log(wranglerVersion);
}
} else if (args.metricsOptOut) {
await writeMetricsConfig({
permission: {
enabled: !args.metricsOptOut,
date: CURRENT_METRICS_DATE,
},
});
logger.log(
`${chalk.green(
"Successfully opted out of metrics collection"
)}.\nYour choice has been saved in the following file: ${path.relative(
process.cwd(),
getMetricsConfigPath()
)}.\n\n` +
" You can override the user level setting for a project in `wrangler.toml`:\n\n" +
" - to disable sending metrics for a project: `send_metrics = false`\n" +
" - to enable sending metrics for a project: `send_metrics = true`"
);
} else {
wrangler.showHelp("log");
}
Expand Down Expand Up @@ -737,32 +707,14 @@ export function createCLIParser(argv: string[]) {
return wrangler;
}

export function createConfigArgParser(argv: string[]) {
return makeCLI(argv)
.scriptName("wrangler")

.option("config", {
alias: "c",
describe: "Path to .toml configuration file",
type: "string",
requiresArg: true,
});
}
export async function main(argv: string[]): Promise<void> {
setupSentry();
captureWranglerCommand(argv);
addBreadcrumb(`wrangler ${argv.join(" ")}`);

const wrangler = createCLIParser(argv);
try {
await wrangler.parse();
} catch (e) {
const configParser = createConfigArgParser(argv);
const parsed = await configParser.argv;
const config = readConfig(
parsed.config,
{} as OnlyCamelCase<CommonYargsOptions>
);

logger.log(""); // Just adds a bit of space
if (e instanceof CommandLineArgsError) {
logger.error(e.message);
Expand All @@ -778,7 +730,6 @@ export async function main(argv: string[]): Promise<void> {
text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/workers-sdk/issues/new/choose",
});
logger.log(formatMessage(e));
await captureGlobalException(e, config.send_metrics);
} else if (
e instanceof Error &&
e.message.includes("Raw mode is not supported on")
Expand Down Expand Up @@ -814,7 +765,7 @@ export async function main(argv: string[]): Promise<void> {
`${fgGreenColor}%s${resetColor}`,
"If you think this is a bug then please create an issue at https://github.com/cloudflare/workers-sdk/issues/new/choose"
);
await captureGlobalException(e, config.send_metrics);
await captureGlobalException(e);
}
throw e;
} finally {
Expand Down
49 changes: 20 additions & 29 deletions packages/wrangler/src/metrics/metrics-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { getAPIToken } from "../user";
* This allows us to prompt the user to re-opt-in when we make substantive changes to our metrics
* gathering.
*/
export const CURRENT_METRICS_DATE = new Date(2023, 12, 8);
export const CURRENT_METRICS_DATE = new Date(2022, 6, 4);
export const USER_ID_CACHE_PATH = "user-id.json";

export const getWranglerSendMetricsFromEnv = getEnvironmentVariableFactory({
Expand Down Expand Up @@ -100,7 +100,7 @@ export async function getMetricsConfig({
return { enabled: permission.enabled, deviceId, userId };
} else if (permission.enabled) {
logger.log(
"Usage metrics & crash reporting has changed since you last granted permission."
"Usage metrics tracking has changed since you last granted permission."
);
}
}
Expand All @@ -113,33 +113,24 @@ export async function getMetricsConfig({

// Otherwise, let's ask the user and store the result in the metrics config.
const enabled = await confirm(
"Would you like to help improve Wrangler by automatically sending crash reports & usage metrics to Cloudflare?"
"Would you like to help improve Wrangler by sending usage metrics to Cloudflare?"
);
if (enabled) {
logger.log(
`Your choice has been saved in the following file: ${path.relative(
process.cwd(),
getMetricsConfigPath()
)}.\n\n` +
" You can override the user level setting for a project in `wrangler.toml`:\n\n" +
" - to disable sending metrics for a project: `send_metrics = false`\n" +
" - to enable sending metrics for a project: `send_metrics = true`"
);
writeMetricsConfig({
permission: {
enabled,
date: CURRENT_METRICS_DATE,
},
deviceId,
});
} else {
logger.log(
"Not sending crash reports or usage metrics to Cloudflare. For Wrangler to remember this choice, run `wrangler --metrics-opt-out`.\n\n" +
" You can override the user level setting for a project in `wrangler.toml`:\n\n" +
" - to disable sending metrics for a project: `send_metrics = false`\n" +
" - to enable sending metrics for a project: `send_metrics = true`"
);
}
logger.log(
`Your choice has been saved in the following file: ${path.relative(
process.cwd(),
getMetricsConfigPath()
)}.\n\n` +
" You can override the user level setting for a project in `wrangler.toml`:\n\n" +
" - to disable sending metrics for a project: `send_metrics = false`\n" +
" - to enable sending metrics for a project: `send_metrics = true`"
);
writeMetricsConfig({
permission: {
enabled,
date: CURRENT_METRICS_DATE,
},
deviceId,
});
return { enabled, deviceId, userId };
}

Expand Down Expand Up @@ -175,7 +166,7 @@ export function readMetricsConfig(): MetricsConfigFile {
/**
* Get the path to the metrics config file.
*/
export function getMetricsConfigPath(): string {
function getMetricsConfigPath(): string {
return path.resolve(getGlobalWranglerConfigPath(), "metrics.json");
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import * as Sentry from "@sentry/node";
import { rejectedSyncPromise } from "@sentry/utils";
import { fetch } from "undici";
import { version as wranglerVersion } from "../package.json";
import { logger } from "./logger";
import { getMetricsConfig } from "./metrics";
import { readMetricsConfig } from "./metrics/metrics-config";
import { version as wranglerVersion } from "../../package.json";
import { confirm } from "../dialogs";
import { logger } from "../logger";
import type { BaseTransportOptions, TransportRequest } from "@sentry/types";
import type { RequestInit } from "undici";

let sentryReportingAllowed = false;

// The SENTRY_DSN is provided at esbuild time as a `define` for production and beta releases.
// Otherwise it is left undefined, which disables reporting.
declare const SENTRY_DSN: string;
Expand All @@ -26,8 +27,7 @@ export const makeSentry10Transport = (options: BaseTransportOptions) => {
};

try {
const metricsConfig = readMetricsConfig();
if (metricsConfig.permission?.enabled) {
if (sentryReportingAllowed) {
for (const event of eventQueue) {
void fetch(event[0], event[1]);
}
Expand Down Expand Up @@ -91,26 +91,28 @@ export function setupSentry() {
}
}

export function captureWranglerCommand(argv: string[]) {
export function addBreadcrumb(
message: string,
level: Sentry.SeverityLevel = "log"
) {
if (typeof SENTRY_DSN !== "undefined") {
Sentry.addBreadcrumb({
message: `wrangler ${argv.join(" ")}`,
level: "log",
message,
level,
});
}
}

// Capture top-level Wrangler errors. Also take this opportunity to ask the user for
// consent if not already granted.
export async function captureGlobalException(
e: unknown,
sendMetrics: boolean | undefined
) {
export async function captureGlobalException(e: unknown) {
if (typeof SENTRY_DSN !== "undefined") {
const metricsConfig = await getMetricsConfig({
sendMetrics,
});
if (!metricsConfig.enabled) {
sentryReportingAllowed = await confirm(
"Would you like to report this error to Cloudflare?",
{ fallbackValue: false }
);

if (!sentryReportingAllowed) {
logger.debug(`Sentry: Reporting disabled - would have sent ${e}.`);
return;
}
Expand Down
1 change: 0 additions & 1 deletion packages/wrangler/src/yargs-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export interface CommonYargsOptions {
config: string | undefined;
env: string | undefined;
"experimental-json-config": boolean | undefined;
"metrics-opt-out": boolean | undefined;
}

export type CommonYargsArgv = Argv<CommonYargsOptions>;
Expand Down

0 comments on commit 5cf6267

Please sign in to comment.