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

hash.ts

367 lines10.8 KB

1import { MurmurHashStream, getSymbolIdentity, randomHash } from './murmur.js'
2import type { Hasher } from './murmur.js'
3​
4/*
5 * Implementation of structural hashing based on the Composites polyfill implementation:
6 * https://github.com/tc39/proposal-composites
7 */
8​
9const TRUE = randomHash()
10const FALSE = randomHash()
11const NULL = randomHash()
12const UNDEFINED = randomHash()
13const KEY = randomHash()
14const FUNCTIONS = randomHash()
15const DATE_MARKER = randomHash()
16const REGEXP_MARKER = randomHash()
17const STRUCTURAL_MARKERS = {
18 object: randomHash(),
19 array: randomHash(),
20 map: randomHash(),
21 set: randomHash(),
23const UINT8ARRAY_MARKER = randomHash()
24const TEMPORAL_MARKER = 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​
30const temporalTypes = new Set([
31 `Temporal.Duration`,
32 `Temporal.Instant`,
33 `Temporal.PlainDate`,
34 `Temporal.PlainDateTime`,
35 `Temporal.PlainMonthDay`,
36 `Temporal.PlainTime`,
37 `Temporal.PlainYearMonth`,
38 `Temporal.ZonedDateTime`,
39])
40​
41interface TemporalLike {
42 [Symbol.toStringTag]: string
43 toString: () => string
45​
46function isTemporal(input: object): input is TemporalLike {
47 const tag = (input as Record<symbol, unknown>)[Symbol.toStringTag]
48 return typeof tag === `string` && temporalTypes.has(tag)
50​
51// Maximum byte length for Uint8Arrays to hash by content instead of reference
52// Arrays smaller than this will be hashed by content, allowing proper equality comparisons
53// for small arrays like ULIDs (16 bytes) while still avoiding performance costs for large arrays
54const UINT8ARRAY_CONTENT_HASH_THRESHOLD = 128
55​
56const hashCache = new WeakMap<object, number>()
57const referenceValues = new WeakSet<object>()
58​
59/** @internal Register a mutable handle before it enters a structural value. */
60export function registerOpaqueHash(value: object): void {
61 cachedReferenceHash(value)
63​
64type HashContext = {
65 activeObjects: Set<object>
66 work: number
67 pendingHashes: Map<object, number>
69​
70export function hash(input: any): number {
71 const hasher = new MurmurHashStream()
72 updateHasher(hasher, input)
73 return hasher.digest()
75​
76function hashObject(input: object, context: HashContext): number {
77 if (context.activeObjects.size >= MAX_STRUCTURAL_HASH_DEPTH) {
78 throw new RangeError(
79 `Value is too complex to hash safely: structural depth`,
80 )
81 }
82​
83 context.activeObjects.add(input)
84​
85 let valueHash: number | undefined
86 try {
87 if (input instanceof Date) {
88 valueHash = hashDate(input)
89 } else if (isBinaryValue(input)) {
90 valueHash = hashUint8Array(input)
91 } else if (isTemporal(input)) {
92 valueHash = hashTemporal(input)
93 } else if (input instanceof RegExp) {
94 valueHash = hashPlainObject(input, REGEXP_MARKER, context, [
95 input.source,
96 input.flags,
97 input.lastIndex,
98 ])
99 } else {
100 const [kind, plainObjectInput] = structuralShape(input)
101 valueHash = hashPlainObject(
102 plainObjectInput,
103 STRUCTURAL_MARKERS[kind],
104 context,
105 kind === `array` ? [input instanceof Array ? input.length : 0] : [],
106 )
107 }
108 } finally {
109 context.activeObjects.delete(input)
110 }
111​
112 context.pendingHashes.set(input, valueHash)
113 return valueHash
115​
116function hashDate(input: Date): number {
117 const hasher = new MurmurHashStream()
118 hasher.update(DATE_MARKER)
119 hasher.update(input.getTime())
120 return hasher.digest()
122​
123function hashUint8Array(input: Uint8Array): number {
124 const hasher = new MurmurHashStream()
125 hasher.update(UINT8ARRAY_MARKER)
126 // Hash the byte length first to differentiate arrays of different sizes
127 hasher.update(input.byteLength)
128 // Hash each byte in the array
129 for (let i = 0; i < input.byteLength; i++) {
130 hasher.writeByte(input[i]!)
131 }
132 return hasher.digest()
134​
135function hashTemporal(input: TemporalLike): number {
136 const hasher = new MurmurHashStream()
137 hasher.update(TEMPORAL_MARKER)
138 hasher.update(input[Symbol.toStringTag])
139 hasher.update(input.toString())
140 return hasher.digest()
142​
143function hashPlainObject(
144 input: object,
145 marker: number,
146 context: HashContext,
147 headerValues: ReadonlyArray<unknown> = [],
148): number {
149 const hasher = new MurmurHashStream()
150​
151 // Mark the type of the input
152 hasher.update(marker)
153 for (const value of headerValues) updateHasher(hasher, value, context)
154 const keys = Object.keys(input)
155 keys.sort(keySort)
156 for (const key of keys) {
157 hasher.update(KEY)
158 hasher.update(key)
159 updateHasher(hasher, input[key as keyof typeof input], context)
160 }
161 const symbolKeys = Object.getOwnPropertySymbols(input)
162 .filter((key) => Object.prototype.propertyIsEnumerable.call(input, key))
163 .sort((left, right) => getSymbolIdentity(left) - getSymbolIdentity(right))
164 for (const key of symbolKeys) {
165 hasher.update(KEY)
166 hasher.update(key)
167 updateHasher(hasher, input[key as keyof typeof input], context)
168 }
169​
170 return hasher.digest()
172​
173function updateHasher(
174 hasher: Hasher,
175 input: unknown,
176 context?: HashContext,
177): void {
178 if (context && ++context.work > MAX_STRUCTURAL_HASH_WORK) {
179 throw new RangeError(`Value is too complex to hash safely: structural work`)
180 }
181 if (input === null) {
182 hasher.update(NULL)
183 return
184 }
185 switch (typeof input) {
186 case `undefined`:
187 hasher.update(UNDEFINED)
188 return
189 case `boolean`:
190 hasher.update(input ? TRUE : FALSE)
191 return
192 case `number`:
193 // Normalize NaNs and -0
194 hasher.update(isNaN(input) ? NaN : input === 0 ? 0 : input)
195 return
196 case `bigint`:
197 case `string`:
198 case `symbol`:
199 hasher.update(input)
200 return
201 case `object`:
202 hasher.update(getCachedHash(input, context))
203 return
204 case `function`:
205 // Functions are assigned a globally unique ID
206 // and that ID is cached in the weak map
207 hasher.update(cachedReferenceHash(input))
208 return
209 default:
210 console.warn(
211 `Ignored input during hashing because it is of type ${typeof input} which is not supported`,
212 )
213 }
215​
216function getCachedHash(input: object, context?: HashContext): number {
217 if (!context) {
218 const cached = hashCache.get(input)
219 if (cached !== undefined) return cached
220 if (isReferenceHashedObject(input)) return cachedReferenceHash(input)
221​
222 // Only an uncached structural root needs graph traversal state. Commit its
223 // cache entries after success so a failed traversal cannot poison retries.
224 context = {
225 activeObjects: new Set(),
226 work: 0,
227 pendingHashes: new Map(),
228 }
229 const result = hashObject(input, context)
230 for (const [object, valueHash] of context.pendingHashes) {
231 hashCache.set(object, valueHash)
232 }
233 return result
234 }
235​
236 if (context.activeObjects.has(input)) {
237 throw new TypeError(`Cannot hash cyclic structural values`)
238 }
239​
240 // Opaque leaves cannot contain structural back-references. Resolve them
241 // before entering structural recursion, even when they have user properties.
242 if (isReferenceHashedObject(input)) return cachedReferenceHash(input)
243​
244 const valueHash = hashCache.get(input) ?? context.pendingHashes.get(input)
245 if (valueHash !== undefined) return valueHash
246​
247 return hashObject(input, context)
249​
250function isReferenceHashedObject(input: object): boolean {
251 return (
252 (typeof File !== `undefined` && input instanceof File) ||
253 (isBinaryValue(input) &&
254 input.byteLength > UINT8ARRAY_CONTENT_HASH_THRESHOLD)
255 )
257​
258function isBinaryValue(input: object): input is Uint8Array {
259 return (
260 (typeof Buffer !== `undefined` && input instanceof Buffer) ||
261 input instanceof Uint8Array
262 )
264​
265function structuralShape(
266 input: object,
267): [keyof typeof STRUCTURAL_MARKERS, object] {
268 if (input instanceof Map) return [`map`, [...input.entries()]]
269 if (input instanceof Set) return [`set`, [...input.values()]]
270 return [input instanceof Array ? `array` : `object`, input]
272​
273/** @internal Compare immutable structural values without computing a digest.
274 * Pair memoization also permits cyclic values that structural hashing rejects.
275 * Reference-valued leaves remain opaque, including registered mutable handles.
276 */
277export function equalHashValues(left: unknown, right: unknown): boolean {
278 const compared = new Map<object, Set<object>>()
279 function equal(a: unknown, b: unknown): boolean {
280 if (a === b || (Number.isNaN(a) && Number.isNaN(b))) return true
281 if (
282 a === null ||
283 b === null ||
284 typeof a !== `object` ||
285 typeof b !== `object`
286 )
287 return false
288 if (
289 referenceValues.has(a) ||
290 referenceValues.has(b) ||
291 isReferenceHashedObject(a) ||
292 isReferenceHashedObject(b)
293 )
294 return false
295 if (a instanceof Date || b instanceof Date)
296 return (
297 a instanceof Date &&
298 b instanceof Date &&
299 equal(a.getTime(), b.getTime())
300 )
301 if (isBinaryValue(a) || isBinaryValue(b))
302 return (
303 isBinaryValue(a) &&
304 isBinaryValue(b) &&
305 a.byteLength === b.byteLength &&
306 a.every((value, index) => value === b[index])
307 )
308 if (isTemporal(a) || isTemporal(b))
309 return (
310 isTemporal(a) &&
311 isTemporal(b) &&
312 a[Symbol.toStringTag] === b[Symbol.toStringTag] &&
313 a.toString() === b.toString()
314 )
315 if (a instanceof RegExp || b instanceof RegExp) {
316 if (
317 !(a instanceof RegExp && b instanceof RegExp) ||
318 a.source !== b.source ||
319 a.flags !== b.flags ||
320 a.lastIndex !== b.lastIndex
321 )
322 return false
323 }
324 if (Array.isArray(a) && Array.isArray(b) && a.length !== b.length)
325 return false
326​
327 // Revisited pairs close cycles and avoid expanding shared subtrees.
328 const peers = compared.get(a)
329 if (peers?.has(b)) return true
330 if (peers) peers.add(b)
331 else compared.set(a, new Set([b]))
332 const [aKind, aShape] = structuralShape(a)
333 const [bKind, bShape] = structuralShape(b)
334 if (aKind !== bKind) return false
335 const keys = (value: object) =>
336 Reflect.ownKeys(value).filter((key) =>
337 Object.prototype.propertyIsEnumerable.call(value, key),
338 )
339 const aKeys = keys(aShape)
340 if (aKeys.length !== keys(bShape).length) return false
341 return aKeys.every(
342 (key) =>
343 Object.prototype.propertyIsEnumerable.call(bShape, key) &&
344 equal(aShape[key as keyof object], bShape[key as keyof object]),
345 )
346 }
347 return equal(left, right)
349​
350let nextRefId = 1
351function cachedReferenceHash(fn: object): number {
352 let valueHash = hashCache.get(fn)
353 if (valueHash === undefined) {
354 valueHash = nextRefId ^ FUNCTIONS
355 nextRefId++
356 hashCache.set(fn, valueHash)
357 referenceValues.add(fn)
358 }
359 return valueHash
361​
362/**
363 * Strings sorted lexicographically.
364 */
365function keySort(a: string, b: string): number {
366 return a.localeCompare(b)