forked from Binaryify/NeteaseCloudMusicApi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapicache.js
830 lines (715 loc) · 21.9 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
var url = require('url')
var MemoryCache = require('./memory-cache')
var t = {
ms: 1,
second: 1000,
minute: 60000,
hour: 3600000,
day: 3600000 * 24,
week: 3600000 * 24 * 7,
month: 3600000 * 24 * 30,
}
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) {
return res.getHeaders ? res.getHeaders() : res._headers
}
function ApiCache() {
var memCache = new MemoryCache()
var globalOptions = {
debug: false,
defaultDuration: 3600000,
enabled: true,
appendKey: [],
jsonp: false,
redisClient: false,
headerBlacklist: [],
statusCodes: {
include: [],
exclude: [],
},
events: {
expire: undefined,
},
headers: {
// 'cache-control': 'no-cache' // example of header overwrite
},
trackPerformance: 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 debug(a, b, c, d) {
var arr = ['\x1b[36m[apicache]\x1b[0m', a, b, c, d].filter(function (arg) {
return arg !== undefined
})
var debugEnv =
process.env.DEBUG &&
process.env.DEBUG.split(',').indexOf('apicache') !== -1
return (globalOptions.debug || debugEnv) && console.log.apply(null, arr)
}
function shouldCacheResponse(request, response, toggle) {
var opt = globalOptions
var codes = opt.statusCodes
if (!response) return false
if (toggle && !toggle(request, response)) {
return false
}
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) {
return Object.keys(headers)
.filter(function (key) {
return globalOptions.headerBlacklist.indexOf(key) === -1
})
.reduce(function (acc, header) {
acc[header] = headers[header]
return acc
}, {})
}
function createCacheObject(status, headers, data, encoding) {
return {
status: status,
headers: filterBlacklistedHeaders(headers),
data: data,
encoding: encoding,
timestamp: new Date().getTime() / 1000, // seconds since epoch. This is used to properly decrement max-age headers in cached responses.
}
}
function cacheResponse(key, value, duration) {
var redis = globalOptions.redisClient
var expireCallback = globalOptions.events.expire
if (redis && redis.connected) {
try {
redis.hset(key, 'response', JSON.stringify(value))
redis.hset(key, 'duration', duration)
redis.expire(key, duration / 1000, expireCallback || function () {})
} catch (err) {
debug('[apicache] error in redis.hset()')
}
} else {
memCache.add(key, value, duration, expireCallback)
}
// add automatic cache clearing from duration, includes max limit on setTimeout
timers[key] = setTimeout(function () {
instance.clear(key, true)
}, Math.min(duration, 2147483647))
}
function accumulateContent(res, content) {
if (content) {
if (typeof content == 'string') {
res._apicache.content = (res._apicache.content || '') + content
} else if (Buffer.isBuffer(content)) {
var oldContent = res._apicache.content
if (typeof oldContent === 'string') {
oldContent = !Buffer.from
? new Buffer(oldContent)
: Buffer.from(oldContent)
}
if (!oldContent) {
oldContent = !Buffer.alloc ? new Buffer(0) : Buffer.alloc(0)
}
res._apicache.content = Buffer.concat(
[oldContent, content],
oldContent.length + content.length,
)
} else {
res._apicache.content = content
}
}
}
function makeResponseCacheable(
req,
res,
next,
key,
duration,
strDuration,
toggle,
) {
// monkeypatch res.end to create cache object
res._apicache = {
write: res.write,
writeHead: res.writeHead,
end: res.end,
cacheable: true,
content: undefined,
}
// append header overwrites if applicable
Object.keys(globalOptions.headers).forEach(function (name) {
res.setHeader(name, globalOptions.headers[name])
})
res.writeHead = function () {
// add cache control headers
if (!globalOptions.headers['cache-control']) {
if (shouldCacheResponse(req, res, toggle)) {
res.setHeader(
'cache-control',
'max-age=' + (duration / 1000).toFixed(0),
)
} else {
res.setHeader('cache-control', 'no-cache, no-store, must-revalidate')
}
}
res._apicache.headers = Object.assign({}, getSafeHeaders(res))
return res._apicache.writeHead.apply(this, arguments)
}
// patch res.write
res.write = function (content) {
accumulateContent(res, content)
return res._apicache.write.apply(this, arguments)
}
// patch res.end
res.end = function (content, encoding) {
if (shouldCacheResponse(req, res, toggle)) {
accumulateContent(res, content)
if (res._apicache.cacheable && res._apicache.content) {
addIndexEntries(key, req)
var headers = res._apicache.headers || getSafeHeaders(res)
var cacheObject = createCacheObject(
res.statusCode,
headers,
res._apicache.content,
encoding,
)
cacheResponse(key, cacheObject, duration)
// display log entry
var elapsed = new Date() - req.apicacheTimer
debug(
'adding cache entry for "' + key + '" @ ' + strDuration,
logDuration(elapsed),
)
debug('_apicache.headers: ', res._apicache.headers)
debug('res.getHeaders(): ', getSafeHeaders(res))
debug('cacheObject: ', cacheObject)
}
}
return res._apicache.end.apply(this, arguments)
}
next()
}
function sendCachedResponse(
request,
response,
cacheObject,
toggle,
next,
duration,
) {
if (toggle && !toggle(request, response)) {
return next()
}
var headers = getSafeHeaders(response)
Object.assign(
headers,
filterBlacklistedHeaders(cacheObject.headers || {}),
{
// set properly-decremented max-age header. This ensures that max-age is in sync with the cache expiration.
'cache-control':
'max-age=' +
Math.max(
0,
(
duration / 1000 -
(new Date().getTime() / 1000 - cacheObject.timestamp)
).toFixed(0),
),
},
)
// only embed apicache headers when not in production environment
// unstringify buffers
var data = cacheObject.data
if (data && data.type === 'Buffer') {
data =
typeof data.data === 'number'
? new Buffer.alloc(data.data)
: new Buffer.from(data.data)
}
// test Etag against If-None-Match for 304
var cachedEtag = cacheObject.headers.etag
var requestEtag = request.headers['if-none-match']
if (requestEtag && cachedEtag === requestEtag) {
response.writeHead(304, headers)
return response.end()
}
response.writeHead(cacheObject.status || 200, headers)
return response.end(data, cacheObject.encoding)
}
function syncOptions() {
for (var i in middlewareOptions) {
Object.assign(
middlewareOptions[i].options,
globalOptions,
middlewareOptions[i].localOptions,
)
}
}
this.clear = function (target, isAutomatic) {
var group = index.groups[target]
var redis = globalOptions.redisClient
if (group) {
debug('clearing group "' + target + '"')
group.forEach(function (key) {
debug('clearing cached entry for "' + key + '"')
clearTimeout(timers[key])
delete timers[key]
if (!globalOptions.redisClient) {
memCache.delete(key)
} else {
try {
redis.del(key)
} catch (err) {
console.log('[apicache] error in redis.del("' + key + '")')
}
}
index.all = index.all.filter(doesntMatch(key))
})
delete index.groups[target]
} else if (target) {
debug(
'clearing ' +
(isAutomatic ? 'expired' : 'cached') +
' entry for "' +
target +
'"',
)
clearTimeout(timers[target])
delete timers[target]
// clear actual cached entry
if (!redis) {
memCache.delete(target)
} else {
try {
redis.del(target)
} catch (err) {
console.log('[apicache] error in redis.del("' + 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),
)
// delete group if now empty
if (!index.groups[groupName].length) {
delete index.groups[groupName]
}
})
} else {
debug('clearing entire index')
if (!redis) {
memCache.clear()
} else {
// clear redis keys one by one from internal index to prevent clearing non-apicache entries
index.all.forEach(function (key) {
clearTimeout(timers[key])
delete timers[key]
try {
redis.del(key)
} catch (err) {
console.log('[apicache] error in redis.del("' + key + '")')
}
})
}
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 (group) {
return index.groups[group]
} else {
return index
}
}
this.middleware = function cache(
strDuration,
middlewareToggle,
localOptions,
) {
var duration = instance.getDuration(strDuration)
var opt = {}
middlewareOptions.push({
options: opt,
})
var options = function (localOptions) {
if (localOptions) {
middlewareOptions.find(function (middleware) {
return middleware.options === opt
}).localOptions = localOptions
}
syncOptions()
return opt
}
options(localOptions)
/**
* A Function for non tracking performance
*/
function NOOPCachePerformance() {
this.report = this.hit = this.miss = function () {} // noop;
}
/**
* A function for tracking and reporting hit rate. These statistics are returned by the getPerformance() call above.
*/
function CachePerformance() {
/**
* Tracks the hit rate for the last 100 requests.
* If there have been fewer than 100 requests, the hit rate just considers the requests that have happened.
*/
this.hitsLast100 = new Uint8Array(100 / 4) // each hit is 2 bits
/**
* Tracks the hit rate for the last 1000 requests.
* If there have been fewer than 1000 requests, the hit rate just considers the requests that have happened.
*/
this.hitsLast1000 = new Uint8Array(1000 / 4) // each hit is 2 bits
/**
* Tracks the hit rate for the last 10000 requests.
* If there have been fewer than 10000 requests, the hit rate just considers the requests that have happened.
*/
this.hitsLast10000 = new Uint8Array(10000 / 4) // each hit is 2 bits
/**
* Tracks the hit rate for the last 100000 requests.
* If there have been fewer than 100000 requests, the hit rate just considers the requests that have happened.
*/
this.hitsLast100000 = new Uint8Array(100000 / 4) // each hit is 2 bits
/**
* The number of calls that have passed through the middleware since the server started.
*/
this.callCount = 0
/**
* The total number of hits since the server started
*/
this.hitCount = 0
/**
* The key from the last cache hit. This is useful in identifying which route these statistics apply to.
*/
this.lastCacheHit = null
/**
* The key from the last cache miss. This is useful in identifying which route these statistics apply to.
*/
this.lastCacheMiss = null
/**
* Return performance statistics
*/
this.report = function () {
return {
lastCacheHit: this.lastCacheHit,
lastCacheMiss: this.lastCacheMiss,
callCount: this.callCount,
hitCount: this.hitCount,
missCount: this.callCount - this.hitCount,
hitRate: this.callCount == 0 ? null : this.hitCount / this.callCount,
hitRateLast100: this.hitRate(this.hitsLast100),
hitRateLast1000: this.hitRate(this.hitsLast1000),
hitRateLast10000: this.hitRate(this.hitsLast10000),
hitRateLast100000: this.hitRate(this.hitsLast100000),
}
}
/**
* Computes a cache hit rate from an array of hits and misses.
* @param {Uint8Array} array An array representing hits and misses.
* @returns a number between 0 and 1, or null if the array has no hits or misses
*/
this.hitRate = function (array) {
var hits = 0
var misses = 0
for (var i = 0; i < array.length; i++) {
var n8 = array[i]
for (j = 0; j < 4; j++) {
switch (n8 & 3) {
case 1:
hits++
break
case 2:
misses++
break
}
n8 >>= 2
}
}
var total = hits + misses
if (total == 0) return null
return hits / total
}
/**
* Record a hit or miss in the given array. It will be recorded at a position determined
* by the current value of the callCount variable.
* @param {Uint8Array} array An array representing hits and misses.
* @param {boolean} hit true for a hit, false for a miss
* Each element in the array is 8 bits, and encodes 4 hit/miss records.
* Each hit or miss is encoded as to bits as follows:
* 00 means no hit or miss has been recorded in these bits
* 01 encodes a hit
* 10 encodes a miss
*/
this.recordHitInArray = function (array, hit) {
var arrayIndex = ~~(this.callCount / 4) % array.length
var bitOffset = (this.callCount % 4) * 2 // 2 bits per record, 4 records per uint8 array element
var clearMask = ~(3 << bitOffset)
var record = (hit ? 1 : 2) << bitOffset
array[arrayIndex] = (array[arrayIndex] & clearMask) | record
}
/**
* Records the hit or miss in the tracking arrays and increments the call count.
* @param {boolean} hit true records a hit, false records a miss
*/
this.recordHit = function (hit) {
this.recordHitInArray(this.hitsLast100, hit)
this.recordHitInArray(this.hitsLast1000, hit)
this.recordHitInArray(this.hitsLast10000, hit)
this.recordHitInArray(this.hitsLast100000, hit)
if (hit) this.hitCount++
this.callCount++
}
/**
* Records a hit event, setting lastCacheMiss to the given key
* @param {string} key The key that had the cache hit
*/
this.hit = function (key) {
this.recordHit(true)
this.lastCacheHit = key
}
/**
* Records a miss event, setting lastCacheMiss to the given key
* @param {string} key The key that had the cache miss
*/
this.miss = function (key) {
this.recordHit(false)
this.lastCacheMiss = key
}
}
var perf = globalOptions.trackPerformance
? new CachePerformance()
: new NOOPCachePerformance()
performanceArray.push(perf)
var cache = function (req, res, next) {
function bypass() {
debug('bypass detected, skipping cache.')
return next()
}
// initial bypass chances
if (!opt.enabled) return bypass()
if (
req.headers['x-apicache-bypass'] ||
req.headers['x-apicache-force-fetch']
)
return bypass()
// REMOVED IN 0.11.1 TO CORRECT MIDDLEWARE TOGGLE EXECUTE ORDER
// if (typeof middlewareToggle === 'function') {
// if (!middlewareToggle(req, res)) return bypass()
// } else if (middlewareToggle !== undefined && !middlewareToggle) {
// return bypass()
// }
// embed timer
req.apicacheTimer = new Date()
// In Express 4.x the url is ambigious based on where a router is mounted. originalUrl will give the full Url
var key = req.originalUrl || req.url
// Remove querystring from key if jsonp option is enabled
if (opt.jsonp) {
key = url.parse(key).pathname
}
// add appendKey (either custom function or response path)
if (typeof opt.appendKey === 'function') {
key += '$$appendKey=' + opt.appendKey(req, res)
} else if (opt.appendKey.length > 0) {
var appendKey = req
for (var i = 0; i < opt.appendKey.length; i++) {
appendKey = appendKey[opt.appendKey[i]]
}
key += '$$appendKey=' + appendKey
}
// attempt cache hit
var redis = opt.redisClient
var cached = !redis ? memCache.getValue(key) : null
// send if cache hit from memory-cache
if (cached) {
var elapsed = new Date() - req.apicacheTimer
debug(
'sending cached (memory-cache) version of',
key,
logDuration(elapsed),
)
perf.hit(key)
return sendCachedResponse(
req,
res,
cached,
middlewareToggle,
next,
duration,
)
}
// send if cache hit from redis
if (redis && redis.connected) {
try {
redis.hgetall(key, function (err, obj) {
if (!err && obj && obj.response) {
var elapsed = new Date() - req.apicacheTimer
debug(
'sending cached (redis) version of',
key,
logDuration(elapsed),
)
perf.hit(key)
return sendCachedResponse(
req,
res,
JSON.parse(obj.response),
middlewareToggle,
next,
duration,
)
} else {
perf.miss(key)
return makeResponseCacheable(
req,
res,
next,
key,
duration,
strDuration,
middlewareToggle,
)
}
})
} catch (err) {
// bypass redis on error
perf.miss(key)
return makeResponseCacheable(
req,
res,
next,
key,
duration,
strDuration,
middlewareToggle,
)
}
} else {
perf.miss(key)
return makeResponseCacheable(
req,
res,
next,
key,
duration,
strDuration,
middlewareToggle,
)
}
}
cache.options = options
return cache
}
this.options = function (options) {
if (options) {
Object.assign(globalOptions, options)
syncOptions()
if ('defaultDuration' in options) {
// Convert the default duration to a number in milliseconds (if needed)
globalOptions.defaultDuration = parseDuration(
globalOptions.defaultDuration,
3600000,
)
}
if (globalOptions.trackPerformance) {
debug(
'WARNING: using trackPerformance flag can cause high memory usage!',
)
}
return this
} else {
return globalOptions
}
}
this.resetIndex = function () {
index = {
all: [],
groups: {},
}
}
this.newInstance = function (config) {
var instance = new ApiCache()
if (config) {
instance.options(config)
}
return instance
}
this.clone = function () {
return this.newInstance(this.options())
}
// initialize index
this.resetIndex()
}
module.exports = new ApiCache()