/** * 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/RedisFrontier * * Cluster coordination for the crawl frontier (PLAN.md Phase 3.1). * * Model: * - The URL space is split into `N` shards by Jump Consistent Hash of the * registrable domain (`consistent-hash.ts`): a site always lives on one * shard, so politeness and domain memory stay local to one worker. * - Each shard is a Redis stream `bxc:{name}:shard:` consumed by the * consumer group `workers`. Ownership is a lease `bxc:{name}:lease:` * (`SET NX PX`, renewed by the heartbeat, compare-and-delete on leave). * - A worker owns a *target* number of shards computed by water-filling the * `N` shards over the live workers and their `maxShards` caps; workers above * target release shards, workers below target acquire free ones. A crashed * worker's leases and registry entry expire together, after which survivors * acquire its shards and reclaim its pending stream entries (`XAUTOCLAIM`). * - Stream entries are fed into the worker's local `RequestQueue` and then * acknowledged and deleted (`XACK` + `XDEL`): at-least-once delivery, * duplicates suppressed by the local queue's unique keys. Exactly-once * *persistence* comes from the index's idempotent upsert on content hash. * - Cross-shard submissions go through a shared partitioned Bloom seen-set * (`seen-set.ts`); the seen-set update and the `XADD` run in one atomic * Lua script, so a URL is never marked seen without being queued. * * Every key of a frontier shares the `{name}` hash tag, so the multi-key Lua * scripts are also valid on Redis Cluster. * * @example * ```ts * const frontier = await ShardedFrontier.join({ name: "web", shards: 16 }); * const crawler = new MassiveCrawler({ * requestQueue: frontier.queue, * routeLink: (url, opts) => frontier.route(url, opts), * }); * await frontier.submit(["https://example.com/"]); * void crawler.run(); * // ... * crawler.stop(); * await frontier.leave(); * ``` */ import type { RedisClient } from "bun"; import { hostname } from "node:os"; import { registrableDomain } from "../../profiles/etld.ts"; import { stripQueryFamilyKey } from "../frontier/scoring.ts"; import { RequestQueue } from "../RequestQueue.ts"; import { shardKeyOf, shardOfKey } from "./consistent-hash.ts"; import { type BloomParams, bloomOffsets, estimatedFalsePositiveRate, RedisSeenSet, type SeenSetOptions, } from "./seen-set.ts"; import { frontierPrefix, isBusyGroupError, openRedis, RedisScript, resolveRedisUrl, toInt, } from "./redis.ts"; /** Consumer group shared by every worker of a frontier. */ export const CONSUMER_GROUP = "workers"; const DEFAULT_SHARDS = 16; const DEFAULT_LEASE_MS = 15_000; const SUBMIT_BATCH = 500; const CLAIM_COUNT = 256; const SHARD_CACHE_LIMIT = 100_000; // --------------------------------------------------------------------------- // Lua scripts // --------------------------------------------------------------------------- /** * Heartbeat: expire dead workers, register this one with its cap, renew the * owned leases whose value is still our token. * KEYS: workers zset, caps hash, owned lease keys… * ARGV: workerId, token, leaseMs, cap (-1 = unlimited) * Returns { live worker ids, their caps, renewed flags }. */ const HEARTBEAT = new RedisScript(` local t = redis.call('TIME') local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000) local ttl = tonumber(ARGV[3]) local dead = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now) if #dead > 0 then redis.call('ZREM', KEYS[1], unpack(dead)) redis.call('HDEL', KEYS[2], unpack(dead)) end redis.call('ZADD', KEYS[1], now + ttl, ARGV[1]) redis.call('HSET', KEYS[2], ARGV[1], ARGV[4]) local renewed = {} for i = 3, #KEYS do if redis.call('GET', KEYS[i]) == ARGV[2] then redis.call('PEXPIRE', KEYS[i], ttl) renewed[#renewed + 1] = 1 else renewed[#renewed + 1] = 0 end end local live = redis.call('ZRANGE', KEYS[1], 0, -1) local caps = redis.call('HMGET', KEYS[2], unpack(live)) return { live, caps, renewed } `); /** * Acquire up to ARGV[3] free leases among KEYS (in order). * ARGV: token, leaseMs, want. Returns 1-based indexes of acquired keys. */ const ACQUIRE = new RedisScript(` local want = tonumber(ARGV[3]) local out = {} for i = 1, #KEYS do if #out >= want then break end if redis.call('SET', KEYS[i], ARGV[1], 'NX', 'PX', ARGV[2]) then out[#out + 1] = i elseif redis.call('GET', KEYS[i]) == ARGV[1] then redis.call('PEXPIRE', KEYS[i], ARGV[2]) out[#out + 1] = i end end return out `); /** Compare-and-delete leases. ARGV: token. Returns 1-based indexes released. */ const RELEASE = new RedisScript(` local out = {} for i = 1, #KEYS do if redis.call('GET', KEYS[i]) == ARGV[1] then redis.call('DEL', KEYS[i]) out[#out + 1] = i end end return out `); /** Acknowledge and delete entries. KEYS: stream. ARGV: group, ids… */ const ACK_DELETE = new RedisScript(` if #ARGV < 2 then return 0 end local ids = {} for i = 2, #ARGV do ids[#ids + 1] = ARGV[i] end redis.call('XACK', KEYS[1], ARGV[1], unpack(ids)) return redis.call('XDEL', KEYS[1], unpack(ids)) `); /** * Put entries read for a shard this worker no longer owns back at the tail * of the stream, then acknowledge and delete the originals. * KEYS: stream. ARGV: group, then per entry: id, field count, fields… */ const REQUEUE = new RedisScript(` local pos = 2 local n = 0 while pos <= #ARGV do local id = ARGV[pos] local nf = tonumber(ARGV[pos + 1]) if nf > 0 then local fields = {} for f = 1, nf do fields[f] = ARGV[pos + 1 + f] end redis.call('XADD', KEYS[1], '*', unpack(fields)) end redis.call('XACK', KEYS[1], ARGV[1], id) redis.call('XDEL', KEYS[1], id) pos = pos + 2 + nf n = n + 1 end return n `); /** * Atomic seen-set update + enqueue. * KEYS: k seen partitions, seen counter, stream keys… * ARGV: k, force (1/0), then per item: stream index (1-based among the stream * keys), k bit offsets, field count, fields… * Returns 1 per item when it was queued. */ const SUBMIT = new RedisScript(` local k = tonumber(ARGV[1]) local force = ARGV[2] == '1' local pos = 3 local out = {} local added = 0 while pos <= #ARGV do local stream = KEYS[k + 1 + tonumber(ARGV[pos])] pos = pos + 1 local fresh = 0 for i = 1, k do if redis.call('SETBIT', KEYS[i], ARGV[pos + i - 1], 1) == 0 then fresh = 1 end end pos = pos + k added = added + fresh local nf = tonumber(ARGV[pos]) pos = pos + 1 if fresh == 1 or force then local fields = {} for f = 1, nf do fields[f] = ARGV[pos + f - 1] end redis.call('XADD', stream, '*', unpack(fields)) out[#out + 1] = 1 else out[#out + 1] = 0 end pos = pos + nf end if added > 0 then redis.call('INCRBY', KEYS[k + 1], added) end return out `); /** Live workers. KEYS: workers zset. */ const LIVE_WORKERS = new RedisScript(` local t = redis.call('TIME') local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000) return redis.call('ZRANGEBYSCORE', KEYS[1], now, '+inf') `); // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- /** A URL submitted to the cluster. */ export interface SubmitItem { url: string; depth?: number; anchorText?: string; boost?: number; userData?: Record; } export interface SubmitOptions { /** Queue even when the seen-set already knows the URL (re-seeding). */ force?: boolean; } export interface SubmitResult { /** URLs appended to a shard stream. */ queued: number; /** URLs suppressed by the seen-set (or repeated in the batch). */ duplicates: number; /** Queued URLs per shard. */ byShard: Record; } export interface RouteOptions { depth?: number; anchorText?: string; parent?: string; boost?: number; } export interface ShardedFrontierConnectOptions { /** Redis URL. Default: `BXC_REDIS_URL`, `REDIS_URL`, `redis://127.0.0.1:6379`. */ redisUrl?: string; /** Frontier name (`[A-Za-z0-9._:-]`). */ name: string; /** * Shard count. Fixed when the frontier is created; a different explicit * value later is an error. Default: the stored value, else 16. */ shards?: number; /** Shard key of a URL. Default: registrable domain (eTLD+1). */ shardKeyFn?: (url: string) => string; /** Seen-set sizing, used when the frontier is created (default 50 M items, 1 %). */ seenSet?: SeenSetOptions; log?: (msg: string) => void; } export interface ShardedFrontierJoinOptions extends ShardedFrontierConnectOptions { /** Stable, unique worker id (consumer name). Default: `-`. */ workerId?: string; /** Hard cap on owned shards. Default: none (fair share of the live workers). */ maxShards?: number; /** Release shards above the fair share when workers join. Default: true. */ rebalance?: boolean; /** Local frontier fed by the owned shards. Default: opened from `queuePath`. */ queue?: RequestQueue; /** Local frontier path when `queue` is not given. Default: `:memory:`. */ queuePath?: string; /** Lease time-to-live. Default: 15 000 ms. */ leaseMs?: number; /** Heartbeat period. Default: `leaseMs / 3`. */ heartbeatMs?: number; /** Periodic reclaim of entries pending longer than this. Default: `leaseMs`. */ claimIdleMs?: number; /** Entries per `XREADGROUP`. Default: 256. */ readCount?: number; /** `XREADGROUP` block time. Default: 500 ms. */ blockMs?: number; /** Stop reading streams while the local frontier holds more pending requests. Default: 100 000. */ maxLocalPending?: number; /** Batching delay of routed links. Default: 10 ms. */ flushDelayMs?: number; /** Called with shards newly acquired by this worker. */ onAssigned?: (shards: number[]) => void; /** Called with shards released or lost by this worker. */ onReleased?: (shards: number[]) => void; } export interface ShardStats { shard: number; stream: string; /** Entries not yet accepted by a worker (undelivered + pending). */ length: number; /** Delivered, not yet acknowledged. */ pending: number; /** Worker id holding the lease, or null. */ owner: string | null; /** Owned by this instance. */ local: boolean; } export interface ShardedFrontierCounters { /** Stream entries delivered to this worker (reads + claims). */ received: number; /** Entries inserted into the local frontier. */ inserted: number; /** Entries already present in the local frontier. */ duplicates: number; /** Entries handed back because the shard was no longer owned. */ requeued: number; /** Pending entries reclaimed with XAUTOCLAIM. */ claimed: number; /** URLs queued by `submit` (including routed links). */ submitted: number; /** URLs suppressed by the seen-set in `submit`. */ suppressed: number; /** Links routed to other shards. */ forwarded: number; /** Links kept local and recorded in the seen-set. */ noted: number; /** Routed links waiting for the next flush. */ buffered: number; forwardErrors: number; leasesAcquired: number; leasesReleased: number; leasesLost: number; errors: number; } export interface ShardedFrontierStats { name: string; workerId: string | null; shards: number; /** Shards owned by this instance. */ owned: number[]; /** Live worker ids. */ workers: string[]; seen: BloomParams & { count: number; estimatedFalsePositiveRate: number }; perShard: ShardStats[]; counters: ShardedFrontierCounters; } interface StreamEntry { id: string; fields: string[]; } interface FrontierMeta { version: 1; shards: number; createdAt: number; } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- /** * Fair shard targets: water-filling of `shards` over the workers, smallest * cap first (ties by id), each taking `min(cap, ceil(remaining / left))`. * Deterministic for a given membership, sums to `shards` when caps allow. */ export function assignShardTargets( shards: number, workers: ReadonlyArray<{ id: string; cap: number }>, ): Map { const sorted = [...workers].sort((a, b) => a.cap - b.cap || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); const targets = new Map(); let remaining = shards; for (let i = 0; i < sorted.length; i++) { const worker = sorted[i] as { id: string; cap: number }; const share = Math.ceil(remaining / (sorted.length - i)); const target = Math.max(0, Math.min(worker.cap, share)); targets.set(worker.id, target); remaining -= target; } return targets; } function encodeFields(item: SubmitItem): string[] { const fields = ["u", item.url, "d", String(Math.max(0, Math.floor(item.depth ?? 0)))]; if (item.anchorText) fields.push("a", item.anchorText.slice(0, 512)); if (item.boost) fields.push("b", String(item.boost)); if (item.userData) fields.push("j", JSON.stringify(item.userData)); return fields; } function decodeFields(fields: readonly string[]): SubmitItem | null { const map = new Map(); for (let i = 0; i + 1 < fields.length; i += 2) map.set(fields[i] as string, fields[i + 1] as string); const url = map.get("u"); if (!url) return null; const item: SubmitItem = { url, depth: toInt(map.get("d")) }; const anchor = map.get("a"); if (anchor) item.anchorText = anchor; const boost = Number(map.get("b")); if (Number.isFinite(boost) && boost !== 0) item.boost = boost; const json = map.get("j"); if (json) { try { item.userData = JSON.parse(json) as Record; } catch { // Ignore malformed user data. } } return item; } function parseEntries(raw: unknown): StreamEntry[] { if (!Array.isArray(raw)) return []; const entries: StreamEntry[] = []; for (const entry of raw) { if (!Array.isArray(entry) || entry.length < 2) continue; const [id, fields] = entry as [unknown, unknown]; let flat: string[] = []; if (Array.isArray(fields)) flat = fields.map(String); else if (fields && typeof fields === "object") flat = Object.entries(fields).flat().map(String); entries.push({ id: String(id), fields: flat }); } return entries; } /** `XREADGROUP` reply (RESP3 map or RESP2 array) → `[stream, entries]` pairs. */ function parseStreams(raw: unknown): Array<[string, StreamEntry[]]> { if (!raw) return []; if (Array.isArray(raw)) { return raw .filter((pair): pair is [unknown, unknown] => Array.isArray(pair) && pair.length >= 2) .map(([key, entries]) => [String(key), parseEntries(entries)]); } if (typeof raw === "object") { return Object.entries(raw as Record).map(([key, entries]) => [key, parseEntries(entries)]); } return []; } function defaultLocalQueue(path: string): RequestQueue { return RequestQueue.open(path, { hostKeyFn: (url) => { try { return registrableDomain(url); } catch { return ""; } }, maxInFlightPerHost: 8, familyKeyFn: stripQueryFamilyKey, }); } // --------------------------------------------------------------------------- // ShardedFrontier // --------------------------------------------------------------------------- export class ShardedFrontier { readonly name: string; /** Shard count of the frontier. */ readonly shards: number; /** Worker id (consumer name), or null for a submit-only client. */ readonly workerId: string | null; readonly redisUrl: string; readonly #prefix: string; readonly #cmd: RedisClient; readonly #seen: RedisSeenSet; readonly #shardKeyFn: (url: string) => string; readonly #log: (msg: string) => void; readonly #shardCache = new Map(); // Worker state (join only) readonly #token: string; #reader: RedisClient | null = null; #queue: RequestQueue | null = null; #ownsQueue = false; /** shard → lease validity deadline (performance.now() ms). */ readonly #owned = new Map(); #options: ShardedFrontierJoinOptions | null = null; #leaseMs = DEFAULT_LEASE_MS; #heartbeatMs = DEFAULT_LEASE_MS / 3; #claimIdleMs = DEFAULT_LEASE_MS; #readCount = 256; #blockMs = 500; #maxLocalPending = 100_000; #flushDelayMs = 10; #running = false; #closed = false; #ticking: Promise | null = null; #heartbeat: ReturnType | null = null; #readLoop: Promise | null = null; #wake: (() => void) | null = null; #lastPendingCheck = 0; #backpressured = false; #liveWorkers: string[] = []; // Routed links #forward: SubmitItem[] = []; #noted: string[] = []; #flushTimer: ReturnType | null = null; #flushChain: Promise = Promise.resolve(); readonly #counters: ShardedFrontierCounters = { received: 0, inserted: 0, duplicates: 0, requeued: 0, claimed: 0, submitted: 0, suppressed: 0, forwarded: 0, noted: 0, buffered: 0, forwardErrors: 0, leasesAcquired: 0, leasesReleased: 0, leasesLost: 0, errors: 0, }; private constructor( options: ShardedFrontierConnectOptions, cmd: RedisClient, seen: RedisSeenSet, shards: number, workerId: string | null, ) { this.name = options.name; this.redisUrl = resolveRedisUrl(options.redisUrl); this.#prefix = frontierPrefix(options.name); this.#cmd = cmd; this.#seen = seen; this.shards = shards; this.workerId = workerId; this.#shardKeyFn = options.shardKeyFn ?? shardKeyOf; this.#log = options.log ?? (() => {}); this.#token = `${workerId ?? "client"}|${Bun.randomUUIDv7()}`; } // ------------------------------------------------------------------------- // Lifecycle // ------------------------------------------------------------------------- /** Submit-only client: `submit`, `stats`, no leases and no consumption. */ static async connect(options: ShardedFrontierConnectOptions): Promise { return ShardedFrontier.#open(options, null); } /** * Join the cluster as a worker: register, acquire shards, reclaim their * pending entries and start feeding the local queue. */ static async join(options: ShardedFrontierJoinOptions): Promise { const workerId = options.workerId ?? `${hostname()}-${process.pid}`; if (workerId.includes("|")) throw new Error(`Invalid worker id "${workerId}": "|" is reserved`); const frontier = await ShardedFrontier.#open(options, workerId); try { await frontier.#start(options); } catch (err) { frontier.kill(); throw err; } return frontier; } static async #open(options: ShardedFrontierConnectOptions, workerId: string | null): Promise { const prefix = frontierPrefix(options.name); if (options.shards !== undefined && !(Number.isInteger(options.shards) && options.shards >= 1)) { throw new RangeError(`shards must be a positive integer, got ${options.shards}`); } const cmd = openRedis(options.redisUrl); try { const metaKey = `${prefix}:meta`; const wanted: FrontierMeta = { version: 1, shards: options.shards ?? DEFAULT_SHARDS, createdAt: Date.now(), }; await cmd.send("SET", [metaKey, JSON.stringify(wanted), "NX"]); const stored = JSON.parse(String(await cmd.send("GET", [metaKey]))) as FrontierMeta; if (options.shards !== undefined && stored.shards !== options.shards) { throw new Error( `Frontier "${options.name}" has ${stored.shards} shards; refusing to use it with ${options.shards}`, ); } const seen = await RedisSeenSet.open({ client: cmd, prefix, ...options.seenSet }); const frontier = new ShardedFrontier(options, cmd, seen, stored.shards, workerId); await Promise.all( Array.from({ length: stored.shards }, (_, shard) => cmd.send("XGROUP", ["CREATE", frontier.streamKey(shard), CONSUMER_GROUP, "0", "MKSTREAM"]).catch((err) => { if (!isBusyGroupError(err)) throw err; }), ), ); return frontier; } catch (err) { cmd.close(); throw err; } } async #start(options: ShardedFrontierJoinOptions): Promise { this.#options = options; this.#leaseMs = Math.max(100, options.leaseMs ?? DEFAULT_LEASE_MS); this.#heartbeatMs = Math.max(20, options.heartbeatMs ?? Math.floor(this.#leaseMs / 3)); this.#claimIdleMs = Math.max(0, options.claimIdleMs ?? this.#leaseMs); this.#readCount = Math.max(1, options.readCount ?? 256); this.#blockMs = Math.max(10, options.blockMs ?? 500); this.#maxLocalPending = Math.max(1, options.maxLocalPending ?? 100_000); this.#flushDelayMs = Math.max(0, options.flushDelayMs ?? 10); if (options.queue) { this.#queue = options.queue; } else { this.#queue = defaultLocalQueue(options.queuePath ?? ":memory:"); this.#ownsQueue = true; } this.#reader = openRedis(this.redisUrl); this.#running = true; await this.#tick(); this.#heartbeat = setInterval(() => void this.#tick(), this.#heartbeatMs); this.#heartbeat.unref?.(); this.#readLoop = this.#consume(); } /** * Leave gracefully: stop consuming, flush routed links, release leases and * unregister. Work already accepted into the local queue stays there. * Closes the local queue when the frontier opened it. */ async leave(): Promise { if (this.#closed) return; this.#stopLoops(); this.#reader?.close(); await this.#readLoop?.catch(() => {}); await this.#ticking?.catch(() => {}); await this.flush(); if (this.workerId !== null) { const shards = [...this.#owned.keys()]; this.#owned.clear(); try { if (shards.length > 0) { await RELEASE.run(this.#cmd, shards.map((s) => this.leaseKey(s)), [this.#token]); this.#counters.leasesReleased += shards.length; } await this.#cmd.send("ZREM", [this.#workersKey, this.workerId]); await this.#cmd.send("HDEL", [this.#capsKey, this.workerId]); } catch (err) { this.#counters.errors++; this.#log(`[frontier] release on leave failed: ${err}`); } if (shards.length > 0) this.#options?.onReleased?.(shards); } if (this.#ownsQueue) this.#queue?.close(); await this.#seen.close(); this.#cmd.close(); } /** * Abandon the cluster without releasing anything: heartbeats stop, leases * and pending entries are left to expire and be reclaimed by other workers. * Simulates a crash (tests, chaos drills). */ kill(): void { if (this.#closed) return; this.#stopLoops(); this.#owned.clear(); this.#reader?.close(); this.#cmd.close(); if (this.#ownsQueue) this.#queue?.close(); } #stopLoops(): void { this.#running = false; this.#closed = true; if (this.#heartbeat) clearInterval(this.#heartbeat); this.#heartbeat = null; if (this.#flushTimer) clearTimeout(this.#flushTimer); this.#flushTimer = null; this.#wake?.(); } // ------------------------------------------------------------------------- // Keys and routing // ------------------------------------------------------------------------- streamKey(shard: number): string { return `${this.#prefix}:shard:${shard}`; } leaseKey(shard: number): string { return `${this.#prefix}:lease:${shard}`; } get #workersKey(): string { return `${this.#prefix}:workers`; } get #capsKey(): string { return `${this.#prefix}:workers:caps`; } /** Local frontier fed by the owned shards (workers only). */ get queue(): RequestQueue { if (!this.#queue) throw new Error("ShardedFrontier.queue is only available on joined workers"); return this.#queue; } /** Shard of a URL. */ shardOf(url: string): number { const key = this.#shardKeyFn(url); let shard = this.#shardCache.get(key); if (shard === undefined) { shard = shardOfKey(key, this.shards); if (this.#shardCache.size >= SHARD_CACHE_LIMIT) this.#shardCache.clear(); this.#shardCache.set(key, shard); } return shard; } /** Shards whose lease this instance currently holds, ascending. */ ownedShards(): number[] { const now = performance.now(); return [...this.#owned.entries()] .filter(([, validUntil]) => validUntil > now) .map(([shard]) => shard) .sort((a, b) => a - b); } /** `true` when this instance holds a valid lease on `shard`. */ owns(shard: number): boolean { return (this.#owned.get(shard) ?? 0) > performance.now(); } /** * `MassiveCrawler.routeLink` adapter. Returns `false` when the URL's shard * is owned here (the crawler enqueues it locally; the URL is recorded in the * seen-set in the background), `true` when the URL was buffered for * submission to its shard. */ route(url: string, opts: RouteOptions = {}): boolean { if (!this.#running) return false; let shard: number; try { shard = this.shardOf(url); } catch { return false; } const local = this.owns(shard); if (local) { this.#noted.push(url); } else { this.#forward.push({ url, depth: opts.depth, anchorText: opts.anchorText, boost: opts.boost }); } this.#scheduleFlush(); return !local; } #scheduleFlush(): void { const size = this.#forward.length + this.#noted.length; this.#counters.buffered = this.#forward.length; if (this.#flushTimer) { if (size < SUBMIT_BATCH) return; clearTimeout(this.#flushTimer); } this.#flushTimer = setTimeout( () => { this.#flushTimer = null; void this.flush(); }, size >= SUBMIT_BATCH ? 0 : this.#flushDelayMs, ); } /** Submit buffered routed links and seen-set notes now. */ flush(): Promise { this.#flushChain = this.#flushChain.then(() => this.#flushOnce()); return this.#flushChain; } async #flushOnce(): Promise { const noted = this.#noted; const forward = this.#forward; this.#noted = []; this.#forward = []; this.#counters.buffered = 0; if (noted.length > 0) { try { await this.#seen.addMany(noted); this.#counters.noted += noted.length; } catch (err) { this.#counters.errors++; this.#log(`[frontier] seen-set update failed: ${err}`); } } if (forward.length > 0) { try { const result = await this.submit(forward); this.#counters.forwarded += result.queued; } catch (err) { this.#counters.forwardErrors++; this.#log(`[frontier] routing ${forward.length} links failed: ${err}`); if (this.#running && this.#forward.length + forward.length <= 100_000) { this.#forward.unshift(...forward); this.#counters.buffered = this.#forward.length; if (!this.#flushTimer) { this.#flushTimer = setTimeout(() => { this.#flushTimer = null; void this.flush(); }, 1_000); } } } } } /** * Queue URLs on their shards. Each URL is checked against (and added to) * the shared seen-set atomically with its `XADD`; already-seen URLs are * suppressed unless `force` is set. */ async submit(items: Iterable, options: SubmitOptions = {}): Promise { const unique = new Map(); let repeated = 0; for (const raw of items) { const item = typeof raw === "string" ? { url: raw } : raw; if (!item?.url) continue; if (unique.has(item.url)) repeated++; else unique.set(item.url, item); } const list = [...unique.values()]; const result: SubmitResult = { queued: 0, duplicates: repeated, byShard: {} }; const params = this.#seen.params; for (let start = 0; start < list.length; start += SUBMIT_BATCH) { const batch = list.slice(start, start + SUBMIT_BATCH); const keys = [...this.#seen.keys.partitions, this.#seen.keys.count]; const streamIndex = new Map(); const shardsOfBatch: number[] = []; const args: Array = [params.hashes, options.force ? 1 : 0]; for (const item of batch) { const shard = this.shardOf(item.url); shardsOfBatch.push(shard); let index = streamIndex.get(shard); if (index === undefined) { index = streamIndex.size + 1; streamIndex.set(shard, index); keys.push(this.streamKey(shard)); } args.push(index); for (const offset of bloomOffsets(item.url, params)) args.push(offset); const fields = encodeFields(item); args.push(fields.length); for (const field of fields) args.push(field); } const reply = (await SUBMIT.run(this.#cmd, keys, args)) as unknown[]; for (let i = 0; i < batch.length; i++) { if (toInt(reply[i]) === 1) { result.queued++; const shard = shardsOfBatch[i] as number; result.byShard[shard] = (result.byShard[shard] ?? 0) + 1; } else { result.duplicates++; } } } this.#counters.submitted += result.queued; this.#counters.suppressed += result.duplicates; return result; } // ------------------------------------------------------------------------- // Heartbeat, leases, rebalancing // ------------------------------------------------------------------------- #tick(): Promise { if (this.#ticking) return this.#ticking; this.#ticking = this.#tickOnce().finally(() => { this.#ticking = null; }); return this.#ticking; } async #tickOnce(): Promise { if (!this.#running || this.workerId === null) return; try { const owned = [...this.#owned.keys()]; const cap = this.#options?.maxShards; const sentAt = performance.now(); const reply = (await HEARTBEAT.run( this.#cmd, [this.#workersKey, this.#capsKey, ...owned.map((s) => this.leaseKey(s))], [this.workerId, this.#token, this.#leaseMs, cap === undefined ? -1 : Math.max(0, Math.floor(cap))], )) as [unknown[], unknown[], unknown[]]; if (!this.#running) return; const [liveRaw, capsRaw, renewedRaw] = reply; const validUntil = sentAt + this.#leaseMs - Math.min(1_000, this.#leaseMs / 10); const lost: number[] = []; owned.forEach((shard, i) => { if (toInt(renewedRaw?.[i]) === 1) { this.#owned.set(shard, validUntil); } else { this.#owned.delete(shard); lost.push(shard); } }); if (lost.length > 0) { this.#counters.leasesLost += lost.length; this.#log(`[frontier] ${this.workerId} lost shards ${lost.join(",")}`); this.#options?.onReleased?.(lost); } const live = (liveRaw ?? []).map(String); this.#liveWorkers = live; const workers = live.map((id, i) => { const value = toInt(capsRaw?.[i], -1); return { id, cap: value < 0 ? Number.POSITIVE_INFINITY : value }; }); let target = assignShardTargets(this.shards, workers).get(this.workerId) ?? 0; if (this.#options?.rebalance === false) { target = cap === undefined ? this.shards : Math.min(this.shards, cap); } if (this.#owned.size > target && this.#options?.rebalance !== false) { await this.#release(this.#owned.size - target); } else if (this.#owned.size < target) { await this.#acquire(target - this.#owned.size, validUntil); } await this.#reclaimOwned(); } catch (err) { if (!this.#running) return; this.#counters.errors++; this.#log(`[frontier] heartbeat failed: ${err}`); } } async #acquire(want: number, validUntil: number): Promise { const offset = this.workerId === null ? 0 : Number(Bun.hash.xxHash32(this.workerId) % this.shards); const candidates: number[] = []; for (let n = 0; n < this.shards; n++) { const shard = (offset + n) % this.shards; if (!this.#owned.has(shard)) candidates.push(shard); } if (candidates.length === 0) return; const reply = (await ACQUIRE.run( this.#cmd, candidates.map((s) => this.leaseKey(s)), [this.#token, this.#leaseMs, want], )) as unknown[]; const acquired = reply.map((index) => candidates[toInt(index) - 1] as number); if (acquired.length === 0) return; if (!this.#running) { // Left while acquiring: hand the leases straight back. await RELEASE.run(this.#cmd, acquired.map((s) => this.leaseKey(s)), [this.#token]); return; } for (const shard of acquired) this.#owned.set(shard, validUntil); this.#counters.leasesAcquired += acquired.length; this.#log(`[frontier] ${this.workerId} acquired shards ${acquired.join(",")}`); this.#options?.onAssigned?.(acquired); this.#wake?.(); // Entries delivered to a previous owner and never acknowledged. for (const shard of acquired) await this.#reclaim(shard, 0); } async #release(count: number): Promise { const shards = [...this.#owned.keys()].sort((a, b) => b - a).slice(0, count); for (const shard of shards) this.#owned.delete(shard); await RELEASE.run(this.#cmd, shards.map((s) => this.leaseKey(s)), [this.#token]); this.#counters.leasesReleased += shards.length; this.#log(`[frontier] ${this.workerId} released shards ${shards.join(",")}`); this.#options?.onReleased?.(shards); } async #reclaimOwned(): Promise { for (const shard of this.ownedShards()) { if (!this.#running) return; await this.#reclaim(shard, this.#claimIdleMs); } } /** Claim entries pending for at least `minIdleMs` on a shard and ingest them. */ async #reclaim(shard: number, minIdleMs: number): Promise { if (this.workerId === null) return 0; let cursor = "0-0"; let total = 0; for (let round = 0; round < 10_000 && this.#running; round++) { const reply = (await this.#cmd.send("XAUTOCLAIM", [ this.streamKey(shard), CONSUMER_GROUP, this.workerId, String(minIdleMs), cursor, "COUNT", String(CLAIM_COUNT), ])) as unknown[]; cursor = String(reply?.[0] ?? "0-0"); const entries = parseEntries(reply?.[1]); if (entries.length > 0) { total += entries.length; this.#counters.claimed += entries.length; await this.#ingest(shard, entries); } if (cursor === "0-0") break; } return total; } // ------------------------------------------------------------------------- // Consumption // ------------------------------------------------------------------------- #idle(ms: number): Promise { return new Promise((resolve) => { const timer = setTimeout(done, ms); function done() { clearTimeout(timer); resolve(); } this.#wake = () => { this.#wake = null; done(); }; }); } #localBacklogFull(): boolean { const now = performance.now(); if (now - this.#lastPendingCheck < 250) return this.#backpressured; this.#lastPendingCheck = now; try { this.#backpressured = (this.#queue?.frontierStats().pending ?? 0) >= this.#maxLocalPending; } catch { this.#backpressured = false; } return this.#backpressured; } async #consume(): Promise { const reader = this.#reader as RedisClient; while (this.#running) { try { const shards = this.ownedShards(); if (shards.length === 0 || this.#localBacklogFull()) { await this.#idle(shards.length === 0 ? 250 : 100); continue; } const reply = await reader.send("XREADGROUP", [ "GROUP", CONSUMER_GROUP, this.workerId as string, "COUNT", String(this.#readCount), "BLOCK", String(this.#blockMs), "STREAMS", ...shards.map((s) => this.streamKey(s)), ...shards.map(() => ">"), ]); if (!this.#running) break; for (const [key, entries] of parseStreams(reply)) { const shard = Number(key.slice(key.lastIndexOf(":") + 1)); if (entries.length > 0 && Number.isInteger(shard)) await this.#ingest(shard, entries); } } catch (err) { if (!this.#running) break; this.#counters.errors++; this.#log(`[frontier] read failed: ${err}`); await this.#idle(500); } } } /** Insert entries into the local queue, then acknowledge + delete them. */ async #ingest(shard: number, entries: StreamEntry[]): Promise { const stream = this.streamKey(shard); if (!this.owns(shard)) { const args: Array = [CONSUMER_GROUP]; for (const entry of entries) { args.push(entry.id, entry.fields.length); for (const field of entry.fields) args.push(field); } await REQUEUE.run(this.#cmd, [stream], args); this.#counters.requeued += entries.length; return; } const queue = this.queue; const items = []; for (const entry of entries) { const item = decodeFields(entry.fields); if (!item) continue; const depth = item.depth ?? 0; items.push({ url: item.url, opts: { depth, anchorText: item.anchorText, boost: item.boost, userData: { ...item.userData, depth }, }, }); } this.#counters.received += entries.length; // Throws when the local queue is closed: entries stay pending and are reclaimed. const inserted = items.length > 0 ? queue.addRequests(items) : 0; this.#counters.inserted += inserted; this.#counters.duplicates += items.length - inserted; await ACK_DELETE.run(this.#cmd, [stream], [CONSUMER_GROUP, ...entries.map((e) => e.id)]); } // ------------------------------------------------------------------------- // Introspection // ------------------------------------------------------------------------- /** Local counters (no Redis round trip). */ counters(): ShardedFrontierCounters { return { ...this.#counters, buffered: this.#forward.length }; } /** Cluster view: per-shard backlog, pending, owner; seen-set fill; live workers. */ async stats(): Promise { const shards = Array.from({ length: this.shards }, (_, i) => i); const [lengths, pendings, owners, live, seenCount] = await Promise.all([ Promise.all(shards.map((s) => this.#cmd.send("XLEN", [this.streamKey(s)]))), Promise.all( shards.map((s) => this.#cmd.send("XPENDING", [this.streamKey(s), CONSUMER_GROUP]).catch(() => null)), ), Promise.all(shards.map((s) => this.#cmd.send("GET", [this.leaseKey(s)]))), LIVE_WORKERS.run(this.#cmd, [this.#workersKey], []) as Promise, this.#seen.count(), ]); const owned = this.ownedShards(); return { name: this.name, workerId: this.workerId, shards: this.shards, owned, workers: (live ?? []).map(String), seen: { ...this.#seen.params, count: seenCount, estimatedFalsePositiveRate: estimatedFalsePositiveRate(this.#seen.params, seenCount), }, perShard: shards.map((shard) => { const lease = owners[shard] == null ? null : String(owners[shard]); return { shard, stream: this.streamKey(shard), length: toInt(lengths[shard]), pending: Array.isArray(pendings[shard]) ? toInt((pendings[shard] as unknown[])[0]) : 0, owner: lease === null ? null : lease.slice(0, lease.lastIndexOf("|")), local: owned.includes(shard), }; }), counters: this.counters(), }; } /** Live worker ids seen by the last heartbeat. */ get liveWorkers(): readonly string[] { return this.#liveWorkers; } /** * Delete every key of a frontier (streams, leases, registry, seen-set). * Workers must be stopped first. */ static async drop(options: { redisUrl?: string; name: string }): Promise { const prefix = frontierPrefix(options.name); const client = openRedis(options.redisUrl); let deleted = 0; try { let cursor = "0"; do { const reply = (await client.send("SCAN", [cursor, "MATCH", `${prefix}:*`, "COUNT", "1000"])) as [ unknown, unknown[], ]; cursor = String(reply[0]); const keys = (reply[1] ?? []).map(String); if (keys.length > 0) deleted += toInt(await client.send("DEL", keys)); } while (cursor !== "0"); return deleted; } finally { client.close(); } } }