Unverified Commit 2731d667 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add store only mode for experimental tracing (#68548)

This adds new handling to allow seeding a cache with the experimental
tracing but not leverage the stitch handling so that more cache hits can
occur without fully opting all environments into the experimental
behavior fully. This is tested in our flying-shuttle suite by the
initial build in the test only seeding the cache and successive builds
using the experimental flag fully.

---------
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent 03a6b186
...@@ -677,7 +677,7 @@ export async function createEntrypoints( ...@@ -677,7 +677,7 @@ export async function createEntrypoints(
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
flyingShuttle: config.experimental.flyingShuttle, flyingShuttle: Boolean(config.experimental.flyingShuttle),
nextConfigExperimentalUseEarlyImport: config.experimental nextConfigExperimentalUseEarlyImport: config.experimental
.useEarlyImport .useEarlyImport
? true ? true
...@@ -743,7 +743,7 @@ export async function createEntrypoints( ...@@ -743,7 +743,7 @@ export async function createEntrypoints(
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
nextConfigOutput: config.output, nextConfigOutput: config.output,
flyingShuttle: config.experimental.flyingShuttle, flyingShuttle: Boolean(config.experimental.flyingShuttle),
// This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead. // This isn't used with edge as it needs to be set on the entry module, which will be the `edgeServerEntry` instead.
// Still passing it here for consistency. // Still passing it here for consistency.
preferredRegion: staticInfo.preferredRegion, preferredRegion: staticInfo.preferredRegion,
......
...@@ -726,9 +726,13 @@ export default async function build( ...@@ -726,9 +726,13 @@ export default async function build(
) )
NextBuildContext.buildId = buildId NextBuildContext.buildId = buildId
const { flyingShuttle } = config.experimental
const isFullFlyingShuttle = flyingShuttle?.mode === 'full'
const isStoreOnlyFlyingShuttle = flyingShuttle?.mode === 'store-only'
const shuttleDir = path.join(distDir, 'cache', 'shuttle') const shuttleDir = path.join(distDir, 'cache', 'shuttle')
if (config.experimental.flyingShuttle) { if (flyingShuttle) {
await fs.mkdir(shuttleDir, { await fs.mkdir(shuttleDir, {
recursive: true, recursive: true,
}) })
...@@ -865,7 +869,7 @@ export default async function build( ...@@ -865,7 +869,7 @@ export default async function build(
unchanged: DetectedEntriesResult unchanged: DetectedEntriesResult
} }
if (pagesPaths && config.experimental.flyingShuttle) { if (pagesPaths && isFullFlyingShuttle) {
changedPagePathsResult = await detectChangedEntries({ changedPagePathsResult = await detectChangedEntries({
pagesPaths, pagesPaths,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
...@@ -965,7 +969,7 @@ export default async function build( ...@@ -965,7 +969,7 @@ export default async function build(
}) })
) )
if (appPaths && config.experimental.flyingShuttle) { if (appPaths && isFullFlyingShuttle) {
changedAppPathsResult = await detectChangedEntries({ changedAppPathsResult = await detectChangedEntries({
appPaths, appPaths,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
...@@ -1198,7 +1202,7 @@ export default async function build( ...@@ -1198,7 +1202,7 @@ export default async function build(
) )
const filterPaths: string[] = [] const filterPaths: string[] = []
if (config.experimental.flyingShuttle) { if (flyingShuttle) {
filterPaths.push( filterPaths.push(
...[ ...[
// client filter always has all app paths // client filter always has all app paths
...@@ -1707,7 +1711,7 @@ export default async function build( ...@@ -1707,7 +1711,7 @@ export default async function build(
hasSsrAmpPages: false, hasSsrAmpPages: false,
buildTraceContext, buildTraceContext,
outputFileTracingRoot, outputFileTracingRoot,
isFlyingShuttle: !!config.experimental.flyingShuttle, isFlyingShuttle: Boolean(flyingShuttle),
}) })
.catch((err) => { .catch((err) => {
console.error(err) console.error(err)
...@@ -2410,7 +2414,7 @@ export default async function build( ...@@ -2410,7 +2414,7 @@ export default async function build(
hasSsrAmpPages, hasSsrAmpPages,
buildTraceContext, buildTraceContext,
outputFileTracingRoot, outputFileTracingRoot,
isFlyingShuttle: !!config.experimental.flyingShuttle, isFlyingShuttle: Boolean(flyingShuttle),
}).catch((err) => { }).catch((err) => {
console.error(err) console.error(err)
process.exit(1) process.exit(1)
...@@ -2517,45 +2521,49 @@ export default async function build( ...@@ -2517,45 +2521,49 @@ export default async function build(
) )
if (!isGenerateMode) { if (!isGenerateMode) {
if (config.experimental.flyingShuttle) { if (flyingShuttle) {
await buildTracesPromise await buildTracesPromise
console.log('stitching builds...') if (isStoreOnlyFlyingShuttle) {
const stitchResult = await stitchBuilds( console.log('skipping stitching builds due to store-only mode')
{ } else {
config, console.log('stitching builds...')
buildId, const stitchResult = await stitchBuilds(
distDir, {
shuttleDir, config,
rewrites, buildId,
redirects, distDir,
edgePreviewProps: { shuttleDir,
__NEXT_PREVIEW_MODE_ID: rewrites,
NextBuildContext.previewProps!.previewModeId, redirects,
__NEXT_PREVIEW_MODE_ENCRYPTION_KEY: edgePreviewProps: {
NextBuildContext.previewProps!.previewModeEncryptionKey, __NEXT_PREVIEW_MODE_ID:
__NEXT_PREVIEW_MODE_SIGNING_KEY: NextBuildContext.previewProps!.previewModeId,
NextBuildContext.previewProps!.previewModeSigningKey, __NEXT_PREVIEW_MODE_ENCRYPTION_KEY:
}, NextBuildContext.previewProps!.previewModeEncryptionKey,
encryptionKey, __NEXT_PREVIEW_MODE_SIGNING_KEY:
allowedErrorRate: NextBuildContext.previewProps!.previewModeSigningKey,
config.experimental.clientRouterFilterAllowedRate, },
}, encryptionKey,
{ allowedErrorRate:
changed: { config.experimental.clientRouterFilterAllowedRate,
pages: changedPagePathsResult?.changed.pages || [],
app: changedAppPathsResult?.changed.app || [],
},
unchanged: {
pages: changedPagePathsResult?.unchanged.pages || [],
app: changedAppPathsResult?.unchanged.app || [],
}, },
pageExtensions: config.pageExtensions, {
changed: {
pages: changedPagePathsResult?.changed.pages || [],
app: changedAppPathsResult?.changed.app || [],
},
unchanged: {
pages: changedPagePathsResult?.unchanged.pages || [],
app: changedAppPathsResult?.unchanged.app || [],
},
pageExtensions: config.pageExtensions,
}
)
// reload pagesManifest since it's been updated on disk
if (stitchResult.pagesManifest) {
pagesManifest = stitchResult.pagesManifest
} }
)
// reload pagesManifest since it's been updated on disk
if (stitchResult.pagesManifest) {
pagesManifest = stitchResult.pagesManifest
} }
console.log('storing shuttle') console.log('storing shuttle')
......
...@@ -728,6 +728,10 @@ export default async function getBaseWebpackConfig( ...@@ -728,6 +728,10 @@ export default async function getBaseWebpackConfig(
isNodeServer ? new OptionalPeerDependencyResolverPlugin() : undefined, isNodeServer ? new OptionalPeerDependencyResolverPlugin() : undefined,
].filter(Boolean) as webpack.ResolvePluginInstance[], ].filter(Boolean) as webpack.ResolvePluginInstance[],
} }
// we don't want to modify the outputs naming if we're
// in store-only mode
const { flyingShuttle } = config.experimental
const isFullFlyingShuttle = flyingShuttle?.mode === 'full'
// Packages which will be split into the 'framework' chunk. // Packages which will be split into the 'framework' chunk.
// Only top-level packages are included, e.g. nested copies like // Only top-level packages are included, e.g. nested copies like
...@@ -968,7 +972,7 @@ export default async function getBaseWebpackConfig( ...@@ -968,7 +972,7 @@ export default async function getBaseWebpackConfig(
if (isNodeServer || isEdgeServer) { if (isNodeServer || isEdgeServer) {
return { return {
filename: `${isEdgeServer ? `edge-chunks${config.experimental.flyingShuttle ? `-${buildId}` : ''}/` : ''}[name].js`, filename: `${isEdgeServer ? `edge-chunks${isFullFlyingShuttle ? `-${buildId}` : ''}/` : ''}[name].js`,
chunks: 'all', chunks: 'all',
minChunks: 2, minChunks: 2,
} }
...@@ -1135,7 +1139,7 @@ export default async function getBaseWebpackConfig( ...@@ -1135,7 +1139,7 @@ export default async function getBaseWebpackConfig(
hashFunction: 'xxhash64', hashFunction: 'xxhash64',
hashDigestLength: 16, hashDigestLength: 16,
...(config.experimental.flyingShuttle ...(isFullFlyingShuttle
? { ? {
// ensure we only use contenthash as it's more deterministic // ensure we only use contenthash as it's more deterministic
filename: (p) => { filename: (p) => {
...@@ -1770,7 +1774,7 @@ export default async function getBaseWebpackConfig( ...@@ -1770,7 +1774,7 @@ export default async function getBaseWebpackConfig(
dev, dev,
}), }),
(isClient || isEdgeServer) && new DropClientPage(), (isClient || isEdgeServer) && new DropClientPage(),
(isNodeServer || (config.experimental.flyingShuttle && isEdgeServer)) && (isNodeServer || (flyingShuttle && isEdgeServer)) &&
!dev && !dev &&
new (require('./webpack/plugins/next-trace-entrypoints-plugin') new (require('./webpack/plugins/next-trace-entrypoints-plugin')
.TraceEntryPointsPlugin as typeof import('./webpack/plugins/next-trace-entrypoints-plugin').TraceEntryPointsPlugin)( .TraceEntryPointsPlugin as typeof import('./webpack/plugins/next-trace-entrypoints-plugin').TraceEntryPointsPlugin)(
...@@ -1784,7 +1788,7 @@ export default async function getBaseWebpackConfig( ...@@ -1784,7 +1788,7 @@ export default async function getBaseWebpackConfig(
turbotrace: config.experimental.turbotrace, turbotrace: config.experimental.turbotrace,
optOutBundlingPackages, optOutBundlingPackages,
traceIgnores: [], traceIgnores: [],
flyingShuttle: !!config.experimental.flyingShuttle, flyingShuttle: Boolean(flyingShuttle),
compilerType, compilerType,
swcLoaderConfig: swcDefaultLoader, swcLoaderConfig: swcDefaultLoader,
} }
......
...@@ -141,7 +141,7 @@ export function getDefineEnv({ ...@@ -141,7 +141,7 @@ export function getDefineEnv({
}: DefineEnvPluginOptions): SerializedDefineEnv { }: DefineEnvPluginOptions): SerializedDefineEnv {
const nextPublicEnv = getNextPublicEnvironmentVariables() const nextPublicEnv = getNextPublicEnvironmentVariables()
if (config.experimental.flyingShuttle) { if (Boolean(config.experimental.flyingShuttle)) {
// we delay inlining these values until after the build // we delay inlining these values until after the build
// with flying shuttle enabled so we can update them // with flying shuttle enabled so we can update them
// without invalidating entries // without invalidating entries
...@@ -213,8 +213,9 @@ export function getDefineEnv({ ...@@ -213,8 +213,9 @@ export function getDefineEnv({
? 5 * 60 // 5 minutes ? 5 * 60 // 5 minutes
: config.experimental.staleTimes?.static : config.experimental.staleTimes?.static
), ),
'process.env.__NEXT_FLYING_SHUTTLE': 'process.env.__NEXT_FLYING_SHUTTLE': Boolean(
config.experimental.flyingShuttle ?? false, config.experimental.flyingShuttle
),
'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED': 'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED':
config.experimental.clientRouterFilter ?? true, config.experimental.clientRouterFilter ?? true,
'process.env.__NEXT_CLIENT_ROUTER_S_FILTER': 'process.env.__NEXT_CLIENT_ROUTER_S_FILTER':
......
...@@ -293,7 +293,13 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -293,7 +293,13 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
externalMiddlewareRewritesResolve: z.boolean().optional(), externalMiddlewareRewritesResolve: z.boolean().optional(),
fallbackNodePolyfills: z.literal(false).optional(), fallbackNodePolyfills: z.literal(false).optional(),
fetchCacheKeyPrefix: z.string().optional(), fetchCacheKeyPrefix: z.string().optional(),
flyingShuttle: z.boolean().optional(), flyingShuttle: z
.strictObject({
mode: z
.union([z.literal('full'), z.literal('store-only')])
.optional(),
})
.optional(),
forceSwcTransforms: z.boolean().optional(), forceSwcTransforms: z.boolean().optional(),
fullySpecified: z.boolean().optional(), fullySpecified: z.boolean().optional(),
gzipSize: z.boolean().optional(), gzipSize: z.boolean().optional(),
......
...@@ -212,7 +212,7 @@ export interface LoggingConfig { ...@@ -212,7 +212,7 @@ export interface LoggingConfig {
export interface ExperimentalConfig { export interface ExperimentalConfig {
appNavFailHandling?: boolean appNavFailHandling?: boolean
flyingShuttle?: boolean flyingShuttle?: { mode?: 'full' | 'store-only' }
prerenderEarlyExit?: boolean prerenderEarlyExit?: boolean
linkNoTouchStart?: boolean linkNoTouchStart?: boolean
caseSensitiveRoutes?: boolean caseSensitiveRoutes?: boolean
...@@ -970,7 +970,11 @@ export const defaultConfig: NextConfig = { ...@@ -970,7 +970,11 @@ export const defaultConfig: NextConfig = {
outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '', outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || '',
experimental: { experimental: {
appNavFailHandling: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE), appNavFailHandling: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE),
flyingShuttle: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE), flyingShuttle: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE)
? {
mode: 'full',
}
: undefined,
prerenderEarlyExit: true, prerenderEarlyExit: true,
serverMinification: true, serverMinification: true,
serverSourceMaps: false, serverSourceMaps: false,
......
...@@ -19,7 +19,7 @@ import { nextTestSetup, isNextStart } from 'e2e-utils' ...@@ -19,7 +19,7 @@ import { nextTestSetup, isNextStart } from 'e2e-utils'
nanoid: '4.0.1', nanoid: '4.0.1',
}, },
env: { env: {
NEXT_PRIVATE_FLYING_SHUTTLE: '1', NEXT_PRIVATE_FLYING_SHUTTLE_STORE_ONLY: '1',
}, },
}) })
let initialConfig: Record<string, any> = {} let initialConfig: Record<string, any> = {}
...@@ -248,6 +248,11 @@ import { nextTestSetup, isNextStart } from 'e2e-utils' ...@@ -248,6 +248,11 @@ import { nextTestSetup, isNextStart } from 'e2e-utils'
} }
it('should only rebuild just a changed app route correctly', async () => { it('should only rebuild just a changed app route correctly', async () => {
// our initial build was built in store-only mode so
// enable full version in successive builds
delete next.env['NEXT_PRIVATE_FLYING_SHUTTLE_STORE_ONLY']
next.env['NEXT_PRIVATE_FLYING_SHUTTLE'] = '1'
await next.stop() await next.stop()
const dataPath = 'app/dashboard/deployments/[id]/data.json' const dataPath = 'app/dashboard/deployments/[id]/data.json'
......
...@@ -7,6 +7,17 @@ module.exports = { ...@@ -7,6 +7,17 @@ module.exports = {
parallelServerCompiles: true, parallelServerCompiles: true,
parallelServerBuildTraces: true, parallelServerBuildTraces: true,
webpackBuildWorker: true, webpackBuildWorker: true,
appNavFailHandling: Boolean(
process.env.NEXT_PRIVATE_FLYING_SHUTTLE_STORE_ONLY ||
process.env.NEXT_PRIVATE_FLYING_SHUTTLE
),
flyingShuttle: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE_STORE_ONLY)
? { mode: 'store-only' }
: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE)
? {
mode: 'full',
}
: undefined,
}, },
// output: 'standalone', // output: 'standalone',
rewrites: async () => { rewrites: async () => {
......
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