Unverified Commit b425b40a authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Replace custom Thenable type with native Promises (#58337)

Next.js's implementation includes a custom Thenable type based on a
similar one used in React's codebase. It was used to implement a
userspace equivalent of the React.use API before that API became stable,
by throwing a promise-like object and tracking the status on an expando
field. However, it didn't cover all the same cases and behaviors that
React.use does, which led to some subtle bugs like the one fixed by
@ztanner in https://github.com/vercel/next.js/pull/55690.

Now that React.use is stable, and we use that for suspending instead of
throwing a promise, we no longer need our custom Thenable type. I've
removed the type and associated functions, and updated our types to use
Promise instead.

Even in cases where a function does return a thenable-object rather than
a native promise, like React Flight's createFromFetch, we should use
TypeScript's built-in PromiseLike utility. Currently, though, we always
await these objects anyway (in fetch-server-response.ts), which turns
them into promises. So Promise is almost always sufficient.
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 00f5b5e7
......@@ -27,7 +27,6 @@ import { RedirectBoundary } from './redirect-boundary'
import { NotFoundBoundary } from './not-found-boundary'
import { getSegmentValue } from './router-reducer/reducers/get-segment-value'
import { createRouterCacheKey } from './router-reducer/create-router-cache-key'
import { createRecordFromThenable } from './router-reducer/create-record-from-thenable'
/**
* Add refetch marker to router state at the point of the current layout segment.
......@@ -379,13 +378,11 @@ function InnerLayoutRouter({
childNode = {
status: CacheStates.DATA_FETCH,
data: createRecordFromThenable(
fetchServerResponse(
new URL(url, location.origin),
refetchTree,
context.nextUrl,
buildId
)
data: fetchServerResponse(
new URL(url, location.origin),
refetchTree,
context.nextUrl,
buildId
),
subTreeData: null,
head:
......
import type { ThenableRecord } from './router-reducer/router-reducer-types'
/*
This is a simple promise queue that allows you to limit the number of concurrent promises
that are running at any given time. It's used to limit the number of concurrent
......@@ -10,7 +8,7 @@ export class PromiseQueue {
#maxConcurrency: number
#runningCount: number
#queue: Array<{
promiseFn: ThenableRecord<any> | Promise<any>
promiseFn: Promise<any>
task: () => void
}>
......@@ -50,7 +48,7 @@ export class PromiseQueue {
return taskPromise
}
bump(promiseFn: ThenableRecord<any> | Promise<any>) {
bump(promiseFn: Promise<any>) {
const index = this.#queue.findIndex((item) => item.promiseFn === promiseFn)
if (index > -1) {
......
import { createRecordFromThenable } from './create-record-from-thenable'
describe('createRecordFromThenable', () => {
it('successful promise', async () => {
const thenable = Promise.resolve('success')
const record = createRecordFromThenable(thenable)
expect(record.status).toBe('pending')
await thenable
expect(record.status).toBe('fulfilled')
// typeguard
if (record.status !== 'fulfilled') {
throw new Error('Invalid Type')
}
expect(record.value).toBe('success')
})
it('rejecting promise', async () => {
const thenable = Promise.reject('error')
const record = createRecordFromThenable(thenable)
expect(record.status).toBe('pending')
await thenable.catch(() => {})
expect(record.status).toBe('rejected')
// typeguard
if (record.status !== 'rejected') {
throw new Error('Invalid Type')
}
expect(record.reason).toBe('error')
})
})
import type { ThenableRecord } from './router-reducer-types'
/**
* Create data fetching record for Promise.
*/
export function createRecordFromThenable<T>(
promise: PromiseLike<T>
): ThenableRecord<T> {
const thenable = promise as any
thenable.status = 'pending'
thenable.then(
(value: any) => {
if (thenable.status === 'pending') {
thenable.status = 'fulfilled'
thenable.value = value
}
},
(err: any) => {
if (thenable.status === 'pending') {
thenable.status = 'rejected'
thenable.reason = err
}
}
)
return thenable
}
......@@ -3,19 +3,16 @@ import type { FetchServerResponseResult } from './fetch-server-response'
import { fillCacheWithDataProperty } from './fill-cache-with-data-property'
import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
import { createRecordFromThenable } from './create-record-from-thenable'
import type { ThenableRecord } from './router-reducer-types'
describe('fillCacheWithDataProperty', () => {
it('should add data property', () => {
const fetchServerResponseMock: jest.Mock<
ThenableRecord<FetchServerResponseResult>
Promise<FetchServerResponseResult>
> = jest.fn(() =>
createRecordFromThenable(
Promise.resolve([
/* TODO-APP: replace with actual FlightData */ '',
undefined,
])
)
Promise.resolve([
/* TODO-APP: replace with actual FlightData */ '',
undefined,
])
)
const pathname = '/dashboard/settings'
const segments = pathname.split('/')
......@@ -97,9 +94,7 @@ describe('fillCacheWithDataProperty', () => {
</React.Fragment>,
},
"dashboard" => {
"data": Promise {
"status": "pending",
},
"data": Promise {},
"parallelRoutes": Map {},
"status": "DATAFETCH",
"subTreeData": null,
......
import type { FetchServerResponseResult } from './fetch-server-response'
import type { ThenableRecord } from './router-reducer-types'
import type { FlightSegmentPath } from '../../../server/app-render/types'
import { CacheStates } from '../../../shared/lib/app-router-context.shared-runtime'
import type { CacheNode } from '../../../shared/lib/app-router-context.shared-runtime'
......@@ -12,7 +11,7 @@ export function fillCacheWithDataProperty(
newCache: CacheNode,
existingCache: CacheNode,
flightSegmentPath: FlightSegmentPath,
fetchResponse: () => ThenableRecord<FetchServerResponseResult>,
fetchResponse: () => Promise<FetchServerResponseResult>,
bailOnParallelRoutes: boolean = false
): { bailOptimistic: boolean } | undefined {
const isLastEntry = flightSegmentPath.length <= 2
......
import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
......@@ -30,13 +29,11 @@ function fastRefreshReducerImpl(
if (!cache.data) {
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.data = createRecordFromThenable(
fetchServerResponse(
new URL(href, origin),
[state.tree[0], state.tree[1], state.tree[2], 'refetch'],
state.nextUrl,
state.buildId
)
cache.data = fetchServerResponse(
new URL(href, origin),
[state.tree[0], state.tree[1], state.tree[2], 'refetch'],
state.nextUrl,
state.buildId
)
}
......
......@@ -274,37 +274,7 @@ describe('navigateReducer', () => {
"nextUrl": "/linking/about",
"prefetchCache": Map {
"/linking/about" => {
"data": Promise {
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"__PAGE__",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"data": Promise {},
"kind": "temporary",
"lastUsedTime": 1690329600000,
"prefetchTime": 1690329600000,
......@@ -973,37 +943,7 @@ describe('navigateReducer', () => {
</React.Fragment>,
},
"about" => {
"data": Promise {
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"__PAGE__",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"data": Promise {},
"parallelRoutes": Map {},
"status": "DATAFETCH",
"subTreeData": null,
......@@ -1422,37 +1362,7 @@ describe('navigateReducer', () => {
"nextUrl": "/linking/about",
"prefetchCache": Map {
"/linking/about" => {
"data": Promise {
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"__PAGE__",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"data": Promise {},
"kind": "auto",
"lastUsedTime": null,
"prefetchTime": 1690329600000,
......@@ -2063,37 +1973,7 @@ describe('navigateReducer', () => {
"nextUrl": "/linking/about",
"prefetchCache": Map {
"/linking/about" => {
"data": Promise {
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"__PAGE__",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"data": Promise {},
"kind": "temporary",
"lastUsedTime": 1690329600000,
"prefetchTime": 1690329600000,
......
......@@ -6,7 +6,6 @@ import type {
} from '../../../../server/app-render/types'
import { fetchServerResponse } from '../fetch-server-response'
import type { FetchServerResponseResult } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { createHrefFromUrl } from '../create-href-from-url'
import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'
import { fillCacheWithDataProperty } from '../fill-cache-with-data-property'
......@@ -19,7 +18,6 @@ import type {
NavigateAction,
ReadonlyReducerState,
ReducerState,
ThenableRecord,
} from '../router-reducer-types'
import { PrefetchKind } from '../router-reducer-types'
import { handleMutable } from '../handle-mutable'
......@@ -77,7 +75,7 @@ function addRefetchToLeafSegments(
currentCache: CacheNode,
flightSegmentPath: FlightSegmentPath,
treePatch: FlightRouterState,
data: () => ThenableRecord<FetchServerResponseResult>
data: () => Promise<FetchServerResponseResult>
) {
let appliedPatch = false
......@@ -158,12 +156,15 @@ export function navigateReducer(
temporaryCacheNode.subTreeData = state.cache.subTreeData
temporaryCacheNode.parallelRoutes = new Map(state.cache.parallelRoutes)
let data: ThenableRecord<FetchServerResponseResult> | null = null
let data: Promise<FetchServerResponseResult> | null = null
const fetchResponse = () => {
if (!data) {
data = createRecordFromThenable(
fetchServerResponse(url, optimisticTree, state.nextUrl, state.buildId)
data = fetchServerResponse(
url,
optimisticTree,
state.nextUrl,
state.buildId
)
}
return data
......@@ -198,7 +199,7 @@ export function navigateReducer(
mutable.canonicalUrl = href
state.prefetchCache.set(createHrefFromUrl(url, false), {
data: data ? createRecordFromThenable(Promise.resolve(data)) : null,
data: data ? data : null,
// this will make sure that the entry will be discarded after 30s
kind: PrefetchKind.TEMPORARY,
prefetchTime: Date.now(),
......@@ -212,20 +213,18 @@ export function navigateReducer(
// If we don't have a prefetch value, we need to create one
if (!prefetchValues) {
const data = createRecordFromThenable(
fetchServerResponse(
url,
state.tree,
state.nextUrl,
state.buildId,
// in dev, there's never gonna be a prefetch entry so we want to prefetch here
// in order to simulate the behavior of the prefetch cache
process.env.NODE_ENV === 'development' ? PrefetchKind.AUTO : undefined
)
const data = fetchServerResponse(
url,
state.tree,
state.nextUrl,
state.buildId,
// in dev, there's never gonna be a prefetch entry so we want to prefetch here
// in order to simulate the behavior of the prefetch cache
process.env.NODE_ENV === 'development' ? PrefetchKind.AUTO : undefined
)
const newPrefetchValue = {
data: createRecordFromThenable(Promise.resolve(data)),
data,
// this will make sure that the entry will be discarded after 30s
kind:
process.env.NODE_ENV === 'development'
......@@ -320,13 +319,11 @@ export function navigateReducer(
treePatch,
// eslint-disable-next-line no-loop-func
() =>
createRecordFromThenable(
fetchServerResponse(
url,
currentTree,
state.nextUrl,
state.buildId
)
fetchServerResponse(
url,
currentTree,
state.nextUrl,
state.buildId
)
)
}
......
......@@ -9,7 +9,6 @@ import { ACTION_PREFETCH, PrefetchKind } from '../router-reducer-types'
import type { PrefetchAction } from '../router-reducer-types'
import { prefetchReducer } from './prefetch-reducer'
import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
jest.mock('../fetch-server-response', () => {
const flightData: FlightData = [
......@@ -142,7 +141,6 @@ describe('prefetchReducer', () => {
)
const prom = Promise.resolve(serverResponse)
const record = createRecordFromThenable(prom)
await prom
const expectedState: ReturnType<typeof prefetchReducer> = {
......@@ -151,7 +149,7 @@ describe('prefetchReducer', () => {
[
'/linking/about',
{
data: record,
data: prom,
kind: PrefetchKind.AUTO,
lastUsedTime: null,
prefetchTime: expect.any(Number),
......@@ -298,7 +296,6 @@ describe('prefetchReducer', () => {
)
const prom = Promise.resolve(serverResponse)
const record = createRecordFromThenable(prom)
await prom
const expectedState: ReturnType<typeof prefetchReducer> = {
......@@ -307,7 +304,7 @@ describe('prefetchReducer', () => {
[
'/linking/about',
{
data: record,
data: prom,
prefetchTime: expect.any(Number),
kind: PrefetchKind.AUTO,
lastUsedTime: null,
......
......@@ -6,7 +6,6 @@ import type {
ReadonlyReducerState,
} from '../router-reducer-types'
import { PrefetchKind } from '../router-reducer-types'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { prunePrefetchCache } from './prune-prefetch-cache'
import { NEXT_RSC_UNION_QUERY } from '../../app-router-headers'
import { PromiseQueue } from '../../promise-queue'
......@@ -57,16 +56,14 @@ export function prefetchReducer(
}
// fetchServerResponse is intentionally not awaited so that it can be unwrapped in the navigate-reducer
const serverResponse = createRecordFromThenable(
prefetchQueue.enqueue(() =>
fetchServerResponse(
url,
// initialTree is used when history.state.tree is missing because the history state is set in `useEffect` below, it being missing means this is the hydration case.
state.tree,
state.nextUrl,
state.buildId,
action.kind
)
const serverResponse = prefetchQueue.enqueue(() =>
fetchServerResponse(
url,
// initialTree is used when history.state.tree is missing because the history state is set in `useEffect` below, it being missing means this is the hydration case.
state.tree,
state.nextUrl,
state.buildId,
action.kind
)
)
......
import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
......@@ -32,13 +31,11 @@ export function refreshReducer(
if (!cache.data) {
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree.
cache.data = createRecordFromThenable(
fetchServerResponse(
new URL(href, origin),
[currentTree[0], currentTree[1], currentTree[2], 'refetch'],
state.nextUrl,
state.buildId
)
cache.data = fetchServerResponse(
new URL(href, origin),
[currentTree[0], currentTree[1], currentTree[2], 'refetch'],
state.nextUrl,
state.buildId
)
}
......
......@@ -10,7 +10,6 @@ import {
NEXT_URL,
RSC_CONTENT_TYPE_HEADER,
} from '../../app-router-headers'
import { createRecordFromThenable } from '../create-record-from-thenable'
// // eslint-disable-next-line import/no-extraneous-dependencies
// import { createFromFetch } from 'react-server-dom-webpack/client'
// // eslint-disable-next-line import/no-extraneous-dependencies
......@@ -158,9 +157,7 @@ export function serverActionReducer(
return handleMutable(state, mutable)
}
mutable.inFlightServerAction = createRecordFromThenable(
fetchServerAction(state, action)
)
mutable.inFlightServerAction = fetchServerAction(state, action)
// suspends until the server action is resolved.
......
......@@ -655,37 +655,7 @@ describe('serverPatchReducer', () => {
"nextUrl": "/linking/somewhere-else",
"prefetchCache": Map {
"/linking/about" => {
"data": Promise {
"status": "fulfilled",
"value": [
[
[
"children",
"linking",
"children",
"about",
[
"about",
{
"children": [
"",
{},
],
},
],
<h1>
About Page!
</h1>,
<React.Fragment>
<title>
About page!
</title>
</React.Fragment>,
],
],
undefined,
],
},
"data": Promise {},
"kind": "temporary",
"lastUsedTime": 1690329600000,
"prefetchTime": 1690329600000,
......
......@@ -41,7 +41,7 @@ export interface Mutable {
}
export interface ServerActionMutable extends Mutable {
inFlightServerAction?: ThenableRecord<any> | null
inFlightServerAction?: Promise<any> | null
actionResultResolved?: boolean
}
......@@ -212,7 +212,7 @@ export type FocusAndScrollRef = {
export type PrefetchCacheEntry = {
treeAtTimeOfPrefetch: FlightRouterState
data: ThenableRecord<FetchServerResponseResult> | null
data: Promise<FetchServerResponseResult> | null
kind: PrefetchKind
prefetchTime: number
lastUsedTime: number | null
......@@ -274,33 +274,11 @@ export type ReducerActions = Readonly<
| ServerActionAction
>
export interface PendingThenable<T> extends ThenableImpl<T> {
status: 'pending'
}
export interface FulfilledThenable<T> extends ThenableImpl<T> {
status: 'fulfilled'
value: T
}
export interface RejectedThenable<T> extends ThenableImpl<T> {
status: 'rejected'
reason: unknown
}
interface ThenableImpl<T> {
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
): Promise<TResult1 | TResult2>
}
export type ThenableRecord<T> =
| PendingThenable<T>
| RejectedThenable<T>
| FulfilledThenable<T>
export function isThenable(value: any): value is Promise<AppRouterState> {
// TODO: We don't gain anything from this abstraction. It's unsound, and only
// makes sense in the specific places where we use it. So it's better to keep
// the type coercion inline, instead of leaking this to other places in
// the codebase.
return (
value &&
(typeof value === 'object' || typeof value === 'function') &&
......
......@@ -3,7 +3,6 @@
import type {
FocusAndScrollRef,
PrefetchKind,
ThenableRecord,
} from '../../client/components/router-reducer/router-reducer-types'
import type { FetchServerResponseResult } from '../../client/components/router-reducer/fetch-server-response'
import type {
......@@ -30,7 +29,7 @@ export type CacheNode =
/**
* In-flight request for this node.
*/
data: ThenableRecord<FetchServerResponseResult> | null
data: Promise<FetchServerResponseResult> | null
head?: React.ReactNode
/**
* React Component for this node.
......
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