Unverified Commit 97df2bb0 authored by Sukka's avatar Sukka Committed by GitHub

refactor: rewrite etag (#38568)

x-ref: https://github.com/vercel/next.js/issues/38235#issuecomment-1182283358

Rewrite ETag generate function with `fnv1a` hash.

FNV hashes are designed to be fast while maintaining a low collision rate. The FNV speed allows one to quickly hash lots of data while maintaining a reasonable collision rate (https://softwareengineering.stackexchange.com/questions/49550/which-hashing-algorithm-is-best-for-uniqueness-and-speed/145633).

[fastify-etag](https://github.com/fastify/fastify-etag) also uses `fnv1a` algorithm by default.

cc @shuding: Should `experimental-edge` also switch to `fnv1a` for ETag, for consistency?
parent 0610f9ac
(The MIT License)
Copyright (c) 2014-2016 Douglas Christopher Wilson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(()=>{"use strict";var e={602:(e,t,r)=>{
/*!
* etag
* Copyright(c) 2014-2016 Douglas Christopher Wilson
* MIT Licensed
*/
e.exports=etag;var i=r(113);var n=r(147).Stats;var a=Object.prototype.toString;function entitytag(e){if(e.length===0){return'"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'}var t=i.createHash("sha1").update(e,"utf8").digest("base64").substring(0,27);var r=typeof e==="string"?Buffer.byteLength(e,"utf8"):e.length;return'"'+r.toString(16)+"-"+t+'"'}function etag(e,t){if(e==null){throw new TypeError("argument entity is required")}var r=isstats(e);var i=t&&typeof t.weak==="boolean"?t.weak:r;if(!r&&typeof e!=="string"&&!Buffer.isBuffer(e)){throw new TypeError("argument entity must be string, Buffer, or fs.Stats")}var n=r?stattag(e):entitytag(e);return i?"W/"+n:n}function isstats(e){if(typeof n==="function"&&e instanceof n){return true}return e&&typeof e==="object"&&"ctime"in e&&a.call(e.ctime)==="[object Date]"&&"mtime"in e&&a.call(e.mtime)==="[object Date]"&&"ino"in e&&typeof e.ino==="number"&&"size"in e&&typeof e.size==="number"}function stattag(e){var t=e.mtime.getTime().toString(16);var r=e.size.toString(16);return'"'+r+"-"+t+'"'}},113:e=>{e.exports=require("crypto")},147:e=>{e.exports=require("fs")}};var t={};function __nccwpck_require__(r){var i=t[r];if(i!==undefined){return i.exports}var n=t[r]={exports:{}};var a=true;try{e[r](n,n.exports,__nccwpck_require__);a=false}finally{if(a)delete t[r]}return n.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r=__nccwpck_require__(602);module.exports=r})();
\ No newline at end of file
{"name":"etag","main":"index.js","license":"MIT"}
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -145,7 +145,6 @@
"@types/cookie": "0.3.3",
"@types/cross-spawn": "6.0.0",
"@types/debug": "4.1.5",
"@types/etag": "1.8.0",
"@types/fresh": "0.5.0",
"@types/glob": "7.1.1",
"@types/jsonwebtoken": "8.3.7",
......@@ -198,7 +197,6 @@
"devalue": "2.0.1",
"domain-browser": "4.19.0",
"edge-runtime": "1.1.0-beta.11",
"etag": "1.8.1",
"events": "3.3.0",
"find-cache-dir": "3.3.1",
"find-up": "4.1.0",
......
......@@ -12,7 +12,7 @@ import type { PreviewData } from 'next/types'
import bytes from 'next/dist/compiled/bytes'
import jsonwebtoken from 'next/dist/compiled/jsonwebtoken'
import { decryptWithSecret, encryptWithSecret } from '../crypto-utils'
import generateETag from 'next/dist/compiled/etag'
import { generateETag } from '../lib/etag'
import { sendEtagResponse } from '../send-payload'
import { Stream } from 'stream'
import { parse } from 'next/dist/compiled/content-type'
......
......@@ -3,26 +3,3 @@
export function byteLength(payload: string): number {
return new TextEncoder().encode(payload).buffer.byteLength
}
// Calculate the ETag for a payload.
export async function generateETag(payload: string) {
if (payload.length === 0) {
// fast-path empty
return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
}
// compute hash of entity
const hash = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(
await crypto.subtle.digest('SHA-1', new TextEncoder().encode(payload))
) as any
)
).substring(0, 27)
// compute length of entity
const len = byteLength(payload)
return '"' + len.toString(16) + '-' + hash + '"'
}
/**
* FNV-1a Hash implementation
* @author Travis Webb (tjwebb) <me@traviswebb.com>
*
* Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js
*
* Simplified, optimized and add modified for 52 bit, which provides a larger hash space
* and still making use of Javascript's 53-bit integer space.
*/
export const fnv1a52 = (str: string) => {
const len = str.length
let i = 0,
t0 = 0,
v0 = 0x2325,
t1 = 0,
v1 = 0x8422,
t2 = 0,
v2 = 0x9ce4,
t3 = 0,
v3 = 0xcbf2
while (i < len) {
v0 ^= str.charCodeAt(i++)
t0 = v0 * 435
t1 = v1 * 435
t2 = v2 * 435
t3 = v3 * 435
t2 += v0 << 8
t3 += v1 << 8
t1 += t0 >>> 16
v0 = t0 & 65535
t2 += t1 >>> 16
v1 = t1 & 65535
v3 = (t3 + (t2 >>> 16)) & 65535
v2 = t2 & 65535
}
return (
(v3 & 15) * 281474976710656 +
v2 * 4294967296 +
v1 * 65536 +
(v0 ^ (v3 >> 4))
)
}
export const generateETag = (payload: string, weak = false) => {
const prefix = weak ? 'W/"' : '"'
return (
prefix + fnv1a52(payload).toString(36) + payload.length.toString(36) + '"'
)
}
import type { IncomingMessage, ServerResponse } from 'http'
import { isResSent } from '../../shared/lib/utils'
import generateETag from 'next/dist/compiled/etag'
import { generateETag } from '../lib/etag'
import fresh from 'next/dist/compiled/fresh'
import RenderResult from '../render-result'
import { setRevalidateHeaders } from './revalidate-headers'
......
......@@ -9,7 +9,8 @@ import type { Options } from './base-server'
import BaseServer from './base-server'
import { renderToHTML } from './render'
import { byteLength, generateETag } from './api-utils/web'
import { byteLength } from './api-utils/web'
import { generateETag } from './lib/etag'
interface WebServerOptions extends Options {
webServerConfig: {
......@@ -183,7 +184,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
const payload = await options.result.toUnchunkedString()
res.setHeader('Content-Length', String(byteLength(payload)))
if (options.generateEtags) {
res.setHeader('ETag', await generateETag(payload))
res.setHeader('ETag', generateETag(payload))
}
res.body(payload)
}
......
......@@ -479,15 +479,6 @@ export async function ncc_cssnano_simple(task, opts) {
.target('compiled/cssnano-simple')
}
// eslint-disable-next-line camelcase
externals['etag'] = 'next/dist/compiled/etag'
export async function ncc_etag(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('etag')))
.ncc({ packageName: 'etag', externals })
.target('compiled/etag')
}
// eslint-disable-next-line camelcase
externals['p-limit'] = 'next/dist/compiled/p-limit'
export async function ncc_p_limit(task, opts) {
......@@ -1738,7 +1729,6 @@ export async function ncc(task, opts) {
'ncc_watchpack',
'ncc_chalk',
'ncc_napirs_triples',
'ncc_etag',
'ncc_p_limit',
'ncc_raw_body',
'ncc_cssnano_simple',
......
......@@ -46,11 +46,6 @@ declare module 'next/dist/compiled/cssnano-simple' {
export = cssnanoSimple
}
declare module 'next/dist/compiled/etag' {
import m from 'etag'
export = m
}
declare module 'next/dist/compiled/p-limit' {
import m from 'p-limit'
export = m
......
......@@ -444,7 +444,6 @@ importers:
'@types/cookie': 0.3.3
'@types/cross-spawn': 6.0.0
'@types/debug': 4.1.5
'@types/etag': 1.8.0
'@types/fresh': 0.5.0
'@types/glob': 7.1.1
'@types/jsonwebtoken': 8.3.7
......@@ -498,7 +497,6 @@ importers:
devalue: 2.0.1
domain-browser: 4.19.0
edge-runtime: 1.1.0-beta.11
etag: 1.8.1
events: 3.3.0
find-cache-dir: 3.3.1
find-up: 4.1.0
......@@ -637,7 +635,6 @@ importers:
'@types/cookie': 0.3.3
'@types/cross-spawn': 6.0.0
'@types/debug': 4.1.5
'@types/etag': 1.8.0
'@types/fresh': 0.5.0
'@types/glob': 7.1.1
'@types/jsonwebtoken': 8.3.7
......@@ -690,7 +687,6 @@ importers:
devalue: 2.0.1
domain-browser: 4.19.0
edge-runtime: 1.1.0-beta.11
etag: 1.8.1
events: 3.3.0
find-cache-dir: 3.3.1
find-up: 4.1.0
......@@ -5575,12 +5571,6 @@ packages:
resolution: {integrity: sha512-CuPgU6f3eT/XgKKPqKd/gLZV1Xmvf1a2R5POBOGQa6uv82xpls89HU5zKeVoyR8XzHd1RGNOlQlvUe3CFkjWNQ==}
dev: true
/@types/etag/1.8.0:
resolution: {integrity: sha512-EdSN0x+Y0/lBv7YAb8IU4Jgm6DWM+Bqtz7o5qozl96fzaqdqbdfHS5qjdpFeIv7xQ8jSLyjMMNShgYtMajEHyQ==}
dependencies:
'@types/node': 17.0.21
dev: true
/@types/events/3.0.0:
resolution: {integrity: sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g==}
dev: true
......@@ -20971,7 +20961,7 @@ packages:
worker-farm: 1.7.0
dev: true
/terser-webpack-plugin/5.2.4_webpack@5.73.0:
/terser-webpack-plugin/5.2.4:
resolution: {integrity: sha512-E2CkNMN+1cho04YpdANyRrn8CyN4yMy+WdFKZIySFZrGXZxJwJP6PMNGGc/Mcr6qygQHUUqRxnAPmi0M9f00XA==}
engines: {node: '>= 10.13.0'}
peerDependencies:
......@@ -20993,7 +20983,6 @@ packages:
serialize-javascript: 6.0.0
source-map: 0.6.1
terser: 5.14.1
webpack: 5.73.0
dev: true
/terser/4.8.0:
......@@ -21350,7 +21339,7 @@ packages:
typescript: 4.6.3
/tty-browserify/0.0.0:
resolution: {integrity: sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=}
resolution: {integrity: sha512-JVa5ijo+j/sOoHGjw0sxw734b1LhBkQ3bvUGNdxnVXDCX81Yx7TFgnZygxrIIWn23hbfTaMYLwRmAxFyDuFmIw==}
dev: true
/tty-browserify/0.0.1:
......@@ -22058,7 +22047,7 @@ packages:
requiresBuild: true
/util-deprecate/1.0.2:
resolution: {integrity: sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=}
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
dev: true
/util-promisify/2.1.0:
......@@ -22433,7 +22422,7 @@ packages:
neo-async: 2.6.2
schema-utils: 3.1.1
tapable: 2.2.0
terser-webpack-plugin: 5.2.4_webpack@5.73.0
terser-webpack-plugin: 5.2.4
watchpack: 2.4.0
webpack-sources: 3.2.3
transitivePeerDependencies:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment