-
Notifications
You must be signed in to change notification settings - Fork 32
/
http-data-source.ts
461 lines (404 loc) · 13.3 KB
/
http-data-source.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
import { DataSource, DataSourceConfig } from 'apollo-datasource'
import { Pool } from 'undici'
import { STATUS_CODES } from 'http'
import QuickLRU from '@alloc/quick-lru'
import { createUnzip, createBrotliDecompress } from 'zlib'
import streamToPromise from 'stream-to-promise'
import { KeyValueCache } from 'apollo-server-caching'
import Dispatcher, { HttpMethod, ResponseData } from 'undici/types/dispatcher'
import { toApolloError } from 'apollo-server-errors'
import { EventEmitter } from 'stream'
import { Logger } from 'apollo-server-types'
import { URLSearchParams } from 'url'
type AbortSignal = unknown
export class RequestError<T = unknown> extends Error {
constructor(
public message: string,
public code: number,
public request: Request,
public response: Response<T>,
) {
super(message)
this.name = 'RequestError'
}
}
export type CacheTTLOptions = {
requestCache?: {
// The maximum time an item is cached in seconds.
maxTtl: number
// The maximum time the cache should be used when the re-fetch from the origin fails.
maxTtlIfError: number
}
}
interface Dictionary<T> {
[Key: string]: T | undefined
}
export type RequestOptions = Omit<Partial<Request>, 'origin' | 'path' | 'method'>
export type Request<T = unknown> = {
context: Dictionary<string>
query: Dictionary<string | number>
body: T
signal?: AbortSignal | EventEmitter | null
json?: boolean
origin: string
path: string
method: HttpMethod
// Indicates if the response of this request should be memoized
memoize?: boolean
headers: Dictionary<string>
} & CacheTTLOptions
export type Response<TResult> = {
body: TResult
memoized: boolean
isFromCache: boolean
// maximum ttl (seconds)
maxTtl?: number
} & Omit<ResponseData, 'body'>
export interface LRUOptions {
readonly maxAge?: number
readonly maxSize: number
}
export interface HTTPDataSourceOptions {
logger?: Logger
pool?: Pool
requestOptions?: RequestOptions
clientOptions?: Pool.Options
lru?: Partial<LRUOptions>
}
// rfc7231 6.1
// We only cache status codes that indicates a successful response
// We don't cache redirects, client errors because we expect to cache JSON payload.
const statusCodeCacheableByDefault = new Set([200, 203])
/**
* HTTPDataSource is an optimized HTTP Data Source for Apollo Server
* It focus on reliability and performance.
*/
export abstract class HTTPDataSource<TContext = any> extends DataSource {
public context!: TContext
private pool: Pool
private logger?: Logger
private cache!: KeyValueCache<string>
private globalRequestOptions?: RequestOptions
private readonly memoizedResults: QuickLRU<string, Response<any>>
constructor(public readonly baseURL: string, private readonly options?: HTTPDataSourceOptions) {
super()
this.memoizedResults = new QuickLRU({
// The maximum number of items before evicting the least recently used items.
maxSize: this.options?.lru?.maxSize ? this.options.lru.maxSize : 100,
// The maximum number of milliseconds an item should remain in cache.
// By default maxAge will be Infinity, which means that items will never expire.
maxAge: this.options?.lru?.maxAge,
})
this.pool = options?.pool ?? new Pool(this.baseURL, options?.clientOptions)
this.globalRequestOptions = options?.requestOptions
this.logger = options?.logger
}
private buildQueryString(query: Dictionary<string | number>): string {
const params = new URLSearchParams()
for (const key in query) {
if (Object.prototype.hasOwnProperty.call(query, key)) {
const value = query[key]
if (value !== undefined) {
params.append(key, value.toString())
}
}
}
// avoid cache fragmentation when the query order is not guaranteed
params.sort()
return params.toString()
}
/**
* Initialize the datasource with apollo internals (context, cache).
*
* @param config
*/
initialize(config: DataSourceConfig<TContext>): void {
this.context = config.context
this.cache = config.cache
}
protected isResponseOk(statusCode: number): boolean {
return statusCode >= 200 && statusCode <= 399
}
protected isResponseCacheable<TResult = unknown>(
request: Request,
response: Response<TResult>,
): boolean {
return statusCodeCacheableByDefault.has(response.statusCode) && this.isRequestCacheable(request)
}
protected isRequestCacheable(request: Request): boolean {
// default behaviour is to cache only get requests
// If extending to non GET requests take care to provide an adequate onCacheKeyCalculation and isResponseCacheable
return request.method === 'GET'
}
/**
* Checks if the GET request is memoizable. This validation is performed before the
* response is set in **memoizedResults**.
* @param request
* @returns *true* if request should be memoized
*/
protected isRequestMemoizable(request: Request): boolean {
return Boolean(request.memoize) && request.method === 'GET'
}
/**
* onCacheKeyCalculation returns the key for the GET request.
* The key is used to memoize the request in the LRU cache.
*
* @param request
* @returns
*/
protected onCacheKeyCalculation(request: Request): string {
return request.origin + request.path
}
/**
* onRequest is executed before a request is made and isn't executed for memoized calls.
* You can manipulate the request e.g to add/remove headers.
*
* @param request
*/
protected async onRequest?(request: Request): Promise<void>
/**
* onResponse is executed when a response has been received.
* By default the implementation will throw for for unsuccessful responses.
*
* @param _request
* @param response
*/
protected onResponse<TResult = unknown>(
request: Request,
response: Response<TResult>,
): Response<TResult> {
if (this.isResponseOk(response.statusCode)) {
return response
}
throw new RequestError(
`Response code ${response.statusCode} (${STATUS_CODES[response.statusCode.toString()]})`,
response.statusCode,
request,
response,
)
}
protected onError?(_error: Error, requestOptions: Request): void
/**
* Execute a HTTP GET request.
* Note that the **memoizedResults** and **cache** will be checked before request is made.
* By default the received response will be memoized.
*
* @param path the path to the resource
* @param requestOptions
*/
public async get<TResult = unknown>(
path: string,
requestOptions?: RequestOptions,
): Promise<Response<TResult>> {
return this.request<TResult>({
headers: {},
query: {},
body: null,
memoize: true,
context: {},
...requestOptions,
method: 'GET',
path,
origin: this.baseURL,
})
}
public async post<TResult = unknown>(
path: string,
requestOptions?: RequestOptions,
): Promise<Response<TResult>> {
return this.request<TResult>({
headers: {},
query: {},
body: null,
context: {},
...requestOptions,
method: 'POST',
path,
origin: this.baseURL,
})
}
public async delete<TResult = unknown>(
path: string,
requestOptions?: RequestOptions,
): Promise<Response<TResult>> {
return this.request<TResult>({
headers: {},
query: {},
body: null,
context: {},
...requestOptions,
method: 'DELETE',
path,
origin: this.baseURL,
})
}
public async put<TResult = unknown>(
path: string,
requestOptions?: RequestOptions,
): Promise<Response<TResult>> {
return this.request<TResult>({
headers: {},
query: {},
body: null,
context: {},
...requestOptions,
method: 'PUT',
path,
origin: this.baseURL,
})
}
public async patch<TResult = unknown>(
path: string,
requestOptions?: RequestOptions,
): Promise<Response<TResult>> {
return this.request<TResult>({
headers: {},
query: {},
body: null,
context: {},
...requestOptions,
method: 'PATCH',
path,
origin: this.baseURL,
})
}
private async performRequest<TResult>(
request: Request,
cacheKey: string,
): Promise<Response<TResult>> {
try {
// in case of JSON set appropriate content-type header
if (request.body !== null && typeof request.body === 'object') {
if (request.headers['content-type'] === undefined) {
request.headers['content-type'] = 'application/json; charset=utf-8'
}
request.body = JSON.stringify(request.body)
}
await this.onRequest?.(request)
const requestOptions: Dispatcher.RequestOptions = {
method: request.method,
origin: request.origin,
path: request.path,
headers: request.headers,
signal: request.signal,
body: request.body as string,
}
const responseData = await this.pool.request(requestOptions)
const body = responseData.body
const headers = responseData.headers
let dataBuffer: Buffer
switch (headers['content-encoding']) {
case 'br':
dataBuffer = await streamToPromise(body.pipe(createBrotliDecompress()))
break
case 'gzip':
case 'deflate':
dataBuffer = await streamToPromise(body.pipe(createUnzip()))
break
default:
dataBuffer = await streamToPromise(body)
break
}
// This will be string initially, but may become any once JSON parsed.
let data: any = dataBuffer.toString('utf-8')
// can we parse it as JSON?
if (
responseData.headers['content-type']?.includes('application/json') &&
data.length &&
typeof data === 'string'
) {
data = JSON.parse(data)
}
const response: Response<TResult> = {
isFromCache: false,
memoized: false,
...responseData,
// in case of the server does not properly respond with JSON we pass it as text.
// this is necessary since POST, DELETE don't always have a JSON body.
body: data as unknown as TResult,
}
this.onResponse<TResult>(request, response)
if (this.isRequestMemoizable(request)) {
this.memoizedResults.set(cacheKey, response)
}
// let's see if we can fill the shared cache
if (request.requestCache && this.isResponseCacheable<TResult>(request, response)) {
response.maxTtl = request.requestCache.maxTtl
const cachedResponse = JSON.stringify(response)
// respond with the result immediately without waiting for the cache
this.cache
.set(cacheKey, cachedResponse, {
ttl: request.requestCache.maxTtl,
})
.catch((err) => this.logger?.error(err))
this.cache
.set(`staleIfError:${cacheKey}`, cachedResponse, {
ttl: request.requestCache.maxTtl + request.requestCache.maxTtlIfError,
})
.catch((err) => this.logger?.error(err))
}
return response
} catch (error: any) {
this.onError?.(error, request)
// in case of an error we try to respond with a stale result from the stale-if-error cache
if (request.requestCache) {
const cacheItem = await this.cache.get(`staleIfError:${cacheKey}`)
if (cacheItem) {
const response: Response<TResult> = JSON.parse(cacheItem)
response.isFromCache = true
return response
}
}
throw toApolloError(error)
}
}
private async request<TResult = unknown>(request: Request): Promise<Response<TResult>> {
if (Object.keys(request.query).length > 0) {
request.path = request.path + '?' + this.buildQueryString(request.query)
}
const cacheKey = this.onCacheKeyCalculation(request)
const isRequestMemoizable = this.isRequestMemoizable(request)
// check if we have a memoizable call in the cache to respond immediately
if (isRequestMemoizable) {
// Memoize calls for the same data source instance
// a single instance of the data sources is scoped to one graphql request
if (this.memoizedResults.has(cacheKey)) {
const response = await this.memoizedResults.get(cacheKey)!
response.memoized = true
response.isFromCache = false
return response
}
}
const headers = {
...(this.globalRequestOptions?.headers || {}),
...request.headers,
}
const options = {
...request,
...this.globalRequestOptions,
headers,
}
const requestIsCacheable = this.isRequestCacheable(request)
if (requestIsCacheable) {
// try to fetch from shared cache
if (request.requestCache) {
try {
const cacheItem = await this.cache.get(cacheKey)
if (cacheItem) {
const cachedResponse: Response<TResult> = JSON.parse(cacheItem)
cachedResponse.memoized = false
cachedResponse.isFromCache = true
return cachedResponse
}
const response = this.performRequest<TResult>(options, cacheKey)
return response
} catch (error: any) {
this.logger?.error(`Cache item '${cacheKey}' could not be loaded: ${error.message}`)
}
}
const response = this.performRequest<TResult>(options, cacheKey)
return response
}
return this.performRequest<TResult>(options, cacheKey)
}
}