Commit 270a0616 authored by Janka Uryga's avatar Janka Uryga

tests

parent 3a62a752
import { cookies, headers } from 'next/headers'
import { CachedData } from '../../data-fetching'
import { connection } from 'next/server'
import { Suspense } from 'react'
const CACHE_KEY = __dirname + '/__PAGE__'
export default function Page({ params, searchParams }) {
return (
<main>
<p>
This page checks whether runtime/dynamic APIs resolve in the correct
stage (regardless of whether we had a cache miss or not)
</p>
<CachedData cacheKey={CACHE_KEY} label="page" />
<LogAfter label="--- dynamic stage ---" api={() => connection()} />
{/* Runtime */}
<LogAfter label="cookies" api={() => cookies()} />
<LogAfter label="headers" api={() => headers()} />
<LogAfter label="params" api={() => params} />
<LogAfter label="searchParams" api={() => searchParams} />
{/* Dynamic */}
<LogAfter label="connection" api={() => connection()} />
</main>
)
}
function LogAfter({ label, api }: { label: string; api: () => Promise<any> }) {
return (
<Suspense fallback={`Waiting for ${label}...`}>
<LogAfterInner label={label} api={api} />
</Suspense>
)
}
async function LogAfterInner({
label,
api,
}: {
label: string
api: () => Promise<any>
}) {
await api()
console.log(`after ${label}`)
return null
}
export async function fetchCached(url: string) {
const response = await fetch(url, { cache: 'force-cache' })
return response.text()
}
export async function getCachedData(_key: string) {
'use cache'
await new Promise((r) => setTimeout(r))
return Math.random()
}
export async function fetchCachedRandom(cacheKey: string) {
return fetchCached(
`https://next-data-api-endpoint.vercel.app/api/random?key=${encodeURIComponent('cached-' + cacheKey)}`
)
}
export async function fetchCached(url: string) {
const response = await fetch(url, { cache: 'force-cache' })
return response.text()
}
export async function getCachedData(_key: string) {
'use cache'
await new Promise((r) => setTimeout(r))
return Math.random()
}
export async function CachedData({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await getCachedData(cacheKey)
console.log(`after cache read - ${label}`)
return (
<dl>
<dt>Cached Data</dt>
<dd>{data}</dd>
</dl>
)
}
export async function CachedFetch({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await fetchCachedRandom(cacheKey)
console.log(`after cached fetch - ${label}`)
return (
<dl>
<dt>Cached Fetch</dt>
<dd>{data}</dd>
</dl>
)
}
export async function UncachedFetch({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const response = await fetch(
`https://next-data-api-endpoint.vercel.app/api/random?key=${encodeURIComponent('uncached-' + cacheKey)}`
)
console.log(`after uncached fetch - ${label}`)
const data = await response.text()
return (
<dl>
<dt>Uncached Fetch</dt>
<dd>{data}</dd>
</dl>
)
}
import { fetchCached, getCachedData } from './data-fetching'
export default function Root({ children }: { children: React.ReactNode }) { export default function Root({ children }: { children: React.ReactNode }) {
return ( return (
<html> <html>
<body> <body>{children}</body>
{children}
<section>
<h1>Layout</h1>
<p>This data is from the root layout</p>
<FetchingComponent />
<CachedFetchingComponent />
<CachedDataComponent />
</section>
</body>
</html> </html>
) )
} }
async function CachedFetchingComponent() {
const data = await fetchCached(
'https://next-data-api-endpoint.vercel.app/api/random?key=cachedlayout'
)
console.log('after cached layout fetch')
return (
<dl>
<dt>
Cached Fetch
(https://next-data-api-endpoint.vercel.app/api/random?key=cachedlayout)
</dt>
<dd>{data}</dd>
</dl>
)
}
async function FetchingComponent() {
const response = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?key=uncachedlayout'
)
console.log('after uncached layout fetch')
const data = await response.text()
return (
<dl>
<dt>
Uncached Fetch
(https://next-data-api-endpoint.vercel.app/api/random?key=uncachedlayout)
</dt>
<dd>{data}</dd>
</dl>
)
}
async function CachedDataComponent() {
const data = await getCachedData('layout')
console.log('after layout cache read')
return (
<dl>
<dt>Cached Data</dt>
<dd>{data}</dd>
</dl>
)
}
import { fetchCached, getCachedData } from './data-fetching'
export default async function Loading() {
await fetchCached(
'https://next-data-api-endpoint.vercel.app/api/random?key=cachedpage'
)
await getCachedData('page')
return <main>loading...</main>
}
export async function PrivateCachedData({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await getPrivateCachedData(cacheKey)
console.log(`after private cache read - ${label}`)
return (
<dl>
<dt>Private Cached Data (Page)</dt>
<dd>{data}</dd>
</dl>
)
}
async function getPrivateCachedData(_key: string) {
'use cache: private'
await new Promise((r) => setTimeout(r))
return Math.random()
}
import { Suspense } from 'react'
import { UncachedFetch, CachedData } from '../data-fetching'
import { PrivateCachedData } from './data-fetching'
const CACHE_KEY = '/private-cache/__LAYOUT__'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<section>
<h1>Layout</h1>
<p>This data is from a layout</p>
<CachedData label="layout" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading private cache...">
<PrivateCachedData label="layout" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="layout" cacheKey={CACHE_KEY} />
</Suspense>
</section>
</>
)
}
import { Suspense } from 'react'
import { CachedData, UncachedFetch } from '../data-fetching'
import { PrivateCachedData } from './data-fetching'
const CACHE_KEY = '/private-cache/__PAGE__'
export default async function Page() {
return (
<main>
<h1>Warmup Dev Renders - private cache</h1>
<CachedData label="page" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading private cache...">
<PrivateCachedData label="page" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="page" cacheKey={CACHE_KEY} />
</Suspense>
</main>
)
}
import { revalidatePath } from 'next/cache' import { revalidatePath } from 'next/cache'
export async function GET() { export async function GET(request: Request) {
revalidatePath('/') const path = new URL(request.url).searchParams.get('path')!
revalidatePath(path)
return Response.json({ revalidated: true }) return Response.json({ revalidated: true })
} }
import { unstable_cacheLife } from 'next/cache'
export async function ShortLivedCache({
label,
cacheKey,
}: {
label: string
cacheKey: string
}) {
const data = await getShortLivedCachedData(cacheKey)
console.log(`after short-lived cache read - ${label}`)
return (
<dl>
<dt>Short-lived Cached Data (Page)</dt>
<dd>{data}</dd>
</dl>
)
}
async function getShortLivedCachedData(_key: string) {
'use cache'
unstable_cacheLife('seconds')
await new Promise((r) => setTimeout(r))
return Math.random()
}
import { Suspense } from 'react'
import { UncachedFetch, CachedData } from '../data-fetching'
import { ShortLivedCache } from './data-fetching'
const CACHE_KEY = __dirname + '/__LAYOUT__'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<section>
<h1>Layout</h1>
<p>This data is from a layout</p>
<CachedData label="layout" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading short-lived cache...">
<ShortLivedCache label="layout" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="layout" cacheKey={CACHE_KEY} />
</Suspense>
</section>
</>
)
}
import { Suspense } from 'react'
import { CachedData, UncachedFetch } from '../data-fetching'
import { ShortLivedCache } from './data-fetching'
const CACHE_KEY = __dirname + '/__PAGE__'
export default async function Page() {
return (
<main>
<h1>Warmup Dev Renders - short lived cache</h1>
<CachedData label="page" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading short-lived cache...">
<ShortLivedCache label="page" cacheKey={CACHE_KEY} />
</Suspense>
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="page" cacheKey={CACHE_KEY} />
</Suspense>
</main>
)
}
import { Suspense } from 'react'
import { UncachedFetch, CachedFetch, CachedData } from '../data-fetching'
const CACHE_KEY = __dirname + '/__LAYOUT__'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
<section>
<h1>Layout</h1>
<p>This data is from a layout</p>
<CachedData label="layout" cacheKey={CACHE_KEY} />
<CachedFetch label="layout" cacheKey={CACHE_KEY} />
<Suspense fallback="Loading uncached fetch...">
<UncachedFetch label="layout" cacheKey={CACHE_KEY} />
</Suspense>
</section>
</>
)
}
import { fetchCachedRandom, getCachedData } from '../data-fetching'
// Deliberately using the same cache keys as the page.
const CACHE_KEY = __dirname + '/__PAGE__'
export default async function Loading() {
await fetchCachedRandom(CACHE_KEY) // Mirrors `CachedFetchingComponent`
await getCachedData(CACHE_KEY) // Mirrors `CachedDataComponent`
return <main>loading...</main>
}
import { fetchCached, getCachedData } from './data-fetching' import { Suspense } from 'react'
import { CachedData, CachedFetch, UncachedFetch } from '../data-fetching'
const CACHE_KEY = __dirname + '/__PAGE__'
export default async function Page() { export default async function Page() {
return ( return (
...@@ -11,53 +14,14 @@ export default async function Page() { ...@@ -11,53 +14,14 @@ export default async function Page() {
itself. When PPR is enabled it will include everything that is itself. When PPR is enabled it will include everything that is
prerenderable including the page if appropriate. prerenderable including the page if appropriate.
</p> </p>
<FetchingComponent />
<CachedFetchingComponent />
<CachedDataComponent />
</main>
)
}
async function CachedFetchingComponent() { <CachedData label="page" cacheKey={CACHE_KEY} />
const data = await fetchCached(
'https://next-data-api-endpoint.vercel.app/api/random?key=cachedpage'
)
console.log('after cached page fetch')
return (
<dl>
<dt>
Cached Fetch
(https://next-data-api-endpoint.vercel.app/api/random?key=cachedpage)
</dt>
<dd>{data}</dd>
</dl>
)
}
async function FetchingComponent() { <CachedFetch label="page" cacheKey={CACHE_KEY} />
const response = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?key=uncachedpage'
)
console.log('after uncached page fetch')
const data = await response.text()
return (
<dl>
<dt>
Uncached Fetch
(https://next-data-api-endpoint.vercel.app/api/random?key=uncachedpage)
</dt>
<dd>{data}</dd>
</dl>
)
}
async function CachedDataComponent() { <Suspense fallback="Loading uncached fetch...">
const data = await getCachedData('page') <UncachedFetch label="page" cacheKey={CACHE_KEY} />
console.log('after page cache read') </Suspense>
return ( </main>
<dl>
<dt>Cached Data (Page)</dt>
<dd>{data}</dd>
</dl>
) )
} }
...@@ -8,40 +8,173 @@ describe('cache-components-dev-warmup', () => { ...@@ -8,40 +8,173 @@ describe('cache-components-dev-warmup', () => {
function assertLog( function assertLog(
logs: Array<{ source: string; message: string }>, logs: Array<{ source: string; message: string }>,
message: string, message: string,
environment: string expectedEnvironment: string
) { ) {
expect(logs.map((l) => l.message)).toEqual( // Match logs that contain the message, with any environment.
expect.arrayContaining([ const logPattern = new RegExp(
expect.stringMatching( `^(?=.*\\b${message}\\b)(?=.*\\b(Cache|Prerender|Server)\\b).*`
new RegExp(`^(?=.*\\b${message}\\b)(?=.*\\b${environment}\\b).*`)
),
])
) )
const logMessages = logs.map((log) => log.message)
const messages = logMessages.filter((message) => logPattern.test(message))
// If there's zero or more than one logs that match, the test is not set up correctly.
if (messages.length === 0) {
throw new Error(
`Found no logs matching '${message}':\n\n${logMessages.map((s, i) => `${i}. ${s}`).join('\n')}}`
)
}
if (messages.length > 1) {
throw new Error(
`Found multiple logs matching '${message}':\n\n${messages.map((s, i) => `${i}. ${s}`).join('\n')}`
)
}
// The message should have the expected environment.
const actualMessageText = messages[0]
const [, actualEnvironment] = actualMessageText.match(logPattern)!
expect([actualEnvironment, actualMessageText]).toEqual([
expectedEnvironment,
expect.stringContaining(message),
])
} }
it('logs with Prerender or Server environment depending based on whether the timing of when the log runs relative to this environment boundary', async () => { describe('logs with Prerender or Server environment depending based on whether the timing of when the log runs relative to this environment boundary', () => {
let browser = await next.browser('/') it('cached data + cached fetch', async () => {
let logs = await browser.log() const path = '/simple'
const browser = await next.browser(path)
const assertLogs = async () => {
const logs = await browser.log()
assertLog(logs, 'after cache read - layout', 'Prerender')
assertLog(logs, 'after cache read - page', 'Prerender')
assertLog(logs, 'after cached fetch - layout', 'Prerender')
assertLog(logs, 'after cached fetch - page', 'Prerender')
assertLog(logs, 'after uncached fetch - layout', 'Server')
assertLog(logs, 'after uncached fetch - page', 'Server')
}
// Initial load.
await assertLogs()
// After another load (with warm caches) the logs should be the same.
await browser.loadPage(next.url + path) // clears old logs
await assertLogs()
// After a revalidation the subsequent warmup render must discard stale
// cache entries.
// This should not affect the environment labels.
await next.fetch(`/revalidate?path=${encodeURIComponent(path)}`)
await browser.loadPage(next.url + path) // clears old logs
await assertLogs()
})
it('cached data + private cache', async () => {
const path = '/private-cache'
const browser = await next.browser(path)
const assertLogs = async () => {
const logs = await browser.log()
assertLog(logs, 'after cache read - layout', 'Prerender')
assertLog(logs, 'after cache read - page', 'Prerender')
// Private caches are dynamic holes in static prerenders,
// so they shouldn't resolve in the static stage.
assertLog(logs, 'after private cache read - page', 'Server') // TODO: 'Runtime Prerender'
assertLog(logs, 'after private cache read - layout', 'Server') // TODO: 'Runtime Prerender'
assertLog(logs, 'after uncached fetch - layout', 'Server')
assertLog(logs, 'after uncached fetch - page', 'Server')
}
// Initial load.
await assertLogs()
// After another load (with warm caches) the logs should be the same.
// Note that private caches are not currently persisted outside of the request that uses them.
await browser.loadPage(next.url + path) // clears old logs
await assertLogs()
// After a revalidation the subsequent warmup render must discard stale
// cache entries.
// This should not affect the environment labels.
await next.fetch(`/revalidate?path=${encodeURIComponent(path)}`)
assertLog(logs, 'after layout cache read', 'Prerender') await browser.loadPage(next.url + path) // clears old logs
assertLog(logs, 'after page cache read', 'Prerender') await assertLogs()
assertLog(logs, 'after cached layout fetch', 'Prerender') })
assertLog(logs, 'after cached page fetch', 'Prerender')
assertLog(logs, 'after uncached layout fetch', 'Server') it('cached data + short-lived cached data', async () => {
assertLog(logs, 'after uncached page fetch', 'Server') const path = '/short-lived-cache'
const browser = await next.browser(path)
const assertLogs = async () => {
const logs = await browser.log()
assertLog(logs, 'after cache read - layout', 'Prerender')
assertLog(logs, 'after cache read - page', 'Prerender')
// Short lived caches are dynamic holes in static prerenders,
// so they shouldn't resolve in the static stage.
assertLog(logs, 'after short-lived cache read - page', 'Server')
assertLog(logs, 'after short-lived cache read - layout', 'Server')
assertLog(logs, 'after uncached fetch - layout', 'Server')
assertLog(logs, 'after uncached fetch - page', 'Server')
}
// Initial load.
await assertLogs()
// After another load (with warm caches) the logs should be the same.
await browser.loadPage(next.url + path) // clears old logs
await assertLogs()
// After a revalidation the subsequent warmup render must discard stale
// cache entries.
// This should not affect the environment labels.
await next.fetch(`/revalidate?path=${encodeURIComponent(path)}`)
await browser.loadPage(next.url + path) // clears old logs
await assertLogs()
})
})
it('runtime/dynamic APIs', async () => {
const path = '/apis/123'
const browser = await next.browser(path)
const assertLogs = async () => {
const logs = await browser.log()
assertLog(logs, 'after cache read - page', 'Prerender')
for (const apiName of [
'cookies',
'headers',
// TODO(restart-on-cache-miss): these two are currently broken/flaky,
// because they're created outside of render and can resolve too early.
// This will be fixed in a follow-up.
// 'params',
// 'searchParams',
'connection',
]) {
assertLog(logs, `after ${apiName}`, 'Server')
}
}
// Initial load.
await assertLogs()
// After another load (with warm caches) the logs should be the same.
await browser.loadPage(next.url + path) // clears old logs
await assertLogs()
// After a revalidation the subsequent warmup render must discard stale // After a revalidation the subsequent warmup render must discard stale
// cache entries. // cache entries.
await next.fetch('/revalidate') // This should not affect the environment labels.
await next.fetch(`/revalidate?path=${encodeURIComponent(path)}`)
browser = await next.browser('/')
logs = await browser.log()
assertLog(logs, 'after layout cache read', 'Prerender') await browser.loadPage(next.url + path) // clears old logs
assertLog(logs, 'after page cache read', 'Prerender') await assertLogs()
assertLog(logs, 'after cached layout fetch', 'Prerender')
assertLog(logs, 'after cached page fetch', 'Prerender')
assertLog(logs, 'after uncached layout fetch', 'Server')
assertLog(logs, 'after uncached page fetch', 'Server')
}) })
}) })
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