Unverified Commit 3cd122d8 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Scope `runInCleanSnapshot` to Work Store (#78930)

parent 4452ca2b
...@@ -59,7 +59,6 @@ ...@@ -59,7 +59,6 @@
// singleton modules should always use "*.external" instead of "*-instance" // singleton modules should always use "*.external" instead of "*-instance"
"packages/next/src/server/app-render/action-async-storage-instance.ts", "packages/next/src/server/app-render/action-async-storage-instance.ts",
"packages/next/src/server/app-render/after-task-async-storage-instance.ts", "packages/next/src/server/app-render/after-task-async-storage-instance.ts",
"packages/next/src/server/app-render/clean-async-snapshot-instance.ts",
"packages/next/src/server/app-render/work-async-storage-instance.ts", "packages/next/src/server/app-render/work-async-storage-instance.ts",
"packages/next/src/server/app-render/work-unit-async-storage-instance.ts", "packages/next/src/server/app-render/work-unit-async-storage-instance.ts",
"packages/next/src/client/components/segment-cache-impl/*" "packages/next/src/client/components/segment-cache-impl/*"
......
...@@ -178,7 +178,6 @@ import { CacheSignal } from './cache-signal' ...@@ -178,7 +178,6 @@ import { CacheSignal } from './cache-signal'
import { getTracedMetadata } from '../lib/trace/utils' import { getTracedMetadata } from '../lib/trace/utils'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import './clean-async-snapshot.external'
import { INFINITE_CACHE } from '../../lib/constants' import { INFINITE_CACHE } from '../../lib/constants'
import { createComponentStylesAndScripts } from './create-component-styles-and-scripts' import { createComponentStylesAndScripts } from './create-component-styles-and-scripts'
import { parseLoaderTree } from './parse-loader-tree' import { parseLoaderTree } from './parse-loader-tree'
......
import { createSnapshot } from '../app-render/async-local-storage'
export const runInCleanSnapshot: <R, TArgs extends any[]>(
fn: (...args: TArgs) => R,
...args: TArgs
) => R = createSnapshot()
// Share the instance module in the next-shared layer
import { runInCleanSnapshot } from './clean-async-snapshot-instance' with { 'turbopack-transition': 'next-shared' }
export { runInCleanSnapshot }
...@@ -98,6 +98,18 @@ export interface WorkStore { ...@@ -98,6 +98,18 @@ export interface WorkStore {
dynamicIOEnabled: boolean dynamicIOEnabled: boolean
dev: boolean dev: boolean
/**
* Run the given function inside a clean AsyncLocalStorage snapshot. This is
* useful when generating cache entries, to ensure that the cache generation
* cannot read anything from the context we're currently executing in, which
* might include request-specific things like `cookies()` inside a
* `React.cache()`.
*/
runInCleanSnapshot: <R, TArgs extends any[]>(
fn: (...args: TArgs) => R,
...args: TArgs
) => R
} }
export type WorkAsyncStorage = AsyncLocalStorage<WorkStore> export type WorkAsyncStorage = AsyncLocalStorage<WorkStore>
......
...@@ -12,6 +12,7 @@ import { AfterContext } from '../after/after-context' ...@@ -12,6 +12,7 @@ import { AfterContext } from '../after/after-context'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { createLazyResult, type LazyResult } from '../lib/lazy-result' import { createLazyResult, type LazyResult } from '../lib/lazy-result'
import { getCacheHandlerEntries } from '../use-cache/handlers' import { getCacheHandlerEntries } from '../use-cache/handlers'
import { createSnapshot } from '../app-render/async-local-storage'
export type WorkStoreContext = { export type WorkStoreContext = {
/** /**
...@@ -138,6 +139,7 @@ export function createWorkStore({ ...@@ -138,6 +139,7 @@ export function createWorkStore({
dev: renderOpts.dev ?? false, dev: renderOpts.dev ?? false,
previouslyRevalidatedTags, previouslyRevalidatedTags,
refreshTagsByCacheKind: createRefreshTagsByCacheKind(), refreshTagsByCacheKind: createRefreshTagsByCacheKind(),
runInCleanSnapshot: createSnapshot(),
} }
// TODO: remove this when we resolve accessing the store outside the execution context // TODO: remove this when we resolve accessing the store outside the execution context
......
...@@ -27,7 +27,6 @@ import { ...@@ -27,7 +27,6 @@ import {
workUnitAsyncStorage, workUnitAsyncStorage,
getDraftModeProviderForCacheScope, getDraftModeProviderForCacheScope,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
import { runInCleanSnapshot } from '../app-render/clean-async-snapshot.external'
import { makeHangingPromise } from '../dynamic-rendering-utils' import { makeHangingPromise } from '../dynamic-rendering-utils'
...@@ -83,7 +82,7 @@ function generateCacheEntry( ...@@ -83,7 +82,7 @@ function generateCacheEntry(
// might include request specific things like cookies() inside a React.cache(). // might include request specific things like cookies() inside a React.cache().
// Note: It is important that we await at least once before this because it lets us // Note: It is important that we await at least once before this because it lets us
// pop out of any stack specific contexts as well - aka "Sync" Local Storage. // pop out of any stack specific contexts as well - aka "Sync" Local Storage.
return runInCleanSnapshot( return workStore.runInCleanSnapshot(
generateCacheEntryWithRestoredWorkStore, generateCacheEntryWithRestoredWorkStore,
workStore, workStore,
outerWorkUnitStore, outerWorkUnitStore,
......
const { AsyncLocalStorage } = require('async_hooks')
exports.requestIdStorage = new AsyncLocalStorage()
import { connection } from 'next/server'
async function Inner({ id }) {
'use cache'
return <p>inner cache</p>
}
async function Outer({ id }) {
'use cache'
return <Inner id="inner" />
}
export default async function Page() {
await connection()
return <Outer id="outer" />
}
// @ts-check
const { requestIdStorage } = require('./als')
const defaultCacheHandler =
require('next/dist/server/lib/cache-handlers/default').default
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2}
*/
const cacheHandler = {
async get(cacheKey) {
return defaultCacheHandler.get(cacheKey)
},
async set(cacheKey, pendingEntry) {
const requestId = requestIdStorage.getStore()
console.log('set cache', cacheKey, 'requestId:', requestId)
return defaultCacheHandler.set(cacheKey, pendingEntry)
},
async refreshTags() {
return defaultCacheHandler.refreshTags()
},
async getExpiration(...tags) {
return defaultCacheHandler.getExpiration(...tags)
},
async expireTags(...tags) {
return defaultCacheHandler.expireTags(...tags)
},
}
module.exports = cacheHandler
...@@ -36,6 +36,17 @@ describe('custom server', () => { ...@@ -36,6 +36,17 @@ describe('custom server', () => {
expect($('body').text()).toMatch(/pages: 19\.\d+\.\d+/) expect($('body').text()).toMatch(/pages: 19\.\d+\.\d+/)
} }
}) })
describe('when using "use cache" with a custom cache handler', () => {
it("should not unset the custom server's ALS context", async () => {
const cliOutputLength = next.cliOutput.length
const $ = await next.render$('/use-cache')
expect($('p').text()).toBe('inner cache')
const cliOutput = next.cliOutput.slice(cliOutputLength)
expect(cliOutput).toMatch(createCacheSetLogRegExp('outer'))
expect(cliOutput).toMatch(createCacheSetLogRegExp('inner'))
})
})
}) })
}) })
...@@ -55,3 +66,11 @@ describe('custom server with quiet setting', () => { ...@@ -55,3 +66,11 @@ describe('custom server with quiet setting', () => {
expect(next.cliOutput).not.toInclude('Server side error') expect(next.cliOutput).not.toInclude('Server side error')
}) })
}) })
function createCacheSetLogRegExp(id: string) {
// Expect a requestId, that's provided through ALS, to be present in the log
// message for the cache handler set call.
return new RegExp(
`set cache \\["[A-Za-z0-9_-]{21}","(?:[0-9a-f]{2})+",\\[{"id":"${id}"},"\\$undefined"\\]\\] requestId: \\d+`
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
useCache: true,
cacheHandlers: {
default: require.resolve('./cache-handler.js'),
},
},
}
module.exports = nextConfig
...@@ -2,8 +2,11 @@ const { createServer } = require('http') ...@@ -2,8 +2,11 @@ const { createServer } = require('http')
const { parse } = require('url') const { parse } = require('url')
const next = require('next') const next = require('next')
const getPort = require('get-port') const getPort = require('get-port')
const { requestIdStorage } = require('./als')
const quiet = process.env.USE_QUIET === 'true' const quiet = process.env.USE_QUIET === 'true'
let requestId = 0
async function main() { async function main() {
const port = await getPort() const port = await getPort()
const hostname = 'localhost' const hostname = 'localhost'
...@@ -12,28 +15,30 @@ async function main() { ...@@ -12,28 +15,30 @@ async function main() {
const handle = app.getRequestHandler() const handle = app.getRequestHandler()
app.prepare().then(() => { app.prepare().then(() => {
createServer(async (req, res) => { createServer((req, res) =>
try { requestIdStorage.run(requestId++, async () => {
// Be sure to pass `true` as the second argument to `url.parse`. try {
// This tells it to parse the query portion of the URL. // Be sure to pass `true` as the second argument to `url.parse`.
const parsedUrl = parse(req.url, true) // This tells it to parse the query portion of the URL.
const { pathname, query } = parsedUrl const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
if (pathname === '/a') { if (pathname === '/a') {
await app.render(req, res, '/a', query) await app.render(req, res, '/a', query)
} else if (pathname === '/b') { } else if (pathname === '/b') {
await app.render(req, res, '/page-b', query) await app.render(req, res, '/page-b', query)
} else if (pathname === '/error') { } else if (pathname === '/error') {
await app.render(req, res, '/page-error') await app.render(req, res, '/page-error')
} else { } else {
await handle(req, res, parsedUrl) await handle(req, res, parsedUrl)
}
} catch (err) {
console.error('Error occurred handling', req.url, err)
res.statusCode = 500
res.end('Internal Server Error')
} }
} catch (err) { })
console.error('Error occurred handling', req.url, err) ).listen(port, undefined, (err) => {
res.statusCode = 500
res.end('Internal Server Error')
}
}).listen(port, undefined, (err) => {
if (err) throw err if (err) throw err
// Start mode // Start mode
console.log(`- Local: http://${hostname}:${port}`) console.log(`- Local: http://${hostname}:${port}`)
......
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