-
Notifications
You must be signed in to change notification settings - Fork 622
/
cache.server.ts
250 lines (231 loc) · 7.49 KB
/
cache.server.ts
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import LRU from 'lru-cache'
import {formatDuration, intervalToDuration} from 'date-fns'
import type {Timings} from './metrics.server'
import {time} from './metrics.server'
import {getUser} from './session.server'
function niceFormatDuration(milliseconds: number) {
const duration = intervalToDuration({start: 0, end: milliseconds})
const formatted = formatDuration(duration, {delimiter: ', '})
const ms = milliseconds % 1000
return [formatted, ms ? `${ms.toFixed(3)}ms` : null]
.filter(Boolean)
.join(', ')
}
declare global {
// This preserves the LRU cache during development
// eslint-disable-next-line
var lruCache:
| (LRU<string, {metadata: CacheMetadata; value: any}> & {name: string})
| undefined
}
const lruCache = (global.lruCache = global.lruCache
? global.lruCache
: createLruCache())
function createLruCache() {
// doing anything other than "any" here was a big pain
const newCache = new LRU<string, {metadata: CacheMetadata; value: any}>({
max: 1000,
ttl: 1000 * 60 * 60, // 1 hour
})
Object.assign(newCache, {name: 'LRU'})
return newCache as typeof newCache & {name: 'LRU'}
}
type CacheMetadata = {
createdTime: number
maxAge: number | null
}
function shouldRefresh(metadata: CacheMetadata) {
if (metadata.maxAge) {
return Date.now() > metadata.createdTime + metadata.maxAge
}
return false
}
type VNUP<Value> = Value | null | undefined | Promise<Value | null | undefined>
const keysRefreshing = new Set()
async function cachified<
Value,
Cache extends {
name: string
get: (key: string) => VNUP<{
metadata: CacheMetadata
value: Value
}>
set: (
key: string,
value: {
metadata: CacheMetadata
value: Value
},
) => unknown | Promise<unknown>
del: (key: string) => unknown | Promise<unknown>
},
>(options: {
key: string
cache: Cache
getFreshValue: () => Promise<Value>
checkValue?: (value: Value) => boolean | string
forceFresh?: boolean | string
request?: Request
fallbackToCache?: boolean
timings?: Timings
timingType?: string
maxAge?: number
}): Promise<Value> {
const {
key,
cache,
getFreshValue,
request,
checkValue = value => Boolean(value),
fallbackToCache = true,
timings,
timingType = 'getting fresh value',
maxAge,
} = options
// if forceFresh is a string, we'll only force fresh if the key is in the
// comma separated list. Otherwise we'll go with it's value and fallback
// to the shouldForceFresh function on the request if the request is provided
// otherwise it's false.
const forceFresh =
typeof options.forceFresh === 'string'
? options.forceFresh.split(',').includes(key)
: options.forceFresh ??
(request ? await shouldForceFresh(request, key) : false)
function assertCacheEntry(entry: unknown): asserts entry is {
metadata: CacheMetadata
value: Value
} {
if (typeof entry !== 'object' || entry === null) {
throw new Error(
`Cache entry for ${key} is not a cache entry object, it's a ${typeof entry}`,
)
}
if (!('metadata' in entry)) {
throw new Error(
`Cache entry for ${key} does not have a metadata property`,
)
}
if (!('value' in entry)) {
throw new Error(`Cache entry for ${key} does not have a value property`)
}
}
if (!forceFresh) {
try {
const cached = await time({
name: `cache.get(${key})`,
type: 'cache read',
fn: () => cache.get(key),
timings,
})
if (cached) {
assertCacheEntry(cached)
if (shouldRefresh(cached.metadata)) {
// time to refresh the value. Fire and forget so we don't slow down
// this request
// we use setTimeout here to make sure this happens on the next tick
// of the event loop so we don't end up slowing this request down in the
// event the cache is synchronous (unlikely now, but if the code is changed
// then it's quite possible this could happen and it would be easy to
// forget to check).
// In practice we have had a handful of situations where multiple
// requests triggered a refresh of the same resource, so that's what
// the keysRefreshing thing is for to ensure we don't refresh a
// value if it's already in the process of being refreshed.
if (!keysRefreshing.has(key)) {
keysRefreshing.add(key)
setTimeout(() => {
// eslint-disable-next-line prefer-object-spread
void cachified(Object.assign({}, options, {forceFresh: true}))
.catch(() => {})
.finally(() => {
keysRefreshing.delete(key)
})
}, 200)
}
}
const valueCheck = checkValue(cached.value)
if (valueCheck === true) {
return cached.value
} else {
const reason = typeof valueCheck === 'string' ? valueCheck : 'unknown'
console.warn(
`check failed for cached value of ${key}\nReason: ${reason}.\nDeleting the cache key and trying to get a fresh value.`,
cached,
)
await cache.del(key)
}
}
} catch (error: unknown) {
console.error(
`error with cache at ${key}. Deleting the cache key and trying to get a fresh value.`,
error,
)
await cache.del(key)
}
}
const start = performance.now()
const value = await time({
name: `getFreshValue for ${key}`,
type: timingType,
fn: getFreshValue,
timings,
}).catch((error: unknown) => {
console.error(
`getting a fresh value for ${key} failed`,
{fallbackToCache, forceFresh},
error,
)
// If we got this far without forceFresh then we know there's nothing
// in the cache so no need to bother trying again without a forceFresh.
// So we need both the option to fallback and the ability to fallback.
if (fallbackToCache && forceFresh) {
return cachified({...options, forceFresh: false})
} else {
throw error
}
})
const totalTime = performance.now() - start
const valueCheck = checkValue(value)
if (valueCheck === true) {
const metadata: CacheMetadata = {
maxAge: maxAge ?? null,
createdTime: Date.now(),
}
try {
console.log(
`Updating the cache value for ${key}.`,
`Getting a fresh value for this took ${niceFormatDuration(totalTime)}.`,
`Caching for a minimum of ${
typeof maxAge === 'number'
? `${niceFormatDuration(maxAge)}`
: 'forever'
} in ${cache.name}.`,
)
await cache.set(key, {metadata, value})
} catch (error: unknown) {
console.error(`error setting cache: ${key}`, error)
}
} else {
const reason = typeof valueCheck === 'string' ? valueCheck : 'unknown'
console.error(
`check failed for cached value of ${key}\nReason: ${reason}.\nDeleting the cache key and trying to get a fresh value.`,
value,
)
throw new Error(`check failed for fresh value of ${key}`)
}
return value
}
async function shouldForceFresh(request: Request, key: string) {
const fresh = new URL(request.url).searchParams.get('fresh')
if (typeof fresh !== 'string') return false
if ((await getUser(request))?.role !== 'ADMIN') return false
if (fresh === '') return true
return fresh.split(',').includes(key)
}
export {cachified, lruCache}
/*
eslint
max-depth: "off",
no-multi-assign: "off",
@typescript-eslint/no-explicit-any: "off",
*/