From d2925da4d4f809b6466f29ea14f582d25a6137c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jacob=20Gro=C3=9F?= Date: Mon, 13 Feb 2023 12:18:28 +0100 Subject: [PATCH] chore: make sha1 the default algo (#98) * chore: make sha1 the default algo * re-mention fnv1a * update default test * fix typo * make linter happy --- README.md | 18 ++++++++++-------- index.js | 4 ++-- test/basic.test.js | 4 ++-- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index e27ab7f..535a9fb 100644 --- a/README.md +++ b/README.md @@ -41,22 +41,24 @@ app.listen(3000) ## Plugin Options -* `algorithm`: all hashing algorithm that Node.js support, and - `'fnv1a'`. Default: `'fnv1a'`. +* `algorithm`: all hashing algorithms the Node.js [`crypto`](https://nodejs.org/api/crypto.html) module supports, and `'fnv1a'. Default: `'sha1'`. * `weak`: generates weak ETags by default. Default: `false`. ## Acknowledgements -The fnv1a logic was forked from https://github.com/sindresorhus/fnv1a -and adapted to support buffers. +The fnv1a logic was forked from https://github.com/sindresorhus/fnv1a and adapted to support buffers. ## Benchmarks -* `md5` algorithm: 29679 req/s (median) -* `sha1` algorithm: 25935 req/s (median) -* `fnv1a` algorithm: 42943 req/s (median) -* No ETag generation: 45471 req/s (median) +Generating an etag will always be slower than not generating an etag. The generation speed also depends on the payload size and type (buffer or string): + +* For very small payloads (< 2 kb), use `'fnv1a'` +* For buffers above 2 mb, use `'md5'` +* In all other scenarios, use `'sha1'` (default) +* YMMV, see [this issue](https://github.com/fastify/fastify-etag/issues/91) where other algorithms such as crc32 for small payloads and murmurhash3-wasm for big buffers have performed better than the mentioned recommendations +* Any etag generation results in at least 10% less op/s (up to 50% less op/s for huge payloads) + ## License diff --git a/index.js b/index.js index 968c27e..de31182 100644 --- a/index.js +++ b/index.js @@ -17,7 +17,7 @@ function validateAlgorithm (algorithm) { } } -function buildHashFn (algorithm = 'fnv1a', weak = false) { +function buildHashFn (algorithm = 'sha1', weak = false) { validateAlgorithm(algorithm) const prefix = weak ? 'W/"' : '"' @@ -26,7 +26,7 @@ function buildHashFn (algorithm = 'fnv1a', weak = false) { } return (payload) => prefix + createHash(algorithm) - .update(payload).digest().toString('base64') + '"' + .update(payload).digest('base64') + '"' } async function fastifyEtag (app, opts) { diff --git a/test/basic.test.js b/test/basic.test.js index 79356c8..085ff25 100644 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -36,8 +36,8 @@ test('weak fnv1a', async (t) => { }) }) -test('default -> fnv1a', async (t) => { +test('default -> sha1', async (t) => { generic(t, {}, (body) => { - return '"' + fnv1a(body).toString(36) + '"' + return '"' + createHash('sha1').update(body).digest().toString('base64') + '"' }) })