Skip to content

Commit

Permalink
feat: run background revalidation at end of response
Browse files Browse the repository at this point in the history
  • Loading branch information
wyattjoh committed Sep 5, 2024
1 parent 4a4ff6c commit d70cb61
Show file tree
Hide file tree
Showing 12 changed files with 119 additions and 42 deletions.
1 change: 1 addition & 0 deletions packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@
"node-html-parser": "5.3.3",
"ora": "4.0.4",
"os-browserify": "0.3.0",
"p-lazy": "3.1.0",
"p-limit": "3.1.0",
"p-queue": "6.6.2",
"path-browserify": "1.0.1",
Expand Down
9 changes: 9 additions & 0 deletions packages/next/src/compiled/p-lazy/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 change: 1 addition & 0 deletions packages/next/src/compiled/p-lazy/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/next/src/compiled/p-lazy/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"p-lazy","main":"index.js","author":{"name":"Sindre Sorhus","email":"sindresorhus@gmail.com","url":"sindresorhus.com"},"license":"MIT"}
13 changes: 13 additions & 0 deletions packages/next/src/lib/scheduler.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import PLazy from 'next/dist/compiled/p-lazy'

export type ScheduledFn<T = void> = () => T | PromiseLike<T>
export type SchedulerFn<T = void> = (cb: ScheduledFn<T>) => void

Expand Down Expand Up @@ -58,3 +60,14 @@ export function waitAtLeastOneReactRenderTask(): Promise<void> {
return new Promise((r) => setImmediate(r))
}
}

/**
* This will create a promise that will not have it's executor run until the
* promise is awaited.
*
* @param fn the function to execute
* @returns a promise that will resolve with the return value of the function
*/
export const scheduleLazily = async <T>(fn: () => Promise<T>) => {
return new PLazy<T>((resolve) => fn().then(resolve))
}
6 changes: 2 additions & 4 deletions packages/next/src/server/after/after-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ export class AfterContext {
this.waitUntil = waitUntil
this.onClose = onClose

this.callbackQueue = new PromiseQueue()
this.callbackQueue.pause()
this.callbackQueue = new PromiseQueue({ autoStart: false })
}

public run<T>(requestStore: RequestStore, callback: () => T): T {
Expand Down Expand Up @@ -105,8 +104,7 @@ export class AfterContext {
wrapRequestStoreForAfterCallbacks(requestStore)

return requestAsyncStorage.run(readonlyRequestStore, () => {
this.callbackQueue.start()
return this.callbackQueue.onIdle()
return this.callbackQueue.start().onIdle()
})
}
}
Expand Down
5 changes: 5 additions & 0 deletions packages/next/src/server/after/noop-wait-until.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function noopWaitUntil(promise: Promise<any>) {
promise.catch((err: unknown) => {
console.error(err)
})
}
71 changes: 37 additions & 34 deletions packages/next/src/server/base-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ import { RouteKind } from './route-kind'
import type { RouteModule } from './route-modules/route-module'
import { FallbackMode, parseFallbackField } from '../lib/fallback'
import { toResponseCacheEntry } from './response-cache/utils'
import { scheduleOnNextTick } from '../lib/scheduler'
import { scheduleLazily } from '../lib/scheduler'
import { noopWaitUntil } from './after/noop-wait-until'

export type FindComponentsResult = {
components: LoadComponentsReturnType
Expand Down Expand Up @@ -1739,7 +1740,7 @@ export default abstract class Server<

if (process.env.__NEXT_TEST_MODE) {
// we're in a test, use a no-op.
return Server.noopWaitUntil
return noopWaitUntil
}

if (this.minimalMode || process.env.NEXT_RUNTIME === 'edge') {
Expand All @@ -1751,13 +1752,7 @@ export default abstract class Server<
}

// we're in `next start` or `next dev`. noop is fine for both.
return Server.noopWaitUntil
}

private static noopWaitUntil(promise: Promise<any>) {
promise.catch((err: unknown) => {
console.error(err)
})
return noopWaitUntil
}

private async renderImpl(
Expand Down Expand Up @@ -2984,39 +2979,47 @@ export default abstract class Server<
}

// If we're not in minimal mode and the cache entry that was returned was a
// app page fallback, then we need to kick off the dynamic shell generation.
// app page fallback, then we need to kick off the route shell generation.
if (
ssgCacheKey &&
!this.minimalMode &&
isRoutePPREnabled &&
this.nextConfig.experimental.pprFallbacks &&
cacheEntry.value?.kind === CachedRouteKind.APP_PAGE &&
cacheEntry.isFallback &&
!isOnDemandRevalidate
!isOnDemandRevalidate &&
process.env.NEXT_RUNTIME !== 'edge'
) {
scheduleOnNextTick(async () => {
try {
await this.responseCache.get(
ssgCacheKey,
() =>
doRender({
// We're an on-demand request, so we don't need to pass in the
// fallbackRouteParams.
fallbackRouteParams: null,
postponed: undefined,
}),
{
routeKind: RouteKind.APP_PAGE,
incrementalCache,
isOnDemandRevalidate: true,
isPrefetch: false,
isRoutePPREnabled: true,
}
)
} catch (err) {
console.error('Error occurred while rendering dynamic shell', err)
}
})
// Wait until the response is completed sending before we start the
// background revalidation. Attaching this to the `waitUntil` queue on the
// render result will not hold the request open until the revalidation is
// completed but instead will just delay the time it starts the
// revalidation.
cacheEntry.value.html.waitUntil(
scheduleLazily(() => {
this.responseCache
.get(
ssgCacheKey,
() =>
doRender({
// We're an on-demand request, so we don't need to pass in the
// fallbackRouteParams.
fallbackRouteParams: null,
postponed: undefined,
}),
{
routeKind: RouteKind.APP_PAGE,
incrementalCache,
isOnDemandRevalidate: true,
isPrefetch: false,
isRoutePPREnabled: true,
}
)
.catch((err) => {
console.error('Error occurred while rendering route shell', err)
})
})
)
}

const didPostpone =
Expand Down
31 changes: 27 additions & 4 deletions packages/next/src/server/render-result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { OutgoingHttpHeaders, ServerResponse } from 'http'
import type { Revalidate } from './lib/revalidate'
import type { FetchMetrics } from './base-http'

import PQueue from 'next/dist/compiled/p-queue'
import {
chainStreams,
streamFromBuffer,
Expand All @@ -10,6 +11,7 @@ import {
streamToString,
} from './stream-utils/node-web-streams-helper'
import { isAbortError, pipeToNodeResponse } from './pipe-readable'
import { scheduleLazily } from '../lib/scheduler'

type ContentTypeOption = string | undefined

Expand Down Expand Up @@ -96,7 +98,7 @@ export default class RenderResult<
return new RenderResult<StaticRenderResultMetadata>(value, { metadata: {} })
}

private readonly waitUntil?: Promise<unknown>
private readonly waitUntilQueue: PQueue = new PQueue({ autoStart: false })

constructor(
response: RenderResultResponse,
Expand All @@ -105,7 +107,14 @@ export default class RenderResult<
this.response = response
this.contentType = contentType
this.metadata = metadata
this.waitUntil = waitUntil

if (waitUntil) {
this.waitUntilQueue.add(() => waitUntil)
}
}

public waitUntil(promise: Promise<unknown>) {
this.waitUntilQueue.add(() => promise)
}

public assignMetadata(metadata: Metadata) {
Expand Down Expand Up @@ -250,7 +259,9 @@ export default class RenderResult<

// If there is a waitUntil promise, wait for it to resolve before
// closing the writable stream.
if (this.waitUntil) await this.waitUntil
if (this.waitUntilQueue.size > 0) {
await this.waitUntilQueue.start().onIdle()
}

// Close the writable stream.
await writable.close()
Expand Down Expand Up @@ -279,6 +290,18 @@ export default class RenderResult<
* @param res
*/
public async pipeToNodeResponse(res: ServerResponse) {
await pipeToNodeResponse(this.readable, res, this.waitUntil)
await pipeToNodeResponse(
this.readable,
res,
// Create a promise that will only run this callback when it's awaited. It
// will start the queue and wait until all the tasks are done.
scheduleLazily(() => {
if (this.waitUntilQueue.size === 0) {
return Promise.resolve()
}

return this.waitUntilQueue.start().onIdle()
})
)
}
}
9 changes: 9 additions & 0 deletions packages/next/taskfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,14 @@ export async function ncc_p_queue(task, opts) {
.ncc({ packageName: 'p-queue', externals })
.target('src/compiled/p-queue')
}
// eslint-disable-next-line camelcase
externals['p-lazy'] = 'next/dist/compiled/p-lazy'
export async function ncc_p_lazy(task, opts) {
await task
.source(relative(__dirname, require.resolve('p-lazy')))
.ncc({ packageName: 'p-lazy', externals })
.target('src/compiled/p-lazy')
}

// eslint-disable-next-line camelcase
externals['raw-body'] = 'next/dist/compiled/raw-body'
Expand Down Expand Up @@ -2280,6 +2288,7 @@ export async function ncc(task, opts) {
'ncc_napirs_triples',
'ncc_p_limit',
'ncc_p_queue',
'ncc_p_lazy',
'ncc_raw_body',
'ncc_image_size',
'ncc_hapi_accept',
Expand Down
5 changes: 5 additions & 0 deletions packages/next/types/$$compiled.internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ declare module 'next/dist/compiled/p-queue' {
export = m
}

declare module 'next/dist/compiled/p-lazy' {
import m from 'p-lazy'
export = m
}

declare module 'next/dist/compiled/raw-body' {
import m from 'raw-body'
export = m
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit d70cb61

Please sign in to comment.