Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

hash.ts

292 lines9.5 KB

1import { MurmurHashStream, getSymbolIdentity, randomHash } from './murmur.js'
2import { isTemporal } from './temporal.js'
3import type { Hasher } from './murmur.js'
4​
5/*
6 * Implementation of structural hashing based on the Composites polyfill implementation:
7 * https://github.com/tc39/proposal-composites
8 */
9​
10const TRUE = randomHash()
11const FALSE = randomHash()
12const NULL = randomHash()
13const UNDEFINED = randomHash()
14const KEY = randomHash()
15const FUNCTIONS = randomHash()
16// Identity is distinct even if two random hash values happen to collide.
17const DATE_MARKER = { hash: randomHash() }
18const REGEXP_MARKER = { hash: randomHash() }
19const OBJECT_MARKER = { hash: randomHash() }
20const ARRAY_MARKER = { hash: randomHash() }
21const MAP_MARKER = { hash: randomHash() }
22const SET_MARKER = { hash: randomHash() }
23const UINT8ARRAY_MARKER = { hash: randomHash() }
24const TEMPORAL_MARKER = { hash: randomHash() }
25// Bound structural recursion and value visits. Shared acyclic subtrees are
26// cached; cycles are rejected rather than given context-dependent hashes.
27const MAX_STRUCTURAL_HASH_WORK = 1_000_000
28const MAX_STRUCTURAL_HASH_DEPTH = 768
29​
30// Maximum byte length for Uint8Arrays to hash by content instead of reference
31// Arrays smaller than this will be hashed by content, allowing proper equality comparisons
32// for small arrays like ULIDs (16 bytes) while still avoiding performance costs for large arrays
33const UINT8ARRAY_CONTENT_HASH_THRESHOLD = 128
34​
35const hashCache = new WeakMap<object, number>()
36const referenceValues = new WeakSet<object>()
37​
38/** @internal Register a mutable handle before it enters a structural value. */
39export function registerOpaqueHash(value: object): void {
40 cachedReferenceHash(value)
42​
43type HashContext = {
44 activeObjects: Set<object>
45 work: number
46 pendingHashes: Map<object, number>
48​
49export function hash(input: any): number {
50 const hasher = new MurmurHashStream()
51 updateHasher(hasher, input)
52 return hasher.digest()
54​
55function hashObject(input: object, context: HashContext): number {
56 if (context.activeObjects.size >= MAX_STRUCTURAL_HASH_DEPTH) {
57 throw new RangeError(
58 `Value is too complex to hash safely: structural depth`,
59 )
60 }
61​
62 context.activeObjects.add(input)
63​
64 let valueHash: number | undefined
65 try {
66 const [marker, header, body] = objectParts(input)
67 const hasher = new MurmurHashStream()
68 hasher.update(marker.hash)
69 // Header values of a type with a body (array length, RegExp fields)
70 // count toward the work cap; Date, binary, and Temporal headers do not.
71 for (const value of header)
72 if (body) updateHasher(hasher, value, context)
73 else hasher.update(value as string | number)
74 if (body) {
75 // Sorted string keys, then enumerable symbol keys by identity.
76 const keys: Array<string | symbol> = Object.keys(body).sort(keySort)
77 keys.push(
78 ...Object.getOwnPropertySymbols(body)
79 .filter((key) =>
80 Object.prototype.propertyIsEnumerable.call(body, key),
81 )
82 .sort(
83 (left, right) => getSymbolIdentity(left) - getSymbolIdentity(right),
84 ),
85 )
86 for (const key of keys) {
87 hasher.update(KEY)
88 hasher.update(key)
89 updateHasher(hasher, body[key as keyof typeof body], context)
90 }
91 }
92 valueHash = hasher.digest()
93 } finally {
94 context.activeObjects.delete(input)
95 }
96​
97 context.pendingHashes.set(input, valueHash)
98 return valueHash
100​
101/**
102 * The one type dispatch shared by structural hashing and equality: a type
103 * marker, primitive header values, and an optional object whose enumerable
104 * own properties are compared structurally.
105 */
106type ObjectParts = [
107 marker: Readonly<{ hash: number }>,
108 // A RegExp `lastIndex` can hold any value; the other headers are strings
109 // or numbers.
110 header: ReadonlyArray<unknown>,
111 body?: object,
113​
114function objectParts(input: object): ObjectParts {
115 if (input instanceof Date) {
116 const time = input.getTime()
117 // Invalid dates are equal to each other; headers compare with `===`.
118 return [DATE_MARKER, [Number.isNaN(time) ? `invalid` : time]]
119 }
120 if (isBinaryValue(input))
121 return [
122 UINT8ARRAY_MARKER,
123 [String.fromCharCode.apply(null, input as unknown as Array<number>)],
124 ]
125 if (isTemporal(input))
126 return [TEMPORAL_MARKER, [input[Symbol.toStringTag], input.toString()]]
127 if (input instanceof RegExp)
128 return [REGEXP_MARKER, [input.source, input.flags, input.lastIndex], input]
129 if (input instanceof Map) return [MAP_MARKER, [], [...input.entries()]]
130 if (input instanceof Set) return [SET_MARKER, [], [...input.values()]]
131 return input instanceof Array
132 ? [ARRAY_MARKER, [input.length], input]
133 : [OBJECT_MARKER, [], input]
135​
136function updateHasher(
137 hasher: Hasher,
138 input: unknown,
139 context?: HashContext,
140): void {
141 if (context && ++context.work > MAX_STRUCTURAL_HASH_WORK) {
142 throw new RangeError(`Value is too complex to hash safely: structural work`)
143 }
144 if (input === null) {
145 hasher.update(NULL)
146 return
147 }
148 switch (typeof input) {
149 case `undefined`:
150 hasher.update(UNDEFINED)
151 return
152 case `boolean`:
153 hasher.update(input ? TRUE : FALSE)
154 return
155 case `number`:
156 // Normalize NaNs and -0
157 hasher.update(isNaN(input) ? NaN : input === 0 ? 0 : input)
158 return
159 case `bigint`:
160 case `string`:
161 case `symbol`:
162 hasher.update(input)
163 return
164 case `object`:
165 hasher.update(getCachedHash(input, context))
166 return
167 case `function`:
168 // Functions are assigned a globally unique ID
169 // and that ID is cached in the weak map
170 hasher.update(cachedReferenceHash(input))
171 }
173​
174function getCachedHash(input: object, context?: HashContext): number {
175 // Active objects are neither cached nor pending, so the cycle check below
176 // still sees every back-reference.
177 const cached = hashCache.get(input) ?? context?.pendingHashes.get(input)
178 if (cached !== undefined) return cached
179​
180 // Opaque leaves cannot contain structural back-references. Resolve them
181 // before entering structural recursion, even when they have user properties.
182 if (isReferenceHashedObject(input)) return cachedReferenceHash(input)
183​
184 if (context) {
185 if (context.activeObjects.has(input)) {
186 throw new TypeError(`Cannot hash cyclic structural values`)
187 }
188 return hashObject(input, context)
189 }
190​
191 // Only an uncached structural root needs graph traversal state. Commit its
192 // cache entries after success so a failed traversal cannot poison retries.
193 const root: HashContext = {
194 activeObjects: new Set(),
195 work: 0,
196 pendingHashes: new Map(),
197 }
198 const result = hashObject(input, root)
199 for (const [object, valueHash] of root.pendingHashes) {
200 hashCache.set(object, valueHash)
201 }
202 return result
204​
205function isReferenceHashedObject(input: object): boolean {
206 return (
207 referenceValues.has(input) ||
208 (typeof File !== `undefined` && input instanceof File) ||
209 (isBinaryValue(input) &&
210 input.byteLength > UINT8ARRAY_CONTENT_HASH_THRESHOLD)
211 )
213​
214// Buffer can come from another realm than Uint8Array (for example under jsdom).
215function isBinaryValue(input: object): input is Uint8Array {
216 return (
217 (typeof Buffer !== `undefined` && input instanceof Buffer) ||
218 input instanceof Uint8Array
219 )
221​
222/** @internal Compare immutable structural values without computing a digest.
223 * Pair memoization also permits cyclic values that structural hashing rejects.
224 * Reference-valued leaves remain opaque, including registered mutable handles.
225 */
226export function equalHashValues(left: unknown, right: unknown): boolean {
227 const compared = new Map<object, Set<object>>()
228 const keys = (value: object) =>
229 Reflect.ownKeys(value).filter((key) =>
230 Object.prototype.propertyIsEnumerable.call(value, key),
231 )
232 function equal(a: unknown, b: unknown): boolean {
233 if (a === b || (Number.isNaN(a) && Number.isNaN(b))) return true
234 if (
235 a === null ||
236 b === null ||
237 typeof a !== `object` ||
238 typeof b !== `object` ||
239 isReferenceHashedObject(a) ||
240 isReferenceHashedObject(b)
241 )
242 return false
243 // Arrays from another realm take the object marker but keep this check.
244 if (Array.isArray(a) && Array.isArray(b) && a.length !== b.length)
245 return false
246​
247 // Revisited pairs close cycles and avoid expanding shared subtrees. Check
248 // before objectParts copies Map or Set entries; record only pairs with a
249 // body, after their markers and headers match.
250 const peers = compared.get(a)
251 if (peers?.has(b)) return true
252 const [aMarker, aHeader, aBody] = objectParts(a)
253 const [bMarker, bHeader, bBody] = objectParts(b)
254 if (
255 aMarker !== bMarker ||
256 !aHeader.every((value, index) => value === bHeader[index])
257 )
258 return false
259 if (!aBody || !bBody) return true
260 if (peers) peers.add(b)
261 else compared.set(a, new Set([b]))
262 const aKeys = keys(aBody)
263 return (
264 aKeys.length === keys(bBody).length &&
265 aKeys.every(
266 (key) =>
267 Object.prototype.propertyIsEnumerable.call(bBody, key) &&
268 equal(aBody[key as keyof object], bBody[key as keyof object]),
269 )
270 )
271 }
272 return equal(left, right)
274​
275let nextRefId = 1
276function cachedReferenceHash(fn: object): number {
277 let valueHash = hashCache.get(fn)
278 if (valueHash === undefined) {
279 valueHash = nextRefId ^ FUNCTIONS
280 nextRefId++
281 hashCache.set(fn, valueHash)
282 referenceValues.add(fn)
283 }
284 return valueHash
286​
287/**
288 * Strings sorted lexicographically.
289 */
290function keySort(a: string, b: string): number {
291 return a.localeCompare(b)