vercel/next.js · #102405
[image-optimizer] Add request cancellation support when using nsio
docs/01-app/03-api-reference/04-functions/image-optimizer-transform.mdx12 + / 2 −
@@ -85,6 +85,7 @@ All fields are optional. | `timeoutInSeconds` | `number` | `7` | Per-image processing timeout. | | `mozjpeg` | `boolean` | `true` | Encodes JPEG output with mozjpeg. Much slower, but produces smaller files. | | `safeImageOptimization` | `boolean` | `false` | Optimizes with `@next/safe-image-optimization` instead of sharp. |+| `signal` | `AbortSignal` | `undefined` | With `safeImageOptimization`, aborting stops in-progress work and rejects with `signal.reason`. sharp can't be interrupted, so with sharp the optimized image is still returned. | | `logger` | `object` | `undefined` | A logger with `error(...args)` and `warnOnce(message)`. When omitted, no logging occurs. | [`sequentialRead`]: https://sharp.pixelplumbing.com/api-constructor/#new@@ -116,7 +117,7 @@ The function runs the following steps in order: 5. Returns SVG, ICO, ICNS, BMP, JXL, and HEIC sources unmodified. 6. Selects the output type: `paramsResult.mimeType` when non-empty, `image/jpeg` for WebP or AVIF sources when no type is requested, otherwise the detected source type. 7. Resizes and re-encodes the image. The output is auto-rotated according to the EXIF orientation of the source image.-8. On failure, returns the upstream buffer and content type with `maxAge` set to `opts.minimumCacheTTL` and the caught value on `result.error`. The failure does not throw.+8. On failure, returns the upstream buffer and content type with `maxAge` set to `opts.minimumCacheTTL` and the caught value on `result.error`. The failure does not throw, unless `opts.signal` was aborted, which rejects with `signal.reason`. ### getMaxAge @@ -165,9 +166,18 @@ The error type thrown by `imageOptimizerTransform` for invalid input. `statusCod - `sharp` is not used if `safeImageOptimization` is enabled. - The module intentionally imports very little so it loads quickly in a separate process, such as a worker or child process. Its file location and exports are a stable public contract. - The `contentType` field of `imageUpstream` is not used for detection. The content type is detected from the first bytes of the buffer.-- Optimization failures do not throw. `imageOptimizerTransform` returns the upstream buffer with `error` set on the result.+- If the transformation is not aborted and fails, `imageOptimizerTransform` returns the upstream buffer with `error` set on the result.+- If the transformation is successfully aborted using the `AbortSignal`, the promise is rejected with `signal.reason`. - Animated WebP, PNG, and GIF images are returned unoptimized. SVG, ICO, ICNS, BMP, JXL, and HEIC images are always passed through without optimization. +### Cancellation++To stop optimizing when the client disconnects, pass in the `AbortSignal` on `request.signal` to `opts.signal`.++Some platforms require [explicitly enabling request cancellation](https://vercel.com/docs/functions/functions-api-reference#cancel-requests). After a cancellation, a serverless function's execution context can be reclaimed at any time, so wrap any cache writes in [`after`](/docs/app/api-reference/functions/after).++If using a cache with request coalescing, you should avoid cancellation of coalesced requests.+ ## Examples ### Optimizing a fetched imagepackages/next/src/build/templates/app-page-runtime.ts3 + / 3 −
@@ -1482,7 +1482,7 @@ export function createAppPageEntrypoint({ // We don't have a prior entry for this param-specific shell. null, hasResolved,- ctx.waitUntil+ { waitUntil: ctx.waitUntil } ) if (result !== null && 'error' in result) { throw result.error@@ -1566,7 +1566,7 @@ export function createAppPageEntrypoint({ (c) => responseGenerator({ ...c, forceStaticRender: true }), null, hasResolved,- ctx.waitUntil+ { waitUntil: ctx.waitUntil } ) if (result !== null && 'error' in result) { return result@@ -1651,7 +1651,7 @@ export function createAppPageEntrypoint({ // change this request's revalidation mode. null, hasResolved,- ctx.waitUntil+ { waitUntil: ctx.waitUntil } ) if (result !== null && 'error' in result) { throw result.errorpackages/next/src/lib/batcher.test.ts109 + / 0 −
@@ -75,4 +75,113 @@ describe('Batcher', () => { expect(workFn).toHaveBeenCalledTimes(1) }) })++ describe('batch with a signal', () => {+ function deferredWork() {+ let resolve!: (value: number) => void+ let workSignal: AbortSignal | undefined+ const workFn = jest.fn(({ signal }: { signal?: AbortSignal }) => {+ workSignal = signal+ return new Promise<number>((r) => {+ resolve = r+ })+ })+ return {+ workFn,+ resolve: (v: number) => resolve(v),+ workSignal: () => workSignal,+ }+ }++ it("doesn't abort work while another caller waits on it", async () => {+ const batcher = Batcher.create<string, number>()+ const work = deferredWork()+ const a = new AbortController()+ const b = new AbortController()++ const resultA = batcher.batch('key', work.workFn, a.signal)+ const resultB = batcher.batch('key', work.workFn, b.signal)+ await Promise.resolve()++ a.abort()+ expect(work.workSignal()!.aborted).toBe(false)++ // The aborted caller still gets the result+ work.resolve(42)+ await expect(resultA).resolves.toBe(42)+ await expect(resultB).resolves.toBe(42)+ expect(work.workFn).toHaveBeenCalledTimes(1)+ })++ it('starts new work for later callers once every caller aborts', async () => {+ const batcher = Batcher.create<string, number>()+ const first = deferredWork()+ const a = new AbortController()+ const b = new AbortController()++ const resultA = batcher.batch('key', first.workFn, a.signal)+ const resultB = batcher.batch('key', first.workFn, b.signal)+ await Promise.resolve()+ a.abort()+ b.abort(new Error('b left'))+ expect(first.workSignal()!.aborted).toBe(true)+ expect(first.workSignal()!.reason).toEqual(new Error('b left'))++ // The aborted work hasn't settled yet, but isn't joined+ const second = deferredWork()+ const resultC = batcher.batch('key', second.workFn)+ await Promise.resolve()+ expect(second.workFn).toHaveBeenCalledTimes(1)+ expect(second.workSignal()).toBeUndefined()++ // Work that ignores the abort still passes its result through, and+ // settling it doesn't remove the new work+ first.resolve(1)+ await expect(resultA).resolves.toBe(1)+ await expect(resultB).resolves.toBe(1)+ const resultD = batcher.batch('key', second.workFn)+ await Promise.resolve()+ expect(second.workFn).toHaveBeenCalledTimes(1)++ second.resolve(2)+ await expect(resultC).resolves.toBe(2)+ await expect(resultD).resolves.toBe(2)+ })++ it("doesn't abort work that a caller without a signal joined", async () => {+ const batcher = Batcher.create<string, number>()+ const work = deferredWork()+ const a = new AbortController()++ const resultA = batcher.batch('key', work.workFn, a.signal)+ const resultB = batcher.batch('key', work.workFn)+ await Promise.resolve()+ a.abort()+ expect(work.workSignal()!.aborted).toBe(false)++ work.resolve(42)+ await expect(resultA).resolves.toBe(42)+ await expect(resultB).resolves.toBe(42)+ })++ it("doesn't run work that every caller aborted before it was scheduled", async () => {+ const scheduled: Array<() => void> = []+ const batcher = Batcher.create<string, number>({+ schedulerFn: (fn) => {+ scheduled.push(fn)+ },+ })+ const workFn = jest.fn().mockResolvedValue(42)+ const a = new AbortController()+ const reason = new Error('left before scheduling')++ const result = batcher.batch('key', workFn, a.signal)+ await Promise.resolve()+ a.abort(reason)+ scheduled.forEach((fn) => fn())++ await expect(result).rejects.toBe(reason)+ expect(workFn).not.toHaveBeenCalled()+ })+ }) })packages/next/src/lib/batcher.ts92 + / 9 −
@@ -14,16 +14,39 @@ type BatcherOptions<K, C extends string | number | null> = { type WorkFnContext<V, K> = { resolve: (value: V | PromiseLike<V>) => void key: K+ /**+ * Aborts once every caller waiting on this work has aborted. `undefined` if+ * the first caller didn't pass a signal. If a later caller doesn't pass one,+ * this never aborts, as the work can't be abandoned then.+ */+ signal: AbortSignal | undefined } type WorkFn<V, K> = (context: WorkFnContext<V, K>) => Promise<V> +type Pending<V> = {+ promise: Promise<V>+ /** Only defined if all callers of the batch were given an AbortSignal */+ abortable:+ | {+ /** The controller for the underlying work item */+ controller: AbortController+ /**+ * Count of callers with a signal that are still waiting to prevent+ * aborting coalesced work items if only some of the callers have+ * cancelled.+ */+ waiting: number+ }+ | undefined+}+ /** * A wrapper for a function that will only allow one call to the function to * execute at a time. */ export class Batcher<K, V, C extends string | number | null> {- private readonly pending = new Map<C, Promise<V>>()+ private readonly pending = new Map<C, Pending<V>>() protected constructor( private readonly cacheKeyFn?: CacheKeyFn<K, C>,@@ -59,36 +82,96 @@ export class Batcher<K, V, C extends string | number | null> { * made, but only one will be executed at a time. The result of the first * call will be returned to all callers. *+ * Once every caller waiting on the work has aborted, the work's own signal+ * aborts and later calls start new work rather than joining it. Callers+ * still get the work's result or rejection, so work that finishes despite+ * the abort still resolves.+ * * @param key the key to use for the cache * @param fn the function to wrap+ * @param signal rejects immediately if already aborted, otherwise counts+ * this caller as no longer needing the result once it aborts * @returns a promise that resolves to the result of the function */- public async batch(key: K, fn: WorkFn<V, K>): Promise<V> {+ public async batch(+ key: K,+ fn: WorkFn<V, K>,+ signal?: AbortSignal+ ): Promise<V> { const cacheKey = (this.cacheKeyFn ? await this.cacheKeyFn(key) : key) as C+ signal?.throwIfAborted()+ if (cacheKey === null) {- return fn({ resolve: (value) => Promise.resolve(value), key })+ // Without a key, calls aren't batched, so `fn` gets the caller's signal+ return fn({ resolve: (value) => Promise.resolve(value), key, signal })+ }++ const entry =+ this.pending.get(cacheKey) ?? this.start(cacheKey, key, fn, signal)++ if (!signal) {+ // if we get a call that is not abortable, a previously-abortable work+ // item is no longer abortable.+ entry.abortable = undefined+ return entry.promise+ }+ const { abortable } = entry+ if (!abortable) {+ return entry.promise } - const pending = this.pending.get(cacheKey)- if (pending) return pending+ abortable.waiting+++ const abort = () => {+ // A caller without a signal may have joined since, clearing `abortable`+ if (!entry.abortable || --abortable.waiting > 0) return+ // Nobody is waiting on the result anymore, so stop the work, and don't+ // coalesce new callers with the aborted work item+ this.removePending(cacheKey, entry)+ abortable.controller.abort(signal.reason)+ }+ signal.addEventListener('abort', abort, { once: true })+ return entry.promise.finally(() =>+ signal.removeEventListener('abort', abort)+ )+ } + private start(+ cacheKey: C,+ key: K,+ fn: WorkFn<V, K>,+ signal: AbortSignal | undefined+ ): Pending<V> { const { promise, resolve, reject } = createPromiseWithResolvers<V>()- this.pending.set(cacheKey, promise)+ const abortable = signal+ ? { controller: new AbortController(), waiting: 0 }+ : undefined+ const entry: Pending<V> = { promise, abortable }+ this.pending.set(cacheKey, entry) + const workSignal = abortable?.controller.signal this.schedulerFn(async () => { try {- const result = await fn({ resolve, key })+ // Every caller may have aborted before the scheduler ran this+ workSignal?.throwIfAborted()+ const result = await fn({ resolve, key, signal: workSignal }) // Resolving a promise multiple times is a no-op, so we can safely // resolve all pending promises with the same result. resolve(result) } catch (err) { reject(err) } finally {- this.pending.delete(cacheKey)+ this.removePending(cacheKey, entry) } }) - return promise+ return entry+ }++ private removePending(cacheKey: C, entry: Pending<V>) {+ // Aborted work is removed early, so new work may have replaced it+ if (this.pending.get(cacheKey) === entry) {+ this.pending.delete(cacheKey)+ } } }packages/next/src/server/image-optimizer.ts50 + / 21 −
@@ -828,7 +828,8 @@ export async function fetchExternalImage( href: string, dangerouslyAllowLocalIP: boolean, maximumResponseBody: number,- count = 3+ count = 3,+ abortSignal?: AbortSignal ): Promise<ImageUpstream> { const url = new URL(href) // `URL.hostname` keeps the brackets around an IPv6 literal, the socket does not@@ -867,11 +868,23 @@ export async function fetchExternalImage( } } - // The signal is owned here rather than by `requestUpstreamImage()` because it- // has to stay readable while the body streams. Node reports an abort during- // the body as a plain `ECONNRESET` on the response, so the signal is the only- // way to tell a timeout apart from the upstream resetting the connection.- const signal = AbortSignal.timeout(agentOptions.timeout)+ // The signals are owned here rather than by `requestUpstreamImage()` because+ // they have to stay readable while the body streams. Node reports an abort+ // during the body as a plain `ECONNRESET` on the response, so the signals are+ // the only way to tell a timeout or abort apart from the upstream resetting+ // the connection.+ const timeoutSignal = AbortSignal.timeout(agentOptions.timeout)+ const signal = abortSignal+ ? AbortSignal.any([timeoutSignal, abortSignal])+ : timeoutSignal+ const toAbortError = (err: unknown) => {+ // Our own errors (e.g. an oversized body) were not caused by the signal,+ // even if it happened to abort around the same time+ if (err instanceof ImageError) return err+ if (abortSignal?.aborted) return abortSignal.reason+ if (timeoutSignal.aborted) return upstreamTimedOut(href)+ return err+ } let res: IncomingMessage try { res = await requestUpstreamImage(@@ -882,10 +895,7 @@ export async function fetchExternalImage( signal ) } catch (err) {- if (signal.aborted) {- throw upstreamTimedOut(href)- }- throw err+ throw toAbortError(err) } const statusCode = res.statusCode@@ -916,7 +926,8 @@ export async function fetchExternalImage( redirect, dangerouslyAllowLocalIP, maximumResponseBody,- count - 1+ count - 1,+ abortSignal ) } @@ -953,10 +964,7 @@ export async function fetchExternalImage( } } catch (err) { res.destroy()- if (signal.aborted) {- throw upstreamTimedOut(href)- }- throw err+ throw toAbortError(err) } if (totalSize === 0) {@@ -984,9 +992,12 @@ export async function fetchInternalImage( newParsedUrl?: NextUrlWithParsedQuery ) => Promise<void>, imagesConfig: ImageConfigComplete,- count = imagesConfig.maximumRedirects+ count = imagesConfig.maximumRedirects,+ abortSignal?: AbortSignal ): Promise<ImageUpstream> { try {+ abortSignal?.throwIfAborted()+ // Coerce HEAD to GET to avoid issues with the image optimizer const method = !_req.method || _req.method === 'HEAD' ? 'GET' : _req.method @@ -1011,8 +1022,21 @@ export async function fetchInternalImage( }), } - await handleRequest(mocked.req, mocked.res, parseReqUrl(href))- await mocked.res.hasStreamed+ // Destroying the mocked response rejects `hasStreamed` with the abort+ // reason, and stops whatever is writing to it (it also aborts the+ // `request.signal` of a route handler serving the image).+ const onAbort = () => mocked.res.destroy(abortSignal?.reason)+ abortSignal?.addEventListener('abort', onAbort, { once: true })+ try {+ // Not awaited in sequence, as `handleRequest` may never settle once the+ // response is destroyed+ await Promise.all([+ handleRequest(mocked.req, mocked.res, parseReqUrl(href)),+ mocked.res.hasStreamed,+ ])+ } finally {+ abortSignal?.removeEventListener('abort', onAbort)+ } const locationHeader = mocked.res.getHeader('Location') if (@@ -1041,15 +1065,17 @@ export async function fetchInternalImage( _res, handleRequest, imagesConfig,- count - 1+ count - 1,+ abortSignal ) } return fetchExternalImage( urlResult.href, imagesConfig.dangerouslyAllowLocalIP, imagesConfig.maximumResponseBody,- count - 1+ count - 1,+ abortSignal ) } @@ -1084,7 +1110,10 @@ export async function fetchInternalImage( return { buffer, contentType, cacheControl, etag } } catch (err) {- if (err instanceof ImageError) {+ if (+ err instanceof ImageError ||+ (abortSignal?.aborted && err === abortSignal.reason)+ ) { throw err } packages/next/src/server/image-optimizer/nsio.ts3 + / 1 −
@@ -53,6 +53,7 @@ export async function nsioOptimizeImage({ maxInputPixels, timeoutInSeconds, mozjpeg = true,+ signal, logger, }: { buffer: Buffer@@ -63,6 +64,7 @@ export async function nsioOptimizeImage({ maxInputPixels?: number timeoutInSeconds: number mozjpeg?: boolean+ signal?: AbortSignal logger?: { warnOnce(message: string): void } }): Promise<Buffer> { if (!NSIO_OUTPUT_MIME_TYPES.includes(contentType)) {@@ -101,5 +103,5 @@ export async function nsioOptimizeImage({ ) } - return pipeline.toBuffer()+ return pipeline.toBuffer({ signal }) }packages/next/src/server/image-optimizer/transform.ts13 + / 0 −
@@ -81,6 +81,14 @@ export interface ImageOptimizerTransformOptions { * Defaults to `false`. */ safeImageOptimization?: boolean+ /**+ * With `safeImageOptimization`, this stops in-progress work (killing the+ * worker process or thread). sharp can't be interrupted.+ *+ * If optimization fails after `signal` aborts, the transform rejects with+ * `signal.reason` instead of falling back to the unoptimized image.+ */+ signal?: AbortSignal logger?: ImageOptimizerTransformLogger } @@ -193,6 +201,11 @@ export async function imageOptimizerTransform( optimized: true, } } catch (error) {+ // Only an abort rejects. Other failures still fall back, even if the signal+ // happened to abort around the same time.+ if (opts.signal?.aborted && error === opts.signal.reason) {+ throw error+ } // If we fail to optimize, fallback to the original image return { buffer: upstreamBuffer,packages/next/src/server/next-server.ts28 + / 6 −
@@ -641,7 +641,8 @@ export default class NextNodeServer extends BaseServer< req: NodeNextRequest, res: NodeNextResponse, paramsResult: import('./image-optimizer').ImageParamsResult,- previousCacheEntry?: IncrementalResponseCacheEntry | null+ previousCacheEntry?: IncrementalResponseCacheEntry | null,+ signal?: AbortSignal ): Promise<{ buffer: Buffer contentType: string@@ -701,20 +702,23 @@ export default class NextNodeServer extends BaseServer< href, this.nextConfig.images.dangerouslyAllowLocalIP, this.nextConfig.images.maximumResponseBody,- this.nextConfig.images.maximumRedirects+ this.nextConfig.images.maximumRedirects,+ signal ) : await fetchInternalImage( href, req.originalRequest, res.originalResponse, handleInternalReq,- this.nextConfig.images+ this.nextConfig.images,+ this.nextConfig.images.maximumRedirects,+ signal ) return imageOptimizer( imageUpstream, paramsResult,- getImageOptimizerTransformOptions(this.nextConfig),+ { ...getImageOptimizerTransformOptions(this.nextConfig), signal }, { isDev: this.dev, previousCacheEntry } ) }@@ -962,19 +966,21 @@ export default class NextNodeServer extends BaseServer< } const cacheKey = ImageOptimizerCache.getCacheKey(paramsResult)+ const signal = signalFromNodeResponse(res.originalResponse) try { const { getExtension } = require('./serve-static') as typeof import('./serve-static') const cacheEntry = await this.imageResponseCache.get( cacheKey,- async ({ previousCacheEntry }) => {+ async ({ previousCacheEntry, signal: optimizeSignal }) => { const { buffer, contentType, maxAge, upstreamEtag, etag } = await this.imageOptimizer( req, res, paramsResult,- previousCacheEntry+ previousCacheEntry,+ optimizeSignal ) return {@@ -992,6 +998,13 @@ export default class NextNodeServer extends BaseServer< routeKind: RouteKind.IMAGE, incrementalCache: imageOptimizerCache, isFallback: false,+ // Passing a signal tells the response cache that the work can be+ // aborted, which is only true for nsio. sharp can't be+ // interrupted, so aborting it would only let another request+ // start a duplicate.+ signal: this.nextConfig.experimental.imgOptSafeMode?.nextImage+ ? signal+ : undefined, } ) @@ -1005,6 +1018,11 @@ export default class NextNodeServer extends BaseServer< ) } + if (signal.aborted) {+ // The client disconnected, so there's nothing to respond to+ return true+ }+ sendResponse( req.originalRequest, res.originalResponse,@@ -1020,6 +1038,10 @@ export default class NextNodeServer extends BaseServer< ) return true } catch (err) {+ if (signal.aborted) {+ // The client disconnected, so there's nothing to respond to+ return true+ } if (err instanceof ImageError) { res.statusCode = err.statusCode res.body(err.message).send()packages/next/src/server/response-cache/index.test.ts60 + / 0 −
@@ -280,4 +280,64 @@ describe('ResponseCache', () => { expect(followUp).not.toBeNull() }) })++ describe('abort signals', () => {+ it('aborts the response generator when the caller aborts', async () => {+ const cache = new ResponseCache({ minimalMode: false, route })+ const incrementalCache = mockIncrementalCache()+ const previous = await fromResponseCacheEntry(makeCacheEntry('cached'))+ // An expired entry is revalidated before responding, like a miss+ incrementalCache.get.mockResolvedValue({ ...previous, isStale: -1 })++ const generator = jest.fn(+ ({ signal }: { signal?: AbortSignal }) =>+ new Promise<never>((_, reject) => {+ signal!.addEventListener('abort', () => reject(signal!.reason))+ })+ )+ const a = new AbortController()+ const result = cache.get('/test', generator, {+ routeKind: RouteKind.APP_PAGE,+ incrementalCache,+ signal: a.signal,+ })+ await new Promise((r) => setTimeout(r, 0))+ expect(generator).toHaveBeenCalledTimes(1)++ a.abort(new Error('left'))+ await expect(result).rejects.toThrow('left')++ // An abort isn't a failure, so the expired entry isn't extended+ await new Promise((r) => setTimeout(r, 0))+ expect(incrementalCache.set).not.toHaveBeenCalled()+ })++ it("doesn't abort a revalidation after responding with a stale entry", async () => {+ const cache = new ResponseCache({ minimalMode: false, route })+ const incrementalCache = mockIncrementalCache()+ const previous = await fromResponseCacheEntry(makeCacheEntry('cached'))+ incrementalCache.get.mockResolvedValue({ ...previous, isStale: true })++ let finishRevalidation!: (signal: AbortSignal | undefined) => void+ const revalidated = new Promise<AbortSignal | undefined>((r) => {+ finishRevalidation = r+ })+ const generator = jest.fn(async ({ signal }) => {+ finishRevalidation(signal)+ return makeCacheEntry('revalidated')+ })++ const a = new AbortController()+ const result = await cache.get('/test', generator, {+ routeKind: RouteKind.APP_PAGE,+ incrementalCache,+ signal: a.signal,+ })+ expect(result).toMatchObject({ isStale: true })+ a.abort()++ expect(await revalidated).toBeUndefined()+ expect(generator).toHaveBeenCalledTimes(1)+ })+ }) })packages/next/src/server/response-cache/index.ts66 + / 29 −
@@ -241,6 +241,14 @@ export default class ResponseCache implements ResponseCacheBase { * invocations can still share a pending render through the batchers. */ invocationID?: string++ /**+ * Concurrent callers share the response generator, so its `signal` only+ * aborts once every caller waiting on it has aborted. Callers still get+ * the generator's result or rejection, and a result that finishes+ * despite the abort is still cached.+ */+ signal?: AbortSignal } ): Promise<ResponseCacheResult> { // If there is no key for the cache, we can't possibly look this up in the@@ -249,6 +257,7 @@ export default class ResponseCache implements ResponseCacheBase { return responseGenerator({ hasResolved: false, previousCacheEntry: null,+ signal: context.signal, }) } @@ -300,11 +309,12 @@ export default class ResponseCache implements ResponseCacheBase { isPrefetch = false, waitUntil, invocationID,+ signal, } = context const response = await this.getBatcher.batch( { key, isOnDemandRevalidate },- ({ resolve }) => {+ ({ resolve, signal: batchSignal }) => { const promise = this.handleGet( key, responseGenerator,@@ -315,6 +325,7 @@ export default class ResponseCache implements ResponseCacheBase { isRoutePPREnabled, isPrefetch, invocationID,+ signal: batchSignal, }, resolve )@@ -323,7 +334,8 @@ export default class ResponseCache implements ResponseCacheBase { if (waitUntil) waitUntil(promise) return promise- }+ },+ signal ) // In minimal mode, each caller with an invocation ID stores the shared@@ -365,6 +377,7 @@ export default class ResponseCache implements ResponseCacheBase { isRoutePPREnabled: boolean isPrefetch: boolean invocationID: string | undefined+ signal: AbortSignal | undefined }, resolve: (value: IncrementalResponseCacheResult) => void ): Promise<IncrementalResponseCacheResult> {@@ -411,6 +424,10 @@ export default class ResponseCache implements ResponseCacheBase { // wins would depend purely on request timing. Running the generator // directly lets every prefetch segment take the same fallback-shell path, // independent of any concurrent background upgrade.+ //+ // Once the callers have the stale entry, the revalidation only fills the+ // cache, so it isn't aborted.+ const signal = resolved ? undefined : context.signal const incrementalResponseCacheEntry = context.isPrefetch && previousIncrementalCacheEntry === null ? await this.handleRevalidate(@@ -420,7 +437,8 @@ export default class ResponseCache implements ResponseCacheBase { context.isFallback, responseGenerator, previousIncrementalCacheEntry,- resolved+ resolved,+ signal ) : await this.revalidate( key,@@ -429,7 +447,8 @@ export default class ResponseCache implements ResponseCacheBase { context.isFallback, responseGenerator, previousIncrementalCacheEntry,- resolved+ resolved,+ { signal } ) if (@@ -481,8 +500,9 @@ export default class ResponseCache implements ResponseCacheBase { * @param responseGenerator - The response generator to use to generate the response cache entry. * @param previousIncrementalCacheEntry - The previous cache entry to use to revalidate the cache entry. * @param hasResolved - Whether the response has been resolved.- * @param waitUntil - Optional function to register background work.- * @param invocationID - The invocation ID for cache key scoping.+ * @param options.waitUntil - Optional function to register background work.+ * @param options.signal - The response generator's signal aborts once every+ * caller waiting on it has aborted. * @returns The revalidated cache entry. */ public async revalidate(@@ -493,24 +513,35 @@ export default class ResponseCache implements ResponseCacheBase { responseGenerator: ResponseGenerator, previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null, hasResolved: boolean,- waitUntil?: (prom: Promise<any>) => void+ {+ waitUntil,+ signal,+ }: {+ waitUntil?: (prom: Promise<any>) => void+ signal?: AbortSignal+ } = {} ) {- return this.revalidateBatcher.batch(key, () => {- const promise = this.handleRevalidate(- key,- incrementalCache,- isRoutePPREnabled,- isFallback,- responseGenerator,- previousIncrementalCacheEntry,- hasResolved- )+ return this.revalidateBatcher.batch(+ key,+ ({ signal: batchSignal }) => {+ const promise = this.handleRevalidate(+ key,+ incrementalCache,+ isRoutePPREnabled,+ isFallback,+ responseGenerator,+ previousIncrementalCacheEntry,+ hasResolved,+ batchSignal+ ) - // We need to ensure background revalidates are passed to waitUntil.- if (waitUntil) waitUntil(promise)+ // We need to ensure background revalidates are passed to waitUntil.+ if (waitUntil) waitUntil(promise) - return promise- })+ return promise+ },+ signal+ ) } private async handleRevalidate(@@ -520,7 +551,8 @@ export default class ResponseCache implements ResponseCacheBase { isFallback: boolean, responseGenerator: ResponseGenerator, previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null,- hasResolved: boolean+ hasResolved: boolean,+ signal: AbortSignal | undefined ): Promise<IncrementalResponseCacheResult> { let failure: PrerenderFailure try {@@ -529,6 +561,7 @@ export default class ResponseCache implements ResponseCacheBase { hasResolved, previousCacheEntry: previousIncrementalCacheEntry, isRevalidating: true,+ signal, }) if (!responseCacheEntry) { return null@@ -556,13 +589,17 @@ export default class ResponseCache implements ResponseCacheBase { return incrementalResponseCacheEntry } } catch (err) {- await this.retainPreviousCacheEntry(- key,- incrementalCache,- isRoutePPREnabled,- isFallback,- previousIncrementalCacheEntry- )+ // An abort isn't a failure, so it shouldn't delay the next attempt+ if (!signal?.aborted || err !== signal.reason) {+ // upon failure, delay retries by extending the cache expiration+ await this.retainPreviousCacheEntry(+ key,+ incrementalCache,+ isRoutePPREnabled,+ isFallback,+ previousIncrementalCacheEntry+ )+ } throw err } packages/next/src/server/response-cache/types.ts8 + / 0 −
@@ -196,6 +196,14 @@ export type ResponseGenerator = (state: { isRevalidating?: boolean span?: any + /**+ * Aborts once every caller waiting on this response has aborted. `undefined`+ * if the first caller didn't pass a signal, or the response is only filling+ * the cache after the callers received a stale entry. Never aborts if any+ * caller didn't pass a signal.+ */+ signal?: AbortSignal+ /** * When true, this indicates that the response generator is being called in a * context where the response must be generated statically.test/unit/image-optimizer/fetch-external-image.test.ts37 + / 0 −
@@ -656,6 +656,43 @@ describe('fetchExternalImage', () => { }, 20_000) }) + describe('abort signal', () => {+ it('should reject with the abort reason before the headers and during the body', async () => {+ let received = 0+ let allReceived!: () => void+ const bothReceived = new Promise<void>((resolve) => {+ allReceived = resolve+ })+ handler = (req, res) => {+ if (req.url === '/stalled-body.jpg') {+ res.writeHead(200, { 'content-type': 'image/jpeg' })+ res.write(Buffer.from([0xff, 0xd8]))+ }+ if (++received === 2) allReceived()+ }++ const controller = new AbortController()+ const fetches = Promise.all(+ ['/stalled-headers.jpg', '/stalled-body.jpg'].map((path) =>+ fetchExternalImage(+ `${origin()}${path}`,+ true,+ MAXIMUM_RESPONSE_BODY,+ undefined,+ controller.signal+ ).catch((e) => e)+ )+ )+ await bothReceived+ // Give the stalled body's headers time to reach the client+ await new Promise((resolve) => setImmediate(resolve))+ const reason = new Error('client disconnected')+ controller.abort(reason)++ expect(await fetches).toEqual([reason, reason])+ })+ })+ describe('response size limit', () => { it('should throw error when exceeding maximumResponseBody config on later chunk', async () => { const maximumResponseBody = 2_000 // 2KB custom limittest/unit/image-optimizer/fetch-internal-image.test.ts28 + / 0 −
@@ -281,6 +281,34 @@ describe('fetchInternalImage', () => { expect(result.buffer.length).toBe(maximumResponseBody) }) })+ describe('abort signal', () => {+ it('should reject with the abort reason and close the internal response', async () => {+ const controller = new AbortController()+ const reason = new Error('client disconnected')+ let internalRes!: ServerResponse++ // Never answers, like a route handler that is still working+ const handleRequest = (_req: IncomingMessage, res: ServerResponse) => {+ internalRes = res+ return new Promise<void>(() => {})+ }++ const fetched = fetchInternalImage(+ '/test-image.jpg',+ {} as IncomingMessage,+ {} as ServerResponse,+ handleRequest,+ getImagesConfig(300_000_000),+ undefined,+ controller.signal+ ).catch((e) => e)+ controller.abort(reason)++ expect(await fetched).toBe(reason)+ expect(internalRes.destroyed).toBe(true)+ })+ })+ 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