Skip to content

Commit

Permalink
Fix dev-env logging (#6909)
Browse files Browse the repository at this point in the history
  • Loading branch information
penalosa authored Oct 7, 2024
1 parent 30b7328 commit 82180a7
Show file tree
Hide file tree
Showing 10 changed files with 82 additions and 29 deletions.
5 changes: 5 additions & 0 deletions .changeset/gentle-apricots-kiss.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wrangler": patch
---

fix: Various fixes for logging in `--x-dev-env`, primarily to ensure the hotkeys don't wipe useful output and are cleaned up correctly
5 changes: 4 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,7 @@ vscode.*.d.ts
templates/*/build
templates/*/dist

.github/pull_request_template.md
.github/pull_request_template.md

# This file intentionally has a syntax error
fixtures/interactive-dev-tests/src/startup-error.ts
5 changes: 5 additions & 0 deletions fixtures/interactive-dev-tests/src/startup-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
async fetch(): Promise<Response {
return new Response("body");
},
};
43 changes: 34 additions & 9 deletions fixtures/interactive-dev-tests/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const processes: PtyProcess[] = [];
afterEach(() => {
for (const p of processes.splice(0)) {
// If the process didn't exit cleanly, log its output for debugging
if (p.exitCode !== 0) console.log(stripAnsi(p.stdout));
if (p.exitCode !== 0) console.log(p.stdout);
// If the process hasn't exited yet, kill it
if (p.exitCode === null) {
// `node-pty` throws if signal passed on Windows
Expand All @@ -97,7 +97,7 @@ afterEach(() => {
});

const readyRegexp = /Ready on (http:\/\/[a-z0-9.]+:[0-9]+)/;
async function startWranglerDev(args: string[]) {
async function startWranglerDev(args: string[], skipWaitingForReady = false) {
const stdoutStream = new stream.PassThrough();
const stdoutInterface = rl.createInterface(stdoutStream);

Expand Down Expand Up @@ -134,13 +134,14 @@ async function startWranglerDev(args: string[]) {
stdoutStream.end();
});

let readyMatch: RegExpMatchArray | null = null;
for await (const line of stdoutInterface) {
if ((readyMatch = readyRegexp.exec(line)) !== null) break;
if (!skipWaitingForReady) {
let readyMatch: RegExpMatchArray | null = null;
for await (const line of stdoutInterface) {
if ((readyMatch = readyRegexp.exec(line)) !== null) break;
}
assert(readyMatch !== null, "Expected ready message");
result.url = readyMatch[1];
}
assert(readyMatch !== null, "Expected ready message");
result.url = readyMatch[1];

return result;
}

Expand Down Expand Up @@ -196,8 +197,8 @@ function getStartedWorkerdProcesses(): Process[] {
}

const devScripts = [
{ args: ["dev"], expectedBody: "body" },
{ args: ["dev", "--x-dev-env"], expectedBody: "body" },
{ args: ["dev", "--no-x-dev-env"], expectedBody: "body" },
{ args: ["pages", "dev", "public"], expectedBody: "<p>body</p>" },
];
const exitKeys = [
Expand Down Expand Up @@ -228,3 +229,27 @@ describe.each(devScripts)("wrangler $args", ({ args, expectedBody }) => {
}
});
});

it.runIf(RUN_IF && nodePtySupported)(
"hotkeys should be unregistered when the initial build fails",
async () => {
const wrangler = await startWranglerDev(
["dev", "--x-dev-env", "src/startup-error.ts"],
true
);

expect(await wrangler.exitPromise).toBe(1);

const hotkeysRenderCount = [
...wrangler.stdout.matchAll(/\[b\] open a browser/g),
];

const clearHotkeysCount = [
// This is the control sequence for moving the cursor up and then clearing from the cursor to the end
...wrangler.stdout.matchAll(/\[\dA\[0J/g),
];

// The hotkeys should be rendered the same number of times as the control sequence for clearing them from the screen
expect(hotkeysRenderCount.length).toBe(clearHotkeysCount.length);
}
);
2 changes: 1 addition & 1 deletion packages/wrangler/src/cfetch/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ export async function fetchWorker(
});

if (!response.ok || !response.body) {
console.error(response.ok, response.body);
logger.error(response.ok, response.body);
throw new Error(
`Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export default async function guessWorkerFormat(
bundle: false,
write: false,
...(tsconfig && { tsconfig }),
logLevel: "silent",
});

// result.metafile is defined because of the `metafile: true` option above.
Expand Down
38 changes: 25 additions & 13 deletions packages/wrangler/src/dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -399,11 +399,15 @@ This is currently not supported 😭, but we think that we'll get it to work soo
() => startDev(args)
);
if (args.experimentalDevEnv) {
assert(devInstance instanceof DevEnv);
await events.once(devInstance, "teardown");
assert(devInstance.devEnv !== undefined);
await events.once(devInstance.devEnv, "teardown");
if (devInstance.teardownRegistryPromise) {
const teardownRegistry = await devInstance.teardownRegistryPromise;
await teardownRegistry(devInstance.devEnv.config.latestConfig?.name);
}
devInstance.unregisterHotKeys?.();
} else {
assert(!(devInstance instanceof DevEnv));

assert(devInstance.devEnv === undefined);
configFileWatcher = devInstance.configFileWatcher;
assetsWatcher = devInstance.assetsWatcher;

Expand Down Expand Up @@ -546,6 +550,12 @@ export async function startDev(args: StartDevOptions) {
let configFileWatcher: ReturnType<typeof watch> | undefined;
let assetsWatcher: ReturnType<typeof watch> | undefined;
let rerender: (node: React.ReactNode) => void | undefined;
const devEnv = new DevEnv();
let teardownRegistryPromise:
| Promise<(name?: string) => Promise<void>>
| undefined;

let unregisterHotKeys: (() => void) | undefined;
try {
if (args.logLevel) {
logger.loggerLevel = args.logLevel;
Expand Down Expand Up @@ -588,8 +598,6 @@ export async function startDev(args: StartDevOptions) {
args.config ||
(args.script && findWranglerToml(path.dirname(args.script)));

const devEnv = new DevEnv();

if (args.experimentalDevEnv) {
// The ProxyWorker will have a stable host and port, so only listen for the first update
void devEnv.proxy.ready.promise.then(({ url }) => {
Expand All @@ -605,13 +613,10 @@ export async function startDev(args: StartDevOptions) {
});

if (!args.disableDevRegistry) {
const teardownRegistryPromise = devRegistry((registry) =>
teardownRegistryPromise = devRegistry((registry) =>
updateDevEnvRegistry(devEnv, registry)
);
devEnv.once("teardown", async () => {
const teardownRegistry = await teardownRegistryPromise;
await teardownRegistry(devEnv.config.latestConfig?.name);
});

devEnv.runtimes.forEach((runtime) => {
runtime.on(
"reloadComplete",
Expand All @@ -631,7 +636,6 @@ export async function startDev(args: StartDevOptions) {
});
}

let unregisterHotKeys: () => void;
if (isInteractive() && args.showInteractiveDevSession !== false) {
unregisterHotKeys = registerDevHotKeys(devEnv, args);
}
Expand Down Expand Up @@ -784,7 +788,7 @@ export async function startDev(args: StartDevOptions) {
}
);

return devEnv;
return { devEnv, unregisterHotKeys, teardownRegistryPromise };
} else {
const projectRoot = configPath && path.dirname(configPath);
let config = readConfig(configPath, args);
Expand Down Expand Up @@ -1042,6 +1046,14 @@ export async function startDev(args: StartDevOptions) {
await Promise.allSettled([
configFileWatcher?.close(),
assetsWatcher?.close(),
devEnv.teardown(),
(async () => {
if (teardownRegistryPromise) {
const teardownRegistry = await teardownRegistryPromise;
await teardownRegistry(devEnv.config.latestConfig?.name);
}
unregisterHotKeys?.();
})(),
]);
throw e;
}
Expand Down
1 change: 0 additions & 1 deletion packages/wrangler/src/dev/hotkeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ export default function registerDevHotKeys(
keys: ["x", "q", "ctrl+c"],
label: "to exit",
handler: async () => {
unregisterHotKeys();
await devEnv.teardown();
},
},
Expand Down
4 changes: 2 additions & 2 deletions packages/wrangler/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export const logger = new Logger();
export function logBuildWarnings(warnings: Message[]) {
const logs = formatMessagesSync(warnings, { kind: "warning", color: true });
for (const log of logs) {
console.warn(log);
logger.console("warn", log);
}
}

Expand All @@ -192,7 +192,7 @@ export function logBuildWarnings(warnings: Message[]) {
export function logBuildFailure(errors: Message[], warnings: Message[]) {
const logs = formatMessagesSync(errors, { kind: "error", color: true });
for (const log of logs) {
console.error(log);
logger.console("error", log);
}
logBuildWarnings(warnings);
}
7 changes: 5 additions & 2 deletions packages/wrangler/src/utils/log-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,11 @@ ${message}
// TODO(consider): recommend opening an issue with the contents of this file?
if (hasSeenErrorMessage) {
// use console.*warn* here so not to pollute stdout -- some commands print json to stdout
// use *console*.warn here so not to have include the *very* visible bright-yellow [WARNING] indicator
console.warn(`🪵 Logs were written to "${debugLogFilepath}"`);
// use logger.*console*("warn", ...) here so not to have include the *very* visible bright-yellow [WARNING] indicator
logger.console(
"warn",
`🪵 Logs were written to "${debugLogFilepath}"`
);
}
});
}
Expand Down

0 comments on commit 82180a7

Please sign in to comment.