improve etag control for res.send
Before adoption: this commit came in with the history the project adopted, so no landing records it.
closes #1435 closes #2129
authored by Douglas Christopher Wilson · committed by Douglas Christopher Wilson · parent 3e35845 · Browse files · 8 files·+251 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+251 added−34 removed
- tests:+143 added−5 removed
- other:+108 added−29 removed
Provenance
- Commit
c21226a- Tree
1d447b1- Author
Douglas Christopher Wilson <doug@somethingdoug.com>- Committer
Douglas Christopher Wilson <doug@somethingdoug.com>- Parent
3e35845
8 files changed+251 added−34 removed
modified:lib/application.js+19 added-9 removed
6 unmodified lines7 , methods = require('methods')8 , middleware = require('./middleware')9 , debug = require('debug')('express:application')10 , locals = require('./utils').locals11+ , compileETag = require('./utils').compileETag12 , compileTrust = require('./utils').compileTrust13 , View = require('./view')14 , utils = connect.utils15 , deprecate = require('./utils').deprecate30 unmodified lines46 47 app.defaultConfiguration = function(){48 // default settings49 this.enable('x-powered-by');49- this.enable('etag');50+ this.set('etag', 'weak');51 this.set('env', process.env.NODE_ENV || 'development');52 this.set('subdomain offset', 2);53 this.set('trust proxy', false);54 debug('booting in %s mode', this.get('env'));196 unmodified lines251 * @api public252 */253 254 app.set = function(setting, val){254- if (1 == arguments.length) {255+ if (arguments.length === 1) {256+ // app.get(setting)257 return this.settings[setting];256- } else {257- this.settings[setting] = val;258+ }259 259- if (setting === 'trust proxy') {260- debug('compile trust proxy %j', val);261- this.set('trust proxy fn', compileTrust(val));262- }260+ // set value261+ this.settings[setting] = val;262 264- return this;263+ // trigger matched settings264+ switch (setting) {265+ case 'etag':266+ debug('compile etag %s', val);267+ this.set('etag fn', compileETag(val));268+ break;269+ case 'trust proxy':270+ debug('compile trust proxy %s', val);271+ this.set('trust proxy fn', compileTrust(val));272+ break;273 }274+275+ return this;276 };277 278 /**279 * Return the app's absolute pathname269 unmodified linesmodified:lib/response.js+17 added-16 removed
9 unmodified lines10 , normalizeType = require('./utils').normalizeType11 , normalizeTypes = require('./utils').normalizeTypes12 , setCharset = require('./utils').setCharset13 , deprecate = require('./utils').deprecate14- , etag = require('./utils').etag14 , statusCodes = http.STATUS_CODES15 , cookie = require('cookie')16 , send = require('send')17 , mime = connect.mime108 unmodified lines126 }127 break;128 }129 131- // populate Content-Length132- if (undefined !== body && !this.get('Content-Length')) {133- this.set('Content-Length', len = Buffer.isBuffer(body)134- ? body.length135- : Buffer.byteLength(body));136- }137-138- // ETag support139- // TODO: W/ support140- if (app.settings.etag && len && ('GET' == req.method || 'HEAD' == req.method)) {141- if (!this.get('ETag')) {142- this.set('ETag', etag(body));143- }144- }145-130 // write strings in utf-8131 if ('string' === typeof body) {132 encoding = 'utf8';133 type = this.get('Content-Type');3 unmodified lines137 this.set('Content-Type', setCharset(type, 'utf-8'));138 }139 }140 141+ // populate Content-Length142+ if (undefined !== body && !this.get('Content-Length')) {143+ len = Buffer.isBuffer(body)144+ ? body.length145+ : Buffer.byteLength(body, encoding);146+ this.set('Content-Length', len);147+ }148+149+ // ETag support150+ var etag = len !== undefined && app.get('etag fn');151+ if (etag && ('GET' === req.method || 'HEAD' === req.method)) {152+ if (!this.get('ETag')) {153+ etag = etag(body, encoding);154+ etag && this.set('ETag', etag);155+ }156+ }157+158 // freshness159 if (req.fresh) this.statusCode = 304;160 161 // strip irrelevant headers677 unmodified linesmodified:lib/utils.js+65 added-3 removed
4 unmodified lines5 6 var mime = require('connect').mime7 , deprecate = require('util').deprecate8 , proxyaddr = require('proxy-addr')9- , crc32 = require('buffer-crc32');9+ , crc32 = require('buffer-crc32')10+ , crypto = require('crypto');11 12 /**13 * toString ref.14 */29 unmodified lines44 return deprecate(fn, msg);45 };46 47 /**47- * Return ETag for `body`.48+ * Return strong ETag for `body`.49 *50 * @param {String|Buffer} body51 * @param {String} [encoding]52 * @return {String}53 * @api private54 */55 55-exports.etag = function(body, encoding){56+exports.etag = function etag(body, encoding){57+ if (body.length === 0) {58+ // fast-path empty body59+ return '"1B2M2Y8AsgTpgAmY7PhCfg=="'60+ }61+62+ var hash = crypto63+ .createHash('md5')64+ .update(body, encoding)65+ .digest('base64')66+ return '"' + hash + '"'67+};68+69+/**70+ * Return weak ETag for `body`.71+ *72+ * @param {String|Buffer} body73+ * @param {String} [encoding]74+ * @return {String}75+ * @api private76+ */77+78+exports.wetag = function wetag(body, encoding){79+ if (body.length === 0) {80+ // fast-path empty body81+ return 'W/"0-0"'82+ }83+84 var buf = Buffer.isBuffer(body)85 ? body86 : new Buffer(body, encoding)87 var len = buf.length289 unmodified lines377 return new RegExp('^' + path + '$', sensitive ? '' : 'i');378 }379 380 /**381+ * Compile "etag" value to function.382+ *383+ * @param {Boolean|String|Function} val384+ * @return {Function}385+ * @api private386+ */387+388+exports.compileETag = function(val) {389+ var fn;390+391+ if (typeof val === 'function') {392+ return val;393+ }394+395+ switch (val) {396+ case true:397+ fn = exports.wetag;398+ break;399+ case false:400+ break;401+ case 'strong':402+ fn = exports.etag;403+ break;404+ case 'weak':405+ fn = exports.wetag;406+ break;407+ default:408+ throw new TypeError('unknown value for etag function: ' + val);409+ }410+411+ return fn;412+}413+414+/**415 * Compile "proxy trust" value to function.416 *417 * @param {Boolean|String|Number|Array|Function} val418 * @return {Function}54 unmodified linesmodified:test/config.js+15 added-1 removed
11 unmodified lines1213141516171819202122232425262728293031323370 unmodified lines1041051061079410811 unmodified lines it('should return the app when undefined', function(){ var app = express(); app.set('foo', undefined).should.equal(app); })
describe('"etag"', function(){ it('should throw on bad value', function(){ var app = express() app.set.bind(app, 'etag', 42).should.throw(/unknown value/) })
it('should set "etag fn"', function(){ var app = express() var fn = function(){} app.set('etag', fn) app.get('etag fn').should.equal(fn) }) }) })
describe('.get()', function(){ it('should return undefined when unset', function(){70 unmodified lines app.set('foo', 'bar'); app.disabled('foo').should.be.false; }) })})No newline at end of file})modified:test/res.send.js+102 added
357 unmodified lines358 .get('/')359 .expect('etag', 'W/"c-1525560792"', done)360 })361 362+ it('should send ETag for empty string response', function(done){363+ var app = express()364+365+ app.use(function(req, res){366+ res.send('')367+ });368+369+ app.enable('etag')370+371+ request(app)372+ .get('/')373+ .expect('etag', 'W/"0-0"', done)374+ })375+376 it('should send ETag for long response', function(done){377 var app = express();378 379 app.use(function(req, res){21 unmodified lines401 request(app)402 .get('/')403 .expect('etag', '"asdf"', done)404 });405+406+ it('should not send ETag for res.send()', function(done){407+ var app = express()408+409+ app.use(function(req, res){410+ res.send()411+ });412+413+ app.enable('etag')414+415+ request(app)416+ .get('/')417+ .end(function(err, res){418+ res.headers.should.not.have.property('etag');419+ done();420+ })421+ })422 });423 424 describe('when disabled', function(){425 it('should send no ETag', function(done){28 unmodified lines454 .get('/')455 .expect('etag', '"asdf"', done)456 });457 });458+459+ describe('when "strong"', function(){460+ it('should send strong ETag', function(done){461+ var app = express()462+463+ app.set('etag', 'strong');464+465+ app.use(function(req, res){466+ res.send('hello, world!');467+ });468+469+ request(app)470+ .get('/')471+ .expect('etag', '"Otu60XkfuuPskIiUxJY4cA=="', done)472+ })473+ })474+475+ describe('when "weak"', function(){476+ it('should send weak ETag', function(done){477+ var app = express()478+479+ app.set('etag', 'weak');480+481+ app.use(function(req, res){482+ res.send('hello, world!');483+ });484+485+ request(app)486+ .get('/')487+ .expect('etag', 'W/"d-1486392595"', done)488+ })489+ })490+491+ describe('when a function', function(){492+ it('should send custom ETag', function(done){493+ var app = express()494+495+ app.set('etag', function(body, encoding){496+ body.should.equal('hello, world!')497+ encoding.should.equal('utf8')498+ return '"custom"'499+ });500+501+ app.use(function(req, res){502+ res.send('hello, world!');503+ });504+505+ request(app)506+ .get('/')507+ .expect('etag', '"custom"', done)508+ })509+510+ it('should not send falsy ETag', function(done){511+ var app = express()512+513+ app.set('etag', function(body, encoding){514+ return undefined515+ });516+517+ app.use(function(req, res){518+ res.send('hello, world!');519+ });520+521+ request(app)522+ .get('/')523+ .end(function(err, res){524+ res.headers.should.not.have.property('etag')525+ done();526+ })527+ })528+ })529 })530 })modified:test/utils.js+26 added-4 removed
3 unmodified lines4 5 describe('utils.etag(body, encoding)', function(){6 it('should support strings', function(){7 utils.etag('express!')8- .should.eql('W/"8-3098196679"')8+ .should.eql('"zZdv4imtWD49AHEviejT6A=="')9 })10 11 it('should support utf8 strings', function(){12 utils.etag('express❤', 'utf8')13- .should.eql('W/"a-1751845617"')13+ .should.eql('"fsFba4IxwQS6h6Umb+FNxw=="')14 })15 16 it('should support buffer', function(){17 var buf = new Buffer('express!')18 utils.etag(buf)19- .should.eql('W/"8-3098196679"');19+ .should.eql('"zZdv4imtWD49AHEviejT6A=="');20 })21 22 it('should support empty string', function(){23- var buf = new Buffer('express!')23 utils.etag('')24+ .should.eql('"1B2M2Y8AsgTpgAmY7PhCfg=="');25+ })26+})27+28+describe('utils.wetag(body, encoding)', function(){29+ it('should support strings', function(){30+ utils.wetag('express!')31+ .should.eql('W/"8-3098196679"')32+ })33+34+ it('should support utf8 strings', function(){35+ utils.wetag('express❤', 'utf8')36+ .should.eql('W/"a-1751845617"')37+ })38+39+ it('should support buffer', function(){40+ var buf = new Buffer('express!')41+ utils.wetag(buf)42+ .should.eql('W/"8-3098196679"');43+ })44+45+ it('should support empty string', function(){46+ utils.wetag('')47 .should.eql('W/"0-0"');48 })49 })50 203 unmodified linesmodified:History.md+6 added
1 3.x2 ===3 4+ * custom etag control with `app.set('etag', val)`5+ - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation6+ - `app.set('etag', 'weak')` weak tag7+ - `app.set('etag', 'strong')` strong etag8+ - `app.set('etag', false)` turn off9+ - `app.set('etag', true)` standard etag10 * Include ETag in HEAD requests11 * mark `res.send` ETag as weak and reduce collisions12 * update connect to 2.18.013 - deps: compression@1.0.31365 unmodified linesmodified:package.json+1 added-1 removed
45 unmodified lines4647484950515253545556575859596061626325 unmodified lines45 unmodified lines ], "repository": "git://github.com/visionmedia/express", "license": "MIT", "dependencies": { "buffer-crc32": "0.2.1", "connect": "2.18.0", "commander": "1.3.2", "methods": "1.0.0", "mkdirp": "0.5.0", "parseurl": "1.0.1", "proxy-addr": "1.0.0", "range-parser": "1.0.0", "send": "0.4.0", "cookie": "0.1.2", "buffer-crc32": "0.2.1", "fresh": "0.2.2", "cookie-signature": "1.0.3", "merge-descriptors": "0.0.2", "debug": ">= 0.8.0 < 1"25 unmodified lines