Repository navigation
[vite-plugin v1 backport] Keep deferred imports alive after requests end #17082
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| "@cloudflare/vite-plugin": patch | ||
| --- | ||
|
|
||
| Keep deferred imports alive after their originating request ends | ||
|
|
||
| Retain the module runner's RPC operation until its result is retrieved and cleaned up. This prevents subsequent requests from hanging on a cached import when the first request returns early or its client disconnects. | ||
182 changes: 182 additions & 0 deletions
182
packages/vite-plugin-cloudflare/src/__tests__/import-lifetime.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| import assert from "node:assert"; | ||
| import * as fs from "node:fs/promises"; | ||
| import { get } from "node:http"; | ||
| import { cloudflare } from "@cloudflare/vite-plugin"; | ||
| import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; | ||
| import { CoreHeaders, Miniflare } from "miniflare"; | ||
| import { createServer } from "vite"; | ||
| import { afterEach, beforeEach, describe, test, vi } from "vitest"; | ||
| import type { ClientRequest } from "node:http"; | ||
|
|
||
| describe("deferred import caller lifetime", () => { | ||
| runInTempDir(); | ||
| beforeEach(async () => { | ||
| if (process.platform === "win32") { | ||
| // Unlike runInTempDir's synchronous realpath, this expands Windows 8.3 | ||
| // names such as RUNNER~1 so Vite can resolve modules. | ||
| const root = await fs.realpath(process.cwd()); | ||
| process.chdir(root); | ||
| vi.stubEnv("PWD", root); | ||
| } | ||
| }); | ||
| afterEach(() => vi.unstubAllEnvs()); | ||
|
|
||
| // https://github.com/cloudflare/workers-sdk/issues/16214 | ||
| test.for([ | ||
| { ending: "response completion", outcome: "fulfilled" }, | ||
| { ending: "response completion", outcome: "rejected" }, | ||
| { ending: "client disconnection", outcome: "fulfilled" }, | ||
| ] as const)( | ||
| "settles a cached import as $outcome after $ending", | ||
| async ({ ending, outcome }, { expect, onTestFinished, skip }) => { | ||
| const disconnect = ending === "client disconnection"; | ||
| if (disconnect && process.platform === "win32") { | ||
| // https://github.com/cloudflare/workerd/pull/5062 | ||
| skip( | ||
| "workerd does not notify Workers of client disconnection on Windows" | ||
| ); | ||
| } | ||
| const runtimeReady = vi.spyOn(Miniflare.prototype, "ready", "get"); | ||
| await fs.writeFile( | ||
| "wrangler.json", | ||
| `{ "name": "import-lifetime", "main": "./index.js", "compatibility_date": "2026-04-01", "compatibility_flags": ["enable_request_signal", "request_signal_passthrough"] }` | ||
| ); | ||
| await fs.writeFile( | ||
| "state.js", | ||
| `export const state = { aborted: false, entered: false, released: false, evaluated: false, settled: "pending" };` | ||
| ); | ||
| await fs.writeFile( | ||
| "delayed.js", | ||
| ` | ||
| import { state } from "./state.js"; | ||
| state.entered = true; | ||
| // Poll in the runner's context; the release request only changes shared state. | ||
| while (!state.released) await new Promise(resolve => setTimeout(resolve, 10)); | ||
| state.evaluated = true; | ||
| ${outcome === "rejected" ? 'throw new Error("import-lifetime-rejection");' : ""} | ||
| export const value = "loaded"; | ||
| ` | ||
| ); | ||
| await fs.writeFile( | ||
| "index.js", | ||
| ` | ||
| import { state } from "./state.js"; | ||
| let cached; | ||
| export default { | ||
| async fetch(request) { | ||
| switch (new URL(request.url).pathname) { | ||
| case "/__import-lifetime/kick": | ||
| request.signal.addEventListener("abort", () => { state.aborted = true; }); | ||
| cached = import("./delayed.js"); | ||
| void cached.then( | ||
| () => { state.settled = "fulfilled"; }, | ||
| () => { state.settled = "rejected"; } | ||
| ); | ||
| if (${!disconnect}) return new Response("kicked"); | ||
| break; | ||
| case "/__import-lifetime/release": | ||
| state.released = true; | ||
| return new Response("released"); | ||
| case "/__import-lifetime/state": | ||
| return Response.json(state); | ||
| case "/__import-lifetime/read": | ||
| break; | ||
| default: | ||
| return new Response("ready"); | ||
| } | ||
| try { | ||
| return new Response((await cached).value); | ||
| } catch (error) { | ||
| return new Response(error.message, { status: 500 }); | ||
| } | ||
| } | ||
| }; | ||
| ` | ||
| ); | ||
| const server = await createServer({ | ||
| root: process.cwd(), | ||
| configFile: false, | ||
| logLevel: "silent", | ||
| server: { watch: null }, | ||
| plugins: [ | ||
| cloudflare({ | ||
| inspectorPort: false, | ||
| persistState: false, | ||
| remoteBindings: false, | ||
| }), | ||
| ], | ||
| }); | ||
| onTestFinished(() => server.close()); | ||
| await server.listen(0); | ||
| const url = server.resolvedUrls?.local[0]; | ||
| assert(url); | ||
|
|
||
| function request(pathname: string) { | ||
| return fetch(new URL(`/__import-lifetime/${pathname}`, url), { | ||
| signal: AbortSignal.timeout(5_000), | ||
| }); | ||
| } | ||
|
|
||
| let first: ClientRequest | undefined; | ||
| if (disconnect) { | ||
| const runtime = runtimeReady.mock.contexts[0]; | ||
| assert(runtime instanceof Miniflare); | ||
| // Connect directly to workerd so the reset affects only this request, | ||
| // without depending on Vite's pooled connection to the runtime. | ||
| first = get(new URL("/__import-lifetime/kick", await runtime.ready), { | ||
| agent: false, | ||
| headers: { [CoreHeaders.ROUTE_OVERRIDE]: "import-lifetime" }, | ||
| }); | ||
| first.on("error", () => {}); // Resetting the connection produces ECONNRESET. | ||
| first.on("response", (response) => response.resume()); | ||
| onTestFinished(() => { | ||
| first?.destroy(); | ||
| }); | ||
| } else { | ||
| expect(await (await request("kick")).text()).toBe("kicked"); | ||
| } | ||
| await vi.waitFor( | ||
| async () => { | ||
| expect(await (await request("state")).json()).toMatchObject({ | ||
| entered: true, | ||
| evaluated: false, | ||
| settled: "pending", | ||
| }); | ||
| }, | ||
| { timeout: 10_000 } | ||
| ); | ||
| if (first) { | ||
| assert(first.socket); | ||
| first.socket.resetAndDestroy(); | ||
| await vi.waitFor( | ||
| async () => { | ||
| expect(await (await request("state")).json()).toMatchObject({ | ||
| aborted: true, | ||
| evaluated: false, | ||
| settled: "pending", | ||
| }); | ||
| }, | ||
| { timeout: 10_000 } | ||
| ); | ||
| } | ||
| expect(await (await request("release")).text()).toBe("released"); | ||
| await vi.waitFor( | ||
| async () => { | ||
| expect(await (await request("state")).json()).toMatchObject({ | ||
| evaluated: true, | ||
| }); | ||
| }, | ||
| { timeout: 10_000 } | ||
| ); | ||
|
|
||
| const response = await request("read"); | ||
| expect(response.status).toBe(outcome === "fulfilled" ? 200 : 500); | ||
| expect(await response.text()).toBe( | ||
| outcome === "fulfilled" ? "loaded" : "import-lifetime-rejection" | ||
| ); | ||
| expect(await (await request("state")).json()).toMatchObject({ | ||
| settled: outcome, | ||
| }); | ||
| } | ||
| ); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.