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

fix thenable types & update another incorrect cache record (#55758)

This is a continuation from https://github.com/vercel/next.js/pull/55690 but also properly types these functions so we can catch these easier
parent ff7e4f49
...@@ -27,6 +27,7 @@ import { RedirectBoundary } from './redirect-boundary' ...@@ -27,6 +27,7 @@ import { RedirectBoundary } from './redirect-boundary'
import { NotFoundBoundary } from './not-found-boundary' import { NotFoundBoundary } from './not-found-boundary'
import { getSegmentValue } from './router-reducer/reducers/get-segment-value' import { getSegmentValue } from './router-reducer/reducers/get-segment-value'
import { createRouterCacheKey } from './router-reducer/create-router-cache-key' 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. * Add refetch marker to router state at the point of the current layout segment.
...@@ -378,11 +379,13 @@ function InnerLayoutRouter({ ...@@ -378,11 +379,13 @@ function InnerLayoutRouter({
childNode = { childNode = {
status: CacheStates.DATA_FETCH, status: CacheStates.DATA_FETCH,
data: fetchServerResponse( data: createRecordFromThenable(
new URL(url, location.origin), fetchServerResponse(
refetchTree, new URL(url, location.origin),
context.nextUrl, refetchTree,
buildId context.nextUrl,
buildId
)
), ),
subTreeData: null, subTreeData: null,
head: 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 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 that are running at any given time. It's used to limit the number of concurrent
...@@ -7,7 +9,10 @@ ...@@ -7,7 +9,10 @@
export class PromiseQueue { export class PromiseQueue {
#maxConcurrency: number #maxConcurrency: number
#runningCount: number #runningCount: number
#queue: Array<{ promiseFn: Promise<any>; task: () => void }> #queue: Array<{
promiseFn: ThenableRecord<any> | Promise<any>
task: () => void
}>
constructor(maxConcurrency = 5) { constructor(maxConcurrency = 5) {
this.#maxConcurrency = maxConcurrency this.#maxConcurrency = maxConcurrency
...@@ -45,7 +50,7 @@ export class PromiseQueue { ...@@ -45,7 +50,7 @@ export class PromiseQueue {
return taskPromise return taskPromise
} }
bump(promiseFn: Promise<any>) { bump(promiseFn: ThenableRecord<any> | Promise<any>) {
const index = this.#queue.findIndex((item) => item.promiseFn === promiseFn) const index = this.#queue.findIndex((item) => item.promiseFn === promiseFn)
if (index > -1) { if (index > -1) {
......
...@@ -7,6 +7,10 @@ describe('createRecordFromThenable', () => { ...@@ -7,6 +7,10 @@ describe('createRecordFromThenable', () => {
expect(record.status).toBe('pending') expect(record.status).toBe('pending')
await thenable await thenable
expect(record.status).toBe('fulfilled') expect(record.status).toBe('fulfilled')
// typeguard
if (record.status !== 'fulfilled') {
throw new Error('Invalid Type')
}
expect(record.value).toBe('success') expect(record.value).toBe('success')
}) })
...@@ -16,6 +20,10 @@ describe('createRecordFromThenable', () => { ...@@ -16,6 +20,10 @@ describe('createRecordFromThenable', () => {
expect(record.status).toBe('pending') expect(record.status).toBe('pending')
await thenable.catch(() => {}) await thenable.catch(() => {})
expect(record.status).toBe('rejected') expect(record.status).toBe('rejected')
expect(record.value).toBe('error') // typeguard
if (record.status !== 'rejected') {
throw new Error('Invalid Type')
}
expect(record.reason).toBe('error')
}) })
}) })
import { ThenableRecord } from './router-reducer-types'
/** /**
* Create data fetching record for Promise. * Create data fetching record for Promise.
*/ */
// TODO-APP: change `any` to type inference.
export function createRecordFromThenable(thenable: any) { export function createRecordFromThenable<T>(
promise: PromiseLike<T>
): ThenableRecord<T> {
const thenable = promise as any
thenable.status = 'pending' thenable.status = 'pending'
thenable.then( thenable.then(
(value: any) => { (value: any) => {
...@@ -14,7 +19,7 @@ export function createRecordFromThenable(thenable: any) { ...@@ -14,7 +19,7 @@ export function createRecordFromThenable(thenable: any) {
(err: any) => { (err: any) => {
if (thenable.status === 'pending') { if (thenable.status === 'pending') {
thenable.status = 'rejected' thenable.status = 'rejected'
thenable.value = err thenable.reason = err
} }
} }
) )
......
...@@ -29,7 +29,7 @@ import { callServer } from '../../app-call-server' ...@@ -29,7 +29,7 @@ import { callServer } from '../../app-call-server'
import { PrefetchKind } from './router-reducer-types' import { PrefetchKind } from './router-reducer-types'
import { hexHash } from '../../../shared/lib/hash' import { hexHash } from '../../../shared/lib/hash'
type FetchServerResponseResult = [ export type FetchServerResponseResult = [
flightData: FlightData, flightData: FlightData,
canonicalUrlOverride: URL | undefined canonicalUrlOverride: URL | undefined
] ]
......
import React from 'react' import React from 'react'
import { fetchServerResponse } from './fetch-server-response' import type { FetchServerResponseResult } from './fetch-server-response'
import { fillCacheWithDataProperty } from './fill-cache-with-data-property' import { fillCacheWithDataProperty } from './fill-cache-with-data-property'
import { import {
CacheStates, CacheStates,
CacheNode, CacheNode,
} from '../../../shared/lib/app-router-context.shared-runtime' } from '../../../shared/lib/app-router-context.shared-runtime'
import { createRecordFromThenable } from './create-record-from-thenable'
import { ThenableRecord } from './router-reducer-types'
describe('fillCacheWithDataProperty', () => { describe('fillCacheWithDataProperty', () => {
it('should add data property', () => { it('should add data property', () => {
const fetchServerResponseMock: jest.Mock< const fetchServerResponseMock: jest.Mock<
ReturnType<typeof fetchServerResponse> ThenableRecord<FetchServerResponseResult>
> = jest.fn(() => > = jest.fn(() =>
Promise.resolve([ createRecordFromThenable(
/* TODO-APP: replace with actual FlightData */ '', Promise.resolve([
undefined, /* TODO-APP: replace with actual FlightData */ '',
]) undefined,
])
)
) )
const pathname = '/dashboard/settings' const pathname = '/dashboard/settings'
const segments = pathname.split('/') const segments = pathname.split('/')
...@@ -95,7 +99,9 @@ describe('fillCacheWithDataProperty', () => { ...@@ -95,7 +99,9 @@ describe('fillCacheWithDataProperty', () => {
</React.Fragment>, </React.Fragment>,
}, },
"dashboard" => Object { "dashboard" => Object {
"data": Promise {}, "data": Promise {
"status": "pending",
},
"parallelRoutes": Map {}, "parallelRoutes": Map {},
"status": "DATAFETCH", "status": "DATAFETCH",
"subTreeData": null, "subTreeData": null,
......
import type { FetchServerResponseResult } from './fetch-server-response'
import type { ThenableRecord } from './router-reducer-types'
import { FlightSegmentPath } from '../../../server/app-render/types' import { FlightSegmentPath } from '../../../server/app-render/types'
import { import {
CacheNode, CacheNode,
CacheStates, CacheStates,
} from '../../../shared/lib/app-router-context.shared-runtime' } from '../../../shared/lib/app-router-context.shared-runtime'
import { createRouterCacheKey } from './create-router-cache-key' import { createRouterCacheKey } from './create-router-cache-key'
import { fetchServerResponse } from './fetch-server-response'
/** /**
* Kick off fetch based on the common layout between two routes. Fill cache with data property holding the in-progress fetch. * Kick off fetch based on the common layout between two routes. Fill cache with data property holding the in-progress fetch.
...@@ -13,7 +14,7 @@ export function fillCacheWithDataProperty( ...@@ -13,7 +14,7 @@ export function fillCacheWithDataProperty(
newCache: CacheNode, newCache: CacheNode,
existingCache: CacheNode, existingCache: CacheNode,
flightSegmentPath: FlightSegmentPath, flightSegmentPath: FlightSegmentPath,
fetchResponse: () => ReturnType<typeof fetchServerResponse>, fetchResponse: () => ThenableRecord<FetchServerResponseResult>,
bailOnParallelRoutes: boolean = false bailOnParallelRoutes: boolean = false
): { bailOptimistic: boolean } | undefined { ): { bailOptimistic: boolean } | undefined {
const isLastEntry = flightSegmentPath.length <= 2 const isLastEntry = flightSegmentPath.length <= 2
......
...@@ -23,6 +23,6 @@ describe('readRecordValue', () => { ...@@ -23,6 +23,6 @@ describe('readRecordValue', () => {
} }
})() })()
expect(result.status).toBe('rejected') expect(result.status).toBe('rejected')
expect(result.value).toBe('failed') expect(result.reason).toBe('failed')
}) })
}) })
import type { ThenableRecord } from './router-reducer-types'
/** /**
* Read record value or throw Promise if it's not resolved yet. * Read record value or throw Promise if it's not resolved yet.
*/ */
export function readRecordValue<T>(thenable: Promise<T>): T { export function readRecordValue<T>(thenable: ThenableRecord<T>): T {
// @ts-expect-error TODO: fix type
if (thenable.status === 'fulfilled') { if (thenable.status === 'fulfilled') {
// @ts-expect-error TODO: fix type
return thenable.value return thenable.value
} else { } else {
throw thenable throw thenable
......
...@@ -6,7 +6,10 @@ import type { ...@@ -6,7 +6,10 @@ import type {
FlightRouterState, FlightRouterState,
FlightSegmentPath, FlightSegmentPath,
} from '../../../../server/app-render/types' } from '../../../../server/app-render/types'
import { fetchServerResponse } from '../fetch-server-response' import {
FetchServerResponseResult,
fetchServerResponse,
} from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value' import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
...@@ -22,6 +25,7 @@ import { ...@@ -22,6 +25,7 @@ import {
PrefetchKind, PrefetchKind,
ReadonlyReducerState, ReadonlyReducerState,
ReducerState, ReducerState,
ThenableRecord,
} from '../router-reducer-types' } from '../router-reducer-types'
import { handleMutable } from '../handle-mutable' import { handleMutable } from '../handle-mutable'
import { applyFlightData } from '../apply-flight-data' import { applyFlightData } from '../apply-flight-data'
...@@ -78,7 +82,7 @@ function addRefetchToLeafSegments( ...@@ -78,7 +82,7 @@ function addRefetchToLeafSegments(
currentCache: CacheNode, currentCache: CacheNode,
flightSegmentPath: FlightSegmentPath, flightSegmentPath: FlightSegmentPath,
treePatch: FlightRouterState, treePatch: FlightRouterState,
data: () => ReturnType<typeof fetchServerResponse> data: () => ThenableRecord<FetchServerResponseResult>
) { ) {
let appliedPatch = false let appliedPatch = false
...@@ -159,7 +163,7 @@ export function navigateReducer( ...@@ -159,7 +163,7 @@ export function navigateReducer(
temporaryCacheNode.subTreeData = state.cache.subTreeData temporaryCacheNode.subTreeData = state.cache.subTreeData
temporaryCacheNode.parallelRoutes = new Map(state.cache.parallelRoutes) temporaryCacheNode.parallelRoutes = new Map(state.cache.parallelRoutes)
let data: ReturnType<typeof createRecordFromThenable> | undefined let data: ThenableRecord<FetchServerResponseResult> | null = null
const fetchResponse = () => { const fetchResponse = () => {
if (!data) { if (!data) {
...@@ -199,7 +203,7 @@ export function navigateReducer( ...@@ -199,7 +203,7 @@ export function navigateReducer(
mutable.canonicalUrl = href mutable.canonicalUrl = href
state.prefetchCache.set(createHrefFromUrl(url, false), { state.prefetchCache.set(createHrefFromUrl(url, false), {
data: createRecordFromThenable(Promise.resolve(data)), data: data ? createRecordFromThenable(Promise.resolve(data)) : null,
// this will make sure that the entry will be discarded after 30s // this will make sure that the entry will be discarded after 30s
kind: PrefetchKind.TEMPORARY, kind: PrefetchKind.TEMPORARY,
prefetchTime: Date.now(), prefetchTime: Date.now(),
......
...@@ -166,16 +166,19 @@ export function serverActionReducer( ...@@ -166,16 +166,19 @@ export function serverActionReducer(
mutable.globalMutable.pendingNavigatePath && mutable.globalMutable.pendingNavigatePath &&
mutable.globalMutable.pendingNavigatePath !== href mutable.globalMutable.pendingNavigatePath !== href
) { ) {
mutable.inFlightServerAction.then(() => { mutable.inFlightServerAction.then(
if (mutable.actionResultResolved) return () => {
if (mutable.actionResultResolved) return
// if the server action resolves after a navigation took place,
// reset ServerActionMutable values & trigger a refresh so that any stale data gets updated // if the server action resolves after a navigation took place,
mutable.inFlightServerAction = null // reset ServerActionMutable values & trigger a refresh so that any stale data gets updated
mutable.globalMutable.pendingNavigatePath = undefined mutable.inFlightServerAction = null
mutable.globalMutable.refresh() mutable.globalMutable.pendingNavigatePath = undefined
mutable.actionResultResolved = true mutable.globalMutable.refresh()
}) mutable.actionResultResolved = true
},
() => {}
)
return state return state
} }
...@@ -305,7 +308,7 @@ export function serverActionReducer( ...@@ -305,7 +308,7 @@ export function serverActionReducer(
} catch (e: any) { } catch (e: any) {
if (e.status === 'rejected') { if (e.status === 'rejected') {
if (!mutable.actionResultResolved) { if (!mutable.actionResultResolved) {
reject(e.value) reject(e.reason)
mutable.actionResultResolved = true mutable.actionResultResolved = true
} }
......
...@@ -4,7 +4,12 @@ import type { ...@@ -4,7 +4,12 @@ import type {
FlightData, FlightData,
FlightSegmentPath, FlightSegmentPath,
} from '../../../server/app-render/types' } from '../../../server/app-render/types'
import { fetchServerResponse } from './fetch-server-response' import type {
FulfilledThenable,
PendingThenable,
RejectedThenable,
} from 'react'
import type { FetchServerResponseResult } from './fetch-server-response'
export const ACTION_REFRESH = 'refresh' export const ACTION_REFRESH = 'refresh'
export const ACTION_NAVIGATE = 'navigate' export const ACTION_NAVIGATE = 'navigate'
...@@ -46,7 +51,7 @@ export interface Mutable { ...@@ -46,7 +51,7 @@ export interface Mutable {
} }
export interface ServerActionMutable extends Mutable { export interface ServerActionMutable extends Mutable {
inFlightServerAction?: Promise<any> | null inFlightServerAction?: ThenableRecord<any> | null
actionResultResolved?: boolean actionResultResolved?: boolean
} }
...@@ -217,7 +222,7 @@ export type FocusAndScrollRef = { ...@@ -217,7 +222,7 @@ export type FocusAndScrollRef = {
export type PrefetchCacheEntry = { export type PrefetchCacheEntry = {
treeAtTimeOfPrefetch: FlightRouterState treeAtTimeOfPrefetch: FlightRouterState
data: ReturnType<typeof fetchServerResponse> | null data: ThenableRecord<FetchServerResponseResult> | null
kind: PrefetchKind kind: PrefetchKind
prefetchTime: number prefetchTime: number
lastUsedTime: number | null lastUsedTime: number | null
...@@ -278,3 +283,8 @@ export type ReducerActions = Readonly< ...@@ -278,3 +283,8 @@ export type ReducerActions = Readonly<
| FastRefreshAction | FastRefreshAction
| ServerActionAction | ServerActionAction
> >
export type ThenableRecord<T> =
| PendingThenable<T>
| RejectedThenable<T>
| FulfilledThenable<T>
'use client' 'use client'
import { import type {
FocusAndScrollRef, FocusAndScrollRef,
PrefetchKind, PrefetchKind,
ThenableRecord,
} from '../../client/components/router-reducer/router-reducer-types' } from '../../client/components/router-reducer/router-reducer-types'
import type { fetchServerResponse } from '../../client/components/router-reducer/fetch-server-response' import type { FetchServerResponseResult } from '../../client/components/router-reducer/fetch-server-response'
import type { import type {
FlightRouterState, FlightRouterState,
FlightData, FlightData,
...@@ -29,7 +30,7 @@ export type CacheNode = ...@@ -29,7 +30,7 @@ export type CacheNode =
/** /**
* In-flight request for this node. * In-flight request for this node.
*/ */
data: ReturnType<typeof fetchServerResponse> | null data: ThenableRecord<FetchServerResponseResult> | null
head?: React.ReactNode head?: React.ReactNode
/** /**
* React Component for this node. * 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