Unverified Commit 567dc18b authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

move segment cache entries to top level segment-cache dir (#85542)

This removes the indirection that was set up to codesplit on the client.
But now that there's only a single client cache entrypoint, we can
delete the indirection and move everything to a top-level export.
parent b57c8a16
...@@ -19,7 +19,7 @@ import { ...@@ -19,7 +19,7 @@ import {
mountFormInstance, mountFormInstance,
unmountPrefetchableInstance, unmountPrefetchableInstance,
} from '../components/links' } from '../components/links'
import { FetchStrategy } from '../components/segment-cache' import { FetchStrategy } from '../components/segment-cache/types'
export type { FormProps } export type { FormProps }
......
...@@ -21,7 +21,7 @@ import { isLocalURL } from '../../shared/lib/router/utils/is-local-url' ...@@ -21,7 +21,7 @@ import { isLocalURL } from '../../shared/lib/router/utils/is-local-url'
import { import {
FetchStrategy, FetchStrategy,
type PrefetchTaskFetchStrategy, type PrefetchTaskFetchStrategy,
} from '../components/segment-cache' } from '../components/segment-cache/types'
import { errorOnce } from '../../shared/lib/utils/error-once' import { errorOnce } from '../../shared/lib/utils/error-once'
type Url = string | UrlObject type Url = string | UrlObject
......
...@@ -16,9 +16,9 @@ import { startTransition } from 'react' ...@@ -16,9 +16,9 @@ import { startTransition } from 'react'
import { isThenable } from '../../shared/lib/is-thenable' import { isThenable } from '../../shared/lib/is-thenable'
import { import {
FetchStrategy, FetchStrategy,
prefetch as prefetchWithSegmentCache,
type PrefetchTaskFetchStrategy, type PrefetchTaskFetchStrategy,
} from './segment-cache' } from './segment-cache/types'
import { prefetch as prefetchWithSegmentCache } from './segment-cache/prefetch'
import { dispatchAppRouterAction } from './use-action-queue' import { dispatchAppRouterAction } from './use-action-queue'
import { addBasePath } from '../add-base-path' import { addBasePath } from '../add-base-path'
import { isExternalURL } from './app-router-utils' import { isExternalURL } from './app-router-utils'
......
...@@ -2,17 +2,17 @@ import type { FlightRouterState } from '../../shared/lib/app-router-types' ...@@ -2,17 +2,17 @@ import type { FlightRouterState } from '../../shared/lib/app-router-types'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime' import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import { import {
FetchStrategy, FetchStrategy,
isPrefetchTaskDirty,
type PrefetchTaskFetchStrategy, type PrefetchTaskFetchStrategy,
} from './segment-cache' PrefetchPriority,
import { createCacheKey } from './segment-cache' } from './segment-cache/types'
import { createCacheKey } from './segment-cache/cache-key'
import { import {
type PrefetchTask, type PrefetchTask,
PrefetchPriority,
schedulePrefetchTask as scheduleSegmentPrefetchTask, schedulePrefetchTask as scheduleSegmentPrefetchTask,
cancelPrefetchTask, cancelPrefetchTask,
reschedulePrefetchTask, reschedulePrefetchTask,
} from './segment-cache' isPrefetchTaskDirty,
} from './segment-cache/scheduler'
import { startTransition } from 'react' import { startTransition } from 'react'
type LinkElement = HTMLAnchorElement | SVGAElement type LinkElement = HTMLAnchorElement | SVGAElement
......
...@@ -40,7 +40,7 @@ import { ...@@ -40,7 +40,7 @@ import {
getRenderedSearch, getRenderedSearch,
urlToUrlWithoutFlightMarker, urlToUrlWithoutFlightMarker,
} from '../../route-params' } from '../../route-params'
import type { NormalizedSearch } from '../segment-cache' import type { NormalizedSearch } from '../segment-cache/cache-key'
const createFromReadableStream = const createFromReadableStream =
createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream'] createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']
......
...@@ -13,10 +13,10 @@ import { handleMutable } from '../handle-mutable' ...@@ -13,10 +13,10 @@ import { handleMutable } from '../handle-mutable'
import { import {
navigate as navigateUsingSegmentCache, navigate as navigateUsingSegmentCache,
NavigationResultTag,
type NavigationResult, type NavigationResult,
getStaleTimeMs, } from '../../segment-cache/navigation'
} from '../../segment-cache' import { NavigationResultTag } from '../../segment-cache/types'
import { getStaleTimeMs } from '../../segment-cache/cache'
// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`) // These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)
// and default to 5 minutes (static) / 0 seconds (dynamic) // and default to 5 minutes (static) / 0 seconds (dynamic)
......
...@@ -19,7 +19,7 @@ import { createEmptyCacheNode } from '../../app-router' ...@@ -19,7 +19,7 @@ import { createEmptyCacheNode } from '../../app-router'
import { handleSegmentMismatch } from '../handle-segment-mismatch' import { handleSegmentMismatch } from '../handle-segment-mismatch'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree' import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import { refreshInactiveParallelSegments } from '../refetch-inactive-parallel-segments' import { refreshInactiveParallelSegments } from '../refetch-inactive-parallel-segments'
import { revalidateEntireCache } from '../../segment-cache' import { revalidateEntireCache } from '../../segment-cache/cache'
export function refreshReducer( export function refreshReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
......
...@@ -55,7 +55,7 @@ import { ...@@ -55,7 +55,7 @@ import {
extractInfoFromServerReferenceId, extractInfoFromServerReferenceId,
omitUnusedArgs, omitUnusedArgs,
} from '../../../../shared/lib/server-reference-info' } from '../../../../shared/lib/server-reference-info'
import { revalidateEntireCache } from '../../segment-cache' import { revalidateEntireCache } from '../../segment-cache/cache'
const createFromFetch = const createFromFetch =
createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch'] createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']
......
/**
* Entry point to the Segment Cache implementation.
*
* All code related to the Segment Cache lives `segment-cache-impl` directory.
* Callers access it through this indirection.
*
* This is to ensure the code is dead code eliminated from the bundle if the
* flag is disabled.
*
* TODO: This is super tedious. Since experimental flags are an essential part
* of our workflow, we should establish a better pattern for dead code
* elimination. Ideally it would be done at the bundler level, like how React's
* build process works. In the React repo, you don't even need to add any extra
* configuration per experiment — if the code is not reachable, it gets stripped
* from the build automatically by Rollup. Or, shorter term, we could stub out
* experimental modules at build time by updating the build config, i.e. a more
* automated version of what I'm doing manually in this file.
*/
export type { NavigationResult } from './segment-cache-impl/navigation'
export type { PrefetchTask } from './segment-cache-impl/scheduler'
export type {
NormalizedPathname,
NormalizedSearch,
} from './segment-cache-impl/cache-key'
export const prefetch: typeof import('./segment-cache-impl/prefetch').prefetch =
function (...args) {
return (
require('./segment-cache-impl/prefetch') as typeof import('./segment-cache-impl/prefetch')
).prefetch(...args)
}
export const navigate: typeof import('./segment-cache-impl/navigation').navigate =
function (...args) {
return (
require('./segment-cache-impl/navigation') as typeof import('./segment-cache-impl/navigation')
).navigate(...args)
}
export const revalidateEntireCache: typeof import('./segment-cache-impl/cache').revalidateEntireCache =
function (...args) {
return (
require('./segment-cache-impl/cache') as typeof import('./segment-cache-impl/cache')
).revalidateEntireCache(...args)
}
export const getCurrentCacheVersion: typeof import('./segment-cache-impl/cache').getCurrentCacheVersion =
function (...args) {
return (
require('./segment-cache-impl/cache') as typeof import('./segment-cache-impl/cache')
).getCurrentCacheVersion(...args)
}
export const schedulePrefetchTask: typeof import('./segment-cache-impl/scheduler').schedulePrefetchTask =
function (...args) {
return (
require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')
).schedulePrefetchTask(...args)
}
export const cancelPrefetchTask: typeof import('./segment-cache-impl/scheduler').cancelPrefetchTask =
function (...args) {
return (
require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')
).cancelPrefetchTask(...args)
}
export const reschedulePrefetchTask: typeof import('./segment-cache-impl/scheduler').reschedulePrefetchTask =
function (...args) {
return (
require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')
).reschedulePrefetchTask(...args)
}
export const isPrefetchTaskDirty: typeof import('./segment-cache-impl/scheduler').isPrefetchTaskDirty =
function (...args) {
return (
require('./segment-cache-impl/scheduler') as typeof import('./segment-cache-impl/scheduler')
).isPrefetchTaskDirty(...args)
}
export const createCacheKey: typeof import('./segment-cache-impl/cache-key').createCacheKey =
function (...args) {
return (
require('./segment-cache-impl/cache-key') as typeof import('./segment-cache-impl/cache-key')
).createCacheKey(...args)
}
/**
* Below are public constants. They're small enough that we don't need to
* DCE them.
*/
export const enum NavigationResultTag {
MPA,
Success,
NoOp,
Async,
}
/**
* The priority of the prefetch task. Higher numbers are higher priority.
*/
export const enum PrefetchPriority {
/**
* Assigned to the most recently hovered/touched link. Special network
* bandwidth is reserved for this task only. There's only ever one Intent-
* priority task at a time; when a new Intent task is scheduled, the previous
* one is bumped down to Default.
*/
Intent = 2,
/**
* The default priority for prefetch tasks.
*/
Default = 1,
/**
* Assigned to tasks when they spawn non-blocking background work, like
* revalidating a partially cached entry to see if more data is available.
*/
Background = 0,
}
export const enum FetchStrategy {
// Deliberately ordered so we can easily compare two segments
// and determine if one segment is "more specific" than another
// (i.e. if it's likely that it contains more data)
LoadingBoundary = 0,
PPR = 1,
PPRRuntime = 2,
Full = 3,
}
/**
* A subset of fetch strategies used for prefetch tasks.
* A prefetch task can't know if it should use `PPR` or `LoadingBoundary`
* until we complete the initial tree prefetch request, so we use `PPR` to signal both cases
* and adjust it based on the route when actually fetching.
* */
export type PrefetchTaskFetchStrategy =
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime
| FetchStrategy.Full
/**
* Ensures a minimum stale time of 30s to avoid issues where the server sends a too
* short-lived stale time, which would prevent anything from being prefetched.
*/
export function getStaleTimeMs(staleTimeSeconds: number): number {
return Math.max(staleTimeSeconds, 30) * 1000
}
...@@ -93,9 +93,17 @@ import { ...@@ -93,9 +93,17 @@ import {
DOC_PREFETCH_RANGE_HEADER_VALUE, DOC_PREFETCH_RANGE_HEADER_VALUE,
doesExportedHtmlMatchBuildId, doesExportedHtmlMatchBuildId,
} from '../../../shared/lib/segment-cache/output-export-prefetch-encoding' } from '../../../shared/lib/segment-cache/output-export-prefetch-encoding'
import { FetchStrategy, getStaleTimeMs } from '../segment-cache' import { FetchStrategy } from './types'
import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers' import { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'
/**
* Ensures a minimum stale time of 30s to avoid issues where the server sends a too
* short-lived stale time, which would prevent anything from being prefetched.
*/
export function getStaleTimeMs(staleTimeSeconds: number): number {
return Math.max(staleTimeSeconds, 30) * 1000
}
// A note on async/await when working in the prefetch cache: // A note on async/await when working in the prefetch cache:
// //
// Most async operations in the prefetch cache should *not* use async/await, // Most async operations in the prefetch cache should *not* use async/await,
......
...@@ -28,7 +28,7 @@ import { ...@@ -28,7 +28,7 @@ import {
} from './cache' } from './cache'
import { createCacheKey } from './cache-key' import { createCacheKey } from './cache-key'
import { addSearchParamsIfPageSegment } from '../../../shared/lib/segment' import { addSearchParamsIfPageSegment } from '../../../shared/lib/segment'
import { NavigationResultTag } from '../segment-cache' import { NavigationResultTag } from './types'
type MPANavigationResult = { type MPANavigationResult = {
tag: NavigationResultTag.MPA tag: NavigationResultTag.MPA
......
...@@ -2,10 +2,7 @@ import type { FlightRouterState } from '../../../shared/lib/app-router-types' ...@@ -2,10 +2,7 @@ import type { FlightRouterState } from '../../../shared/lib/app-router-types'
import { createPrefetchURL } from '../app-router-utils' import { createPrefetchURL } from '../app-router-utils'
import { createCacheKey } from './cache-key' import { createCacheKey } from './cache-key'
import { schedulePrefetchTask } from './scheduler' import { schedulePrefetchTask } from './scheduler'
import { import { PrefetchPriority, type PrefetchTaskFetchStrategy } from './types'
PrefetchPriority,
type PrefetchTaskFetchStrategy,
} from '../segment-cache'
/** /**
* Entrypoint for prefetching a URL into the Segment Cache. * Entrypoint for prefetching a URL into the Segment Cache.
......
...@@ -33,9 +33,9 @@ import { createCacheKey } from './cache-key' ...@@ -33,9 +33,9 @@ import { createCacheKey } from './cache-key'
import { import {
FetchStrategy, FetchStrategy,
type PrefetchTaskFetchStrategy, type PrefetchTaskFetchStrategy,
getCurrentCacheVersion,
PrefetchPriority, PrefetchPriority,
} from '../segment-cache' } from './types'
import { getCurrentCacheVersion } from './cache'
import { import {
addSearchParamsIfPageSegment, addSearchParamsIfPageSegment,
PAGE_SEGMENT_KEY, PAGE_SEGMENT_KEY,
......
/**
* Shared types and constants for the Segment Cache.
*/
export const enum NavigationResultTag {
MPA,
Success,
NoOp,
Async,
}
/**
* The priority of the prefetch task. Higher numbers are higher priority.
*/
export const enum PrefetchPriority {
/**
* Assigned to the most recently hovered/touched link. Special network
* bandwidth is reserved for this task only. There's only ever one Intent-
* priority task at a time; when a new Intent task is scheduled, the previous
* one is bumped down to Default.
*/
Intent = 2,
/**
* The default priority for prefetch tasks.
*/
Default = 1,
/**
* Assigned to tasks when they spawn non-blocking background work, like
* revalidating a partially cached entry to see if more data is available.
*/
Background = 0,
}
export const enum FetchStrategy {
// Deliberately ordered so we can easily compare two segments
// and determine if one segment is "more specific" than another
// (i.e. if it's likely that it contains more data)
LoadingBoundary = 0,
PPR = 1,
PPRRuntime = 2,
Full = 3,
}
/**
* A subset of fetch strategies used for prefetch tasks.
* A prefetch task can't know if it should use `PPR` or `LoadingBoundary`
* until we complete the initial tree prefetch request, so we use `PPR` to signal both cases
* and adjust it based on the route when actually fetching.
* */
export type PrefetchTaskFetchStrategy =
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime
| FetchStrategy.Full
...@@ -9,7 +9,7 @@ import type { ...@@ -9,7 +9,7 @@ import type {
InitialRSCPayload, InitialRSCPayload,
} from '../shared/lib/app-router-types' } from '../shared/lib/app-router-types'
import { PAGE_SEGMENT_KEY } from '../shared/lib/segment' import { PAGE_SEGMENT_KEY } from '../shared/lib/segment'
import type { NormalizedSearch } from './components/segment-cache' import type { NormalizedSearch } from './components/segment-cache/cache-key'
import { import {
getCacheKeyForDynamicParam, getCacheKeyForDynamicParam,
parseDynamicParamFromURLPart, parseDynamicParamFromURLPart,
......
...@@ -13,7 +13,7 @@ import { ...@@ -13,7 +13,7 @@ import {
import type { import type {
NormalizedPathname, NormalizedPathname,
NormalizedSearch, NormalizedSearch,
} from './components/segment-cache' } from './components/segment-cache/cache-key'
import type { RSCResponse } from './components/router-reducer/fetch-server-response' import type { RSCResponse } from './components/router-reducer/fetch-server-response'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
......
import { PAGE_SEGMENT_KEY } from '../segment' import { PAGE_SEGMENT_KEY } from '../segment'
import type { Segment as FlightRouterStateSegment } from '../app-router-types' import type { Segment as FlightRouterStateSegment } from '../app-router-types'
import type { NormalizedPathname } from '../../../client/components/segment-cache' import type { NormalizedPathname } from '../../../client/components/segment-cache/cache-key'
// TypeScript trick to simulate opaque types, like in Flow. // TypeScript trick to simulate opaque types, like in Flow.
type Opaque<K, T> = T & { __brand: K } type Opaque<K, T> = T & { __brand: K }
......
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