Skip to content

Commit

Permalink
restore logging & enable tests
Browse files Browse the repository at this point in the history
  • Loading branch information
penalosa committed May 30, 2024
1 parent 4a87a51 commit c678631
Show file tree
Hide file tree
Showing 7 changed files with 123 additions and 98 deletions.
2 changes: 1 addition & 1 deletion fixtures/worker-ts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ export default {
): Promise<Response> {
const url = new URL(request.url);
if (url.pathname === "/error") throw new Error("Hello Error");
return new Response("Hello World!");
return new Response("no no no World!");
},
};
8 changes: 8 additions & 0 deletions packages/wrangler/e2e/__snapshots__/dev.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`basic js dev: 'wrangler dev --remote --x-devenv-runt…' > can modify worker during wrangler dev --remote --x-devenv-runtime 1`] = `"Hello World!"`;

exports[`basic js dev: 'wrangler dev --remote --x-devenv-runt…' > can modify worker during wrangler dev --remote --x-devenv-runtime 2`] = `"Updated Worker! value"`;

exports[`basic js dev: 'wrangler dev --remote' > can modify worker during wrangler dev --remote 1`] = `"Hello World!"`;

exports[`basic js dev: 'wrangler dev --remote' > can modify worker during wrangler dev --remote 2`] = `"Updated Worker! value"`;

exports[`basic js dev: 'wrangler dev --x-devenv-runtime' > can modify worker during wrangler dev --x-devenv-runtime 1`] = `"Hello World!"`;

exports[`basic js dev: 'wrangler dev --x-devenv-runtime' > can modify worker during wrangler dev --x-devenv-runtime 2`] = `"Updated Worker! value"`;

exports[`basic js dev: 'wrangler dev' > can modify worker during wrangler dev 1`] = `"Hello World!"`;

exports[`basic js dev: 'wrangler dev' > can modify worker during wrangler dev 2`] = `"Updated Worker! value"`;
1 change: 1 addition & 0 deletions packages/wrangler/e2e/dev-with-resources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,7 @@ describe.each(RUNTIMES)("Bindings: $flags", ({ runtime, flags }) => {
"src/index.ts": dedent`
export default {
async fetch(request, env, ctx) {
console.log(await env.NAMESPACE.list())
const value = await env.NAMESPACE.get("existing-key");
await env.NAMESPACE.put("new-key", "new-value");
return new Response(value);
Expand Down
170 changes: 86 additions & 84 deletions packages/wrangler/e2e/dev.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,17 @@ e2eTest(
}
);

describe.each([{ cmd: "wrangler dev" }, { cmd: "wrangler dev --remote" }])(
"basic js dev: $cmd",
({ cmd }) => {
e2eTest(
`can modify worker during ${cmd}`,
async ({ run, seed, waitForReady, waitForReload }) => {
await seed({
"wrangler.toml": dedent`
describe.each([
{ cmd: "wrangler dev" },
{ cmd: "wrangler dev --remote" },
{ cmd: "wrangler dev --x-devenv-runtime" },
{ cmd: "wrangler dev --remote --x-devenv-runtime" },
])("basic js dev: $cmd", ({ cmd }) => {
e2eTest(
`can modify worker during ${cmd}`,
async ({ run, seed, waitForReady, waitForReload }) => {
await seed({
"wrangler.toml": dedent`
name = "worker"
main = "src/index.ts"
compatibility_date = "2023-01-01"
Expand All @@ -62,158 +65,157 @@ describe.each([{ cmd: "wrangler dev" }, { cmd: "wrangler dev --remote" }])(
[vars]
KEY = "value"
`,
"src/index.ts": dedent`
"src/index.ts": dedent`
export default {
fetch(request) {
return new Response("Hello World!")
}
}`,
"package.json": dedent`
"package.json": dedent`
{
"name": "worker",
"version": "0.0.0",
"private": true
}
`,
});
const worker = run(cmd);
});
const worker = run(cmd);

const { url } = await waitForReady(worker);
const { url } = await waitForReady(worker);

await expect(
fetch(url).then((r) => r.text())
).resolves.toMatchSnapshot();
await expect(fetch(url).then((r) => r.text())).resolves.toMatchSnapshot();

await seed({
"src/index.ts": dedent`
await seed({
"src/index.ts": dedent`
export default {
fetch(request, env) {
return new Response("Updated Worker! " + env.KEY)
}
}`,
});
});

await waitForReload(worker);
await waitForReload(worker);

await expect(fetchText(url)).resolves.toMatchSnapshot();
}
);
}
);
await expect(fetchText(url)).resolves.toMatchSnapshot();
}
);
});

describe.each([{ cmd: "wrangler dev" }, { cmd: "wrangler dev --remote" }])(
"basic python dev: $cmd",
({ cmd }) => {
e2eTest(
`can modify entrypoint during ${cmd}`,
async ({ run, seed, waitForReady, waitForReload }) => {
await seed({
"wrangler.toml": dedent`
describe.each([
{ cmd: "wrangler dev" },
{ cmd: "wrangler dev --remote" },
{ cmd: "wrangler dev --x-devenv-runtime" },
{ cmd: "wrangler dev --remote --x-devenv-runtime" },
])("basic python dev: $cmd", ({ cmd }) => {
e2eTest(
`can modify entrypoint during ${cmd}`,
async ({ run, seed, waitForReady, waitForReload }) => {
await seed({
"wrangler.toml": dedent`
name = "worker"
main = "index.py"
compatibility_date = "2023-01-01"
compatibility_flags = ["python_workers"]
`,
"arithmetic.py": dedent`
"arithmetic.py": dedent`
def mul(a,b):
return a*b`,
"index.py": dedent`
"index.py": dedent`
from arithmetic import mul
from js import Response
def on_fetch(request):
return Response.new(f"py hello world {mul(2,3)}")`,
"package.json": dedent`
"package.json": dedent`
{
"name": "worker",
"version": "0.0.0",
"private": true
}
`,
});
const worker = run(cmd);
});
const worker = run(cmd);

const { url } = await waitForReady(worker);
const { url } = await waitForReady(worker);

await expect(fetchText(url)).resolves.toBe("py hello world 6");
await expect(fetchText(url)).resolves.toBe("py hello world 6");

await seed({
"index.py": dedent`
await seed({
"index.py": dedent`
from js import Response
def on_fetch(request):
return Response.new('Updated Python Worker value')`,
});
});

await waitForReload(worker);
await waitForReload(worker);

// TODO(soon): work out why python workers need this retry before returning new content
const { text } = await retry(
(s) => s.status !== 200 || s.text === "py hello world 6",
async () => {
const r = await fetch(url);
return { text: await r.text(), status: r.status };
}
);
// TODO(soon): work out why python workers need this retry before returning new content
const { text } = await retry(
(s) => s.status !== 200 || s.text === "py hello world 6",
async () => {
const r = await fetch(url);
return { text: await r.text(), status: r.status };
}
);

expect(text).toBe("Updated Python Worker value");
}
);
expect(text).toBe("Updated Python Worker value");
}
);

e2eTest(
`can modify imports during ${cmd}`,
async ({ run, seed, waitForReady, waitForReload }) => {
await seed({
"wrangler.toml": dedent`
e2eTest(
`can modify imports during ${cmd}`,
async ({ run, seed, waitForReady, waitForReload }) => {
await seed({
"wrangler.toml": dedent`
name = "worker"
main = "index.py"
compatibility_date = "2023-01-01"
compatibility_flags = ["python_workers"]
`,
"arithmetic.py": dedent`
"arithmetic.py": dedent`
def mul(a,b):
return a*b`,
"index.py": dedent`
"index.py": dedent`
from arithmetic import mul
from js import Response
def on_fetch(request):
return Response.new(f"py hello world {mul(2,3)}")`,
"package.json": dedent`
"package.json": dedent`
{
"name": "worker",
"version": "0.0.0",
"private": true
}
`,
});
const worker = run(cmd);
});
const worker = run(cmd);

const { url } = await waitForReady(worker);
const { url } = await waitForReady(worker);

await expect(fetchText(url)).resolves.toBe("py hello world 6");
await expect(fetchText(url)).resolves.toBe("py hello world 6");

await seed({
"arithmetic.py": dedent`
await seed({
"arithmetic.py": dedent`
def mul(a,b):
return a+b`,
});
});

await waitForReload(worker);
await waitForReload(worker);

// TODO(soon): work out why python workers need this retry before returning new content
const { text } = await retry(
(s) => s.status !== 200 || s.text === "py hello world 6",
async () => {
const r = await fetch(url);
return { text: await r.text(), status: r.status };
}
);
// TODO(soon): work out why python workers need this retry before returning new content
const { text } = await retry(
(s) => s.status !== 200 || s.text === "py hello world 6",
async () => {
const r = await fetch(url);
return { text: await r.text(), status: r.status };
}
);

expect(text).toBe("py hello world 5");
}
);
}
);
expect(text).toBe("py hello world 5");
}
);
});

describe("dev registry", () => {
let a: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import chalk from "chalk";
import { Miniflare, Mutex } from "miniflare";
import { getLocalPersistencePath } from "../../dev/get-local-persistence-path";
import * as MF from "../../dev/miniflare";
import { logger } from "../../logger";
import { RuntimeController } from "./BaseController";
import { castErrorCause } from "./events";
import { convertBindingsToCfWorkerInitBindings } from "./utils";
Expand All @@ -14,7 +16,7 @@ import type {
ReloadCompleteEvent,
ReloadStartEvent,
} from "./events";
import type { File, ServiceFetch, StartDevWorkerOptions } from "./types";
import type { File, StartDevWorkerOptions } from "./types";

async function getBinaryFileContents(file: File<string | Uint8Array>) {
if ("contents" in file) {
Expand Down Expand Up @@ -169,8 +171,12 @@ export class LocalRuntimeController extends RuntimeController {
this.#proxyToUserWorkerAuthenticationSecret
);
if (this.#mf === undefined) {
logger.log(chalk.dim("⎔ Starting local server..."));

this.#mf = new Miniflare(options);
} else {
logger.log(chalk.dim("⎔ Reloading local server..."));

await this.#mf.setOptions(options);
}
// All asynchronous `Miniflare` methods will wait for all `setOptions()`
Expand All @@ -184,6 +190,7 @@ export class LocalRuntimeController extends RuntimeController {
if (id !== this.#currentBundleId) {
return;
}

// Get entrypoint addresses
const entrypointAddresses: WorkerEntrypointsDefinition = {};
for (const name of entrypointNames) {
Expand Down Expand Up @@ -251,6 +258,8 @@ export class LocalRuntimeController extends RuntimeController {
}

#teardown = async (): Promise<void> => {
logger.log(chalk.dim("⎔ Shutting down local server..."));

await this.#mf?.dispose();
this.#mf = undefined;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import chalk from "chalk";
import { Mutex } from "miniflare";
import {

Check failure on line 3 in packages/wrangler/src/api/startDevWorker/RemoteRuntimeController.ts

View workflow job for this annotation

GitHub Actions / Checks (ubuntu-latest)

Imports "CfPreviewSession" and "CfPreviewToken" are only used as types

Check failure on line 3 in packages/wrangler/src/api/startDevWorker/RemoteRuntimeController.ts

View workflow job for this annotation

GitHub Actions / Checks (macos-13)

Imports "CfPreviewSession" and "CfPreviewToken" are only used as types
CfPreviewSession,
Expand Down Expand Up @@ -165,6 +166,10 @@ export class RemoteRuntimeController extends RuntimeController {
}
const auth = await unwrapHook(config.dev.auth);

if (this.#session) {
logger.log(chalk.dim("⎔ Detected changes, restarted server."));
}

this.#session ??= await this.#previewSession({
accountId: auth.accountId,
env: config.env, // deprecated service environments -- just pass it through for now
Expand Down
24 changes: 12 additions & 12 deletions packages/wrangler/src/dev/local.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,18 +142,6 @@ export function maybeRegisterLocalWorker(
}

export function Local(props: LocalProps) {
if (!props.experimentalDevenvRuntime) {
// this condition WILL be static and therefore safe to wrap around a hook
useLocalWorker(props);
}

return null;
}

function useLocalWorker(props: LocalProps) {
const miniflareServerRef = useRef<MiniflareServer>();
const removeMiniflareServerExitListenerRef = useRef<() => void>();

useEffect(() => {
if (props.bindings.services && props.bindings.services.length > 0) {
logger.warn(
Expand All @@ -174,6 +162,18 @@ function useLocalWorker(props: LocalProps) {
}
}, [props.bindings.durable_objects?.bindings]);

if (!props.experimentalDevenvRuntime) {
// this condition WILL be static and therefore safe to wrap around a hook
useLocalWorker(props);

Check failure on line 167 in packages/wrangler/src/dev/local.tsx

View workflow job for this annotation

GitHub Actions / Checks (ubuntu-latest)

React Hook "useLocalWorker" is called conditionally. React Hooks must be called in the exact same order in every component render

Check failure on line 167 in packages/wrangler/src/dev/local.tsx

View workflow job for this annotation

GitHub Actions / Checks (macos-13)

React Hook "useLocalWorker" is called conditionally. React Hooks must be called in the exact same order in every component render
}

return null;
}

function useLocalWorker(props: LocalProps) {
const miniflareServerRef = useRef<MiniflareServer>();
const removeMiniflareServerExitListenerRef = useRef<() => void>();

useEffect(() => {
const abortController = new AbortController();

Expand Down

0 comments on commit c678631

Please sign in to comment.