Unverified Commit b15d4818 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

[dynamicIO] show dev & build warnings when using incompatible segment configs (#71500)

This logs an error in dev and fails a build when using incompatible
segment configs (`dynamic`, `fetchCache`, `runtime`, `dynamicParams`)
with dynamicIO. It will point to all discovered pages that contained the
invalid segment config at the end of the build.

![CleanShot 2024-10-18 at 15 55
17@2x](https://github.com/user-attachments/assets/d8c21ede-a71d-4b26-a76d-26e330aa8de2)

In dev, it will show the error in an overlay. The invalid segment
configs must be removed to build.

![CleanShot 2024-10-19 at 11 47
59@2x](https://github.com/user-attachments/assets/c53797d8-5729-4567-9fb0-5d12c2860382)

Note: This removes all incompatible test cases that were previously part
of the `dynamic-io` test suites, and disables one that was using a
fetchCache workaround until it's properly handled.
parent 272ff8f6
...@@ -79,6 +79,12 @@ export interface AppPageStaticInfo { ...@@ -79,6 +79,12 @@ export interface AppPageStaticInfo {
runtime: AppSegmentConfig['runtime'] | undefined runtime: AppSegmentConfig['runtime'] | undefined
preferredRegion: AppSegmentConfig['preferredRegion'] | undefined preferredRegion: AppSegmentConfig['preferredRegion'] | undefined
maxDuration: number | undefined maxDuration: number | undefined
/**
* This field is only populated when `experimental.dynamicIO` is enabled.
* It contains a list of segment configs that are part of the page
* and are not supported with the feature.
*/
unsupportedSegmentConfigs: string[] | undefined
} }
export interface PagesPageStaticInfo { export interface PagesPageStaticInfo {
...@@ -488,6 +494,7 @@ export async function getAppPageStaticInfo({ ...@@ -488,6 +494,7 @@ export async function getAppPageStaticInfo({
runtime: undefined, runtime: undefined,
preferredRegion: undefined, preferredRegion: undefined,
maxDuration: undefined, maxDuration: undefined,
unsupportedSegmentConfigs: undefined,
} }
} }
...@@ -527,6 +534,22 @@ export async function getAppPageStaticInfo({ ...@@ -527,6 +534,22 @@ export async function getAppPageStaticInfo({
const route = normalizeAppPath(page) const route = normalizeAppPath(page)
const config = parseAppSegmentConfig(exportedConfig, route) const config = parseAppSegmentConfig(exportedConfig, route)
let unsupportedSegmentConfigs: string[] | undefined
// Enabling dynamicIO will disable certain segment configs, as they pertain to the old
// model of detecting dynamic behavior and these options aren't meant to be used together.
if (nextConfig.experimental?.dynamicIO) {
const unsupportedSegments = [
'dynamicParams',
'dynamic',
'runtime',
'fetchCache',
'revalidate',
] as const
unsupportedSegmentConfigs = unsupportedSegments
.filter((prop) => typeof config[prop] !== 'undefined')
.sort()
}
// Prevent edge runtime and generateStaticParams in the same file. // Prevent edge runtime and generateStaticParams in the same file.
if (isEdgeRuntime(config.runtime) && generateStaticParams) { if (isEdgeRuntime(config.runtime) && generateStaticParams) {
...@@ -553,6 +576,7 @@ export async function getAppPageStaticInfo({ ...@@ -553,6 +576,7 @@ export async function getAppPageStaticInfo({
runtime: config.runtime, runtime: config.runtime,
preferredRegion: config.preferredRegion, preferredRegion: config.preferredRegion,
maxDuration: config.maxDuration, maxDuration: config.maxDuration,
unsupportedSegmentConfigs,
} }
} }
......
...@@ -160,6 +160,18 @@ export async function getStaticInfoIncludingLayouts({ ...@@ -160,6 +160,18 @@ export async function getStaticInfoIncludingLayouts({
pageType: isInsideAppDir ? PAGE_TYPES.APP : PAGE_TYPES.PAGES, pageType: isInsideAppDir ? PAGE_TYPES.APP : PAGE_TYPES.PAGES,
}) })
if (layoutStaticInfo.unsupportedSegmentConfigs) {
// Merge unsupported segment configs from the layout into the page
// while deduping the list as it's possible for overlap
layoutStaticInfo.unsupportedSegmentConfigs =
layoutStaticInfo.unsupportedSegmentConfigs.concat(
pageStaticInfo.unsupportedSegmentConfigs || []
)
pageStaticInfo.unsupportedSegmentConfigs = [
...new Set(layoutStaticInfo.unsupportedSegmentConfigs),
]
}
segments.unshift(layoutStaticInfo) segments.unshift(layoutStaticInfo)
} }
} }
......
...@@ -2421,11 +2421,38 @@ export default async function build( ...@@ -2421,11 +2421,38 @@ export default async function build(
pageDuration: undefined, pageDuration: undefined,
ssgPageDurations: undefined, ssgPageDurations: undefined,
hasEmptyPrelude: undefined, hasEmptyPrelude: undefined,
unsupportedSegmentConfigs:
staticInfo && 'unsupportedSegmentConfigs' in staticInfo
? staticInfo.unsupportedSegmentConfigs
: undefined,
}) })
}) })
}) })
) )
// When dynamicIO is enabled, certain segment configs are not supported as they conflict with dynamicIO behavior.
// This will print all the pages along with the segment configs that were used.
if (config.experimental.dynamicIO) {
const pagesWithSegmentConfigs: string[] = []
pageInfos.forEach((pageInfo, page) => {
if (
pageInfo.unsupportedSegmentConfigs &&
pageInfo.unsupportedSegmentConfigs.length > 0
) {
const configs = pageInfo.unsupportedSegmentConfigs.join(', ')
pagesWithSegmentConfigs.push(`${page}: ${configs}`)
}
})
if (pagesWithSegmentConfigs.length > 0) {
Log.error(
`The following pages used segment configs which are not supported with "experimental.dynamicIO" and must be removed to build your application:\n${pagesWithSegmentConfigs.join('\n')}\n`
)
process.exit(1)
}
}
if (hadUnsupportedValue) { if (hadUnsupportedValue) {
Log.error( Log.error(
`Invalid config value exports detected, these can cause unexpected behavior from the configs not being applied. Please fix them to continue` `Invalid config value exports detected, these can cause unexpected behavior from the configs not being applied. Please fix them to continue`
......
...@@ -372,6 +372,7 @@ export interface PageInfo { ...@@ -372,6 +372,7 @@ export interface PageInfo {
hasEmptyPrelude?: boolean hasEmptyPrelude?: boolean
hasPostponed?: boolean hasPostponed?: boolean
isDynamicAppRoute?: boolean isDynamicAppRoute?: boolean
unsupportedSegmentConfigs: string[] | undefined
} }
export type PageInfos = Map<string, PageInfo> export type PageInfos = Map<string, PageInfo>
......
...@@ -298,6 +298,7 @@ async function startWatcher(opts: SetupOpts) { ...@@ -298,6 +298,7 @@ async function startWatcher(opts: SetupOpts) {
const conflictingAppPagePaths = new Set<string>() const conflictingAppPagePaths = new Set<string>()
const appPageFilePaths = new Map<string, string>() const appPageFilePaths = new Map<string, string>()
const pagesPageFilePaths = new Map<string, string>() const pagesPageFilePaths = new Map<string, string>()
const pagesWithUnsupportedSegments = new Map<string, string[]>()
let envChange = false let envChange = false
let tsconfigChange = false let tsconfigChange = false
...@@ -309,6 +310,7 @@ async function startWatcher(opts: SetupOpts) { ...@@ -309,6 +310,7 @@ async function startWatcher(opts: SetupOpts) {
appFiles.clear() appFiles.clear()
pageFiles.clear() pageFiles.clear()
devPageFiles.clear() devPageFiles.clear()
pagesWithUnsupportedSegments.clear()
const sortedKnownFiles: string[] = [...knownFiles.keys()].sort( const sortedKnownFiles: string[] = [...knownFiles.keys()].sort(
sortByPageExts(nextConfig.pageExtensions) sortByPageExts(nextConfig.pageExtensions)
...@@ -489,6 +491,28 @@ async function startWatcher(opts: SetupOpts) { ...@@ -489,6 +491,28 @@ async function startWatcher(opts: SetupOpts) {
appFiles.add(pageName) appFiles.add(pageName)
} }
if (nextConfig.experimental.dynamicIO) {
const staticInfo = await getStaticInfoIncludingLayouts({
pageFilePath: fileName,
config: nextConfig,
appDir: appDir,
page: rootFile,
isDev: true,
isInsideAppDir: isAppPath,
pageExtensions: nextConfig.pageExtensions,
})
if (
'unsupportedSegmentConfigs' in staticInfo &&
staticInfo.unsupportedSegmentConfigs?.length
) {
pagesWithUnsupportedSegments.set(
pageName,
staticInfo.unsupportedSegmentConfigs
)
}
}
if (routedPages.includes(pageName)) { if (routedPages.includes(pageName)) {
continue continue
} }
...@@ -523,6 +547,30 @@ async function startWatcher(opts: SetupOpts) { ...@@ -523,6 +547,30 @@ async function startWatcher(opts: SetupOpts) {
routedPages.push(pageName) routedPages.push(pageName)
} }
// When dynamicIO is enabled, certain segment configs are not supported as they conflict with dynamicIO behavior.
// This will print all the pages along with the segment configs that were used.
if (nextConfig.experimental.dynamicIO) {
const pagesWithIncompatibleSegmentConfigs: string[] = []
pagesWithUnsupportedSegments.forEach(
(unsupportedSegmentConfigs, page) => {
if (
unsupportedSegmentConfigs &&
unsupportedSegmentConfigs.length > 0
) {
const configs = unsupportedSegmentConfigs.join(', ')
pagesWithIncompatibleSegmentConfigs.push(`${page}: ${configs}`)
}
}
)
if (pagesWithIncompatibleSegmentConfigs.length > 0) {
const errorMessage = `The following pages used segment configs which are not supported with "experimental.dynamicIO" and must be removed to build your application:\n${pagesWithIncompatibleSegmentConfigs.join('\n')}\n`
Log.error(errorMessage)
hotReloader.setHmrServerError(new Error(errorMessage))
}
}
const numConflicting = conflictingAppPagePaths.size const numConflicting = conflictingAppPagePaths.size
conflictingPageChange = numConflicting - previousConflictingPagePaths.size conflictingPageChange = numConflicting - previousConflictingPagePaths.size
......
// Return a list of `params` to populate the [slug] dynamic segment
export async function generateStaticParams() {
return [{ slug: 'foo' }, { slug: 'bar' }, { slug: 'baz' }]
}
export default function Page({ params }) {
const { slug } = params
return <div>Hello from {slug}</div>
}
export const dynamicParams = false
export const dynamic = 'force-dynamic'
export default function Page() {
return <div>This page uses `export const dynamic`.</div>
}
export const dynamic = 'force-dynamic'
export default function Page() {
return <div>This page uses `export const dynamic`.</div>
}
export const fetchCache = 'force-no-store'
export default function Page() {
return <div>This page uses `export const fetchCache`.</div>
}
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<main>{children}</main>
</body>
</html>
)
}
export const runtime = 'edge'
export const dynamic = 'force-dynamic'
export const fetchCache = 'force-no-store'
export default function Page() {
return (
<div>
This page uses `export const runtime`, `export const dynamic`, and `export
const fetchCache`.
</div>
)
}
export default function Page() {
return <div>Hello World</div>
}
export const revalidate = 1
export default function Page() {
return <div>This page uses `export const revalidate`.</div>
}
export const runtime = 'edge'
export default function Page() {
return <div>This page uses `export const runtime`.</div>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('dynamic-io-segment-configs', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it("it should error when using segment configs that aren't supported by dynamicIO", async () => {
try {
await next.start()
} catch {
// we expect the build to fail
}
expect(next.cliOutput).toContain(
'The following pages used segment configs which are not supported with "experimental.dynamicIO"'
)
expect(next.cliOutput).toContain('/runtime: runtime')
expect(next.cliOutput).toContain('/multiple: dynamic, fetchCache, runtime')
expect(next.cliOutput).toContain('/dynamic/nested: dynamic')
expect(next.cliOutput).toContain('/dynamic-params/[slug]: dynamicParams')
expect(next.cliOutput).toContain('/fetch-cache: fetchCache')
expect(next.cliOutput).toContain('/dynamic: dynamic')
expect(next.cliOutput).toContain('/revalidate: revalidate')
})
it('should propagate configurations from layouts to pages', async () => {
// patch the root layout. We expect the "dynamic" segment config to now be part of
// each sub-page that uses this layout.
await next.patchFile(
'app/layout.tsx',
(content) => {
return `
export const dynamic = 'force-dynamic';
${content}
`
},
async () => {
try {
await next.start()
} catch {
// we expect the build to fail
}
await retry(async () => {
expect(next.cliOutput).toContain(
'The following pages used segment configs which are not supported with "experimental.dynamicIO"'
)
expect(next.cliOutput).toContain('/runtime: dynamic, runtime')
expect(next.cliOutput).toContain(
'/multiple: dynamic, fetchCache, runtime'
)
expect(next.cliOutput).toContain('/dynamic/nested: dynamic')
expect(next.cliOutput).toContain(
'/dynamic-params/[slug]: dynamic, dynamicParams'
)
expect(next.cliOutput).toContain('/fetch-cache: dynamic, fetchCache')
expect(next.cliOutput).toContain('/dynamic: dynamic')
expect(next.cliOutput).toContain('/revalidate: dynamic, revalidate')
})
}
)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
dynamicIO: true,
},
}
module.exports = nextConfig
import { Suspense } from 'react' import { Suspense } from 'react'
// TODO once we make fetchCache inert with dynamicIO this test is expected
// to start failing. Right now the force cache causes the fetches to be identical
// and we get only one prebuilt route. once we remove the caching behavior of fetchCache
// when dynamicIO is on we will get more than one route.
// The ideal test wouldn't even use fetchCache but at the moment the default caching for fetch
// is to not cache and so we can't rely on the default to produce a differentiating result.
export const fetchCache = 'default-cache'
export async function generateStaticParams() { export async function generateStaticParams() {
const set = new Set() const set = new Set()
set.add(await fetchRandom('a')) set.add(await fetchRandom('a'))
......
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(
request: NextRequest,
props: { params: Promise<{ dyn: string }> }
) {
const { dyn } = await props.params
return new Response(
JSON.stringify({
value: getSentinelValue(),
type: 'dynamic params',
param: dyn,
})
)
}
import type { NextRequest, UnsafeUnwrappedParams } from 'next/server'
import { getSentinelValue } from '../../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(
request: NextRequest,
props: { params: Promise<{ dyn: string }> }
) {
const dyn = (
props.params as unknown as UnsafeUnwrappedParams<typeof props.params>
).dyn
return new Response(
JSON.stringify({
value: getSentinelValue(),
type: 'dynamic params',
param: dyn,
})
)
}
import type { NextRequest } from 'next/server'
import { cookies } from 'next/headers'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const sentinel = (await cookies()).get('x-sentinel')
return new Response(
JSON.stringify({
value: getSentinelValue(),
type: 'cookies',
'x-sentinel': sentinel,
})
)
}
import type { NextRequest } from 'next/server'
import { headers } from 'next/headers'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const sentinel = (await headers()).get('x-sentinel')
return new Response(
JSON.stringify({
value: getSentinelValue(),
type: 'headers',
'x-sentinel': sentinel,
})
)
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const result = JSON.stringify({
value: getSentinelValue(),
message: 'dynamic stream',
})
const part1 = result.slice(0, result.length / 2)
const part2 = result.slice(result.length / 2)
const encoder = new TextEncoder()
const chunks = [encoder.encode(part1), encoder.encode(part2)]
let sent = 0
const stream = new ReadableStream({
async pull(controller) {
controller.enqueue(chunks[sent++])
await new Promise((r) => setTimeout(r, 1))
if (sent === chunks.length) {
controller.close()
}
},
})
return new Response(stream)
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const search = request.nextUrl.search
return new Response(
JSON.stringify({
value: getSentinelValue(),
search,
})
)
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const fetcheda = await fetchRandomCached('a')
const fetchedb = await fetchRandomCached('b')
return new Response(
JSON.stringify({
value: getSentinelValue(),
random1: fetcheda,
random2: fetchedb,
})
)
}
const fetchRandomCached = async (entropy: string) => {
const response = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?b=' + entropy,
{ cache: 'force-cache' }
)
return response.text()
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const fetcheda = await fetchRandomCached('a')
const fetchedb = await fetchRandomUncached('b')
return new Response(
JSON.stringify({
value: getSentinelValue(),
random1: fetcheda,
random2: fetchedb,
})
)
}
const fetchRandomCached = async (entropy: string) => {
const response = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?b=' + entropy,
{ cache: 'force-cache' }
)
return response.text()
}
const fetchRandomUncached = async (entropy: string) => {
const response = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?b=' + entropy
)
return response.text()
}
import type { NextRequest } from 'next/server'
import { unstable_cache as cache } from 'next/cache'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const messagea = await getCachedMessage('hello cached fast', 0)
const messageb = await getCachedMessage('hello cached slow', 20)
return new Response(
JSON.stringify({
value: getSentinelValue(),
message1: messagea,
message2: messageb,
})
)
}
async function getMessage(echo, delay) {
const tag = ((Math.random() * 10000) | 0).toString(16)
await new Promise((r) => setTimeout(r, delay))
return `${tag}:${echo}`
}
const getCachedMessage = cache(getMessage)
import type { NextRequest } from 'next/server'
import { unstable_cache as cache } from 'next/cache'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const messagea = await getCachedMessage('hello cached fast', 0)
const messageb = await getMessage('hello uncached slow', 20)
return new Response(
JSON.stringify({
value: getSentinelValue(),
message1: messagea,
message2: messageb,
})
)
}
async function getMessage(echo, delay) {
const tag = ((Math.random() * 10000) | 0).toString(16)
await new Promise((r) => setTimeout(r, delay))
return `${tag}:${echo}`
}
const getCachedMessage = cache(getMessage)
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
await Promise.resolve()
const response = JSON.stringify({
value: getSentinelValue(),
message: 'microtask',
})
return new Response(response)
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const response = JSON.stringify({
value: getSentinelValue(),
message: 'stream response',
})
const part1 = response.slice(0, Math.floor(response.length / 2))
const part2 = response.slice(Math.floor(response.length / 2))
const encoder = new TextEncoder()
const chunks = [encoder.encode(part1), encoder.encode(part2)]
let sent = 0
const stream = new ReadableStream({
pull(controller) {
controller.enqueue(chunks[sent++])
if (sent === chunks.length) {
controller.close()
}
},
})
return new Response(stream)
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export function GET(request: NextRequest) {
const response = JSON.stringify({
value: getSentinelValue(),
message: 'stream response',
})
const part1 = response.slice(0, Math.floor(response.length / 2))
const part2 = response.slice(Math.floor(response.length / 2))
const encoder = new TextEncoder()
const chunks = [encoder.encode(part1), encoder.encode(part2)]
let sent = 0
const stream = new ReadableStream({
pull(controller) {
controller.enqueue(chunks[sent++])
if (sent === chunks.length) {
controller.close()
}
},
})
return new Response(stream)
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const response = JSON.stringify({
value: getSentinelValue(),
message: 'string response',
})
return new Response(response)
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export function GET(request: NextRequest) {
const response = JSON.stringify({
value: getSentinelValue(),
message: 'string response',
})
return new Response(response)
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
await new Promise((r) => setTimeout(r, 10))
const response = JSON.stringify({
value: getSentinelValue(),
message: 'task',
})
return new Response(response)
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const messagea = await getCachedMessage('hello cached fast', 0)
const messageb = await getCachedMessage('hello cached slow', 20)
return new Response(
JSON.stringify({
value: getSentinelValue(),
message1: messagea,
message2: messageb,
})
)
}
async function getCachedMessage(echo, delay) {
'use cache'
const tag = ((Math.random() * 10000) | 0).toString(16)
await new Promise((r) => setTimeout(r, delay))
return `${tag}:${echo}`
}
import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) {
const messagea = await getCachedMessage('hello cached fast', 0)
const messageb = await getMessage('hello uncached slow', 20)
return new Response(
JSON.stringify({
value: getSentinelValue(),
message1: messagea,
message2: messageb,
})
)
}
async function getMessage(echo, delay) {
const tag = ((Math.random() * 10000) | 0).toString(16)
await new Promise((r) => setTimeout(r, delay))
return `${tag}:${echo}`
}
async function getCachedMessage(echo, delay) {
'use cache'
return getMessage(echo, delay)
}
...@@ -2,8 +2,6 @@ import type { NextRequest } from 'next/server' ...@@ -2,8 +2,6 @@ import type { NextRequest } from 'next/server'
import { getSentinelValue } from '../../getSentinelValue' import { getSentinelValue } from '../../getSentinelValue'
export const runtime = 'edge'
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
const fetcheda = await fetchRandomCached('a') const fetcheda = await fetchRandomCached('a')
const fetchedb = await fetchRandomUncached('b') const fetchedb = await fetchRandomUncached('b')
......
...@@ -2472,7 +2472,8 @@ describe('dynamic-io', () => { ...@@ -2472,7 +2472,8 @@ describe('dynamic-io', () => {
if (!isNextDev) { if (!isNextDev) {
describe('generateStaticParams', () => { describe('generateStaticParams', () => {
it('should have dynamicIO semantics inside generateStaticParams', async () => { // This test is skipped as the previous workaround of using `fetch-cache` will no longer be supported with DIO.
it.skip('should have dynamicIO semantics inside generateStaticParams', async () => {
// This test is named what we want but our current implementation is not actually correct yet. // This test is named what we want but our current implementation is not actually correct yet.
// We are asserting current behavior and will update the test when we land the correct behavior // We are asserting current behavior and will update the test when we land the correct behavior
......
...@@ -48,30 +48,6 @@ describe('dynamic-io', () => { ...@@ -48,30 +48,6 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(json.search).toEqual('?foo=bar') expect(json.search).toEqual('?foo=bar')
str = await next.render('/routes/-edge/dynamic-cookies', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.type).toEqual('cookies')
str = await next.render('/routes/-edge/dynamic-headers', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.type).toEqual('headers')
str = await next.render('/routes/-edge/dynamic-stream', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.message).toEqual('dynamic stream')
str = await next.render('/routes/-edge/dynamic-url?foo=bar', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.search).toEqual('?foo=bar')
}) })
it('should prerender GET route handlers that have entirely cached io (fetches)', async () => { it('should prerender GET route handlers that have entirely cached io (fetches)', async () => {
...@@ -103,23 +79,6 @@ describe('dynamic-io', () => { ...@@ -103,23 +79,6 @@ describe('dynamic-io', () => {
expect(random1).toEqual(json.random1) expect(random1).toEqual(json.random1)
expect(random2).toEqual(json.random2) expect(random2).toEqual(json.random2)
} }
str = await next.render('/routes/-edge/fetch-cached', {})
json = JSON.parse(str)
random1 = json.random1
random2 = json.random2
expect(json.value).toEqual('at runtime')
expect(typeof random1).toBe('string')
expect(typeof random2).toBe('string')
str = await next.render('/routes/-edge/fetch-cached', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(random1).toEqual(json.random1)
expect(random2).toEqual(json.random2)
}) })
it('should not prerender GET route handlers that have some uncached io (fetches)', async () => { it('should not prerender GET route handlers that have some uncached io (fetches)', async () => {
...@@ -139,23 +98,6 @@ describe('dynamic-io', () => { ...@@ -139,23 +98,6 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(random1).toEqual(json.random1) expect(random1).toEqual(json.random1)
expect(random2).not.toEqual(json.random2) expect(random2).not.toEqual(json.random2)
str = await next.render('/routes/-edge/fetch-mixed', {})
json = JSON.parse(str)
random1 = json.random1
random2 = json.random2
expect(json.value).toEqual('at runtime')
expect(typeof random1).toBe('string')
expect(typeof random2).toBe('string')
str = await next.render('/routes/-edge/fetch-mixed', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(random1).toEqual(json.random1)
expect(random2).not.toEqual(json.random2)
}) })
it('should prerender GET route handlers that have entirely cached io (unstable_cache)', async () => { it('should prerender GET route handlers that have entirely cached io (unstable_cache)', async () => {
...@@ -187,23 +129,6 @@ describe('dynamic-io', () => { ...@@ -187,23 +129,6 @@ describe('dynamic-io', () => {
expect(message1).toEqual(json.message1) expect(message1).toEqual(json.message1)
expect(message2).toEqual(json.message2) expect(message2).toEqual(json.message2)
} }
str = await next.render('/routes/-edge/io-cached', {})
json = JSON.parse(str)
message1 = json.message1
message2 = json.message2
expect(json.value).toEqual('at runtime')
expect(typeof message1).toBe('string')
expect(typeof message2).toBe('string')
str = await next.render('/routes/-edge/io-cached', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(message1).toEqual(json.message1)
expect(message2).toEqual(json.message2)
}) })
it('should prerender GET route handlers that have entirely cached io ("use cache")', async () => { it('should prerender GET route handlers that have entirely cached io ("use cache")', async () => {
...@@ -235,23 +160,6 @@ describe('dynamic-io', () => { ...@@ -235,23 +160,6 @@ describe('dynamic-io', () => {
expect(message1).toEqual(json.message1) expect(message1).toEqual(json.message1)
expect(message2).toEqual(json.message2) expect(message2).toEqual(json.message2)
} }
str = await next.render('/routes/-edge/use_cache-cached', {})
json = JSON.parse(str)
message1 = json.message1
message2 = json.message2
expect(json.value).toEqual('at runtime')
expect(typeof message1).toBe('string')
expect(typeof message2).toBe('string')
str = await next.render('/routes/-edge/use_cache-cached', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(message1).toEqual(json.message1)
expect(message2).toEqual(json.message2)
}) })
it('should not prerender GET route handlers that have some uncached io (unstable_cache)', async () => { it('should not prerender GET route handlers that have some uncached io (unstable_cache)', async () => {
...@@ -271,23 +179,6 @@ describe('dynamic-io', () => { ...@@ -271,23 +179,6 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(message1).toEqual(json.message1) expect(message1).toEqual(json.message1)
expect(message2).not.toEqual(json.message2) expect(message2).not.toEqual(json.message2)
str = await next.render('/routes/-edge/io-mixed', {})
json = JSON.parse(str)
message1 = json.message1
message2 = json.message2
expect(json.value).toEqual('at runtime')
expect(typeof message1).toBe('string')
expect(typeof message2).toBe('string')
str = await next.render('/routes/-edge/io-mixed', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(message1).toEqual(json.message1)
expect(message2).not.toEqual(json.message2)
}) })
it('should prerender GET route handlers that complete synchronously or in a microtask', async () => { it('should prerender GET route handlers that complete synchronously or in a microtask', async () => {
...@@ -345,38 +236,6 @@ describe('dynamic-io', () => { ...@@ -345,38 +236,6 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at buildtime') expect(json.value).toEqual('at buildtime')
expect(json.message).toBe('string response') expect(json.message).toBe('string response')
} }
// Edge versions are always dynamic
str = await next.render('/routes/-edge/microtask', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.message).toBe('microtask')
str = await next.render('/routes/-edge/static-stream-sync', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.message).toBe('stream response')
str = await next.render('/routes/-edge/static-stream-async', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.message).toBe('stream response')
str = await next.render('/routes/-edge/static-string-sync', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.message).toBe('string response')
str = await next.render('/routes/-edge/static-string-async', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.message).toBe('string response')
}) })
it('should not prerender GET route handlers that complete in a new Task', async () => { it('should not prerender GET route handlers that complete in a new Task', async () => {
...@@ -385,12 +244,6 @@ describe('dynamic-io', () => { ...@@ -385,12 +244,6 @@ describe('dynamic-io', () => {
expect(json.value).toEqual('at runtime') expect(json.value).toEqual('at runtime')
expect(json.message).toBe('task') expect(json.message).toBe('task')
str = await next.render('/routes/-edge/task', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.message).toBe('task')
}) })
it('should prerender GET route handlers when accessing awaited params', async () => { it('should prerender GET route handlers when accessing awaited params', async () => {
...@@ -424,23 +277,6 @@ describe('dynamic-io', () => { ...@@ -424,23 +277,6 @@ describe('dynamic-io', () => {
expect(json.param).toBe('2') expect(json.param).toBe('2')
expect(getLines('In route /routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
} }
// Edge versions are always dynamic
str = await next.render('/routes/-edge/1/async', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1')
expect(getLines('In route /routes/-edge/[dyn]')).toEqual([])
str = await next.render('/routes/-edge/2/async', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2')
expect(getLines('In route /routes/-edge/[dyn]')).toEqual([])
}) })
it('should prerender GET route handlers when accessing params without awaiting first', async () => { it('should prerender GET route handlers when accessing params without awaiting first', async () => {
...@@ -482,38 +318,5 @@ describe('dynamic-io', () => { ...@@ -482,38 +318,5 @@ describe('dynamic-io', () => {
expect(json.param).toBe('2') expect(json.param).toBe('2')
expect(getLines('In route /routes/[dyn]')).toEqual([]) expect(getLines('In route /routes/[dyn]')).toEqual([])
} }
// Edge versions are always dynamic
str = await next.render('/routes/-edge/1/sync', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('1')
if (isNextDev) {
expect(getLines('In route /routes/-edge/[dyn]')).toEqual([
expect.stringContaining(
'a param property was accessed directly with `params.dyn`.'
),
])
} else {
expect(getLines('In route /routes/-edge/[dyn]')).toEqual([])
}
str = await next.render('/routes/-edge/2/sync', {})
json = JSON.parse(str)
expect(json.value).toEqual('at runtime')
expect(json.type).toBe('dynamic params')
expect(json.param).toBe('2')
if (isNextDev) {
expect(getLines('In route /routes/-edge/[dyn]')).toEqual([
expect.stringContaining(
'a param property was accessed directly with `params.dyn`.'
),
])
} else {
expect(getLines('In route /routes/-edge/[dyn]')).toEqual([])
}
}) })
}) })
export const runtime = 'edge'
export async function GET() {
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
async function getCachedRandom() {
'use cache'
return Math.random()
}
export const runtime = 'edge'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
async function getCachedRandom() {
'use cache'
return Math.random()
}
export const runtime = 'edge'
export function GET() {
const response = JSON.stringify({
rand1: Math.random(),
rand2: Math.random(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
export const runtime = 'edge'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return Math.random()
}
import { unstable_cache as cache } from 'next/cache'
export const runtime = 'edge'
export async function GET() {
const response = JSON.stringify({
rand1: await getCachedRandom(),
rand2: await getCachedRandom(),
})
return new Response(response, {
headers: {
'content-type': 'application/json',
},
})
}
const getCachedRandom = cache(async () => {
return Math.random()
})
import { unstable_cache as cache } from 'next/cache'
export const runtime = 'edge'
export default async function Page() {
return (
<ul>
<li>
<RandomValue />
</li>
<li>
<RandomValue />
</li>
</ul>
)
}
async function RandomValue() {
return getCachedRandom()
}
const getCachedRandom = cache(async () => {
return Math.random()
})
...@@ -53,16 +53,6 @@ describe('Node Extensions', () => { ...@@ -53,16 +53,6 @@ describe('Node Extensions', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
$ = await next.render$('/app/rendered/use-cache') $ = await next.render$('/app/rendered/use-cache')
expect($('li').length).toBe(2) expect($('li').length).toBe(2)
res = await next.fetch('/app/edge/uncached')
expect(res.status).toBe(200)
$ = await next.render$('/app/edge/uncached')
expect($('li').length).toBe(2)
res = await next.fetch('/app/edge/unstable-cache')
expect(res.status).toBe(200)
$ = await next.render$('/app/edge/unstable-cache')
expect($('li').length).toBe(2)
}) })
it('should not error when accessing routes that use Math.random() in App Router', async () => { it('should not error when accessing routes that use Math.random() in App Router', async () => {
...@@ -115,22 +105,6 @@ describe('Node Extensions', () => { ...@@ -115,22 +105,6 @@ describe('Node Extensions', () => {
rand1: expect.any(Number), rand1: expect.any(Number),
rand2: expect.any(Number), rand2: expect.any(Number),
}) })
res = await next.fetch('/app/edge/uncached/api')
expect(res.status).toBe(200)
body = await res.json()
expect(body).toEqual({
rand1: expect.any(Number),
rand2: expect.any(Number),
})
res = await next.fetch('/app/edge/unstable-cache/api')
expect(res.status).toBe(200)
body = await res.json()
expect(body).toEqual({
rand1: expect.any(Number),
rand2: expect.any(Number),
})
}) })
it('should not error when accessing pages that use Math.random() in Pages Router', async () => { it('should not error when accessing pages that use Math.random() in Pages Router', async () => {
...@@ -216,16 +190,6 @@ describe('Node Extensions', () => { ...@@ -216,16 +190,6 @@ describe('Node Extensions', () => {
expect(res.status).toBe(200) expect(res.status).toBe(200)
$ = await next.render$('/app/rendered/unstable-cache') $ = await next.render$('/app/rendered/unstable-cache')
expect($('li').length).toBe(2) expect($('li').length).toBe(2)
res = await next.fetch('/app/edge/uncached')
expect(res.status).toBe(200)
$ = await next.render$('/app/edge/uncached')
expect($('li').length).toBe(2)
res = await next.fetch('/app/edge/unstable-cache')
expect(res.status).toBe(200)
$ = await next.render$('/app/edge/unstable-cache')
expect($('li').length).toBe(2)
}) })
it('should not error when accessing routes that use Math.random() in App Router', async () => { it('should not error when accessing routes that use Math.random() in App Router', async () => {
...@@ -262,22 +226,6 @@ describe('Node Extensions', () => { ...@@ -262,22 +226,6 @@ describe('Node Extensions', () => {
rand1: expect.any(Number), rand1: expect.any(Number),
rand2: expect.any(Number), rand2: expect.any(Number),
}) })
res = await next.fetch('/app/edge/uncached/api')
expect(res.status).toBe(200)
body = await res.json()
expect(body).toEqual({
rand1: expect.any(Number),
rand2: expect.any(Number),
})
res = await next.fetch('/app/edge/unstable-cache/api')
expect(res.status).toBe(200)
body = await res.json()
expect(body).toEqual({
rand1: expect.any(Number),
rand2: expect.any(Number),
})
}) })
it('should not error when accessing pages that use Math.random() in Pages Router', async () => { it('should not error when accessing pages that use Math.random() in Pages Router', async () => {
......
export const runtime = 'edge'
export { GET } from '../node/route'
...@@ -13,11 +13,4 @@ describe('use-cache-route-handler-only', () => { ...@@ -13,11 +13,4 @@ describe('use-cache-route-handler-only', () => {
expect(rand1).toEqual(rand2) expect(rand1).toEqual(rand2)
}) })
it('should cache results in edge route handlers', async () => {
const response = await next.fetch('/edge')
const { rand1, rand2 } = await response.json()
expect(rand1).toEqual(rand2)
})
}) })
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