File size: 6,191 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'

export type CacheLife = {
  // How long the client can cache a value without checking with the server.
  stale?: number
  // How frequently you want the cache to refresh on the server.
  // Stale values may be served while revalidating.
  revalidate?: number
  // In the worst case scenario, where you haven't had traffic in a while,
  // how stale can a value be until you prefer deopting to dynamic.
  // Must be longer than revalidate.
  expire?: number
}
// The equivalent header is kind of like:
// Cache-Control: max-age=[stale],s-max-age=[revalidate],stale-while-revalidate=[expire-revalidate],stale-if-error=[expire-revalidate]
// Except that stale-while-revalidate/stale-if-error only applies to shared caches - not private caches.

// The default revalidates relatively frequently but doesn't expire to ensure it's always
// able to serve fast results but by default doesn't hang.

// This gets overridden by the next-types-plugin
type CacheLifeProfiles =
  | 'default'
  | 'seconds'
  | 'minutes'
  | 'hours'
  | 'days'
  | 'weeks'
  | 'max'
  | (string & {})

function validateCacheLife(profile: CacheLife) {
  if (profile.stale !== undefined) {
    if ((profile.stale as any) === false) {
      throw new Error(
        'Pass `Infinity` instead of `false` if you want to cache on the client forever ' +
          'without checking with the server.'
      )
    } else if (typeof profile.stale !== 'number') {
      throw new Error('The stale option must be a number of seconds.')
    }
  }
  if (profile.revalidate !== undefined) {
    if ((profile.revalidate as any) === false) {
      throw new Error(
        'Pass `Infinity` instead of `false` if you do not want to revalidate by time.'
      )
    } else if (typeof profile.revalidate !== 'number') {
      throw new Error('The revalidate option must be a number of seconds.')
    }
  }
  if (profile.expire !== undefined) {
    if ((profile.expire as any) === false) {
      throw new Error(
        'Pass `Infinity` instead of `false` if you want to cache on the server forever ' +
          'without checking with the origin.'
      )
    } else if (typeof profile.expire !== 'number') {
      throw new Error('The expire option must be a number of seconds.')
    }
  }

  if (profile.revalidate !== undefined && profile.expire !== undefined) {
    if (profile.revalidate > profile.expire) {
      throw new Error(
        'If providing both the revalidate and expire options, ' +
          'the expire option must be greater than the revalidate option. ' +
          'The expire option indicates how many seconds from the start ' +
          'until it can no longer be used.'
      )
    }
  }

  if (profile.stale !== undefined && profile.expire !== undefined) {
    if (profile.stale > profile.expire) {
      throw new Error(
        'If providing both the stale and expire options, ' +
          'the expire option must be greater than the stale option. ' +
          'The expire option indicates how many seconds from the start ' +
          'until it can no longer be used.'
      )
    }
  }
}

export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
  if (!process.env.__NEXT_USE_CACHE) {
    throw new Error(
      'cacheLife() is only available with the experimental.useCache config.'
    )
  }

  const workUnitStore = workUnitAsyncStorage.getStore()

  switch (workUnitStore?.type) {
    case 'prerender':
    case 'prerender-client':
    case 'prerender-ppr':
    case 'prerender-legacy':
    case 'request':
    case 'unstable-cache':
    case undefined:
      throw new Error(
        'cacheLife() can only be called inside a "use cache" function.'
      )
    case 'cache':
    case 'private-cache':
      break
    default:
      workUnitStore satisfies never
  }

  if (typeof profile === 'string') {
    const workStore = workAsyncStorage.getStore()
    if (!workStore) {
      throw new Error(
        'cacheLife() can only be called during App Router rendering at the moment.'
      )
    }
    if (!workStore.cacheLifeProfiles) {
      throw new Error(
        'cacheLifeProfiles should always be provided. This is a bug in Next.js.'
      )
    }

    // TODO: This should be globally available and not require an AsyncLocalStorage.
    const configuredProfile = workStore.cacheLifeProfiles[profile]
    if (configuredProfile === undefined) {
      if (workStore.cacheLifeProfiles[profile.trim()]) {
        throw new Error(
          `Unknown cacheLife profile "${profile}" is not configured in next.config.js\n` +
            `Did you mean "${profile.trim()}" without the spaces?`
        )
      }
      throw new Error(
        `Unknown cacheLife profile "${profile}" is not configured in next.config.js\n` +
          'module.exports = {\n' +
          '  experimental: {\n' +
          '    cacheLife: {\n' +
          `      "${profile}": ...\n` +
          '    }\n' +
          '  }\n' +
          '}'
      )
    }
    profile = configuredProfile
  } else if (
    typeof profile !== 'object' ||
    profile === null ||
    Array.isArray(profile)
  ) {
    throw new Error(
      'Invalid cacheLife() option. Either pass a profile name or object.'
    )
  } else {
    validateCacheLife(profile)
  }

  if (profile.revalidate !== undefined) {
    // Track the explicit revalidate time.
    if (
      workUnitStore.explicitRevalidate === undefined ||
      workUnitStore.explicitRevalidate > profile.revalidate
    ) {
      workUnitStore.explicitRevalidate = profile.revalidate
    }
  }
  if (profile.expire !== undefined) {
    // Track the explicit expire time.
    if (
      workUnitStore.explicitExpire === undefined ||
      workUnitStore.explicitExpire > profile.expire
    ) {
      workUnitStore.explicitExpire = profile.expire
    }
  }
  if (profile.stale !== undefined) {
    // Track the explicit stale time.
    if (
      workUnitStore.explicitStale === undefined ||
      workUnitStore.explicitStale > profile.stale
    ) {
      workUnitStore.explicitStale = profile.stale
    }
  }
}