/** * 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/RequestQueue * * Persistent, crash-safe crawl frontier backed by `bun:sqlite` (Frontier v2). * * Inspired by Crawlee's RequestQueue v2 (packages/core/src/storages/request_queue_v2.ts) * but rewritten Bun-native: no fs, no DynamoDB, no external deps. * * Design: * - SQLite (WAL) is the durable store; every mutation is written through. * PENDING → LOCKED → DONE / FAILED state machine, `unique_key` dedup, * dead-letter queue for requests exceeding `maxRetries`. * - Scheduling happens in memory, rebuilt lazily from PENDING rows on first * use (stats-only openers never pay for it): * • one max-heap of requests per host, ordered by (forefront lane, score, * insertion id ASC) — equal scores therefore stay FIFO; * • hosts ready now live in a max-heap keyed by their top request; hosts * throttled by politeness live in a min-heap keyed by * `(nextAllowedAt, -topScore)`. Together they implement the global * `(nextAllowedAt, -score)` order with `nextAllowedAt` clamped to now. * - Score = OPIC cash + anchor relevance + depth decay + boost − duplicate * family penalty (see `frontier/scoring.ts`), pluggable via `scoreFn`. * - Event-driven dequeue: `waitForWork()` resolves on insert, requeue, slot * release, host-delay expiry (single timer armed at the earliest * `nextAllowedAt`) or when the queue is finished. No polling. * - Optional revisit scheduler (Poisson change-rate estimation, see * `frontier/revisit.ts`) re-queues DONE rows when `next_fetch_at` is due. * * @example * ```ts * const q = RequestQueue.open("./crawl.db", { perHostDelayMs: 1000 }); * q.addRequest("https://google.com"); * for await (const batch of q.drain(5)) { * for (const req of batch) q.markDone(req.id); * } * q.close(); * ``` */ import { Database } from "bun:sqlite"; import { mkdirSync } from "node:fs"; import { dirname, join } from "node:path"; import { BxcConfig } from "../config/BxcConfig.ts"; import { type HeapNode, IndexedHeap } from "./frontier/heap.ts"; import { DEFAULT_REVISIT_POLICY, estimateChangeRate, type RevisitPolicy, revisitIntervalMs, revisitPriority, } from "./frontier/revisit.ts"; import { anchorRelevance, type CrawlGoal, compileGoal, DEFAULT_SCORE_PARAMS, defaultFrontierScore, defaultHostKey, type FrontierScoreFn, type FrontierScoreParams, } from "./frontier/scoring.ts"; export type { FrontierScoreFn, FrontierScoreInput, FrontierScoreParams, } from "./frontier/scoring.ts"; export type { RevisitPolicy } from "./frontier/revisit.ts"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- /** Valid lifecycle states for a queued request. */ export type RequestState = "PENDING" | "LOCKED" | "DONE" | "FAILED"; /** * A scrape target stored in the queue. * Mirrors Crawlee's Request shape but simplified to what Bxc needs. */ export interface QueuedRequest { /** Internal SQLite rowid alias — assigned on insert. */ id: number; /** Stable unique identifier — used for dedup (defaults to URL). */ uniqueKey: string; url: string; method: string; /** Raw HTTP POST body/payload string. */ payload: string | null; /** Optional headers record. */ headers: Record | null; /** Optional metadata record. */ userData: Record | null; state: RequestState; retries: number; /** 1 for forefront requests, 0 otherwise. */ priority: number; createdAt: number; lockedAt: number | null; handledAt: number | null; errorMessage: string | null; /** Frontier score as of the last write of the row (higher = dequeued sooner). */ score: number; /** Link depth from the seeds. */ depth: number; /** Current OPIC cash. */ opicCash: number; /** OPIC cash already distributed by this URL. */ opicHistory: number; /** Anchor text the URL was discovered with. */ anchorText: string | null; /** Duplicate-family key (query-stripped URL, SimHash bucket, ...). */ familyKey: string | null; /** Static caller prior added to the score. */ boost: number; /** Number of successful fetches. */ fetchCount: number; /** Number of fetches that detected a content change. */ changeCount: number; lastFetchedAt: number | null; /** Next revisit time (revisit scheduler), or null. */ nextFetchAt: number | null; /** Estimated change rate in changes per ms (revisit scheduler), or null. */ changeRate: number | null; } export interface AddRequestOptions { /** Override the dedup key (default: URL). */ uniqueKey?: string; method?: string; /** Arbitrary metadata — will be JSON.stringify-ed. */ userData?: Record; headers?: Record; /** If true, request is put at the front of the queue. */ forefront?: boolean; /** Raw HTTP POST body/payload string. */ payload?: string | null; /** * Link depth. Default: `parent depth + 1` when added with a `parent`, * else numeric `userData.depth`, else 0. */ depth?: number; /** Anchor text used for goal relevance. */ anchorText?: string | null; /** Duplicate-family key. Default: `familyKeyFn(url)` when configured, else none. */ familyKey?: string | null; /** Static prior added to the score (e.g. sitemap priority / recency). */ boost?: number; /** Initial OPIC cash. Default: parent share with `parent`, else `initialCash`. */ opicCash?: number; } export interface AddRequestsOptions { /** * Unique key of the page the URLs were discovered on. Its OPIC cash is * split equally among the (deduplicated) children; children that already * exist accumulate their share. */ parent?: string; } export interface MarkDoneOptions { /** Content fingerprint; a different value than last time counts as a change. */ contentHash?: string | null; /** Explicit change flag (overrides hash comparison). */ changed?: boolean; } export interface WaitForWorkOptions { /** Keep waiting when the queue is finished (daemon mode). Default: false. */ ignoreFinished?: boolean; } export interface RequestQueueOptions { /** Maximum retries before a request is moved to FAILED. Default: 3 */ maxRetries?: number; /** How long (ms) a LOCKED request can be held before re-queued. Default: 120_000 */ lockTimeoutMs?: number; /** Time source (ms since epoch). Inject a fake clock in tests. Default: `Date.now`. */ clock?: () => number; /** Scheduling bucket of a URL. Default: lower-case hostname. */ hostKeyFn?: (url: string) => string; /** Minimum delay between two locks on the same host. Default: 0 (no throttling). */ perHostDelayMs?: number; /** Maximum concurrently LOCKED requests per host. Default: Infinity. */ maxInFlightPerHost?: number; /** Custom score function. Default: {@link defaultFrontierScore}. */ scoreFn?: FrontierScoreFn; /** Anchor relevance multiplier. Default: 1. */ anchorWeight?: number; /** Depth decay base. Default: 0.5. */ depthDecay?: number; /** Penalty per DONE member of the same family. Default: 0.25. */ familyPenalty?: number; /** Cap of the family penalty. Default: 1. */ familyPenaltyCap?: number; /** OPIC cash of seeds (requests added without parent). Default: 1. */ initialCash?: number; /** Derive a family key for requests that do not pass one. */ familyKeyFn?: (url: string) => string | null; /** Crawl goal used for anchor relevance. */ goal?: string; /** Enable the revisit scheduler. Default: false. */ enableRevisits?: boolean; /** Revisit scheduler tuning. */ revisitPolicy?: Partial; /** * While `waitForWork()` is pending on a file database, check this often * (via `PRAGMA data_version`) for rows written by other processes. * Default: 1000 for file databases, 0 (disabled) for `:memory:`. */ externalSyncMs?: number; } export interface RequestQueueStats { pending: number; locked: number; done: number; failed: number; total: number; } /** In-memory scheduler diagnostics. */ export interface FrontierStats { /** Tracked hosts (with pending, in-flight or throttled requests). */ hosts: number; /** Hosts that can be dequeued now. */ readyHosts: number; /** Hosts waiting for their politeness delay. */ waitingHosts: number; /** Hosts at `maxInFlightPerHost`. */ blockedHosts: number; /** Pending requests held by the scheduler. */ pending: number; /** Requests locked by this process. */ inFlight: number; /** Earliest `nextAllowedAt` among waiting hosts. */ nextAllowedAt: number | null; /** Earliest due revisit, when revisits are enabled. */ nextRevisitAt: number | null; /** Active crawl goal text. */ goal: string | null; } // --------------------------------------------------------------------------- // SQL strings (kept as constants to avoid template-literal overhead on hot path) // --------------------------------------------------------------------------- const DDL = ` CREATE TABLE IF NOT EXISTS requests ( id INTEGER PRIMARY KEY AUTOINCREMENT, unique_key TEXT NOT NULL UNIQUE, url TEXT NOT NULL, method TEXT NOT NULL DEFAULT 'GET', payload TEXT, headers TEXT, user_data TEXT, state TEXT NOT NULL DEFAULT 'PENDING', retries INTEGER NOT NULL DEFAULT 0, priority INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL, locked_at INTEGER, handled_at INTEGER, error_msg TEXT ); CREATE INDEX IF NOT EXISTS idx_pending ON requests (state, priority DESC, id ASC) WHERE state = 'PENDING'; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA temp_store=MEMORY; PRAGMA mmap_size=30000000000; `; /** * Columns added after the first schema. Existing databases are migrated with * guarded `ALTER TABLE` statements. `opic_cash` defaults to 1 so migrated rows * keep their relative (FIFO) order against new seeds. */ const MIGRATION_COLUMNS: ReadonlyArray = [ ["headers", "TEXT"], ["user_data", "TEXT"], ["score", "REAL NOT NULL DEFAULT 0"], ["depth", "INTEGER NOT NULL DEFAULT 0"], ["opic_cash", "REAL NOT NULL DEFAULT 1"], ["opic_history", "REAL NOT NULL DEFAULT 0"], ["anchor_text", "TEXT"], ["family_key", "TEXT"], ["boost", "REAL NOT NULL DEFAULT 0"], ["revisit_priority", "REAL NOT NULL DEFAULT 0"], ["fetch_count", "INTEGER NOT NULL DEFAULT 0"], ["change_count", "INTEGER NOT NULL DEFAULT 0"], ["first_fetched_at", "INTEGER"], ["last_fetched_at", "INTEGER"], ["next_fetch_at", "INTEGER"], ["content_hash", "TEXT"], ["change_rate", "REAL"], ]; const POST_MIGRATION_DDL = ` CREATE INDEX IF NOT EXISTS idx_locked ON requests (locked_at) WHERE state = 'LOCKED'; CREATE INDEX IF NOT EXISTS idx_revisit ON requests (next_fetch_at) WHERE state = 'DONE' AND next_fetch_at IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_family_done ON requests (family_key) WHERE state = 'DONE' AND family_key IS NOT NULL; `; /** * Columns of a {@link QueuedRequest}, aliased to camelCase so a returned row * becomes the result object in place (no second allocation per dequeue). */ const REQUEST_COLS = [ "id", "unique_key AS uniqueKey", "url", "method", "payload", "headers", "user_data AS userData", "state", "retries", "priority", "created_at AS createdAt", "locked_at AS lockedAt", "handled_at AS handledAt", "error_msg AS errorMessage", "score", "depth", "opic_cash AS opicCash", "opic_history AS opicHistory", "anchor_text AS anchorText", "family_key AS familyKey", "boost", "fetch_count AS fetchCount", "change_count AS changeCount", "last_fetched_at AS lastFetchedAt", "next_fetch_at AS nextFetchAt", "change_rate AS changeRate", ].join(", "); /** Columns needed to rebuild a scheduler entry. */ const ENTRY_COLS = "id, url, priority, depth, opic_cash, opic_history, anchor_text, family_key, boost, revisit_priority"; // --------------------------------------------------------------------------- // In-memory scheduler structures // --------------------------------------------------------------------------- interface EntryRow { id: number; url: string; priority: number; depth: number; opic_cash: number; opic_history: number; anchor_text: string | null; family_key: string | null; boost: number; revisit_priority: number; } interface DoneRow { fetch_count: number; change_count: number; first_fetched_at: number | null; last_fetched_at: number | null; opic_cash: number; opic_history: number; score: number; } /** A pending request inside a host heap. */ interface FrontierEntry extends HeapNode { id: number; host: HostState; /** 1 = forefront lane (always first), 0 = scored lane. */ lane: number; score: number; depth: number; cash: number; history: number; boost: number; revisit: number; relevance: number; familyKey: string | null; } const SLOT_IDLE = 0; const SLOT_READY = 1; const SLOT_WAITING = 2; const SLOT_BLOCKED = 3; interface HostState extends HeapNode { key: string; heap: IndexedHeap; inFlight: number; lastLockAt: number; nextAllowedAt: number; slot: number; } interface Waiter { ignoreFinished: boolean; resolve: () => void; } function entryBefore(a: FrontierEntry, b: FrontierEntry): boolean { if (a.lane !== b.lane) return a.lane > b.lane; if (a.score !== b.score) return a.score > b.score; return a.id < b.id; } function readyHostBefore(a: HostState, b: HostState): boolean { return entryBefore(a.heap.peek() as FrontierEntry, b.heap.peek() as FrontierEntry); } function waitingHostBefore(a: HostState, b: HostState): boolean { if (a.nextAllowedAt !== b.nextAllowedAt) return a.nextAllowedAt < b.nextAllowedAt; return readyHostBefore(a, b); } function finiteOr(value: unknown, fallback: number): number { return typeof value === "number" && Number.isFinite(value) ? value : fallback; } const EMPTY_OPTS: AddRequestOptions = Object.freeze({}); // --------------------------------------------------------------------------- // RequestQueue // --------------------------------------------------------------------------- type Stmt = ReturnType; export class RequestQueue { readonly #db: Database; readonly #maxRetries: number; readonly #lockTimeoutMs: number; readonly #clock: () => number; readonly #hostKeyFn: (url: string) => string; readonly #perHostDelayMs: number; readonly #maxInFlightPerHost: number; readonly #scoreFn: FrontierScoreFn; readonly #scoreParams: FrontierScoreParams; readonly #initialCash: number; readonly #familyKeyFn: ((url: string) => string | null) | null; readonly #enableRevisits: boolean; readonly #revisitPolicy: RevisitPolicy; readonly #externalSyncMs: number; #goal: CrawlGoal | null; #closed = false; // Scheduler state (materialised lazily by #ensureLoaded) #loaded = false; readonly #hosts = new Map(); readonly #hostDelays = new Map(); readonly #pending = new Map(); readonly #inFlight = new Map(); readonly #familyDone = new Map(); readonly #familyPending = new Map>(); readonly #readyHosts = new IndexedHeap(readyHostBefore); readonly #waitingHosts = new IndexedHeap(waitingHostBefore); #maxKnownId = 0; #dataVersion = 0; #nextRevisitAt = Number.POSITIVE_INFINITY; // Event-driven waiting readonly #waiters = new Set(); #notifyScheduled = false; #timer: ReturnType | null = null; #timerAt = Number.POSITIVE_INFINITY; // Prepared statements (compiled once, reused on every call) readonly #statements: Stmt[] = []; readonly #stmtInsert: Stmt; readonly #stmtLockAndReturn: Stmt; readonly #stmtGetRetries: Stmt; readonly #stmtDoneInfo: Stmt; readonly #stmtMarkDone: Stmt; readonly #stmtScheduleRevisit: Stmt; readonly #stmtMarkFailed: Stmt; readonly #stmtRequeue: Stmt; readonly #stmtStats: Stmt; readonly #stmtRecoverStale: Stmt; readonly #stmtReplayFailed: Stmt; readonly #stmtDlq: Stmt; readonly #stmtExists: Stmt; readonly #stmtActive: Stmt; readonly #stmtPendingRows: Stmt; readonly #stmtPendingAfter: Stmt; readonly #stmtPendingCount: Stmt; readonly #stmtPendingAnchors: Stmt; readonly #stmtMaxId: Stmt; readonly #stmtDataVersion: Stmt; readonly #stmtFamilyDone: Stmt; readonly #stmtCashByKey: Stmt; readonly #stmtDebitCash: Stmt; readonly #stmtCreditCash: Stmt; readonly #stmtUpdateScore: Stmt; readonly #stmtDueRevisits: Stmt; readonly #stmtRequeueDue: Stmt; readonly #stmtSetRevisitPriority: Stmt; readonly #stmtMinRevisit: Stmt; /** Finish a row selected with {@link REQUEST_COLS}: decode JSON columns in place. */ #mapRow(row: any): QueuedRequest { if (row.headers) { try { row.headers = JSON.parse(row.headers); } catch { row.headers = null; } } else { row.headers = null; } if (row.userData) { try { row.userData = JSON.parse(row.userData); } catch { row.userData = null; } } else { row.userData = null; } return row as QueuedRequest; } /** Run `fn` inside a transaction (the wrapper is compiled once, not per call). */ readonly #tx: (fn: () => void) => void; #prepare(sql: string): Stmt { const stmt = this.#db.prepare(sql); this.#statements.push(stmt); return stmt; } private constructor(dbPath: string, opts: RequestQueueOptions = {}) { this.#maxRetries = opts.maxRetries ?? 3; this.#lockTimeoutMs = opts.lockTimeoutMs ?? 120_000; this.#clock = opts.clock ?? Date.now; this.#hostKeyFn = opts.hostKeyFn ?? defaultHostKey; this.#perHostDelayMs = Math.max(0, finiteOr(opts.perHostDelayMs, 0)); this.#maxInFlightPerHost = typeof opts.maxInFlightPerHost === "number" && opts.maxInFlightPerHost >= 1 ? opts.maxInFlightPerHost : Number.POSITIVE_INFINITY; this.#scoreFn = opts.scoreFn ?? defaultFrontierScore; this.#scoreParams = { anchorWeight: finiteOr(opts.anchorWeight, DEFAULT_SCORE_PARAMS.anchorWeight), depthDecay: finiteOr(opts.depthDecay, DEFAULT_SCORE_PARAMS.depthDecay), familyPenalty: finiteOr(opts.familyPenalty, DEFAULT_SCORE_PARAMS.familyPenalty), familyPenaltyCap: finiteOr(opts.familyPenaltyCap, DEFAULT_SCORE_PARAMS.familyPenaltyCap), }; this.#initialCash = finiteOr(opts.initialCash, 1); this.#familyKeyFn = opts.familyKeyFn ?? null; this.#goal = compileGoal(opts.goal); this.#enableRevisits = opts.enableRevisits === true; this.#revisitPolicy = { ...DEFAULT_REVISIT_POLICY, ...opts.revisitPolicy }; this.#externalSyncMs = Math.max( 0, finiteOr(opts.externalSyncMs, dbPath === ":memory:" ? 0 : 1000), ); this.#db = new Database(dbPath, { create: true }); this.#db.exec(DDL); this.#tx = this.#db.transaction((fn: () => void) => fn()); // Guarded migration: add any column missing from older databases. const existing = new Set( (this.#db.query("PRAGMA table_info(requests)").all() as Array<{ name: string }>).map( (c) => c.name, ), ); for (const [name, type] of MIGRATION_COLUMNS) { if (existing.has(name)) continue; try { this.#db.exec(`ALTER TABLE requests ADD COLUMN ${name} ${type};`); } catch {} } this.#db.exec(POST_MIGRATION_DDL); // --------------- prepared statements --------------- this.#stmtInsert = this.#prepare(` INSERT OR IGNORE INTO requests (unique_key, url, method, payload, headers, user_data, state, priority, created_at, score, depth, opic_cash, anchor_text, family_key, boost) VALUES ($uniqueKey, $url, $method, $payload, $headers, $userData, 'PENDING', $priority, $now, $score, $depth, $cash, $anchorText, $familyKey, $boost) `); this.#stmtLockAndReturn = this.#prepare(` UPDATE requests SET state = 'LOCKED', locked_at = $now, score = $score WHERE id = $id AND state = 'PENDING' RETURNING ${REQUEST_COLS} `); this.#stmtGetRetries = this.#prepare("SELECT retries FROM requests WHERE id = ?"); this.#stmtDoneInfo = this.#prepare( "SELECT state, family_key, content_hash FROM requests WHERE id = ?", ); this.#stmtMarkDone = this.#prepare(` UPDATE requests SET state = 'DONE', handled_at = $now, fetch_count = fetch_count + 1, change_count = change_count + $changed, first_fetched_at = COALESCE(first_fetched_at, $now), last_fetched_at = $now, content_hash = COALESCE($hash, content_hash), revisit_priority = 0, next_fetch_at = NULL WHERE id = $id RETURNING fetch_count, change_count, first_fetched_at, last_fetched_at, opic_cash, opic_history, score `); this.#stmtScheduleRevisit = this.#prepare( "UPDATE requests SET change_rate = $rate, next_fetch_at = $next WHERE id = $id", ); this.#stmtMarkFailed = this.#prepare(` UPDATE requests SET state = 'FAILED', error_msg = $msg, handled_at = $now WHERE id = $id `); this.#stmtRequeue = this.#prepare(` UPDATE requests SET state = 'PENDING', retries = retries + 1, locked_at = NULL, error_msg = $msg WHERE id = $id RETURNING ${ENTRY_COLS} `); this.#stmtStats = this.#prepare(` SELECT COALESCE(SUM(state = 'PENDING'), 0) AS pending, COALESCE(SUM(state = 'LOCKED'), 0) AS locked, COALESCE(SUM(state = 'DONE'), 0) AS done, COALESCE(SUM(state = 'FAILED'), 0) AS failed, COUNT(*) AS total FROM requests `); this.#stmtRecoverStale = this.#prepare(` UPDATE requests SET state = 'PENDING', locked_at = NULL WHERE state = 'LOCKED' AND locked_at < $staleThreshold RETURNING ${ENTRY_COLS} `); this.#stmtReplayFailed = this.#prepare(` UPDATE requests SET state = 'PENDING', retries = 0, error_msg = NULL, handled_at = NULL WHERE state = 'FAILED' RETURNING ${ENTRY_COLS} `); this.#stmtDlq = this.#prepare( `SELECT ${REQUEST_COLS} FROM requests WHERE state = 'FAILED'`, ); this.#stmtExists = this.#prepare( "SELECT 1 FROM requests WHERE unique_key = $uniqueKey LIMIT 1", ); this.#stmtActive = this.#prepare(` SELECT EXISTS(SELECT 1 FROM requests WHERE state = 'PENDING') OR EXISTS(SELECT 1 FROM requests WHERE state = 'LOCKED') AS active `); this.#stmtPendingRows = this.#prepare( `SELECT ${ENTRY_COLS} FROM requests WHERE state = 'PENDING'`, ); this.#stmtPendingAfter = this.#prepare( `SELECT ${ENTRY_COLS} FROM requests WHERE state = 'PENDING' AND id > $id`, ); this.#stmtPendingCount = this.#prepare( "SELECT COUNT(*) AS n FROM requests WHERE state = 'PENDING'", ); this.#stmtPendingAnchors = this.#prepare( "SELECT id, url, anchor_text FROM requests WHERE state = 'PENDING'", ); this.#stmtMaxId = this.#prepare("SELECT COALESCE(MAX(id), 0) AS id FROM requests"); this.#stmtDataVersion = this.#prepare("PRAGMA data_version"); this.#stmtFamilyDone = this.#prepare(` SELECT family_key, COUNT(*) AS n FROM requests WHERE state = 'DONE' AND family_key IS NOT NULL GROUP BY family_key `); this.#stmtCashByKey = this.#prepare( "SELECT id, opic_cash, depth FROM requests WHERE unique_key = $key", ); this.#stmtDebitCash = this.#prepare(` UPDATE requests SET opic_history = opic_history + opic_cash, opic_cash = 0 WHERE id = $id `); this.#stmtCreditCash = this.#prepare(` UPDATE requests SET opic_cash = opic_cash + $share WHERE unique_key = $key RETURNING id, state, opic_cash `); this.#stmtUpdateScore = this.#prepare( "UPDATE requests SET score = $score WHERE id = $id", ); this.#stmtDueRevisits = this.#prepare(` SELECT ${REQUEST_COLS} FROM requests WHERE state = 'DONE' AND next_fetch_at IS NOT NULL AND next_fetch_at <= $now ORDER BY next_fetch_at ASC LIMIT $limit `); this.#stmtRequeueDue = this.#prepare(` UPDATE requests SET state = 'PENDING', retries = 0, locked_at = NULL, error_msg = NULL, next_fetch_at = NULL WHERE id IN ( SELECT id FROM requests WHERE state = 'DONE' AND next_fetch_at IS NOT NULL AND next_fetch_at <= $now ORDER BY next_fetch_at ASC LIMIT $limit ) RETURNING ${ENTRY_COLS}, change_rate, last_fetched_at `); this.#stmtSetRevisitPriority = this.#prepare( "UPDATE requests SET revisit_priority = $priority, score = $score WHERE id = $id", ); this.#stmtMinRevisit = this.#prepare(` SELECT MIN(next_fetch_at) AS at FROM requests WHERE state = 'DONE' AND next_fetch_at IS NOT NULL `); } // --------------------------------------------------------------------------- // Factory // --------------------------------------------------------------------------- /** * Open (or create) a persistent queue at `dbPathOrName`. * Pass `":memory:"` for ephemeral in-process queue (useful in tests). */ static open( dbPathOrName: string, opts?: RequestQueueOptions & { storageDir?: string }, ): RequestQueue { let dbPath = dbPathOrName; if ( !dbPathOrName.includes("/") && !dbPathOrName.includes("\\") && dbPathOrName !== ":memory:" ) { const storageDir = opts?.storageDir ?? BxcConfig.getGlobal().storageDir; dbPath = join(storageDir, "request_queues", `${dbPathOrName}.db`); } if (dbPath !== ":memory:") { try { mkdirSync(dirname(dbPath), { recursive: true }); } catch {} } return new RequestQueue(dbPath, opts); } // --------------------------------------------------------------------------- // Write operations // --------------------------------------------------------------------------- /** * Enqueue a URL. Silently de-duplicates by `uniqueKey`. * Returns `true` when the request was newly inserted, `false` if it already existed. */ addRequest(url: string, opts: AddRequestOptions = {}): boolean { this.#ensureLoaded(); const now = this.#clock(); const fresh: FrontierEntry[] = []; const inserted = this.#insertOne(url, opts, now, null, fresh); this.#attach(fresh, now); return inserted; } /** * Bulk add URLs from an iterable. Each URL that is already in the queue is skipped. * Runs in a single transaction with one prepared statement, then pushes the * new entries into the host heaps in bulk. * Returns the count of newly inserted requests. * * With `options.parent`, the parent's OPIC cash is split among the children. */ addRequests( urls: Iterable, options: AddRequestsOptions = {}, ): number { this.#ensureLoaded(); const now = this.#clock(); const fresh: FrontierEntry[] = []; let inserted = 0; const parentKey = options.parent; this.#tx(() => { if (parentKey === undefined) { for (const item of urls) { const url = typeof item === "string" ? item : item.url; const opts = typeof item === "string" ? EMPTY_OPTS : (item.opts ?? EMPTY_OPTS); if (this.#insertOne(url, opts, now, null, fresh)) inserted++; } return; } // OPIC: dedupe children, split the parent's cash equally. const children = new Map(); for (const item of urls) { const url = typeof item === "string" ? item : item.url; const opts = typeof item === "string" ? EMPTY_OPTS : (item.opts ?? EMPTY_OPTS); const key = opts.uniqueKey ?? url; if (key !== parentKey && !children.has(key)) children.set(key, { url, opts }); } const parent = this.#stmtCashByKey.get({ $key: parentKey }) as { id: number; opic_cash: number; depth: number; } | null; const share = parent && children.size > 0 ? parent.opic_cash / children.size : 0; const inherited = parent ? { cash: share, depth: parent.depth + 1 } : null; for (const [key, child] of children) { if (this.#insertOne(child.url, child.opts, now, inherited, fresh)) { inserted++; } else if (share > 0) { this.#creditChild(key, share, now); } } if (parent && children.size > 0) this.#debitParent(parent.id, parent.opic_cash, now); }); this.#attach(fresh, now); return inserted; } /** * OPIC step for a crawled page: move the parent's cash to its history and * split it equally among the existing children (duplicates and the parent * itself are ignored). Pending children are re-prioritised immediately. * Returns the number of children credited. */ distributeCash(parentUniqueKey: string, childUniqueKeys: Iterable): number { this.#ensureLoaded(); const now = this.#clock(); let credited = 0; this.#tx(() => { const parent = this.#stmtCashByKey.get({ $key: parentUniqueKey }) as { id: number; opic_cash: number; } | null; if (!parent) return; const children = new Set(childUniqueKeys); children.delete(parentUniqueKey); if (children.size === 0) return; const share = parent.opic_cash / children.size; this.#debitParent(parent.id, parent.opic_cash, now); if (!(share > 0)) return; for (const key of children) { if (this.#creditChild(key, share, now)) credited++; } }); return credited; } /** * Check whether a URL (or uniqueKey) is already tracked by the queue. */ has(uniqueKey: string): boolean { return this.#stmtExists.get({ $uniqueKey: uniqueKey }) !== null; } /** * Set (or clear with `null`) the crawl goal. Anchor relevance of every * pending request is recomputed and the heaps are rebuilt. */ setGoal(goal: string | null): void { this.#goal = compileGoal(goal); if (!this.#loaded) return; const rows = this.#stmtPendingAnchors.all() as Array<{ id: number; url: string; anchor_text: string | null; }>; for (const row of rows) { const entry = this.#pending.get(row.id); if (!entry) continue; entry.relevance = this.#goal ? anchorRelevance(this.#goal, row.anchor_text, row.url) : 0; entry.score = this.#computeScore(entry, entry.host.key); } for (const host of this.#hosts.values()) host.heap.rebuild(); this.#readyHosts.rebuild(); this.#waitingHosts.rebuild(); } /** * Politeness delay for one host (hostname or URL), e.g. learned from 429/503 * backoff by a domain-memory module. A negative value removes the override. * Applied from the last lock: `nextAllowedAt = lastLockAt + delay`. */ setHostDelay(host: string, delayMs: number): void { const key = this.#hostKeyOfArg(host); if (!(delayMs >= 0)) this.#hostDelays.delete(key); else this.#hostDelays.set(key, delayMs); const state = this.#hosts.get(key); if (!state) return; const now = this.#clock(); state.nextAllowedAt = state.lastLockAt + this.#delayFor(key); this.#reschedule(state, now); this.#notify(); } /** Effective politeness delay of a host (hostname or URL). */ getHostDelay(host: string): number { return this.#delayFor(this.#hostKeyOfArg(host)); } // --------------------------------------------------------------------------- // Scheduler internals // --------------------------------------------------------------------------- #hostKeyOf(url: string): string { try { return this.#hostKeyFn(url); } catch { return ""; } } #hostKeyOfArg(host: string): string { return this.#hostKeyOf(host.includes("://") ? host : `http://${host}/`); } #delayFor(key: string): number { return this.#hostDelays.get(key) ?? this.#perHostDelayMs; } #hostFor(key: string): HostState { let host = this.#hosts.get(key); if (!host) { host = { heapIndex: -1, key, heap: new IndexedHeap(entryBefore), inFlight: 0, lastLockAt: Number.NEGATIVE_INFINITY, nextAllowedAt: Number.NEGATIVE_INFINITY, slot: SLOT_IDLE, }; this.#hosts.set(key, host); } return host; } #computeScore(entry: FrontierEntry, hostKey: string): number { const score = this.#scoreFn( { opicCash: entry.cash, opicHistory: entry.history, anchorRelevance: entry.relevance, depth: entry.depth, familyDoneCount: entry.familyKey === null ? 0 : (this.#familyDone.get(entry.familyKey) ?? 0), boost: entry.boost, revisitPriority: entry.revisit, hostKey, }, this.#scoreParams, ); return Number.isNaN(score) ? 0 : score; } /** Insert one row; on success push a detached entry into `fresh`. */ #insertOne( url: string, opts: AddRequestOptions, now: number, inherited: { cash: number; depth: number } | null, fresh: FrontierEntry[], ): boolean { const hostKey = this.#hostKeyOf(url); const userDepth = opts.userData?.depth; const depth = Math.max( 0, Math.floor( finiteOr(opts.depth, inherited ? inherited.depth : finiteOr(userDepth, 0)), ), ); const anchorText = opts.anchorText ?? null; const familyKey = opts.familyKey !== undefined ? opts.familyKey : this.#familyKeyFn ? this.#familyKeyFn(url) : null; const draft: FrontierEntry = { heapIndex: -1, id: 0, host: undefined as unknown as HostState, lane: opts.forefront === true ? 1 : 0, score: 0, depth, cash: finiteOr(opts.opicCash, inherited ? inherited.cash : this.#initialCash), history: 0, boost: finiteOr(opts.boost, 0), revisit: 0, relevance: this.#goal ? anchorRelevance(this.#goal, anchorText, url) : 0, familyKey, }; draft.score = this.#computeScore(draft, hostKey); const result = this.#stmtInsert.run({ $uniqueKey: opts.uniqueKey ?? url, $url: url, $method: (opts.method ?? "GET").toUpperCase(), $payload: opts.payload ?? null, $headers: opts.headers ? JSON.stringify(opts.headers) : null, $userData: opts.userData ? JSON.stringify(opts.userData) : null, $priority: draft.lane, $now: now, $score: draft.score, $depth: depth, $cash: draft.cash, $anchorText: anchorText, $familyKey: familyKey, $boost: draft.boost, }); if (result.changes === 0) return false; draft.id = Number(result.lastInsertRowid); draft.host = this.#hostFor(hostKey); fresh.push(draft); return true; } #entryFromRow(row: EntryRow): FrontierEntry { const hostKey = this.#hostKeyOf(row.url); const entry: FrontierEntry = { heapIndex: -1, id: row.id, host: this.#hostFor(hostKey), lane: row.priority > 0 ? 1 : 0, score: 0, depth: row.depth ?? 0, cash: row.opic_cash ?? 0, history: row.opic_history ?? 0, boost: row.boost ?? 0, revisit: row.revisit_priority ?? 0, relevance: this.#goal ? anchorRelevance(this.#goal, row.anchor_text, row.url) : 0, familyKey: row.family_key ?? null, }; entry.score = this.#computeScore(entry, hostKey); return entry; } /** Register new pending entries and push them into their host heaps. */ #attach(entries: FrontierEntry[], now: number): void { if (entries.length === 0) return; if (entries.length === 1) { const entry = entries[0]; this.#register(entry); entry.host.heap.push(entry); this.#reschedule(entry.host, now); } else { const byHost = new Map(); for (const entry of entries) { this.#register(entry); const list = byHost.get(entry.host); if (list) list.push(entry); else byHost.set(entry.host, [entry]); } for (const [host, list] of byHost) { host.heap.pushAll(list); this.#reschedule(host, now); } } this.#notify(); } #register(entry: FrontierEntry): void { this.#pending.set(entry.id, entry); if (entry.id > this.#maxKnownId) this.#maxKnownId = entry.id; if (entry.familyKey !== null) { const members = this.#familyPending.get(entry.familyKey); if (members) members.add(entry); else this.#familyPending.set(entry.familyKey, new Set([entry])); } } /** Forget a pending entry that was already popped from its host heap. */ #unregister(entry: FrontierEntry): void { this.#pending.delete(entry.id); if (entry.familyKey !== null) { const members = this.#familyPending.get(entry.familyKey); if (members) { members.delete(entry); if (members.size === 0) this.#familyPending.delete(entry.familyKey); } } } /** Remove a pending entry from the scheduler (state changed outside the heap path). */ #dropPending(entry: FrontierEntry, now: number): void { entry.host.heap.remove(entry); this.#unregister(entry); this.#reschedule(entry.host, now); } /** Move a host into the heap matching its current state. */ #reschedule(host: HostState, now: number): void { let slot: number; if (host.heap.size === 0) slot = SLOT_IDLE; else if (host.inFlight >= this.#maxInFlightPerHost) slot = SLOT_BLOCKED; else if (host.nextAllowedAt > now) slot = SLOT_WAITING; else slot = SLOT_READY; if (slot === host.slot) { if (slot === SLOT_READY) this.#readyHosts.update(host); else if (slot === SLOT_WAITING) this.#waitingHosts.update(host); } else { if (host.slot === SLOT_READY) this.#readyHosts.remove(host); else if (host.slot === SLOT_WAITING) this.#waitingHosts.remove(host); host.slot = slot; if (slot === SLOT_READY) this.#readyHosts.push(host); else if (slot === SLOT_WAITING) this.#waitingHosts.push(host); } if (slot === SLOT_IDLE && host.inFlight === 0 && host.nextAllowedAt <= now) { this.#hosts.delete(host.key); } } /** Promote waiting hosts whose politeness delay expired. */ #promote(now: number): void { while (true) { const host = this.#waitingHosts.peek(); if (!host || host.nextAllowedAt > now) return; this.#waitingHosts.pop(); host.slot = SLOT_IDLE; this.#reschedule(host, now); } } #releaseSlot(id: number, now: number): void { const host = this.#inFlight.get(id); if (!host) return; this.#inFlight.delete(id); host.inFlight = Math.max(0, host.inFlight - 1); if (!this.#hosts.has(host.key)) this.#hosts.set(host.key, host); this.#reschedule(host, now); } /** Re-score a set of entries after a shared input changed. */ #rescore(entries: Iterable, now: number): void { const byHost = new Map(); for (const entry of entries) { entry.score = this.#computeScore(entry, entry.host.key); const list = byHost.get(entry.host); if (list) list.push(entry); else byHost.set(entry.host, [entry]); } for (const [host, list] of byHost) { if (list.length === 1) host.heap.update(list[0]); else host.heap.rebuild(); } if (byHost.size === 1) { for (const host of byHost.keys()) this.#reschedule(host, now); } else if (byHost.size > 1) { this.#readyHosts.rebuild(); this.#waitingHosts.rebuild(); } } #bumpFamily(familyKey: string, delta: number, now: number): void { const count = Math.max(0, (this.#familyDone.get(familyKey) ?? 0) + delta); if (count === 0) this.#familyDone.delete(familyKey); else this.#familyDone.set(familyKey, count); const members = this.#familyPending.get(familyKey); if (members && members.size > 0) this.#rescore(members, now); } #debitParent(id: number, cash: number, now: number): void { this.#stmtDebitCash.run({ $id: id }); const entry = this.#pending.get(id); if (!entry) return; entry.history += cash; entry.cash = 0; this.#rescore([entry], now); } #creditChild(uniqueKey: string, share: number, now: number): boolean { const row = this.#stmtCreditCash.get({ $key: uniqueKey, $share: share }) as { id: number; state: RequestState; opic_cash: number; } | null; if (!row) return false; const entry = this.#pending.get(row.id); if (entry) { entry.cash = row.opic_cash; this.#rescore([entry], now); this.#stmtUpdateScore.run({ $id: row.id, $score: entry.score }); } return true; } /** Build the in-memory scheduler from PENDING rows (once). */ #ensureLoaded(): void { if (this.#loaded) return; this.#loaded = true; for (const row of this.#stmtFamilyDone.all() as Array<{ family_key: string; n: number }>) { this.#familyDone.set(row.family_key, row.n); } const entries: FrontierEntry[] = []; for (const row of this.#stmtPendingRows.iterate() as IterableIterator) { entries.push(this.#entryFromRow(row)); } this.#maxKnownId = (this.#stmtMaxId.get() as { id: number }).id; this.#dataVersion = this.#readDataVersion(); if (this.#enableRevisits) this.#refreshNextRevisit(); this.#attach(entries, this.#clock()); } #readDataVersion(): number { return (this.#stmtDataVersion.get() as { data_version: number }).data_version; } #refreshNextRevisit(): void { const row = this.#stmtMinRevisit.get() as { at: number | null } | null; this.#nextRevisitAt = row?.at ?? Number.POSITIVE_INFINITY; } /** * Pick up rows written by other connections (other processes sharing the * file). Cheap when nothing changed: a single `PRAGMA data_version`. */ #syncExternal(now: number): boolean { if (!this.#loaded || this.#closed) return false; const version = this.#readDataVersion(); if (version === this.#dataVersion) return false; this.#dataVersion = version; let rows = this.#stmtPendingAfter.all({ $id: this.#maxKnownId }) as EntryRow[]; const sqlPending = (this.#stmtPendingCount.get() as { n: number }).n; if (sqlPending !== this.#pending.size + rows.length) { // Requeues / locks by other processes: reconcile the whole pending set. rows = []; const seen = new Set(); for (const row of this.#stmtPendingRows.iterate() as IterableIterator) { seen.add(row.id); if (!this.#pending.has(row.id)) rows.push(row); } for (const entry of Array.from(this.#pending.values())) { if (!seen.has(entry.id)) this.#dropPending(entry, now); } } const maxId = (this.#stmtMaxId.get() as { id: number }).id; if (maxId > this.#maxKnownId) this.#maxKnownId = maxId; if (this.#enableRevisits) this.#refreshNextRevisit(); const fresh = rows.filter((row) => !this.#pending.has(row.id)).map((row) => this.#entryFromRow(row)); this.#attach(fresh, now); return fresh.length > 0; } /** Time-driven maintenance run before dequeuing or waiting. */ #tick(now: number): void { if (this.#enableRevisits && now >= this.#nextRevisitAt) this.requeueDueRevisits(now); this.#promote(now); if (this.#readyHosts.size === 0 && this.#externalSyncMs > 0 && this.#syncExternal(now)) { this.#promote(now); } } // --------------------------------------------------------------------------- // Fetch / lock // --------------------------------------------------------------------------- /** * Atomically fetch and lock up to `limit` requests from hosts that are ready * now, highest score first. When a host has a politeness delay, at most one * of its requests is taken per call (its `nextAllowedAt` moves into the future). * Returns the locked rows as `QueuedRequest[]`. */ fetchBatch(limit = 1): QueuedRequest[] { const results: QueuedRequest[] = []; if (this.#closed) return results; this.#ensureLoaded(); const now = this.#clock(); this.#tick(now); if (!(limit > 0) || this.#readyHosts.size === 0) return results; this.#tx(() => { while (results.length < limit) { const host = this.#readyHosts.peek(); if (!host) break; const entry = host.heap.pop() as FrontierEntry; this.#unregister(entry); const row = this.#stmtLockAndReturn.get({ $id: entry.id, $now: now, $score: entry.score, }); if (row === null) { // Locked or removed by another connection meanwhile. this.#reschedule(host, now); continue; } host.inFlight++; host.lastLockAt = now; host.nextAllowedAt = now + this.#delayFor(host.key); this.#inFlight.set(entry.id, host); this.#reschedule(host, now); results.push(this.#mapRow(row)); } }); return results; } // --------------------------------------------------------------------------- // Completion / retry // --------------------------------------------------------------------------- /** * Mark a request as successfully handled. Tracks fetch/change counters and, * when revisits are enabled, schedules the next visit from the estimated * change rate and importance. */ markDone(id: number, opts: MarkDoneOptions = {}): void { const prev = this.#stmtDoneInfo.get(id) as { state: RequestState; family_key: string | null; content_hash: string | null; } | null; if (prev === null) return; const now = this.#clock(); const hash = opts.contentHash ?? null; const changed = opts.changed ?? (hash !== null && prev.content_hash !== null && prev.content_hash !== hash); const row = this.#stmtMarkDone.get({ $id: id, $now: now, $hash: hash, $changed: changed ? 1 : 0, }) as DoneRow; if (this.#loaded) { this.#releaseSlot(id, now); const pendingEntry = this.#pending.get(id); if (pendingEntry) this.#dropPending(pendingEntry, now); if (prev.state !== "DONE" && prev.family_key !== null) { this.#bumpFamily(prev.family_key, 1, now); } } if (this.#enableRevisits) this.#scheduleRevisit(id, row, now); this.#notify(); } /** * Mark a request as failed. If retries < maxRetries, it is re-queued as PENDING. * Otherwise, it enters the dead-letter queue (state = FAILED). */ markFailed(id: number, errorMessage: string): void { const row = this.#stmtGetRetries.get(id) as { retries: number } | null; if (row === null) return; const now = this.#clock(); if (this.#loaded) this.#releaseSlot(id, now); if (row.retries < this.#maxRetries) { const requeued = this.#stmtRequeue.get({ $id: id, $msg: errorMessage }) as EntryRow | null; if (requeued && this.#loaded && !this.#pending.has(id)) { this.#attach([this.#entryFromRow(requeued)], now); } } else { this.#stmtMarkFailed.run({ $id: id, $msg: errorMessage, $now: now, }); const pendingEntry = this.#pending.get(id); if (pendingEntry) this.#dropPending(pendingEntry, now); } this.#notify(); } // --------------------------------------------------------------------------- // Revisit scheduler // --------------------------------------------------------------------------- #scheduleRevisit(id: number, row: DoneRow, now: number): void { const rate = estimateChangeRate( { fetchCount: row.fetch_count, changeCount: row.change_count, firstFetchedAt: row.first_fetched_at, lastFetchedAt: row.last_fetched_at, }, this.#revisitPolicy, ); const opic = row.opic_history + row.opic_cash; const importance = opic > 0 ? opic : Math.max(0, row.score); const next = Math.round(now + revisitIntervalMs(rate, importance, this.#revisitPolicy)); this.#stmtScheduleRevisit.run({ $id: id, $rate: rate, $next: next }); if (next < this.#nextRevisitAt) this.#nextRevisitAt = next; } /** DONE requests whose revisit is due at `now` (read-only view). */ dueRevisits(now: number = this.#clock(), limit = 1000): QueuedRequest[] { return (this.#stmtDueRevisits.all({ $now: now, $limit: limit }) as any[]).map((row) => this.#mapRow(row), ); } /** * Move due revisits back to PENDING. Their `revisitPriority` is the expected * freshness gain (importance weight × probability the page changed since the * last fetch). Called automatically by `fetchBatch()` / `waitForWork()` when * `enableRevisits` is set. Returns the number of re-queued requests. */ requeueDueRevisits(now: number = this.#clock(), limit = 10_000): number { this.#ensureLoaded(); let count = 0; const fresh: FrontierEntry[] = []; this.#tx(() => { const rows = this.#stmtRequeueDue.all({ $now: now, $limit: limit }) as Array< EntryRow & { change_rate: number | null; last_fetched_at: number | null } >; count = rows.length; for (const row of rows) { if (row.family_key !== null) this.#bumpFamily(row.family_key, -1, now); } for (const row of rows) { const opic = row.opic_history + row.opic_cash; const elapsed = row.last_fetched_at === null ? 0 : now - row.last_fetched_at; row.revisit_priority = revisitPriority( row.change_rate ?? 0, opic > 0 ? opic : 1, elapsed, this.#revisitPolicy, ); if (this.#pending.has(row.id)) continue; const entry = this.#entryFromRow(row); this.#stmtSetRevisitPriority.run({ $id: row.id, $priority: row.revisit_priority, $score: entry.score, }); fresh.push(entry); } }); this.#refreshNextRevisit(); this.#attach(fresh, now); return count; } // --------------------------------------------------------------------------- // Maintenance // --------------------------------------------------------------------------- /** * Recover stale LOCKED requests (e.g., worker crashed mid-task). * Any request locked more than `lockTimeoutMs` ago is reset to PENDING. * Returns the number of recovered requests. */ recoverStaleLocks(): number { const now = this.#clock(); const rows = this.#stmtRecoverStale.all({ $staleThreshold: now - this.#lockTimeoutMs, }) as EntryRow[]; if (rows.length === 0 || !this.#loaded) return rows.length; const fresh: FrontierEntry[] = []; for (const row of rows) this.#releaseSlot(row.id, now); for (const row of rows) { if (!this.#pending.has(row.id)) fresh.push(this.#entryFromRow(row)); } this.#attach(fresh, now); return rows.length; } /** Return stats about the queue state. */ stats(): RequestQueueStats { return this.#stmtStats.get() as RequestQueueStats; } /** In-memory scheduler diagnostics (hosts, heaps, in-flight). */ frontierStats(): FrontierStats { this.#ensureLoaded(); let blockedHosts = 0; for (const host of this.#hosts.values()) if (host.slot === SLOT_BLOCKED) blockedHosts++; return { hosts: this.#hosts.size, readyHosts: this.#readyHosts.size, waitingHosts: this.#waitingHosts.size, blockedHosts, pending: this.#pending.size, inFlight: this.#inFlight.size, nextAllowedAt: this.#waitingHosts.peek()?.nextAllowedAt ?? null, nextRevisitAt: Number.isFinite(this.#nextRevisitAt) ? this.#nextRevisitAt : null, goal: this.#goal?.text ?? null, }; } /** Return all requests in the dead-letter queue (state = FAILED). */ deadLetterQueue(): QueuedRequest[] { return (this.#stmtDlq.all() as any[]).map((row) => this.#mapRow(row)); } /** * Re-enqueue all failed requests (reset to PENDING, retries reset to 0). * Useful for resuming a partially-failed crawl. * Returns the total number of pending requests afterwards. */ replayFailed(): number { const rows = this.#stmtReplayFailed.all() as EntryRow[]; if (this.#loaded && rows.length > 0) { const now = this.#clock(); const fresh = rows .filter((row) => !this.#pending.has(row.id)) .map((row) => this.#entryFromRow(row)); this.#attach(fresh, now); } return this.stats().pending; } /** * Perform WAL checkpoint to flush and truncate WAL logs, preventing unbounded growth during 24/7 crawls. */ checkpoint(mode: "PASSIVE" | "FULL" | "RESTART" | "TRUNCATE" = "PASSIVE"): void { try { this.#db.exec(`PRAGMA wal_checkpoint(${mode});`); } catch (err) { console.warn("[queue] WAL checkpoint failed:", err); } } /** Close the underlying SQLite connection, clear timers and release waiters. */ close(): void { if (this.#closed) return; this.#closed = true; this.#clearTimer(); for (const waiter of Array.from(this.#waiters)) waiter.resolve(); for (const stmt of this.#statements) stmt.finalize(); this.#db.close(); } // --------------------------------------------------------------------------- // Event-driven waiting // --------------------------------------------------------------------------- /** `true` when no request is PENDING or LOCKED (in any connection). */ isFinished(): boolean { if (this.#closed) return true; const row = this.#stmtActive.get() as { active: number }; return row.active === 0; } /** * Resolve when a request can be dequeued now, or when the queue is finished * (unless `ignoreFinished`), or when `signal` aborts, or when the queue is * closed. Never rejects: callers re-check state after it resolves. * * Wake-ups come from inserts, requeues, slot releases (markDone / * markFailed), a single timer armed at the earliest host `nextAllowedAt` or * revisit, and — for file databases — `PRAGMA data_version` checks every * `externalSyncMs` while waiting. */ waitForWork(signal?: AbortSignal, opts: WaitForWorkOptions = {}): Promise { if (this.#closed || signal?.aborted) return Promise.resolve(); this.#ensureLoaded(); const now = this.#clock(); this.#tick(now); if (this.#readyHosts.size > 0) return Promise.resolve(); const ignoreFinished = opts.ignoreFinished === true; if (!ignoreFinished && this.isFinished()) return Promise.resolve(); return new Promise((resolve) => { let settled = false; const waiter: Waiter = { ignoreFinished, resolve: () => { if (settled) return; settled = true; this.#waiters.delete(waiter); signal?.removeEventListener("abort", waiter.resolve); if (this.#waiters.size === 0) this.#clearTimer(); resolve(); }, }; signal?.addEventListener("abort", waiter.resolve, { once: true }); this.#waiters.add(waiter); this.#armTimer(now); }); } #notify(): void { if (this.#waiters.size === 0 || this.#closed || this.#notifyScheduled) return; this.#notifyScheduled = true; queueMicrotask(() => { this.#notifyScheduled = false; this.#checkWaiters(); }); } #checkWaiters(): void { if (this.#waiters.size === 0) return; if (this.#closed) { for (const waiter of Array.from(this.#waiters)) waiter.resolve(); return; } const now = this.#clock(); this.#tick(now); if (this.#readyHosts.size > 0) { for (const waiter of Array.from(this.#waiters)) waiter.resolve(); return; } let finished: boolean | null = null; for (const waiter of Array.from(this.#waiters)) { if (waiter.ignoreFinished) continue; finished ??= this.isFinished(); if (!finished) break; waiter.resolve(); } if (this.#waiters.size > 0) this.#armTimer(now); } /** Arm one timer at the earliest time something may become ready. */ #armTimer(now: number): void { let at = Number.POSITIVE_INFINITY; const waiting = this.#waitingHosts.peek(); if (waiting) at = waiting.nextAllowedAt; if (this.#enableRevisits && this.#nextRevisitAt < at) at = this.#nextRevisitAt; if (this.#externalSyncMs > 0) at = Math.min(at, now + this.#externalSyncMs); if (!Number.isFinite(at)) { this.#clearTimer(); return; } if (this.#timer !== null && this.#timerAt <= at) return; this.#clearTimer(); this.#timerAt = at; this.#timer = setTimeout( () => { this.#timer = null; this.#timerAt = Number.POSITIVE_INFINITY; this.#checkWaiters(); }, Math.max(1, Math.ceil(at - now)), ); } #clearTimer(): void { if (this.#timer !== null) clearTimeout(this.#timer); this.#timer = null; this.#timerAt = Number.POSITIVE_INFINITY; } // --------------------------------------------------------------------------- // Async iteration helper // --------------------------------------------------------------------------- /** * Async generator that continuously yields batches of locked requests * until the queue is empty and there are nothing locked. * * @param batchSize - Number of requests to fetch per tick. Default: 10. * @param _pollMs - Unused (kept for backward compatibility): waiting is event-driven. */ async *drain(batchSize = 10, _pollMs = 500): AsyncGenerator { const size = Math.max(1, batchSize); while (!this.#closed) { const batch = this.fetchBatch(size); if (batch.length > 0) { yield batch; continue; } if (this.isFinished()) break; await this.waitForWork(); } } }