Unverified Commit 7cdb4d0f authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Abstract deployment id access into module (#86727)

This also helps with persistent-caching performance, since fewer chunks change (only the ones containing this module, as opposed to the chunks containing all the users of the value)
parent 342adb0e
export function getDeploymentIdQueryOrEmptyString(): string {
if (process.env.NEXT_DEPLOYMENT_ID) {
return `?dpl=${process.env.NEXT_DEPLOYMENT_ID}`
}
return ''
}
...@@ -19,7 +19,7 @@ import { getProxiedPluginState } from '../../build-context' ...@@ -19,7 +19,7 @@ import { getProxiedPluginState } from '../../build-context'
import { WEBPACK_LAYERS } from '../../../lib/constants' import { WEBPACK_LAYERS } from '../../../lib/constants'
import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../../../shared/lib/page-path/normalize-page-path'
import { CLIENT_STATIC_FILES_RUNTIME_MAIN_APP } from '../../../shared/lib/constants' import { CLIENT_STATIC_FILES_RUNTIME_MAIN_APP } from '../../../shared/lib/constants'
import { getDeploymentIdQueryOrEmptyString } from '../../deployment-id' import { getDeploymentIdQueryOrEmptyString } from '../../../shared/lib/deployment-id'
import { import {
formatBarrelOptimizedResource, formatBarrelOptimizedResource,
getModuleReferencesInOrder, getModuleReferencesInOrder,
......
// Override chunk URL mapping in the webpack runtime // Override chunk URL mapping in the webpack runtime
// https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204 // https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204
import { getDeploymentIdQueryOrEmptyString } from '../build/deployment-id' import { getDeploymentIdQueryOrEmptyString } from '../shared/lib/deployment-id'
import { encodeURIPath } from '../shared/lib/encode-uri-path' import { encodeURIPath } from '../shared/lib/encode-uri-path'
declare const __webpack_require__: any declare const __webpack_require__: any
......
...@@ -46,6 +46,7 @@ import RootErrorBoundary from './errors/root-error-boundary' ...@@ -46,6 +46,7 @@ import RootErrorBoundary from './errors/root-error-boundary'
import DefaultGlobalError from './builtin/global-error' import DefaultGlobalError from './builtin/global-error'
import { RootLayoutBoundary } from '../../lib/framework/boundary-components' import { RootLayoutBoundary } from '../../lib/framework/boundary-components'
import type { StaticIndicatorState } from '../dev/hot-reloader/app/hot-reloader-app' import type { StaticIndicatorState } from '../dev/hot-reloader/app/hot-reloader-app'
import { getDeploymentIdQueryOrEmptyString } from '../../shared/lib/deployment-id'
const globalMutable: { const globalMutable: {
pendingMpaPath?: string pendingMpaPath?: string
...@@ -622,9 +623,7 @@ function RuntimeStyles() { ...@@ -622,9 +623,7 @@ function RuntimeStyles() {
} }
}, [renderedStylesSize, forceUpdate]) }, [renderedStylesSize, forceUpdate])
const dplId = process.env.NEXT_DEPLOYMENT_ID const dplId = getDeploymentIdQueryOrEmptyString()
? `?dpl=${process.env.NEXT_DEPLOYMENT_ID}`
: ''
return [...runtimeStyles].map((href, i) => ( return [...runtimeStyles].map((href, i) => (
<link <link
key={i} key={i}
......
...@@ -41,6 +41,7 @@ import { ...@@ -41,6 +41,7 @@ import {
urlToUrlWithoutFlightMarker, urlToUrlWithoutFlightMarker,
} from '../../route-params' } from '../../route-params'
import type { NormalizedSearch } from '../segment-cache/cache-key' import type { NormalizedSearch } from '../segment-cache/cache-key'
import { getDeploymentId } from '../../../shared/lib/deployment-id'
const createFromReadableStream = const createFromReadableStream =
createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream'] createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']
...@@ -329,8 +330,9 @@ export async function createFetch<T>( ...@@ -329,8 +330,9 @@ export async function createFetch<T>(
headers['Next-Test-Fetch-Priority'] = fetchPriority headers['Next-Test-Fetch-Priority'] = fetchPriority
} }
if (process.env.NEXT_DEPLOYMENT_ID) { const deploymentId = getDeploymentId()
headers['x-deployment-id'] = process.env.NEXT_DEPLOYMENT_ID if (deploymentId) {
headers['x-deployment-id'] = deploymentId
} }
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
......
...@@ -56,6 +56,7 @@ import { ...@@ -56,6 +56,7 @@ import {
omitUnusedArgs, omitUnusedArgs,
} from '../../../../shared/lib/server-reference-info' } from '../../../../shared/lib/server-reference-info'
import { revalidateEntireCache } from '../../segment-cache/cache' import { revalidateEntireCache } from '../../segment-cache/cache'
import { getDeploymentId } from '../../../../shared/lib/deployment-id'
const createFromFetch = const createFromFetch =
createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch'] createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']
...@@ -110,8 +111,9 @@ async function fetchServerAction( ...@@ -110,8 +111,9 @@ async function fetchServerAction(
), ),
} }
if (process.env.NEXT_DEPLOYMENT_ID) { const deploymentId = getDeploymentId()
headers['x-deployment-id'] = process.env.NEXT_DEPLOYMENT_ID if (deploymentId) {
headers['x-deployment-id'] = deploymentId
} }
if (nextUrl) { if (nextUrl) {
......
...@@ -3,7 +3,7 @@ import type { ProxyMatcher } from '../build/analysis/get-page-static-info' ...@@ -3,7 +3,7 @@ import type { ProxyMatcher } from '../build/analysis/get-page-static-info'
import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route' import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route'
import { __unsafeCreateTrustedScriptURL } from './trusted-types' import { __unsafeCreateTrustedScriptURL } from './trusted-types'
import { requestIdleCallback } from './request-idle-callback' import { requestIdleCallback } from './request-idle-callback'
import { getDeploymentIdQueryOrEmptyString } from '../build/deployment-id' import { getDeploymentIdQueryOrEmptyString } from '../shared/lib/deployment-id'
import { encodeURIPath } from '../shared/lib/encode-uri-path' import { encodeURIPath } from '../shared/lib/encode-uri-path'
// 3.8s was arbitrarily chosen as it's what https://web.dev/interactive // 3.8s was arbitrarily chosen as it's what https://web.dev/interactive
......
declare const __webpack_require__: any declare const __webpack_require__: any
declare let __webpack_public_path__: string declare let __webpack_public_path__: string
import { getDeploymentIdQueryOrEmptyString } from '../build/deployment-id' import {
getDeploymentId,
getDeploymentIdQueryOrEmptyString,
} from '../shared/lib/deployment-id'
// If we have a deployment ID, we need to append it to the webpack chunk names // If we have a deployment ID, we need to append it to the webpack chunk names
// I am keeping the process check explicit so this can be statically optimized // I am keeping the process check explicit so this can be statically optimized
if (process.env.NEXT_DEPLOYMENT_ID) { if (getDeploymentId()) {
const suffix = getDeploymentIdQueryOrEmptyString() const suffix = getDeploymentIdQueryOrEmptyString()
const getChunkScriptFilename = __webpack_require__.u const getChunkScriptFilename = __webpack_require__.u
__webpack_require__.u = (...args: any[]) => __webpack_require__.u = (...args: any[]) =>
......
...@@ -42,6 +42,7 @@ import type { ...@@ -42,6 +42,7 @@ import type {
GetStaticPaths, GetStaticPaths,
GetStaticProps, GetStaticProps,
} from '../../../types' } from '../../../types'
import { getDeploymentId } from '../../../shared/lib/deployment-id'
export const getHandler = ({ export const getHandler = ({
srcPage: originalSrcPage, srcPage: originalSrcPage,
...@@ -257,7 +258,7 @@ export const getHandler = ({ ...@@ -257,7 +258,7 @@ export const getHandler = ({
buildId, buildId,
customServer: customServer:
Boolean(routerServerContext?.isCustomServer) || undefined, Boolean(routerServerContext?.isCustomServer) || undefined,
deploymentId: process.env.NEXT_DEPLOYMENT_ID, deploymentId: getDeploymentId(),
}, },
renderOpts: { renderOpts: {
params, params,
......
// This could also be a variable instead of a function, but some unit tests want to change the ID at
// runtime. Even though that would never happen in a real deployment.
export function getDeploymentId(): string | undefined {
return process.env.NEXT_DEPLOYMENT_ID
}
export function getDeploymentIdQueryOrEmptyString(): string {
let deploymentId = getDeploymentId()
if (deploymentId) {
return `?dpl=${deploymentId}`
}
return ''
}
import type { ImageLoaderPropsWithConfig } from './image-config' import type { ImageLoaderPropsWithConfig } from './image-config'
import { findClosestQuality } from './find-closest-quality' import { findClosestQuality } from './find-closest-quality'
import { getDeploymentId } from './deployment-id'
function defaultLoader({ function defaultLoader({
config, config,
...@@ -94,9 +95,10 @@ function defaultLoader({ ...@@ -94,9 +95,10 @@ function defaultLoader({
const q = findClosestQuality(quality, config) const q = findClosestQuality(quality, config)
let deploymentId = getDeploymentId()
return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${q}${ return `${config.path}?url=${encodeURIComponent(src)}&w=${width}&q=${q}${
src.startsWith('/_next/static/media/') && process.env.NEXT_DEPLOYMENT_ID src.startsWith('/_next/static/media/') && deploymentId
? `&dpl=${process.env.NEXT_DEPLOYMENT_ID}` ? `&dpl=${deploymentId}`
: '' : ''
}` }`
} }
......
...@@ -4,6 +4,7 @@ import { preload } from 'react-dom' ...@@ -4,6 +4,7 @@ import { preload } from 'react-dom'
import { workAsyncStorage } from '../../../server/app-render/work-async-storage.external' import { workAsyncStorage } from '../../../server/app-render/work-async-storage.external'
import { encodeURIPath } from '../encode-uri-path' import { encodeURIPath } from '../encode-uri-path'
import { getDeploymentIdQueryOrEmptyString } from '../deployment-id'
export function PreloadChunks({ export function PreloadChunks({
moduleIds, moduleIds,
...@@ -37,9 +38,7 @@ export function PreloadChunks({ ...@@ -37,9 +38,7 @@ export function PreloadChunks({
return null return null
} }
const dplId = process.env.NEXT_DEPLOYMENT_ID const dplId = getDeploymentIdQueryOrEmptyString()
? `?dpl=${process.env.NEXT_DEPLOYMENT_ID}`
: ''
return ( return (
<> <>
......
...@@ -43,6 +43,7 @@ import { interpolateAs } from './utils/interpolate-as' ...@@ -43,6 +43,7 @@ import { interpolateAs } from './utils/interpolate-as'
import { disableSmoothScrollDuringRouteTransition } from './utils/disable-smooth-scroll' import { disableSmoothScrollDuringRouteTransition } from './utils/disable-smooth-scroll'
import type { Params } from '../../../server/request/params' import type { Params } from '../../../server/request/params'
import { MATCHED_PATH_HEADER } from '../../../lib/constants' import { MATCHED_PATH_HEADER } from '../../../lib/constants'
import { getDeploymentId } from '../deployment-id'
let resolveRewrites: typeof import('./utils/resolve-rewrites').default let resolveRewrites: typeof import('./utils/resolve-rewrites').default
if (process.env.__NEXT_HAS_REWRITES) { if (process.env.__NEXT_HAS_REWRITES) {
...@@ -497,15 +498,14 @@ function fetchNextData({ ...@@ -497,15 +498,14 @@ function fetchNextData({
unstable_skipClientCache, unstable_skipClientCache,
}: FetchNextDataParams): Promise<FetchDataOutput> { }: FetchNextDataParams): Promise<FetchDataOutput> {
const { href: cacheKey } = new URL(dataHref, window.location.href) const { href: cacheKey } = new URL(dataHref, window.location.href)
const deploymentId = getDeploymentId()
const getData = (params?: { method?: 'HEAD' | 'GET' }) => const getData = (params?: { method?: 'HEAD' | 'GET' }) =>
fetchRetry(dataHref, isServerRender ? 3 : 1, { fetchRetry(dataHref, isServerRender ? 3 : 1, {
headers: Object.assign( headers: Object.assign(
{} as HeadersInit, {} as HeadersInit,
isPrefetch ? { purpose: 'prefetch' } : {}, isPrefetch ? { purpose: 'prefetch' } : {},
isPrefetch && hasMiddleware ? { 'x-middleware-prefetch': '1' } : {}, isPrefetch && hasMiddleware ? { 'x-middleware-prefetch': '1' } : {},
process.env.NEXT_DEPLOYMENT_ID deploymentId ? { 'x-deployment-id': deploymentId } : {}
? { 'x-deployment-id': process.env.NEXT_DEPLOYMENT_ID }
: {}
), ),
method: params?.method ?? 'GET', method: params?.method ?? 'GET',
}) })
......
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