staticCache.js
5.64 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
/*!
* Connect - staticCache
* Copyright(c) 2011 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var utils = require('../utils')
, Cache = require('../cache')
, fresh = require('fresh');
/**
* Static cache:
*
* Enables a memory cache layer on top of
* the `static()` middleware, serving popular
* static files.
*
* By default a maximum of 128 objects are
* held in cache, with a max of 256k each,
* totalling ~32mb.
*
* A Least-Recently-Used (LRU) cache algo
* is implemented through the `Cache` object,
* simply rotating cache objects as they are
* hit. This means that increasingly popular
* objects maintain their positions while
* others get shoved out of the stack and
* garbage collected.
*
* Benchmarks:
*
* static(): 2700 rps
* node-static: 5300 rps
* static() + staticCache(): 7500 rps
*
* Options:
*
* - `maxObjects` max cache objects [128]
* - `maxLength` max cache object length 256kb
*
* @param {Object} options
* @return {Function}
* @api public
*/
module.exports = function staticCache(options){
var options = options || {}
, cache = new Cache(options.maxObjects || 128)
, maxlen = options.maxLength || 1024 * 256;
console.warn('connect.staticCache() is deprecated and will be removed in 3.0');
console.warn('use varnish or similar reverse proxy caches.');
return function staticCache(req, res, next){
var key = cacheKey(req)
, ranges = req.headers.range
, hasCookies = req.headers.cookie
, hit = cache.get(key);
// cache static
// TODO: change from staticCache() -> cache()
// and make this work for any request
req.on('static', function(stream){
var headers = res._headers
, cc = utils.parseCacheControl(headers['cache-control'] || '')
, contentLength = headers['content-length']
, hit;
// dont cache set-cookie responses
if (headers['set-cookie']) return hasCookies = true;
// dont cache when cookies are present
if (hasCookies) return;
// ignore larger files
if (!contentLength || contentLength > maxlen) return;
// don't cache partial files
if (headers['content-range']) return;
// dont cache items we shouldn't be
// TODO: real support for must-revalidate / no-cache
if ( cc['no-cache']
|| cc['no-store']
|| cc['private']
|| cc['must-revalidate']) return;
// if already in cache then validate
if (hit = cache.get(key)){
if (headers.etag == hit[0].etag) {
hit[0].date = new Date;
return;
} else {
cache.remove(key);
}
}
// validation notifiactions don't contain a steam
if (null == stream) return;
// add the cache object
var arr = [];
// store the chunks
stream.on('data', function(chunk){
arr.push(chunk);
});
// flag it as complete
stream.on('end', function(){
var cacheEntry = cache.add(key);
delete headers['x-cache']; // Clean up (TODO: others)
cacheEntry.push(200);
cacheEntry.push(headers);
cacheEntry.push.apply(cacheEntry, arr);
});
});
if (req.method == 'GET' || req.method == 'HEAD') {
if (ranges) {
next();
} else if (!hasCookies && hit && !mustRevalidate(req, hit)) {
res.setHeader('X-Cache', 'HIT');
respondFromCache(req, res, hit);
} else {
res.setHeader('X-Cache', 'MISS');
next();
}
} else {
next();
}
}
};
/**
* Respond with the provided cached value.
* TODO: Assume 200 code, that's iffy.
*
* @param {Object} req
* @param {Object} res
* @param {Object} cacheEntry
* @return {String}
* @api private
*/
function respondFromCache(req, res, cacheEntry) {
var status = cacheEntry[0]
, headers = utils.merge({}, cacheEntry[1])
, content = cacheEntry.slice(2);
headers.age = (new Date - new Date(headers.date)) / 1000 || 0;
switch (req.method) {
case 'HEAD':
res.writeHead(status, headers);
res.end();
break;
case 'GET':
if (utils.conditionalGET(req) && fresh(req.headers, headers)) {
headers['content-length'] = 0;
res.writeHead(304, headers);
res.end();
} else {
res.writeHead(status, headers);
function write() {
while (content.length) {
if (false === res.write(content.shift())) {
res.once('drain', write);
return;
}
}
res.end();
}
write();
}
break;
default:
// This should never happen.
res.writeHead(500, '');
res.end();
}
}
/**
* Determine whether or not a cached value must be revalidated.
*
* @param {Object} req
* @param {Object} cacheEntry
* @return {String}
* @api private
*/
function mustRevalidate(req, cacheEntry) {
var cacheHeaders = cacheEntry[1]
, reqCC = utils.parseCacheControl(req.headers['cache-control'] || '')
, cacheCC = utils.parseCacheControl(cacheHeaders['cache-control'] || '')
, cacheAge = (new Date - new Date(cacheHeaders.date)) / 1000 || 0;
if ( cacheCC['no-cache']
|| cacheCC['must-revalidate']
|| cacheCC['proxy-revalidate']) return true;
if (reqCC['no-cache']) return true;
if (null != reqCC['max-age']) return reqCC['max-age'] < cacheAge;
if (null != cacheCC['max-age']) return cacheCC['max-age'] < cacheAge;
return false;
}
/**
* The key to use in the cache. For now, this is the URL path and query.
*
* 'http://example.com?key=value' -> '/?key=value'
*
* @param {Object} req
* @return {String}
* @api private
*/
function cacheKey(req) {
return utils.parseUrl(req).path;
}