Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for brotli compression #3198

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -2310,8 +2310,8 @@ following options:
clean up the files generated by the framework. This can be done by keeping track
of which files are used (e.g. using the `request.app` object), and listening to
the server `'response'` event to perform any needed cleanup.
- `parse` - can be `true`, `false`, or `gunzip`; determines if the incoming payload is
processed or presented raw. `true` and `gunzip` includes gunzipping when the appropriate
- `parse` - can be `true`, `false`, `gunzip`, or `br`; determines if the incoming payload is
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

below where we describe that true and gunzip will gunzip as appropriate, you should also mention that br is for brotli support. also why abbreviate it? brotli is plenty short IMO

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nlf it seems that this will be added as a plugin but in any case I updated the API doc (not sure if the added text is the best / most comprehensible though).

Regarding the use of br (instead of brotli), it is the naming scheme that it is being used: google/brotli#299

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fair enough, silly decision on their part IMO, but if it's an established thing then we should probably stick with it

processed or presented raw. `true` and `gunzip` includes gunzipping and `br` supports `brotli` when the appropriate
'Content-Encoding' is specified on the received request. If parsing is enabled and the
'Content-Type' is known (for the whole payload as well as parts), the payload is
converted into an object when possible. If the format is unknown, a Bad Request (400)
Expand Down Expand Up @@ -3164,7 +3164,7 @@ The response object provides the following methods:
- `weak` - if `true`, the tag will be prefixed with the `'W/'` weak signifier. Weak tags
will fail to match identical tags for the purpose of determining 304 response status.
Defaults to `false`.
- `vary` - if `true` and content encoding is set or applied to the response (e.g 'gzip' or
- `vary` - if `true` and content encoding is set or applied to the response (e.g 'gzip', 'br' or
'deflate'), the encoding name will be automatically added to the tag at transmission time
(separated by a `'-'` character). Ignored when `weak` is `true`. Defaults to `true`.
- `header(name, value, options)` - sets an HTTP header where:
Expand Down
2 changes: 1 addition & 1 deletion lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ internals.Request = function (connection, req, res, options) {
remotePort: req.connection.remotePort || '',
referrer: req.headers.referrer || req.headers.referer || '',
host: req.headers.host ? req.headers.host.replace(/\s/g, '') : '',
acceptEncoding: Accept.encoding(this.headers['accept-encoding'], ['identity', 'gzip', 'deflate'])
acceptEncoding: Accept.encoding(this.headers['accept-encoding'], ['identity', 'br', 'gzip', 'deflate'])
};

this.info.hostname = this.info.host.split(':')[0];
Expand Down
2 changes: 1 addition & 1 deletion lib/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ internals.routeBase = Joi.object({
jsonp: Joi.string(),
payload: Joi.object({
output: Joi.string().valid('data', 'stream', 'file'),
parse: Joi.boolean().allow('gunzip'),
parse: Joi.boolean().allow('gunzip', 'br'),
allow: [
Joi.string(),
Joi.array()
Expand Down
8 changes: 4 additions & 4 deletions lib/transmit.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const Shot = require('shot');
const Auth = require('./auth');
const Cors = require('./cors');
const Response = require('./response');

const compressStream = require('iltorb').compressStream;

// Declare internals

Expand Down Expand Up @@ -65,7 +65,8 @@ internals.marshal = function (request, next) {
else if (response.settings.varyEtag) {
const etagBase = response.headers.etag.slice(0, -1);
if (etag === etagBase + '-gzip"' ||
etag === etagBase + '-deflate"') {
etag === etagBase + '-deflate"' ||
etag === etagBase + '-br"') {

response.code(304);
break;
Expand Down Expand Up @@ -263,8 +264,7 @@ internals.transmit = function (response, callback) {

delete response.headers['content-length'];
response._header('content-encoding', encoding);

compressor = (encoding === 'gzip' ? Zlib.createGzip() : Zlib.createDeflate());
compressor = (encoding === 'gzip' ? Zlib.createGzip() : (encoding === 'br' ? compressStream() : Zlib.createDeflate()));
}

if ((response.headers['content-encoding'] || encoding) &&
Expand Down
3 changes: 2 additions & 1 deletion package.json
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@
},
"dependencies": {
"accept": "2.x.x",
"ammo": "2.x.x",
"ammo": "2.x.x",
"boom": "3.x.x",
"call": "3.x.x",
"catbox": "7.x.x",
"catbox-memory": "2.x.x",
"cryptiles": "3.x.x",
"heavy": "4.x.x",
"hoek": "4.x.x",
"iltorb": "^1.0.9",
"iron": "4.x.x",
"items": "2.x.x",
"joi": "8.x.x",
Expand Down
Binary file added test/file/image.png.br
Binary file not shown.
68 changes: 66 additions & 2 deletions test/payload.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const Hapi = require('..');
const Hoek = require('hoek');
const Lab = require('lab');
const Wreck = require('wreck');

const compress = require('iltorb').compress;

// Declare internals

Expand Down Expand Up @@ -266,7 +266,43 @@ describe('payload', () => {
});
});

it('saves a file after content decoding', (done) => {
it('handles br payload', (done) => {

const handler = function (request, reply) {

return reply(request.payload);
};

const message = { 'msg': 'This message is going to be compressed using br.' };
const server = new Hapi.Server();
server.connection();
server.route({ method: 'POST', path: '/', handler: handler });

compress(new Buffer(JSON.stringify(message)), (err, buf) => {

expect(err).to.not.exist();

const request = {
method: 'POST',
url: '/',
headers: {
'content-type': 'application/json',
'content-encoding': 'br',
'content-length': buf.length
},
payload: buf
};

server.inject(request, (res) => {

expect(res.result).to.exist();
expect(res.result).to.equal(message);
done();
});
});
});

it('saves a file after content decoding (gzipped)', (done) => {

const path = Path.join(__dirname, './file/image.jpg');
const sourceContents = Fs.readFileSync(path);
Expand Down Expand Up @@ -294,6 +330,34 @@ describe('payload', () => {
});
});

it('saves a file after content decoding (br)', (done) => {

const path = Path.join(__dirname, './file/image.jpg');
const sourceContents = Fs.readFileSync(path);
const stats = Fs.statSync(path);

const handler = function (request, reply) {

const receivedContents = Fs.readFileSync(request.payload.path);
Fs.unlinkSync(request.payload.path);
expect(receivedContents).to.equal(sourceContents);
return reply(request.payload.bytes);
};

compress(sourceContents, (err, compressed) => {

expect(err).to.not.exist();
const server = new Hapi.Server();
server.connection();
server.route({ method: 'POST', path: '/file', config: { handler: handler, payload: { output: 'file' } } });
server.inject({ method: 'POST', url: '/file', payload: compressed, headers: { 'content-encoding': 'br' } }, (res) => {

expect(res.result).to.equal(stats.size);
done();
});
});
});

it('errors saving a file without parse', (done) => {

const handler = function (request, reply) { };
Expand Down
44 changes: 44 additions & 0 deletions test/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,30 @@ describe('Response', () => {
});
});

it('leaves etag header when varyEtag is false (br)', (done) => {

const handler = function (request, reply) {

return reply('ok').etag('abc', { vary: false }).vary('x');
};

const server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', (res1) => {

expect(res1.statusCode).to.equal(200);
expect(res1.headers.etag).to.equal('"abc"');

server.inject({ url: '/', headers: { 'if-none-match': '"abc-br"', 'accept-encoding': 'br' } }, (res2) => {

expect(res2.statusCode).to.equal(200);
expect(res2.headers.etag).to.equal('"abc"');
done();
});
});
});

it('applies varyEtag when returning 304 due to if-modified-since match', (done) => {

const mdate = new Date().toUTCString();
Expand All @@ -577,6 +601,26 @@ describe('Response', () => {
done();
});
});

it('applies varyEtag when returning 304 due to if-modified-since match (br)', (done) => {

const mdate = new Date().toUTCString();

const handler = function (request, reply) {

return reply('ok').etag('abc').header('last-modified', mdate);
};

const server = new Hapi.Server();
server.connection();
server.route({ method: 'GET', path: '/', handler: handler });
server.inject({ url: '/', headers: { 'if-modified-since': mdate, 'accept-encoding': 'br' } }, (res) => {

expect(res.statusCode).to.equal(304);
expect(res.headers.etag).to.equal('"abc-br"');
done();
});
});
});

describe('passThrough()', () => {
Expand Down
Loading