-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcache.ts
More file actions
249 lines (205 loc) · 8.15 KB
/
cache.ts
File metadata and controls
249 lines (205 loc) · 8.15 KB
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
import { AxiosRequestConfig, AxiosResponse } from 'axios'
import { CacheLayer } from '../../caches/CacheLayer'
import { LOCALE_HEADER, SEGMENT_HEADER, SESSION_HEADER } from '../../constants'
import { HttpLogEvents } from '../../tracing/LogEvents'
import { HttpCacheLogFields } from '../../tracing/LogFields'
import { CustomHttpTags } from '../../tracing/Tags'
import { MiddlewareContext, RequestConfig } from '../typings'
const RANGE_HEADER_QS_KEY = '__range_header'
const cacheableStatusCodes = [200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501] // https://tools.ietf.org/html/rfc7231#section-6.1
export const cacheKey = (config: AxiosRequestConfig) => {
const {baseURL = '', url = '', params, headers} = config
const locale = headers[LOCALE_HEADER]
const encodedBaseURL = baseURL.replace(/\//g, '\\')
const encodedURL = url.replace(/\//g, '\\')
let key = `${locale}--${encodedBaseURL}--${encodedURL}?`
if (params) {
Object.keys(params).sort().forEach(p =>
key = key.concat(`--${p}=${params[p]}`)
)
}
if (headers?.range) {
key = key.concat(`--${RANGE_HEADER_QS_KEY}=${headers.range}`)
}
return key
}
const parseCacheHeaders = (headers: Record<string, string>) => {
const {'cache-control': cacheControl = '', etag, age: ageStr} = headers
const cacheDirectives = cacheControl.split(',').map(d => d.trim())
const maxAgeDirective = cacheDirectives.find(d => d.startsWith('max-age'))
const [, maxAgeStr] = maxAgeDirective ? maxAgeDirective.split('=') : [null, null]
const maxAge = maxAgeStr ? parseInt(maxAgeStr, 10) : 0
const age = ageStr ? parseInt(ageStr, 10) : 0
return {
age,
etag,
maxAge,
noCache: cacheDirectives.indexOf('no-cache') !== -1,
noStore: cacheDirectives.indexOf('no-store') !== -1,
}
}
export function isLocallyCacheable (arg: RequestConfig, type: CacheType): arg is CacheableRequestConfig {
return arg && !!arg.cacheable
&& (arg.cacheable === type || arg.cacheable === CacheType.Any || type === CacheType.Any)
}
const addNotModified = (validateStatus: (status: number) => boolean) =>
(status: number) => validateStatus(status) || status === 304
export enum CacheType {
None,
Memory,
Disk,
Any,
}
export const enum CacheResult {
HIT = 'HIT',
MISS = 'MISS',
STALE = 'STALE',
}
const CacheTypeNames = {
[CacheType.None]: 'none',
[CacheType.Memory]: 'memory',
[CacheType.Disk]: 'disk',
[CacheType.Any]: 'any',
}
interface CacheOptions {
type: CacheType
storage: CacheLayer<string, Cached>
}
export const cacheMiddleware = ({ type, storage }: CacheOptions) => {
const CACHE_RESULT_TAG = type === CacheType.Disk ? CustomHttpTags.HTTP_DISK_CACHE_RESULT : CustomHttpTags.HTTP_MEMORY_CACHE_RESULT
const cacheType = CacheTypeNames[type]
return async (ctx: MiddlewareContext, next: () => Promise<void>) => {
if (!isLocallyCacheable(ctx.config, type)) {
return await next()
}
const span = ctx.tracing?.rootSpan
const key = cacheKey(ctx.config)
const segmentToken = ctx.config.headers[SEGMENT_HEADER]
const keyWithSegment = key + segmentToken
span?.log({
event: HttpLogEvents.CACHE_KEY_CREATE,
[HttpCacheLogFields.CACHE_TYPE]: cacheType,
[HttpCacheLogFields.KEY]: key,
[HttpCacheLogFields.KEY_WITH_SEGMENT]: keyWithSegment,
})
const cacheHasWithSegment = await storage.has(keyWithSegment)
const cached = cacheHasWithSegment ? await storage.get(keyWithSegment) : await storage.get(key)
if (cached && cached.response) {
const {etag: cachedEtag, response, expiration, responseType, responseEncoding} = cached as Cached
if (type === CacheType.Disk && responseType === 'arraybuffer') {
response.data = Buffer.from(response.data, responseEncoding)
}
const now = Date.now()
span?.log({
event: HttpLogEvents.LOCAL_CACHE_HIT_INFO,
[HttpCacheLogFields.CACHE_TYPE]: cacheType,
[HttpCacheLogFields.ETAG]: cachedEtag,
[HttpCacheLogFields.EXPIRATION_TIME]: (expiration-now)/1000,
[HttpCacheLogFields.RESPONSE_TYPE]: responseType,
[HttpCacheLogFields.RESPONSE_ENCONDING]: responseEncoding,
})
if (expiration > now) {
ctx.response = response as AxiosResponse
ctx.cacheHit = {
memory: 1,
revalidated: 0,
router: 0,
}
span?.setTag(CACHE_RESULT_TAG, CacheResult.HIT)
return
}
span?.setTag(CACHE_RESULT_TAG, CacheResult.STALE)
const validateStatus = addNotModified(ctx.config.validateStatus!)
if (cachedEtag && validateStatus(response.status as number)) {
ctx.config.headers['if-none-match'] = cachedEtag
ctx.config.validateStatus = validateStatus
}
} else {
span?.setTag(CACHE_RESULT_TAG, CacheResult.MISS)
}
await next()
if (!ctx.response) {
return
}
const revalidated = ctx.response.status === 304
if (revalidated && cached) {
ctx.response = cached.response as AxiosResponse
ctx.cacheHit = {
memory: 1,
revalidated: 1,
router: 0,
}
}
const {data, headers, status} = ctx.response as AxiosResponse
const {age, etag, maxAge: headerMaxAge, noStore, noCache} = parseCacheHeaders(headers)
const {forceMaxAge} = ctx.config
const maxAge = forceMaxAge && cacheableStatusCodes.includes(status) ? Math.max(forceMaxAge, headerMaxAge) : headerMaxAge
span?.log({
event: HttpLogEvents.CACHE_CONFIG,
[HttpCacheLogFields.CACHE_TYPE]: cacheType,
[HttpCacheLogFields.AGE]: age,
[HttpCacheLogFields.CALCULATED_MAX_AGE]: maxAge,
[HttpCacheLogFields.MAX_AGE]: headerMaxAge,
[HttpCacheLogFields.FORCE_MAX_AGE]: forceMaxAge,
[HttpCacheLogFields.ETAG]: etag,
[HttpCacheLogFields.NO_CACHE]: noCache,
[HttpCacheLogFields.NO_STORE]: noStore,
})
// Indicates this should NOT be cached and this request will not be considered a miss.
if (!forceMaxAge && (noStore || (noCache && !etag))) {
span?.log({ event: HttpLogEvents.NO_LOCAL_CACHE_SAVE, [HttpCacheLogFields.CACHE_TYPE]: cacheType })
return
}
const shouldCache = maxAge || etag
const varySession = ctx.response.headers.vary && ctx.response.headers.vary.includes(SESSION_HEADER)
if (shouldCache && !varySession) {
const {responseType, responseEncoding: configResponseEncoding} = ctx.config
const currentAge = revalidated ? 0 : age
const varySegment = ctx.response.headers.vary && ctx.response.headers.vary.includes(SEGMENT_HEADER)
const setKey = varySegment ? keyWithSegment : key
const responseEncoding = configResponseEncoding || (responseType === 'arraybuffer' ? 'base64' : undefined)
const cacheableData = type === CacheType.Disk && responseType === 'arraybuffer'
? (data as Buffer).toString(responseEncoding)
: data
const now = Date.now()
const expiration = now + (maxAge - currentAge) * 1000
const alreadyExpired = expiration <= now
const reusingRevalidatedCache = cached && (ctx.response === cached.response)
const shouldSkipCacheUpdate = alreadyExpired && reusingRevalidatedCache
if (shouldSkipCacheUpdate) {
return
}
await storage.set(setKey, {
etag,
expiration,
response: {data: cacheableData, headers, status},
responseEncoding,
responseType,
})
span?.log({
event: HttpLogEvents.LOCAL_CACHE_SAVED,
[HttpCacheLogFields.CACHE_TYPE]: cacheType,
[HttpCacheLogFields.KEY_SET]: setKey,
[HttpCacheLogFields.AGE]: currentAge,
[HttpCacheLogFields.ETAG]: etag,
[HttpCacheLogFields.EXPIRATION_TIME]: (expiration - Date.now())/1000,
[HttpCacheLogFields.RESPONSE_ENCONDING]: responseEncoding,
[HttpCacheLogFields.RESPONSE_TYPE]: responseType,
})
return
}
span?.log({ event: HttpLogEvents.NO_LOCAL_CACHE_SAVE, [HttpCacheLogFields.CACHE_TYPE]: cacheType })
}
}
export interface Cached {
etag: string
expiration: number
response: Partial<AxiosResponse>
responseType?: string
responseEncoding?: BufferEncoding
}
export type CacheableRequestConfig = RequestConfig & {
url: string,
cacheable: CacheType,
memoizable: boolean
}