-
Notifications
You must be signed in to change notification settings - Fork 12
/
apicache.js
1428 lines (1259 loc) · 44.3 KB
/
apicache.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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var zlib = require('zlib')
var accepts = require('accepts')
var stream = require('stream')
var querystring = require('querystring')
var jsonSortify = require('json.sortify')
var generateUuidV4 = require('uuid').v4
var MemoryCache = require('./memory-cache')
var RedisCache = require('./redis-cache')
var Compressor = require('./compressor')
var pkg = require('../package.json')
var helpers = require('./helpers')
var setLongTimeout = helpers.setLongTimeout
var clearLongTimeout = helpers.clearLongTimeout
var delegateLazily = helpers.delegateLazily
var isKoa = helpers.isKoa
var FIVE_MINUTES = 5 * 60 * 1000
var SAFE_HTTP_METHODS = ['GET', 'HEAD', 'OPTIONS']
var CACHEABLE_STATUS_CODES = {
200: null,
201: null,
202: null,
203: null,
204: null,
205: null,
300: null,
301: null,
302: null,
305: null,
307: null,
}
var t = {
ms: 1,
second: 1000,
minute: 60000,
hour: 3600000,
day: 3600000 * 24,
week: 3600000 * 24 * 7,
month: 3600000 * 24 * 30,
year: 3600000 * 24 * 365,
}
var instances = []
var matches = function(a) {
return function(b) {
return a === b
}
}
var doesntMatch = function(a) {
return function(b) {
return !matches(a)(b)
}
}
var logDuration = function(d, prefix) {
var str = d > 1000 ? (d / 1000).toFixed(2) + 'sec' : d + 'ms'
return '\x1b[33m- ' + (prefix ? prefix + ' ' : '') + str + '\x1b[0m'
}
function getSafeHeaders(res) {
// getHeaders added in node v7.7.0
return Object.assign({}, res.getHeaders ? res.getHeaders() : res._headers)
}
function ApiCache() {
var memCache = new MemoryCache()
var redisCache
var globalOptions = {
debug: false,
defaultDuration: 3600000,
enabled: true,
isBypassable: false,
append: null,
interceptKeyParts: null,
jsonp: false,
redisClient: false,
redisPrefix: '',
headerBlacklist: [],
statusCodes: {
include: [],
exclude: [],
},
events: {
expire: undefined,
},
headers: {
// 'cache-control': 'no-cache' // example of header overwrite
},
shouldSyncExpiration: false,
afterHit: null,
trackPerformance: false,
optimizeDuration: false,
}
var middlewareOptions = []
var instance = this
var index = null
var timers = {}
var performanceArray = [] // for tracking cache hit rate
instances.push(this)
this.id = instances.length
function shouldDebug() {
var debugEnv = process.env.DEBUG && process.env.DEBUG.split(',').indexOf('apicache') !== -1
return !!(globalOptions.debug || debugEnv)
}
function debug(a, b, c, d) {
if (!shouldDebug()) return
var arr = ['\x1b[36m[apicache]\x1b[0m', a, b, c, d].filter(function(arg) {
return arg !== undefined
})
console.log.apply(null, arr)
}
function shouldCacheResponse(request, response, toggle, options) {
if (!response) return false
var codes = (options || globalOptions).statusCodes
if (toggle && !toggle(request, response)) {
return false
}
if ((!codes.exclude || !codes.exclude.length) && (!codes.include || !codes.include.length)) {
return response.statusCode in CACHEABLE_STATUS_CODES
}
if (
codes.exclude &&
codes.exclude.length &&
codes.exclude.indexOf(response.statusCode) !== -1
) {
return false
}
if (
codes.include &&
codes.include.length &&
codes.include.indexOf(response.statusCode) === -1
) {
return false
}
return true
}
function addIndexEntries(key, req) {
var groupName = req.apicacheGroup
if (groupName) {
debug('group detected "' + groupName + '"')
var group = (index.groups[groupName] = index.groups[groupName] || [])
group.unshift(key)
}
index.all.unshift(key)
}
function filterBlacklistedHeaders(headers, options) {
return Object.keys(headers)
.filter(function(key) {
return (options || globalOptions).headerBlacklist.indexOf(key) === -1
})
.reduce(function(acc, header) {
acc[header] = headers[header]
return acc
}, {})
}
function createCacheObject(status, headers, data, encoding, options) {
return {
status: status,
headers: filterBlacklistedHeaders(headers, options),
data: data,
encoding: encoding,
timestamp: Date.now(), // This is used to properly decrement max-age headers in cached responses
}
}
function cacheResponse(key, value, duration) {
var expireCallback = globalOptions.events.expire
memCache.add(key, value, duration, expireCallback)
// add automatic cache clearing from duration
timers[key] = setLongTimeout(function() {
instance.clear(key, true)
}, duration)
}
function debugCacheAddition(cache, key, strDuration, req, res, options) {
if (!shouldDebug()) return Promise.resolve()
var elapsed = new Date() - req.apicacheTimer
return Promise.resolve(cache.get(key))
.then(function(cached) {
var cacheObject
if (cached && cached.value) {
cached = cached.value
cacheObject = createCacheObject(
cached.status,
cached.headers,
cached.data && cached.data.toString(cached.encoding),
cached.encoding,
options
)
cacheObject.timestamp = cached.timestamp
} else cacheObject = {}
debug('adding cache entry for "' + key + '" @ ' + strDuration, logDuration(elapsed))
debug('cacheObject: ', cacheObject)
})
.catch(function(err) {
debug('error debugging cache addition', err)
})
}
var isNodeLte7 = (function(ret) {
return function() {
if (ret !== undefined) return ret
return (ret = parseInt(process.versions.node.split('.')[0], 10) <= 7)
}
})()
function getHeadersFromParams(res, statusMsgOrHeaders, maybeHeaders) {
if (statusMsgOrHeaders && typeof statusMsgOrHeaders !== 'string') {
maybeHeaders = statusMsgOrHeaders
}
if (!maybeHeaders) maybeHeaders = {}
return Object.keys(maybeHeaders).reduce(function(memo, item) {
memo[item.toLowerCase()] = maybeHeaders[item]
return memo
// some framework writeHead patches remove headers from params, so merge with res.getHeaders()
}, getSafeHeaders(res))
}
function preWriteHead(res, statusCode, statusMsgOrHeaders, maybeHeaders) {
if (statusCode) res.statusCode = statusCode
if (statusMsgOrHeaders && typeof statusMsgOrHeaders !== 'string') {
maybeHeaders = statusMsgOrHeaders
} else if (statusMsgOrHeaders) res.statusMessage = statusMsgOrHeaders
if (!maybeHeaders) maybeHeaders = {}
Object.keys(maybeHeaders).forEach(function(name) {
res.setHeader(name, maybeHeaders[name])
})
}
function fixEncodingHeaders(chunk, headers) {
if (!chunk || !headers) return
if (Compressor.isReallyCompressed(chunk, headers['content-encoding'])) {
delete headers['content-length']
} else {
delete headers['content-encoding']
}
}
function getCacheControlMaxAge(syncedMaxAge, group, options) {
var maxAge
if (group) maxAge = Math.min(3, syncedMaxAge)
else if (!options.shouldSyncExpiration) maxAge = Math.min(30, syncedMaxAge)
else maxAge = syncedMaxAge
var directive = options.append || options.appendKey ? 'private, ' : '' // public is default
return directive + 'max-age=' + maxAge.toFixed(0) + ', must-revalidate'
}
function makeResponseCacheable(
req,
res,
next,
key,
duration,
strDuration,
toggle,
options,
afterFn
) {
if (!afterFn) afterFn = Promise.resolve.bind(Promise)
var afterTryingToCache = (function(isCalled) {
return function() {
if (isCalled !== undefined) return isCalled
return (isCalled = afterFn())
}
})()
var shouldCacheRes = (function(shouldIt) {
return function(req, res, toggle, options) {
if (shouldIt !== undefined) return shouldIt
return (shouldIt = shouldCacheResponse(req, res, toggle, options))
}
})()
// monkeypatch res to create cache object
var apicacheResPatches = {
write: res.write,
writeHead: res.writeHead,
end: res.end,
}
if (!req.apicacheResPatches) {
req.apicacheResPatches = apicacheResPatches
req.customWriteHeads = []
req.runReversedCustomWriteHeadsOnce = (function(isCalled) {
return function() {
if (isCalled) return
isCalled = true
var fn
while ((fn = req.customWriteHeads.pop())) {
fn.apply(null, arguments)
}
}
})()
}
function customWriteHead(statusCode, statusMsgOrHeaders, maybeHeaders) {
if (res._shouldCacheResWriteHeadVersionAlreadyRun) return
// to use with shouldCacheRes()
res.statusCode = statusCode
if (!res._currentResponseHeaders) {
// these most likely (if default node writeHead implementation) won't be available at res.getHeaders() yet
res._currentResponseHeaders = getHeadersFromParams(res, statusMsgOrHeaders, maybeHeaders)
}
// add cache control headers
if (!options.headers['cache-control'] && !res._currentResponseHeaders['cache-control']) {
if (shouldCacheRes(req, res, toggle, options)) {
var cacheControl
if (SAFE_HTTP_METHODS.indexOf(req.method) !== -1) {
var syncedMaxAge = Math.ceil(duration / 1000)
cacheControl = getCacheControlMaxAge(syncedMaxAge, req.apicacheGroup, options)
} else {
cacheControl = 'no-store'
}
res.setHeader('cache-control', cacheControl)
res._currentResponseHeaders['cache-control'] = cacheControl
} else {
res.setHeader('cache-control', 'no-store')
}
}
if (shouldCacheRes(req, res, toggle, options)) {
res._shouldCacheResWriteHeadVersionAlreadyRun = true
// append header overwrites if applicable
Object.keys(options.headers).forEach(function(name) {
res.setHeader(name, options.headers[name])
res._currentResponseHeaders[name.toLowerCase()] = options.headers[name]
})
}
}
req.customWriteHeads.unshift(customWriteHead)
res.writeHead = function(statusCode, statusMsgOrHeaders, maybeHeaders) {
req.runReversedCustomWriteHeadsOnce(statusCode, statusMsgOrHeaders, maybeHeaders)
return apicacheResPatches.writeHead.apply(this, arguments)
}
var getWstream = (function(wstream) {
return function(method, chunk, encoding) {
if (wstream) return wstream
if (
res._shouldCacheResWriteOrEndVersionAlreadyRun ||
!shouldCacheRes(req, res, toggle, options)
) {
var emptyWstream = new stream.Writable({
write(_c, _e, cb) {
cb()
},
}).on('finish', afterTryingToCache)
return (wstream = Promise.resolve(emptyWstream))
}
res._shouldCacheResWriteOrEndVersionAlreadyRun = true
var getCacheObject = function() {
return createCacheObject(res.statusCode, res._currentResponseHeaders, null, null, options)
}
var getGroup = function() {
return req.apicacheGroup
}
var expireCallback = globalOptions.events.expire
var cache = redisCache || memCache
var chunkSize = Buffer.byteLength(chunk || '', encoding)
// if res.end was called first (without calling write), it will have only one chunk
// res.socket.writableHighWaterMark is node gte 9
var highWaterMark =
method === 'end'
? chunkSize
: res.socket.writableHighWaterMark || res.socket._writableState.highWaterMark
var cacheWstream = cache
.createWriteStream(
key,
getCacheObject,
duration,
expireCallback,
getGroup,
highWaterMark,
// this is needed while memCache index/groups are still handled externally
!redisCache &&
function(statusCode, headers, data, encoding) {
addIndexEntries(key, req)
var cacheObject = createCacheObject(statusCode, headers, data, encoding, options)
cacheResponse(key, cacheObject, duration)
}
)
.then(function(wstream) {
return wstream
.on('error', function(err) {
debug('error in makeResponseCacheable function', err)
})
.on('finish', function() {
afterTryingToCache()
if (!wstream.isLocked) {
debugCacheAddition(cache, key, strDuration, req, res, options)
}
})
.on('unpipe', afterTryingToCache)
})
return (wstream = cacheWstream.then(function(wstream) {
if (wstream.isLocked) return wstream
// also indicates it may be already compressed
var otherMiddlewareMayWantToChangeCompression =
Compressor.getFirstContentEncoding(res._currentResponseHeaders['content-encoding']) !==
'identity'
// some middlewares will preset content-encoding to e.g. gzip too early
// even if apicache is about to receive uncompressed response stream (middleware attached before apicache's one)
fixEncodingHeaders(chunk, res._currentResponseHeaders)
// don't compress before caching
if (otherMiddlewareMayWantToChangeCompression) return wstream
var tstream = Compressor.run(
{
chunkSize: chunkSize,
requestMehod: req.method,
responseStatusCode: res.statusCode,
responseMethod: method,
responseHeaders: res._currentResponseHeaders,
},
debug
).on('error', function(err) {
debug('error in makeResponseCacheable function', err)
wstream.emit('error')
})
tstream.pipe(wstream)
return tstream
}))
}
})()
;['write', 'end'].forEach(function(method) {
var ret
res[method] = function(chunk, encoding) {
if (!this.headersSent) {
req.runReversedCustomWriteHeadsOnce(
res.statusCode,
res.statusMsgOrHeaders,
getSafeHeaders(res)
)
}
ret = apicacheResPatches[method].apply(this, arguments)
getWstream(method, chunk, encoding).then(function(wstream) {
wstream[method](chunk, encoding)
})
return ret
}
})
// res.end(data) writes data twice
if (isNodeLte7()) {
var _end = res.end
res.end = function(chunk, encoding) {
if (Buffer.byteLength(chunk || '') > 0) {
this.write(chunk, encoding)
arguments[0] = undefined
}
return _end.apply(this, arguments)
}
}
return next()
}
var CACHE_CONTROL_NO_TRANSFORM_REGEX = /(?:^|,)\s*?no-transform\s*?(?:,|$)/
var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/
function sendCachedResponse(request, response, cacheObject, toggle, next, duration, options) {
if (toggle && !toggle(request, response)) {
return next()
}
if (isKoa(request)) request.respond = false
var isMarkedToCache = !!request.apicacheResPatches
if (isMarkedToCache) {
// undo patches
Object.keys(request.apicacheResPatches).forEach(function(key) {
response[key] = request.apicacheResPatches[key]
})
}
if (options.afterHit) {
response.on('finish', function() {
isKoa(request) ? options.afterHit(request) : options.afterHit(request, response)
})
}
var elapsed = new Date() - request.apicacheTimer
debug(
'sending cached',
redisCache ? '(redis)' : '(memory-cache)',
'version of',
cacheObject.key,
logDuration(elapsed)
)
var headers = getSafeHeaders(response)
var cacheObjectHeaders = cacheObject.headers || {}
var cacheControl
// sync max-age with the cache expiration.
var elapsedMs = Date.now() - cacheObject.timestamp
var updatedMaxAge = Math.ceil((duration - elapsedMs) / 1000)
// when caching with options.interceptKeyParts,
// same key/cache could be reused for responding
// with different middleware options.headers
// and to different request methods, so recheck
if (options.headers['cache-control']) cacheControl = options.headers['cache-control']
else if (SAFE_HTTP_METHODS.indexOf(request.method) !== -1) {
if (cacheObjectHeaders['cache-control']) cacheControl = cacheObjectHeaders['cache-control']
else {
cacheControl = getCacheControlMaxAge(updatedMaxAge, request.apicacheGroup, options)
}
} else cacheControl = 'no-store'
Object.assign(headers, filterBlacklistedHeaders(cacheObjectHeaders, options), {
'cache-control': cacheControl.replace(/max-age=\s*([+-]?\d+)/, function(_match, maxAge) {
return 'max-age=' + Math.max(0, Math.min(parseInt(maxAge, 10), updatedMaxAge))
}),
})
// only embed apicache headers when not in production environment
if (process.env.NODE_ENV !== 'production') {
Object.assign(headers, {
'apicache-store': globalOptions.redisClient ? 'redis' : 'memory',
'apicache-version': pkg.version,
})
}
function hasNoBodyRequestingPreconditionCheck() {
return (
!request.headers['if-match'] &&
!request.headers['if-unmodified-since'] &&
!request.headers['if-range']
)
}
function clientDoesntWantToReloadItsCache() {
return (
!request.headers['cache-control'] ||
!CACHE_CONTROL_NO_CACHE_REGEXP.test(request.headers['cache-control'])
)
}
// test Etag against If-None-Match for 304
function isEtagFresh() {
var cachedEtag = cacheObjectHeaders.etag
var requestEtags = (request.headers['if-none-match'] || '').replace('*', '').split(/\s*,\s*/)
return Boolean(
cachedEtag &&
requestEtags.length > 0 &&
(requestEtags.indexOf(cachedEtag) !== -1 ||
requestEtags.indexOf('W/' + cachedEtag) !== -1 ||
requestEtags
.map(function(rEtag) {
return 'W/' + rEtag
})
.indexOf(cachedEtag) !== -1)
)
}
function isResourceFresh() {
var cachedLastModified = cacheObjectHeaders['last-modified']
var requestModifiedSince = request.headers['if-modified-since']
if (!cachedLastModified || !requestModifiedSince) return false
try {
return Date.parse(cachedLastModified) <= Date.parse(requestModifiedSince)
} catch (err) {
return false
}
}
if (
hasNoBodyRequestingPreconditionCheck() &&
clientDoesntWantToReloadItsCache() &&
(isEtagFresh() || isResourceFresh())
) {
if ('content-length' in headers) delete headers['content-length']
response.writeHead(304, headers)
return response.end()
}
if (request.method === 'HEAD') {
response.writeHead(cacheObject.status || 200, headers)
// skip body for HEAD
return response.end()
}
function getRstream() {
return (redisCache || memCache)
.createReadStream(
cacheObject.key,
cacheObject['data-token'] || cacheObject.data,
cacheObject.encoding,
// res.socket.writableHighWaterMark is node gte 9
response.socket.writableHighWaterMark || response.socket._writableState.highWaterMark
)
.on('error', function() {
debug('error in sendCachedResponse function')
response.end()
})
}
// dont use headers['content-encoding'] as it may be already changed to e.g. gzip by some middleware
var cachedEncoding = (cacheObjectHeaders['content-encoding'] || 'identity').split(',')[0]
var currentResCacheEncoding = (headers['content-encoding'] || 'identity').split(',')[0]
var noOtherMiddlewareMayWantToChangeCompression = cachedEncoding === currentResCacheEncoding
var requestAccepts = accepts(request)
if (
(cachedEncoding === 'identity' ||
(noOtherMiddlewareMayWantToChangeCompression &&
!CACHE_CONTROL_NO_TRANSFORM_REGEX.test(headers['cache-control'] || ''))) &&
requestAccepts.encodings(cachedEncoding)
) {
// Doing response.writeHead(cacheObject.status || 200, headers)
// can make writeHead patch from some compression middlewares fail
// (although using res.writeHead with headers that don't mess with content-length / content-encoding
// would mostly be ok)
preWriteHead(response, cacheObject.status || 200, headers)
return getRstream().pipe(response)
// try to decompress
} else if (cachedEncoding !== 'identity' && requestAccepts.encodings('identity')) {
var tstream
if (cachedEncoding === 'br' && zlib.createBrotliDecompress) {
tstream = zlib.createBrotliDecompress()
} else if (['gzip', 'deflate'].indexOf(cachedEncoding) !== -1) {
tstream = zlib.createUnzip()
} else {
var errorMessage = "can't decompress" + cachedEncoding + 'encoding'
throw new Error(errorMessage)
}
delete headers['content-encoding']
preWriteHead(response, cacheObject.status || 200, headers)
tstream.on('error', function() {
debug('error in decompression stream')
this.unpipe()
// if erroed cause didn't need to decompress
// try sending it without transforming
getRstream()
.on('error', function() {
debug('error in decompression stream')
this.unpipe()
response.end()
// if node < 8
if (!this.destroy) return this.pause()
this.destroy()
})
.pipe(response)
// if node < 8
if (!this.destroy) return this.pause()
this.destroy()
})
return getRstream()
.pipe(tstream)
.pipe(response)
} else {
var contentEncodings = Array.from(new Set([cachedEncoding, 'identity']))
var statusMessage =
'Please accept' +
contentEncodings.slice(0, -1).join(', ') +
contentEncodings.slice(-1).join(', or ')
response.writeHead(406, statusMessage)
return response.end()
}
}
var syncOptions = (function() {
function syncOptionsByIndex(i) {
Object.assign(middlewareOptions[i].options, globalOptions, middlewareOptions[i].localOptions)
var options = middlewareOptions[i].options
if (options.headerBlacklist) {
options.headerBlacklist = options.headerBlacklist.map(function(v) {
return v.toLowerCase()
})
}
}
return function(i) {
if (i) return syncOptionsByIndex(i)
else {
for (i in middlewareOptions) {
syncOptionsByIndex(i)
}
}
}
})()
function getAppendice(append, req, res) {
if (!append) return ''
var appendice
if (typeof append === 'function') {
appendice = isKoa(req) ? append(req) : append(req, res)
// ['x', 'y'] => req?.x?.y
} else if (append.length > 0) {
appendice = req
for (var i = 0; i < append.length; i++) {
if (!appendice) break
appendice = appendice[append[i]]
}
}
return appendice || ''
}
function getKeyParts(req, res, options) {
var query
if (req.query !== null && typeof req.query === 'object') query = Object.assign({}, req.query)
// In Express,the url is ambiguous based on where a router is mounted. originalUrl will give the full Url
var url = (req.originalUrl || req.url).replace(/\/?(?:\?([^#]*)(?:#.*)?)?$/, function(
_match,
qs
) {
if (!query) {
query = querystring.parse(qs)
delete query['']
}
return ''
})
// couldn't use (?:(?<!^)\/)? negative look-behind instead of \/? at regexp above to keep / if at beginning (node gte 9)
// also, it will consider a maybe possible req.originalUrl || req.url '' as '/'
if (url === '') url = '/'
if (options.jsonp) {
if ([true, false].indexOf(options.jsonp) === -1) {
delete query.jsonp
delete query.callback
} else delete query[options.jsonp]
}
var parts = {
method: req.method,
url: url,
params: Object.assign(query, typeof req.body === 'object' ? Object.assign({}, req.body) : {}),
appendice: getAppendice(options.append || options.appendKey, req, res),
}
if (options.interceptKeyParts) {
parts =
(isKoa(req)
? options.interceptKeyParts(req, parts)
: options.interceptKeyParts(req, res, parts)) || parts
}
return parts
}
function getSimilarKeyFromOtherMethod(key, method, otherMethod) {
return key.replace(method.toLowerCase(), otherMethod.toLowerCase())
}
this.getKey = function(keyParts) {
if (!keyParts || typeof keyParts !== 'object') return '{}'
var url
if (typeof keyParts.url === 'string') {
url = keyParts.url.trim()
if (url[0] !== '/') url = '/' + url
if (url.length > 1) url = url.replace(/\/$/, '')
} else url = ''
var appendice
if (typeof keyParts.appendice === 'string') appendice = keyParts.appendice
else if (Number.isNaN(keyParts.appendice)) appendice = 'NaN'
else if ([null, undefined].indexOf(keyParts.appendice) === -1) {
try {
appendice = jsonSortify(keyParts.appendice)
} catch (err) {
appendice = ''
}
} else appendice = ''
return (
(typeof keyParts.method === 'string' ? keyParts.method.toLowerCase() : '') +
url +
(keyParts.params !== null && typeof keyParts.params === 'object'
? jsonSortify(keyParts.params)
: '{}') +
appendice
)
}
this.has = function(key) {
if ([null, undefined].indexOf(key) !== -1) return Promise.resolve(false)
return (redisCache || memCache).has(key)
}
this.get = function(key) {
if ([null, undefined].indexOf(key) !== -1) return Promise.resolve(false)
return Promise.resolve((redisCache || memCache).get(key)).then(function(cached) {
if (!cached) return null
cached = cached.value
// this.set can store any value, so return raw cached if not what apicache regularly stores
if (
cached === null ||
typeof cached !== 'object' ||
!['status', 'headers', 'data', 'encoding', 'timestamp'].every(function(k) {
return k in cached
})
) {
return cached
}
// try formatting and decompressing
try {
var data = cached.data
if ([null, undefined].indexOf(data) === -1) {
if (Buffer.byteLength(data) === 0) data = ''
else {
var cachedEncoding = cached.headers['content-encoding']
if (cachedEncoding && cachedEncoding !== 'identity') {
var decompress = {
br: zlib.brotliDecompressSync,
gzip: zlib.unzipSync,
deflate: zlib.unzipSync,
}[cachedEncoding]
if (decompress) data = decompress(data)
}
data = data.toString(cached.encoding)
try {
data = JSON.parse(data)
} catch (err) {}
}
}
// don't send with all properties if it's really what apicache regularly stores
// (e.g. encoding as it was already used above for parsing and redis data-extra-pttl prop)
return {
status: cached.status,
headers: cached.headers,
data: data,
timestamp: cached.timestamp,
}
} catch (err) {
return cached
}
})
}
this.set = function(key, value, duration, group, expirationCallback) {
if ([null, undefined].indexOf(key) !== -1) return Promise.resolve(false)
duration = this.getDuration(duration)
return (
// for now, this is the way we make sure .set can safely modify an already existing item
// e.g. it will remove from old group
Promise.resolve(this.clear(key))
.then(function() {
return Promise.resolve(
(redisCache || memCache).add(key, value, duration, expirationCallback, group)
)
})
// this is needed while memCache index/groups are still handled externally
.then(function() {
if (!redisCache) {
addIndexEntries(key, { apicacheGroup: group })
}
return value
})
.catch(function() {
return false
})
)
}
this.clear = function(target, isAutomatic) {
if (redisCache) {
return redisCache
.clear(target)
.then(function(deleteCount) {
debug(deleteCount, 'keys cleared')
return deleteCount
})
.catch(function() {
debug('error in clear function')
})
}
var group = index.groups[target]
if (group) {
debug('clearing group "' + target + '"')
group.forEach(function(key) {
debug('clearing cached entry for "' + key + '"')
clearLongTimeout(timers[key])
delete timers[key]
memCache.delete(key)
index.all = index.all.filter(doesntMatch(key))
})
delete index.groups[target]
} else if (target || target === '') {
debug('clearing ' + (isAutomatic ? 'expired' : 'cached') + ' entry for "' + target + '"')
clearLongTimeout(timers[target])
delete timers[target]
// clear actual cached entry
memCache.delete(target)
// remove from global index
index.all = index.all.filter(doesntMatch(target))
// remove target from each group that it may exist in
Object.keys(index.groups).forEach(function(groupName) {
index.groups[groupName] = index.groups[groupName].filter(doesntMatch(target))
var isGroupEmpty = !index.groups[groupName].length
// delete group if now empty
if (isGroupEmpty) {
delete index.groups[groupName]
}
})
} else {
debug('clearing entire index')
memCache.clear()
this.resetIndex()
}
return this.getIndex()
}
function parseDuration(duration, defaultDuration) {
if (typeof duration === 'number') return duration
if (typeof duration === 'string') {
var split = duration.match(/^([\d.,]+)\s?(\w+)$/)
if (split.length === 3) {
var len = parseFloat(split[1])
var unit = split[2].replace(/s$/i, '').toLowerCase()
if (unit === 'm') {
unit = 'ms'
}
return (len || 1) * (t[unit] || 0)
}
}
return defaultDuration
}
this.getDuration = function(duration) {
return parseDuration(duration, globalOptions.defaultDuration)
}
/**
* Return cache performance statistics (hit rate). Suitable for putting into a route:
* <code>
* app.get('/api/cache/performance', (req, res) => {
* res.json(apicache.getPerformance())
* })
* </code>
*/
this.getPerformance = function() {
return performanceArray.map(function(p) {
return p.report()
})
}
this.getIndex = function(group) {
if (redisCache) return redisCache.getIndex(group)
if (group) {
return index.groups[group]
} else {
return index
}
}