Unverified Commit dcbfff77 authored by Kazma Endo's avatar Kazma Endo Committed by GitHub

fix(next/image): don't share the requester's socket with the internal image response (#98168)

Co-authored-by: 's avatarClaude Fable 5.1 <noreply@anthropic.com>
parent ac55fd99
...@@ -8,7 +8,7 @@ import type { ImageConfigComplete } from '../shared/lib/image-config' ...@@ -8,7 +8,7 @@ import type { ImageConfigComplete } from '../shared/lib/image-config'
import { hasLocalMatch } from '../shared/lib/match-local-pattern' import { hasLocalMatch } from '../shared/lib/match-local-pattern'
import { hasRemoteMatch } from '../shared/lib/match-remote-pattern' import { hasRemoteMatch } from '../shared/lib/match-remote-pattern'
import type { NextConfigComplete, NextConfigRuntime } from './config-shared' import type { NextConfigComplete, NextConfigRuntime } from './config-shared'
import { createRequestResponseMocks } from './lib/mock-request' import { MockedRequest, MockedResponse } from './lib/mock-request'
import type { NextUrlWithParsedQuery } from './request-meta' import type { NextUrlWithParsedQuery } from './request-meta'
import { import {
CachedRouteKind, CachedRouteKind,
...@@ -644,12 +644,24 @@ export async function fetchInternalImage( ...@@ -644,12 +644,24 @@ export async function fetchInternalImage(
// Coerce HEAD to GET to avoid issues with the image optimizer // Coerce HEAD to GET to avoid issues with the image optimizer
const method = !_req.method || _req.method === 'HEAD' ? 'GET' : _req.method const method = !_req.method || _req.method === 'HEAD' ? 'GET' : _req.method
const mocked = createRequestResponseMocks({ // The mocked request keeps the requester's socket so that protocol and
url: href, // remote address detection keep working, but the mocked response must not
method, // reference it. `send` (used by `serveStatic`) watches `res.socket` through
socket: _req.socket, // `on-finished` and treats the response as finished as soon as that socket
maximumResponseBody, // stops being writable. When the requester disconnected mid-transfer this
}) // tore down the file stream without ever ending the mocked response, and
// since `ResponseCache` coalesces every request for the same cache key onto
// this single fetch, the key stayed pending for every later requester until
// the server restarted.
const mocked = {
req: new MockedRequest({
url: href,
method,
headers: {},
socket: _req.socket,
}),
res: new MockedResponse({ maximumResponseBody }),
}
await handleRequest(mocked.req, mocked.res, parseReqUrl(href)) await handleRequest(mocked.req, mocked.res, parseReqUrl(href))
await mocked.res.hasStreamed await mocked.res.hasStreamed
......
...@@ -3,7 +3,13 @@ import { ...@@ -3,7 +3,13 @@ import {
fetchInternalImage, fetchInternalImage,
ImageError, ImageError,
} from 'next/dist/server/image-optimizer' } from 'next/dist/server/image-optimizer'
import { serveStatic } from 'next/dist/server/serve-static'
import { EventEmitter } from 'events'
import { promises as fs } from 'fs'
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import type { Socket } from 'net'
import { tmpdir } from 'os'
import { join } from 'path'
describe('fetchInternalImage', () => { describe('fetchInternalImage', () => {
describe('non-2xx responses', () => { describe('non-2xx responses', () => {
...@@ -206,4 +212,57 @@ describe('fetchInternalImage', () => { ...@@ -206,4 +212,57 @@ describe('fetchInternalImage', () => {
expect(result.buffer.length).toBe(maximumResponseBody) expect(result.buffer.length).toBe(maximumResponseBody)
}) })
}) })
describe('when the requesting client disconnects', () => {
it('should complete the internal fetch even if the requester socket is no longer writable', async () => {
const size = 1024 * 1024
const fileName = 'disconnect.png'
const dir = await fs.mkdtemp(join(tmpdir(), 'fetch-internal-image-'))
await fs.writeFile(join(dir, fileName), Buffer.alloc(size, 1))
try {
// Emulate a requester whose connection already went away. `send`
// (used by `serveStatic`) consults `on-finished`, which treats a
// response as finished as soon as `res.socket.writable` is false.
const closedSocket = Object.assign(new EventEmitter(), {
writable: false,
destroyed: true,
}) as unknown as Socket
const mockReq = {
method: 'GET',
socket: closedSocket,
} as unknown as IncomingMessage
const mockRes = {} as ServerResponse
const handleRequest = (req: IncomingMessage, res: ServerResponse) =>
serveStatic(req, res, fileName, { root: dir })
const result = await Promise.race([
fetchInternalImage(
`/${fileName}`,
mockReq,
mockRes,
300_000_000,
handleRequest
),
new Promise<never>((_resolve, reject) => {
const timer = setTimeout(
() =>
reject(
new Error(
'fetchInternalImage did not settle after the requester disconnected'
)
),
5_000
)
timer.unref()
}),
])
expect(result.buffer.length).toBe(size)
expect(result.contentType).toBe('image/png')
} finally {
await fs.rm(dir, { recursive: true, force: true })
}
})
})
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment