Unverified Commit 4ae6d033 authored by Josh Story's avatar Josh Story Committed by GitHub

[dynamicio] Instrument Date to be dynamic when accessing current time (#70916)

Date can be considered IO when it infers the current time when using
`new Date()` or `Date.now()`. Both of these are queries to the computer
clock and while they are synchronous they are semantically IO. When
`dyanmicIO` is enabled these APIs should be treated like other IO and be
excluded from prerenders unless explicitly cached
parent e5d0e38e
/**
* We extend `Date` during builds and revalidates to ensure that prerenders don't observe the clock as a source of IO
* When dynamicIO is enabled. The current time is a form of IO even though it resolves synchronously. When dyanmicIO is
* enabled we need to ensure that clock time is excluded from prerenders.
*
* There is tension here because time is used for both output and introspection. While arbitrary we intend to reserve
* `Date` for output use cases and `performance` for introspection use cases. If you want to measure
* how long something takes use `performance.timeOrigin` and `performance.now()` rather than `Date.now()` for instance.
*
* The extensions here never error nor alter the underlying Date objects, strings, and numbers created and thus should be transparent to callers.
*/
import { workAsyncStorage } from '../../client/components/work-async-storage.external'
import {
isDynamicIOPrerender,
workUnitAsyncStorage,
} from '../app-render/work-unit-async-storage.external'
import { abortOnSynchronousDynamicDataAccess } from '../app-render/dynamic-rendering'
function io(expression: string) {
const workUnitStore = workUnitAsyncStorage.getStore()
if (
workUnitStore &&
workUnitStore.type === 'prerender' &&
isDynamicIOPrerender(workUnitStore)
) {
const workStore = workAsyncStorage.getStore()
const route = workStore ? workStore.route : ''
if (workStore) {
abortOnSynchronousDynamicDataAccess(route, expression, workUnitStore)
}
}
}
function createNow(originalNow: typeof Date.now) {
return {
now: function now() {
io('`Date.now()`')
return originalNow()
},
}['now'.slice() as 'now'].bind(null)
}
function createDate(originalConstructor: typeof Date): typeof Date {
const properties = Object.getOwnPropertyDescriptors(originalConstructor)
properties.now.value = createNow(originalConstructor.now)
const apply = Reflect.apply
const construct = Reflect.construct
const newConstructor = Object.defineProperties(
// Ideally this should not minify the name.
function Date() {
if (new.target === undefined) {
io('`Date()`')
return apply(originalConstructor, undefined, arguments)
}
if (arguments.length === 0) {
io('`new Date()`')
}
return construct(originalConstructor, arguments, new.target)
},
properties
)
Object.defineProperty(originalConstructor.prototype, 'constructor', {
value: newConstructor,
})
return newConstructor as typeof Date
}
// eslint-disable-next-line no-native-reassign
Date = createDate(Date)
......@@ -3,3 +3,4 @@
import './node-environment-baseline'
import './node-environment-extensions/random'
import './node-environment-extensions/date'
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
const date = await getDate()
return (
<div>
<label>Date()</label>
<span id="value">{date}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
async function getDate() {
'use cache'
return Date()
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
if (typeof window === 'undefined') {
await new Promise((r) => process.nextTick(r))
}
const date = Date()
return (
<div>
<label>Date()</label>
<span id="value">{date}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { Suspense } from 'react'
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
return (
<Suspense fallback={<div data-fallback="">loading...</div>}>
{children}
</Suspense>
)
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
const newDate = await getNewDate()
return (
<div>
<label>new Date()</label>
<span id="value">{newDate}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
async function getNewDate() {
'use cache'
// We should really return the date object but
// at the time of writing "use cache" can't serialize the Date
// back to the server
return new Date().toString()
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
if (typeof window === 'undefined') {
await new Promise((r) => process.nextTick(r))
}
const newDate = new Date()
return (
<div>
<label>new Date()</label>
<span id="value">{newDate.toString()}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
const now = await getNow()
return (
<div>
<label>now</label>
<span id="value">{now}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
async function getNow() {
'use cache'
return Date.now()
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
if (typeof window === 'undefined') {
await new Promise((r) => process.nextTick(r))
}
const now = Date.now()
return (
<div>
<label>now</label>
<span id="value">{now}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
const staticDate = await getStaticDate()
return (
<div>
<label>new Date(0)</label>
<span id="value">{staticDate}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
async function getStaticDate() {
'use cache'
// We should really return the date object but
// at the time of writing "use cache" can't serialize the Date
// back to the server
return new Date(0).toString()
}
import { SentinelValue } from '../../../getSentinelValue'
export default async function Page() {
if (typeof window === 'undefined') {
await new Promise((r) => process.nextTick(r))
}
const staticDate = new Date(0)
return (
<div>
<label>new Date(0)</label>
<span id="value">{staticDate.toString()}</span>
<span id="page">
<SentinelValue />
</span>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
const WITH_PPR = !!process.env.__NEXT_EXPERIMENTAL_PPR
describe('dynamic-io', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should not have route specific errors', async () => {
expect(next.cliOutput).not.toMatch('Error: Route /')
expect(next.cliOutput).not.toMatch('Error occurred prerendering page')
})
it('should prerender pages with cached `Date.now()` calls', async () => {
let $ = await next.render$('/date/now/cached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toMatch(/^\d+$/)
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime')
expect($('#value').text()).toMatch(/^\d+$/)
}
})
it('should not prerender pages with uncached `Date.now()` calls', async () => {
let $ = await next.render$('/date/now/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toMatch(/^\d+$/)
} else if (WITH_PPR) {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toMatch(/^\d+$/)
} else {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toMatch(/^\d+$/)
}
})
it('should prerender pages with cached `Date()` calls', async () => {
let $ = await next.render$('/date/date/cached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime')
expect($('#value').text()).toContain('GMT')
}
})
it('should not prerender pages with uncached `Date()` calls', async () => {
let $ = await next.render$('/date/date/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else if (WITH_PPR) {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
}
})
it('should prerender pages with cached `new Date()` calls', async () => {
let $ = await next.render$('/date/new-date/cached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime')
expect($('#value').text()).toContain('GMT')
}
})
it('should not prerender pages with uncached `new Date()` calls', async () => {
let $ = await next.render$('/date/new-date/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else if (WITH_PPR) {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
}
})
it('should prerender pages with cached static Date instances like `new Date(0)`', async () => {
let $ = await next.render$('/date/static-date/cached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime')
expect($('#value').text()).toContain('GMT')
}
})
it('should not prerender pages with uncached static Date instances like `new Date(0)`', async () => {
let $ = await next.render$('/date/static-date/uncached', {})
if (isNextDev) {
expect($('#layout').text()).toBe('at runtime')
expect($('#page').text()).toBe('at runtime')
expect($('#value').text()).toContain('GMT')
} else {
expect($('#layout').text()).toBe('at buildtime')
expect($('#page').text()).toBe('at buildtime')
expect($('#value').text()).toContain('GMT')
}
})
})
......@@ -6,7 +6,6 @@ const nextConfig = {
ppr: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
pprFallbacks: process.env.__NEXT_EXPERIMENTAL_PPR === 'true',
dynamicIO: true,
serverMinification: false,
},
}
......
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