/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @module bxc/queue/sharded/consistent-hash * * Shard assignment for the sharded frontier. * * A URL is mapped to its shard key (the registrable domain, eTLD+1), the key * to a stable 64-bit hash (xxHash64, seed 0 — a published algorithm, so other * languages compute the same value), and the hash to a shard with Jump * Consistent Hash (Lamping & Veach, "A Fast, Minimal Memory, Consistent Hash * Algorithm", 2014): * * - every URL of a site lands on the same shard, hence on the same worker, so * politeness and domain memory stay local to one process; * - O(ln n) time, no lookup table; * - balanced: each shard receives `1/n` of the keys in expectation; * - monotone: growing from `n` to `n + 1` shards moves only `≈ 1/(n + 1)` of * the keys, and every moved key goes to the new shard. */ import { registrableDomain } from "../../profiles/etld.ts"; const JUMP_MULTIPLIER = 2862933555777941757n; const TWO_POW_31 = 2 ** 31; /** Stable 64-bit hash of a shard key (xxHash64, seed 0). */ export function hash64(key: string): bigint { return BigInt.asUintN(64, Bun.hash.xxHash64(key)); } /** * Jump Consistent Hash: bucket in `[0, buckets)` for a 64-bit key. * Bit-exact port of the reference implementation (64-bit LCG + double * division). */ export function jumpConsistentHash(key: bigint, buckets: number): number { if (!Number.isInteger(buckets) || buckets < 1) { throw new RangeError(`buckets must be a positive integer, got ${buckets}`); } let k = BigInt.asUintN(64, key); let b = -1; let j = 0; while (j < buckets) { b = j; k = BigInt.asUintN(64, k * JUMP_MULTIPLIER + 1n); j = Math.floor((b + 1) * (TWO_POW_31 / Number((k >> 33n) + 1n))); } return b; } /** * Shard key of a URL: its registrable domain (eTLD+1), or the host for IP * literals / single labels. Falls back to the raw string when it is not a URL. */ export function shardKeyOf(url: string): string { try { const key = registrableDomain(url); if (key) return key; } catch { // Not a parsable URL: hash the raw string. } return url; } /** Shard of a shard key. */ export function shardOfKey(key: string, shards: number): number { return jumpConsistentHash(hash64(key), shards); } /** Shard of a URL (`keyFn` defaults to {@link shardKeyOf}). */ export function shardOfUrl( url: string, shards: number, keyFn: (url: string) => string = shardKeyOf, ): number { return shardOfKey(keyFn(url), shards); }