-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
323 lines (283 loc) · 10.2 KB
/
index.js
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
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
'use strict';
const { EventEmitter } = require('events');
const { URLSearchParams } = require('url');
const {
context,
Request,
AbortController,
AbortError,
TimeoutError,
} = require('fetch-h2');
const FormData = require('form-data');
const LRU = require('lru-cache');
const sizeof = require('object-sizeof');
const CachePolicy = require('./policy');
const { cacheableResponse, decoratedResponse } = require('./response');
const { decorateHeaders } = require('./headers');
const CACHEABLE_METHODS = ['GET', 'HEAD'];
const DEFAULT_FETCH_OPTIONS = { method: 'GET', cache: 'default', redirect: 'follow' };
const DEFAULT_CONTEXT_OPTIONS = { userAgent: 'helix-fetch', overwriteUserAgent: true };
const DEFAULT_MAX_CACHE_SIZE = 100 * 1024 * 1024; // 100mb
// events
const PUSH_EVENT = 'push';
/**
* Cache the response as appropriate. The body stream of the
* response is consumed & buffered to allow repeated reads.
*
* @param {Object} ctx context
* @param {Request} request
* @param {Response} response
* @returns {Response} cached response with buffered body or original response if uncached.
*/
const cacheResponse = async (ctx, request, response) => {
if (!CACHEABLE_METHODS.includes(request.method)) {
// return original un-cacheable response
// (decorate original response providing the same extensions as the cacheable response)
return decoratedResponse(response);
}
const policy = new CachePolicy(request, response, { shared: false });
if (policy.storable()) {
// update cache
// create cacheable response (i.e. make it reusable)
const cacheable = await cacheableResponse(response);
ctx.cache.set(request.url, { policy, response: cacheable }, policy.timeToLive());
return cacheable;
} else {
// return original un-cacheable response
// (decorate original response providing the same extensions as the cacheable response)
return decoratedResponse(response);
}
};
function createPushHandler(ctx) {
return async (origin, request, getResponse) => {
// request.url is the relative URL for pushed resources => need to convert to absolute url
const req = request.clone(new URL(request.url, origin).toString());
// check if we've already cached the pushed resource
const { policy } = ctx.cache.get(req.url) || {};
if (!policy || !policy.satisfiesWithoutRevalidation(req)) {
// consume pushed response
const response = await getResponse();
// update cache
await cacheResponse(ctx, req, response);
}
ctx.eventEmitter.emit(PUSH_EVENT, req.url);
};
}
function createUrl(url, qs = {}) {
const urlWithQuery = new URL(url);
if (typeof qs !== 'object' || Array.isArray(qs)) {
throw new TypeError('qs: object expected');
}
Object.entries(qs).forEach(([k, v]) => {
if (Array.isArray(v)) {
v.forEach((entry) => urlWithQuery.searchParams.append(k, entry));
} else {
urlWithQuery.searchParams.append(k, v);
}
});
return urlWithQuery.href;
}
const sanitizeHeaders = (headers) => {
const result = {};
// make all header names lower case
Object.keys(headers).forEach((name) => {
result[name.toLowerCase()] = headers[name];
});
return result;
};
const wrappedFetch = async (ctx, url, options = {}) => {
const opts = { ...DEFAULT_FETCH_OPTIONS, ...options };
// sanitze method name (#24)
if (typeof opts.method === 'string') {
opts.method = opts.method.toUpperCase();
}
// sanitize headers (lowercase names)
opts.headers = sanitizeHeaders(opts.headers || {});
if (opts.body instanceof URLSearchParams) {
opts.headers['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
opts.body = opts.body.toString();
} else if (opts.body instanceof FormData) {
const form = opts.body;
opts.headers['content-type'] = `multipart/form-data;boundary=${form.getBoundary()}`;
opts.body = form.getBuffer();
}
const lookupCache = CACHEABLE_METHODS.includes(opts.method)
// respect cache mode (https://developer.mozilla.org/en-US/docs/Web/API/Request/cache)
&& !['no-store', 'reload'].includes(opts.cache);
if (lookupCache) {
// check cache
const { policy, response } = ctx.cache.get(url) || {};
// TODO: respect cache mode (https://developer.mozilla.org/en-US/docs/Web/API/Request/cache)
if (policy && policy.satisfiesWithoutRevalidation(
new Request(url, { ...opts, allowForbiddenHeaders: true }),
)) {
// update headers of cached response: update age, remove uncacheable headers, etc.
response.headers = decorateHeaders(policy.responseHeaders(response));
// decorate response before delivering it (fromCache=true)
const resp = response.clone();
resp.fromCache = true;
return resp;
}
}
// fetch
const fetchOptions = { ...opts, mode: 'no-cors', allowForbiddenHeaders: true };
const request = new Request(url, fetchOptions);
if (!fetchOptions.headers.host) {
// workaround for https://github.com/grantila/fetch-h2/issues/110
// TODO: remove once underlying issue has been fixed
fetchOptions.headers.host = new URL(url).host;
}
// workaround for https://github.com/grantila/fetch-h2/issues/84
const response = await ctx.fetch(new Request(url, fetchOptions), fetchOptions);
return opts.cache !== 'no-store' ? cacheResponse(ctx, request, response) : decoratedResponse(response);
};
/**
* Creates a timeout signal which allows to specify
* a timeout for a `fetch` call via the `signal` option.
*
* @param {number} ms timeout in milliseconds
*/
const timeoutSignal = (ms) => {
const controller = new AbortController();
setTimeout(() => {
controller.abort();
}, ms);
return controller.signal;
};
class FetchContext {
constructor(options = {}) {
// setup context
const opts = { ...DEFAULT_CONTEXT_OPTIONS, ...options };
this._ctx = context(opts);
// setup cache
const max = typeof opts.maxCacheSize === 'number' && opts.maxCacheSize >= 0 ? opts.maxCacheSize : DEFAULT_MAX_CACHE_SIZE;
const length = ({ response }, _) => sizeof(response);
this._ctx.cache = new LRU({ max, length });
// event emitter
this._ctx.eventEmitter = new EventEmitter();
// register push handler
this._ctx.onPush(createPushHandler(this._ctx));
}
/**
* Returns the `helix-fetch` API.
*/
api() {
return {
/**
* Fetches a resource from the network or from the cache if the cached response
* can be reused according to HTTP RFC 7234 rules. Returns a Promise which resolves once
* the Response is available.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
* @see https://httpwg.org/specs/rfc7234.html
*/
fetch: async (url, options) => this.fetch(url, options),
/**
* This function returns an object which looks like the global `helix-fetch` API,
* i.e. it will have the functions `fetch`, `disconnectAll`, etc. and provide its
* own isolated cache.
*
* @param {Object} options
*/
context: (options = {}) => this.context(options),
/**
* Disconnect all open/pending sessions.
*/
disconnectAll: async () => this.disconnectAll(),
/**
* Register a callback which gets called once a server Push has been received.
*
* @param {Function} fn callback function invoked with the url of the pushed resource
*/
onPush: (fn) => this.onPush(fn),
/**
* Deregister a callback previously registered with {#onPush}.
*
* @param {Function} fn callback function registered with {#onPush}
*/
offPush: (fn) => this.offPush(fn),
/**
* Clear the cache entirely, throwing away all values.
*/
clearCache: () => this.clearCache(),
/**
* Cache stats for diagnostic purposes
*/
cacheStats: () => this.cacheStats(),
/**
* Error thrown when a request timed out.
* Deprecated: Use `AbortController` and `AbortError` instead.
* @deprecated
*/
TimeoutError,
/**
* AbortController represents a controller object that allows
* to abort one or more `fetch` operations as and when desired.
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortController
*/
AbortController,
/**
* Error thrown in case of an abort signal triggered by an AbortController.
*/
AbortError,
/**
* FormData implementation.
*
* See https://github.com/form-data/form-data,
* https://developer.mozilla.org/en-US/docs/Web/API/FormData
*/
FormData,
/**
* Create a URL with query parameters
*
* @param {string} url request url
* @param {object} [qs={}] request query parameters
*/
createUrl,
/**
* Creates a timeout signal which allows to specify
* a timeout for a `fetch` operation via the `signal` option.
*
* @param {number} ms timeout in milliseconds
*/
timeoutSignal,
};
}
// eslint-disable-next-line class-methods-use-this
context(options) {
return new FetchContext(options).api();
}
disconnectAll() {
this._ctx.disconnectAll();
}
onPush(fn) {
return this._ctx.eventEmitter.on(PUSH_EVENT, fn);
}
offPush(fn) {
return this._ctx.eventEmitter.off(PUSH_EVENT, fn);
}
clearCache() {
this._ctx.cache.reset();
}
cacheStats() {
return {
size: this._ctx.cache.length,
count: this._ctx.cache.itemCount,
};
}
async fetch(url, options) {
return wrappedFetch(this._ctx, url, options);
}
}
module.exports = new FetchContext().api();