Skip to content

Commit e20fb2a

Browse files
committed
WIP: perf: Don't inject the entire nextConfig in edge templates
1 parent dae80fb commit e20fb2a

File tree

11 files changed

+57
-109
lines changed

11 files changed

+57
-109
lines changed

crates/next-core/src/next_app/app_page_entry.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -145,17 +145,14 @@ async fn wrap_edge_page(
145145
) -> Result<Vc<Box<dyn Module>>> {
146146
const INNER: &str = "INNER_PAGE_ENTRY";
147147

148-
let next_config_val = &*next_config.await?;
149-
150148
let source = load_next_js_template(
151149
"edge-ssr-app.js",
152150
project_root.clone(),
153151
&[("VAR_USERLAND", INNER), ("VAR_PAGE", &page.to_string())],
154-
&[
155-
// TODO do we really need to pass the entire next config here?
156-
// This is bad for invalidation as any config change will invalidate this
157-
("nextConfig", &*serde_json::to_string(next_config_val)?),
158-
],
152+
&[(
153+
"cacheMaxMemorySize",
154+
&*serde_json::to_string(&next_config.cache_max_memory_size().await?)?,
155+
)],
159156
&[("incrementalCacheHandler", None)],
160157
)
161158
.await?;

crates/next-core/src/next_app/app_route_entry.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,14 @@ async fn wrap_edge_route(
136136
) -> Result<Vc<Box<dyn Module>>> {
137137
let inner = rcstr!("INNER_ROUTE_ENTRY");
138138

139-
let next_config = &*next_config.await?;
140-
141139
let source = load_next_js_template(
142140
"edge-app-route.js",
143141
project_root.clone(),
144142
&[("VAR_USERLAND", &*inner), ("VAR_PAGE", &page.to_string())],
145-
&[("nextConfig", &*serde_json::to_string(next_config)?)],
143+
&[(
144+
"cacheLifeProfiles",
145+
&*serde_json::to_string(&next_config.cache_life().await?)?,
146+
)],
146147
&[],
147148
)
148149
.await?;

crates/next-core/src/next_config.rs

Lines changed: 12 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,11 @@ pub struct NextConfig {
8181
config_file: Option<RcStr>,
8282
config_file_name: RcStr,
8383

84+
cache_life: Option<JsonValue>,
8485
/// In-memory cache size in bytes.
8586
///
8687
/// If `cache_max_memory_size: 0` disables in-memory caching.
87-
cache_max_memory_size: Option<f64>,
88+
cache_max_memory_size: Option<JsonValue>,
8889
/// custom path to a cache handler to use
8990
cache_handler: Option<RcStr>,
9091
cache_handlers: Option<FxIndexMap<RcStr, RcStr>>,
@@ -835,7 +836,6 @@ pub struct ExperimentalConfig {
835836
adjust_font_fallbacks_with_size_adjust: Option<bool>,
836837
after: Option<bool>,
837838
app_document_preloading: Option<bool>,
838-
cache_life: Option<FxIndexMap<String, CacheLifeProfile>>,
839839
case_sensitive_routes: Option<bool>,
840840
cpus: Option<f64>,
841841
cra_compat: Option<bool>,
@@ -908,63 +908,6 @@ pub struct ExperimentalConfig {
908908
devtool_segment_explorer: Option<bool>,
909909
}
910910

911-
#[derive(
912-
Clone, Debug, PartialEq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue,
913-
)]
914-
#[serde(rename_all = "camelCase")]
915-
pub struct CacheLifeProfile {
916-
#[serde(skip_serializing_if = "Option::is_none")]
917-
pub stale: Option<u32>,
918-
#[serde(skip_serializing_if = "Option::is_none")]
919-
pub revalidate: Option<u32>,
920-
#[serde(skip_serializing_if = "Option::is_none")]
921-
pub expire: Option<u32>,
922-
}
923-
924-
#[test]
925-
fn test_cache_life_profiles() {
926-
let json = serde_json::json!({
927-
"cacheLife": {
928-
"frequent": {
929-
"stale": 19,
930-
"revalidate": 100,
931-
},
932-
}
933-
});
934-
935-
let config: ExperimentalConfig = serde_json::from_value(json).unwrap();
936-
let mut expected_cache_life = FxIndexMap::default();
937-
938-
expected_cache_life.insert(
939-
"frequent".to_string(),
940-
CacheLifeProfile {
941-
stale: Some(19),
942-
revalidate: Some(100),
943-
expire: None,
944-
},
945-
);
946-
947-
assert_eq!(config.cache_life, Some(expected_cache_life));
948-
}
949-
950-
#[test]
951-
fn test_cache_life_profiles_invalid() {
952-
let json = serde_json::json!({
953-
"cacheLife": {
954-
"invalid": {
955-
"stale": "invalid_value",
956-
},
957-
}
958-
});
959-
960-
let result: Result<ExperimentalConfig, _> = serde_json::from_value(json);
961-
962-
assert!(
963-
result.is_err(),
964-
"Deserialization should fail due to invalid 'stale' value type"
965-
);
966-
}
967-
968911
#[derive(
969912
Clone, Debug, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, NonLocalValue, OperationValue,
970913
)]
@@ -1312,6 +1255,16 @@ impl NextConfig {
13121255
Vc::cell(self.base_path.clone())
13131256
}
13141257

1258+
#[turbo_tasks::function]
1259+
pub fn cache_life(&self) -> Vc<OptionJsonValue> {
1260+
Vc::cell(self.cache_life.clone())
1261+
}
1262+
1263+
#[turbo_tasks::function]
1264+
pub fn cache_max_memory_size(&self) -> Vc<OptionJsonValue> {
1265+
Vc::cell(self.cache_max_memory_size.clone())
1266+
}
1267+
13151268
#[turbo_tasks::function]
13161269
pub fn cache_handler(&self, project_path: FileSystemPath) -> Result<Vc<OptionFileSystemPath>> {
13171270
if let Some(handler) = &self.cache_handler {

crates/next-core/src/next_pages/page_entry.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -223,8 +223,6 @@ async fn wrap_edge_page(
223223
const INNER_ERROR: &str = "INNER_ERROR";
224224
const INNER_ERROR_500: &str = "INNER_500";
225225

226-
let next_config_val = &*next_config.await?;
227-
228226
let source = load_next_js_template(
229227
"edge-ssr.js",
230228
project_root.clone(),
@@ -236,9 +234,10 @@ async fn wrap_edge_page(
236234
("VAR_MODULE_GLOBAL_ERROR", INNER_ERROR),
237235
],
238236
&[
239-
// TODO do we really need to pass the entire next config here?
240-
// This is bad for invalidation as any config change will invalidate this
241-
("nextConfig", &*serde_json::to_string(next_config_val)?),
237+
(
238+
"cacheMaxMemorySize",
239+
&*serde_json::to_string(&next_config.cache_max_memory_size().await?)?,
240+
),
242241
(
243242
"pageRouteModuleOptions",
244243
&serde_json::to_string(&get_route_module_options(page.clone(), pathname.clone()))?,

packages/next/src/build/entries.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -616,7 +616,9 @@ export function getEdgeServerEntry(opts: {
616616
absolutePagePath: opts.absolutePagePath,
617617
page: opts.page,
618618
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
619-
nextConfig: Buffer.from(JSON.stringify(opts.config)).toString('base64'),
619+
cacheLifeProfiles: Buffer.from(
620+
JSON.stringify(opts.config.cacheLife)
621+
).toString('base64'),
620622
preferredRegion: opts.preferredRegion,
621623
middlewareConfig: Buffer.from(
622624
JSON.stringify(opts.middlewareConfig || {})
@@ -677,9 +679,7 @@ export function getEdgeServerEntry(opts: {
677679
dev: opts.isDev,
678680
isServerComponent: opts.isServerComponent,
679681
page: opts.page,
680-
stringifiedConfig: Buffer.from(JSON.stringify(opts.config)).toString(
681-
'base64'
682-
),
682+
cacheMaxMemorySize: JSON.stringify(opts.config.cacheMaxMemorySize),
683683
pagesType: opts.pagesType,
684684
appDirLoader: Buffer.from(opts.appDirLoader || '').toString('base64'),
685685
sriEnabled: !opts.isDev && !!opts.config.experimental.sri?.algorithm,

packages/next/src/build/templates/edge-app-route.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapp
77
import * as module from 'VAR_USERLAND'
88

99
// injected by the loader afterwards.
10-
declare const nextConfig: NextConfigComplete
11-
// INJECT:nextConfig
10+
declare const cacheLifeProfiles: NextConfigComplete['cacheLife']
11+
// INJECT:cacheLifeProfiles
1212

1313
const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)
1414

@@ -28,4 +28,6 @@ if (rscManifest && rscServerManifest) {
2828

2929
export const ComponentMod = module
3030

31-
export default EdgeRouteModuleWrapper.wrap(module.routeModule, { nextConfig })
31+
export default EdgeRouteModuleWrapper.wrap(module.routeModule, {
32+
cacheLifeProfiles,
33+
})

packages/next/src/build/templates/edge-ssr-app.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import { IncrementalCache } from '../../server/lib/incremental-cache'
55
import * as pageMod from 'VAR_USERLAND'
66

77
import type { RequestData } from '../../server/web/types'
8-
import type { NextConfigComplete } from '../../server/config-shared'
98
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils'
109
import { createServerModuleMap } from '../../server/app-render/action-utils'
1110
import { initializeCacheHandlers } from '../../server/use-cache/handlers'
@@ -27,12 +26,12 @@ import { checkIsOnDemandRevalidate } from '../../server/api-utils'
2726
import { CloseController } from '../../server/web/web-on-close'
2827

2928
declare const incrementalCacheHandler: any
30-
declare const nextConfig: NextConfigComplete
29+
declare const cacheMaxMemorySize: number
3130
// OPTIONAL_IMPORT:incrementalCacheHandler
32-
// INJECT:nextConfig
31+
// INJECT:cacheMaxMemorySize
3332

3433
// Initialize the cache handlers interface.
35-
initializeCacheHandlers(nextConfig.cacheMaxMemorySize)
34+
initializeCacheHandlers(cacheMaxMemorySize)
3635

3736
const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)
3837

@@ -77,6 +76,7 @@ async function requestHandler(
7776
const {
7877
query,
7978
params,
79+
nextConfig,
8080
buildId,
8181
buildManifest,
8282
prerenderManifest,

packages/next/src/build/templates/edge-ssr.ts

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import RouteModule, {
1919
import { WebNextRequest, WebNextResponse } from '../../server/base-http/web'
2020

2121
import type { RequestData } from '../../server/web/types'
22-
import type { NextConfigComplete } from '../../server/config-shared'
2322
import type { NextFetchEvent } from '../../server/web/spec-extension/fetch-event'
2423
import type RenderResult from '../../server/render-result'
2524
import type { RenderResultMetadata } from '../../server/render-result'
@@ -28,20 +27,17 @@ import { BaseServerSpan } from '../../server/lib/trace/constants'
2827
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
2928

3029
// injected by the loader afterwards.
31-
declare const nextConfig: NextConfigComplete
30+
declare const cacheMaxMemorySize: number
3231
declare const pageRouteModuleOptions: any
3332
declare const errorRouteModuleOptions: any
3433
declare const user500RouteModuleOptions: any
35-
// INJECT:nextConfig
34+
// INJECT:cacheMaxMemorySize
3635
// INJECT:pageRouteModuleOptions
3736
// INJECT:errorRouteModuleOptions
3837
// INJECT:user500RouteModuleOptions
3938

4039
// Initialize the cache handlers interface.
41-
initializeCacheHandlers(nextConfig.cacheMaxMemorySize)
42-
43-
// expose this for the route-module
44-
;(globalThis as any).nextConfig = nextConfig
40+
initializeCacheHandlers(cacheMaxMemorySize)
4541

4642
const pageMod = {
4743
...userlandPage,
@@ -106,6 +102,7 @@ async function requestHandler(
106102
const {
107103
query,
108104
params,
105+
nextConfig,
109106
buildId,
110107
isNextDataRequest,
111108
buildManifest,

packages/next/src/build/webpack/loaders/next-edge-app-route-loader/index.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export type EdgeAppRouteLoaderQuery = {
1111
page: string
1212
appDirLoader: string
1313
preferredRegion: string | string[] | undefined
14-
nextConfig: string
14+
cacheLifeProfiles: string
1515
middlewareConfig: string
1616
cacheHandlers: string
1717
}
@@ -24,7 +24,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
2424
preferredRegion,
2525
appDirLoader: appDirLoaderBase64 = '',
2626
middlewareConfig: middlewareConfigBase64 = '',
27-
nextConfig: nextConfigBase64,
27+
cacheLifeProfiles: cacheLifeProfilesBase64,
2828
cacheHandlers: cacheHandlersStringified,
2929
} = this.getOptions()
3030

@@ -64,8 +64,8 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
6464
stringifiedPagePath.length - 1
6565
)}?${WEBPACK_RESOURCE_QUERIES.edgeSSREntry}`
6666

67-
const stringifiedConfig = Buffer.from(
68-
nextConfigBase64 || '',
67+
const stringifiedCacheLifeProfiles = Buffer.from(
68+
cacheLifeProfilesBase64 || '',
6969
'base64'
7070
).toString()
7171

@@ -76,7 +76,7 @@ const EdgeAppRouteLoader: webpack.LoaderDefinitionFunction<EdgeAppRouteLoaderQue
7676
VAR_PAGE: page,
7777
},
7878
{
79-
nextConfig: stringifiedConfig,
79+
cacheLifeProfiles: stringifiedCacheLifeProfiles,
8080
}
8181
)
8282
}

packages/next/src/build/webpack/loaders/next-edge-ssr-loader/index.ts

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export type EdgeSSRLoaderQuery = {
1919
dev: boolean
2020
isServerComponent: boolean
2121
page: string
22-
stringifiedConfig: string
22+
cacheMaxMemorySize: string
2323
appDirLoader?: string
2424
pagesType: PAGE_TYPES
2525
sriEnabled: boolean
@@ -73,7 +73,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
7373
absolute500Path,
7474
absoluteErrorPath,
7575
isServerComponent,
76-
stringifiedConfig: stringifiedConfigBase64,
76+
cacheMaxMemorySize: cacheMaxMemorySizeStringified,
7777
appDirLoader: appDirLoaderBase64,
7878
pagesType,
7979
cacheHandler,
@@ -94,10 +94,6 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
9494
Buffer.from(middlewareConfigBase64, 'base64').toString()
9595
)
9696

97-
const stringifiedConfig = Buffer.from(
98-
stringifiedConfigBase64 || '',
99-
'base64'
100-
).toString()
10197
const appDirLoader = Buffer.from(
10298
appDirLoaderBase64 || '',
10399
'base64'
@@ -161,7 +157,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
161157
VAR_PAGE: page,
162158
},
163159
{
164-
nextConfig: stringifiedConfig,
160+
cacheMaxMemorySize: cacheMaxMemorySizeStringified,
165161
},
166162
{
167163
incrementalCacheHandler: cacheHandler ?? null,
@@ -178,7 +174,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
178174
VAR_MODULE_GLOBAL_ERROR: errorPath,
179175
},
180176
{
181-
nextConfig: stringifiedConfig,
177+
cacheMaxMemorySize: cacheMaxMemorySizeStringified,
182178
pageRouteModuleOptions: JSON.stringify(getRouteModuleOptions(page)),
183179
errorRouteModuleOptions: JSON.stringify(
184180
getRouteModuleOptions('/_error')

0 commit comments

Comments
 (0)