Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/vite/deploy-server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,14 @@ describe("adaptvDeployServerPlugins", () => {
.filter(Boolean)
expect(names.length).toBeGreaterThan(0)
//no adaptv-authored wrapper in the chain — the plugins are upstream's own, plus
//the one below, which only rewrites React requires in the SSR environment
//the one below, which only rewrites React requires in the SSR environment, and
//the dev-only re-send of a request whose pooled socket was reset
expect(
names.filter(
(name) =>
name?.startsWith("adaptv:") &&
name !== "adaptv:ssr-react-require-as-import",
name !== "adaptv:ssr-react-require-as-import" &&
name !== "adaptv:dev-ssr-socket-reset-resend",
),
).toEqual([])
})
Expand Down
2 changes: 2 additions & 0 deletions src/vite/deploy-server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Plugin, PluginOption } from "vite"
import { esmExternalRequirePlugin } from "vite"
import { devSsrSocketResetResend } from "#adaptv/vite/dev-ssr-socket-reset.ts"

/**
* The Vite environment the deploy plugin bundles the server into.
Expand Down Expand Up @@ -138,6 +139,7 @@ export async function adaptvDeployServerPlugins(
prerender ? { prerender: PRERENDER } : undefined,
) as PluginOption,
ssrReactRequireAsImport(),
devSsrSocketResetResend(DEPLOY_SERVER_ENVIRONMENT),
]
}

Expand Down
161 changes: 161 additions & 0 deletions src/vite/dev-ssr-socket-reset.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// @vitest-environment node
import { readFileSync, realpathSync } from "node:fs"
import type { Server } from "node:http"
import { createServer } from "node:http"
import type { AddressInfo } from "node:net"
import { dirname, join } from "node:path"
import { fileURLToPath, pathToFileURL } from "node:url"
import type { Plugin } from "vite"
import { afterEach, describe, expect, it, vi } from "vitest"
import {
devSsrSocketResetResend,
resendOnSocketReset,
} from "#adaptv/vite/dev-ssr-socket-reset.ts"

//nitro's own dependency tree, not a copy: the pooled agent under test is the
//module-level one inside the httpxy that env-runner proxies the SSR worker with
const nitroDir = dirname(fileURLToPath(import.meta.resolve("nitro/vite")))
const envRunnerDir = realpathSync(join(nitroDir, "../../env-runner"))
const { proxyFetch } = (await import(
pathToFileURL(
join(realpathSync(join(envRunnerDir, "../httpxy")), "dist/index.mjs"),
).href
)) as {
proxyFetch: (addr: string, input: Request) => Promise<Response>
}

let server: Server | undefined
afterEach(async () => {
const open = server
if (!open) return
open.closeAllConnections()
await new Promise((resolve) => open.close(resolve))
server = undefined
})

/**
* The SSR worker at the moment its keep-alive timer fires: the first request on a
* socket is answered, the next one sent on that same pooled socket is reset. On
* a real server this needs the two to cross within a tick; here it is every time.
*/
async function workerClosingIdleSockets() {
const served = new WeakSet<object>()
let resets = 0
server = createServer((req, res) => {
if (served.has(req.socket) && resets === 0) {
resets++
req.socket.resetAndDestroy()
return
}
served.add(req.socket)
res.end("<div data-adaptv-screen></div>")
})
await new Promise<void>((resolve) =>
server?.listen(0, "127.0.0.1", resolve),
)
const { port } = server.address() as AddressInfo
const addr = `http://127.0.0.1:${port}`
return {
fetch: (input: Request | string | URL) =>
proxyFetch(addr, input as Request),
page: () => new Request(`${addr}/`),
resets: () => resets,
}
}

describe("resendOnSocketReset", () => {
it("a page requested on a socket the worker just reset is the app, not a 500", async () => {
//TUD-5881: `GET /` sent on a pooled socket the worker was closing failed with
//`read ECONNRESET`, and Vite answered the navigation with its error overlay
const worker = await workerClosingIdleSockets()
const first = await worker.fetch(worker.page())
expect(await first.text()).toContain("data-adaptv-screen")

//the upstream path alone: the reused socket's reset is the request's error
await expect(worker.fetch(worker.page())).rejects.toMatchObject({
code: "ECONNRESET",
})
expect(worker.resets()).toBe(1)
})

it("re-sends it once on a fresh socket", async () => {
const worker = await workerClosingIdleSockets()
const fetch = resendOnSocketReset(worker.fetch)
await (await fetch(worker.page())).text()
const second = await fetch(worker.page())
expect(worker.resets()).toBe(1)
expect(second.status).toBe(200)
expect(await second.text()).toContain("data-adaptv-screen")
})

const reset = () =>
Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" })

it("never repeats a POST: a server function could run twice", async () => {
const fetch = vi.fn().mockRejectedValue(reset())
await expect(
resendOnSocketReset(fetch)(
new Request("http://x/_server", { method: "POST", body: "{}" }),
),
).rejects.toMatchObject({ code: "ECONNRESET" })
expect(fetch).toHaveBeenCalledTimes(1)
})

it("leaves any other error, and a second reset, to Vite's error page", async () => {
const other = vi.fn().mockRejectedValue(new Error("render threw"))
await expect(
resendOnSocketReset(other)(new Request("http://x/")),
).rejects.toThrow("render threw")
expect(other).toHaveBeenCalledTimes(1)

const twice = vi.fn().mockRejectedValue(reset())
await expect(
resendOnSocketReset(twice)(new Request("http://x/")),
).rejects.toMatchObject({ code: "ECONNRESET" })
expect(twice).toHaveBeenCalledTimes(2)
})
})

describe("devSsrSocketResetResend", () => {
const configure = (environments: Record<string, unknown>) => {
const plugin = devSsrSocketResetResend("nitro")
// biome-ignore lint/suspicious/noExplicitAny: calling a Vite hook outside Vite
;(plugin.configureServer as any)({ environments })
return plugin
}

it("wraps the fetch of Nitro's dev runner, in dev only", async () => {
const fetch = vi
.fn()
.mockRejectedValueOnce(
Object.assign(new Error("read ECONNRESET"), {
code: "ECONNRESET",
}),
)
.mockResolvedValue(new Response("ok"))
const runner = { fetch }
const plugin: Plugin = configure({ nitro: { devServer: runner } })
expect(plugin.apply).toBe("serve")
expect(runner.fetch).not.toBe(fetch)
expect(
await (await runner.fetch(new Request("http://x/"))).text(),
).toBe("ok")
expect(fetch).toHaveBeenCalledTimes(2)
})

it("does nothing without a Nitro dev environment", () => {
expect(() => configure({})).not.toThrow()
})

it("wraps the call Nitro's dev middleware renders every page through", () => {
//the pinned nitro proxies a page as `nitroEnv.dispatchFetch(req)`, which is
//`this.devServer.fetch(request)`; a bump that moves it would leave the wrap
//above on a function nothing calls
const source = readFileSync(
join(nitroDir, "_build/vite.dev.mjs"),
"utf8",
)
expect(source).toContain("return this.devServer.fetch(request)")
expect(source).toContain("await nitroEnv.dispatchFetch(req)")
})
})
75 changes: 75 additions & 0 deletions src/vite/dev-ssr-socket-reset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type { Plugin } from "vite"

/**
* The dev server re-sends a GET or HEAD once when the socket to Nitro's SSR
* worker was reset under it, instead of answering the page with a 500.
*
* ## The race
*
* In dev, Nitro renders in a worker thread that serves HTTP on `127.0.0.1`
* (env-runner, `srvx`), and the Vite middleware proxies every page request to it
* with httpxy's `proxyFetch`, over sockets pooled in httpxy's module-level
* `keepAlive` agent. The worker's server closes a socket left idle on its own
* keep-alive timer, on another thread. A request written to a pooled socket the
* worker has just closed fails with `read ECONNRESET`: Vite's error middleware
* logs `Internal server error: read ECONNRESET` and the browser gets the
* error-overlay page with a 500, not the app.
*
* MEASURED: the nightly `stress, chromium` cell failed this way (TUD-5881). The
* navigation came ~6 s after the one before it, its `GET /` answered 500 in
* 14 ms, and the page held only the overlay. On an idle machine the agent drops
* its idle socket before the worker does (0 resets in 167 page requests 3.95 to
* 6.05 s apart), so it takes a loaded one — which is where a suite runs.
*
* ## Why a re-send, and why only this one
*
* The request never reached the app, and HTTP lets a client repeat an
* idempotent request whose connection closed before the response arrived
* (RFC 9112 §9.3.1). A POST is not repeated: a server function could run
* twice. Any other error, and a second reset, still reach Vite's error page.
*
* The fix belongs upstream (httpxy's pool or env-runner's worker server); this
* goes when the pinned `nitro` brings one.
*/
export function devSsrSocketResetResend(nitroEnvironment: string): Plugin {
return {
name: "adaptv:dev-ssr-socket-reset-resend",
apply: "serve",
configureServer(server) {
const runner = (
server.environments[nitroEnvironment] as
| { devServer?: { fetch?: unknown } }
| undefined
)?.devServer
//no Nitro dev environment (a spa app): nothing is proxied
if (!runner || typeof runner.fetch !== "function") return
runner.fetch = resendOnSocketReset(
runner.fetch.bind(runner) as SsrFetch,
)
},
}
}

type SsrFetch = (
input: Request | string | URL,
init?: RequestInit,
) => Promise<Response>

const IDEMPOTENT = new Set(["GET", "HEAD"])
const RESET = new Set(["ECONNRESET", "EPIPE"])

export function resendOnSocketReset(fetch: SsrFetch): SsrFetch {
return async (input, init) => {
try {
return await fetch(input, init)
} catch (error) {
const method = (
init?.method ?? (input instanceof Request ? input.method : "GET")
).toUpperCase()
const code = (error as { code?: unknown } | null)?.code
if (!IDEMPOTENT.has(method) || !RESET.has(code as string))
throw error
return fetch(input, init)
}
}
}
Loading