/** * 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. */ /** * Domain memory: persistent, per-eTLD+1 knowledge of how to fetch a site. * * For every registrable domain it learns, from recorded attempts: * - which escalation tier works (EWMA success per tier), so the next URL on the * same site (any subdomain) starts at the right tier instead of re-failing * through the cheap ones; * - which proxies work (Thompson sampling on Beta(successes+1, failures+1), * bans with exponential backoff after consecutive failures); * - the block signatures seen and the last fingerprint that succeeded; * - a politeness delay (AIMD: multiplicative increase on 429/503, additive * decrease on success) that honours `Retry-After`. * * Storage is SQLite (`bun:sqlite`, WAL, prepared statements); every method is * synchronous and costs a few tens of microseconds. * * Usage (per request): * const memory = DomainMemory.shared(); * const tier = memory.startTier(url); * const proxy = memory.chooseProxy(url, proxyPool); * await Bun.sleep(memory.politenessDelayMs(url)); * // ... fetch ... * memory.recordAttempt(url, { tier, proxy, outcome: "success", status, latencyMs }); */ import { Database, type Statement } from "bun:sqlite"; import { mkdirSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { ESCALATION_ORDER, type EscalationStep } from "./auto-escalation.ts"; import { registrableDomain } from "./etld.ts"; export type AttemptOutcome = "success" | "blocked" | "error" | "throttled"; export interface AttemptRecord { /** Tier (profile) the attempt used. */ tier: EscalationStep; outcome: AttemptOutcome; /** Detector reason, e.g. `cloudflare`, `js_required`, `status_403`. */ reason?: string; /** HTTP status, when a response was received. 429/503 grow the politeness delay. */ status?: number; /** Proxy URL used for the attempt; updates its score for this domain. */ proxy?: string; /** Fingerprint / profile variant id; remembered when the attempt succeeds. */ fingerprint?: string; /** Wall-clock latency of a successful attempt. */ latencyMs?: number; /** Parsed `Retry-After` in milliseconds (see {@link parseRetryAfter}). */ retryAfterMs?: number; /** Block signature for blocked/throttled attempts. Defaults to `reason@status`. */ signature?: string; } export interface DomainMemoryOptions { /** SQLite path. Default: `$BXC_DOMAIN_MEMORY_PATH` or `~/.bxc/domain-memory.sqlite`. `":memory:"` for tests. */ path?: string; /** EWMA smoothing factor in (0, 1]. Default 0.3. */ alpha?: number; /** EWMA success a tier needs to be considered good. Default 0.6. */ successThreshold?: number; /** Attempts on a tier before its EWMA is trusted. Default 2. */ minEvidence?: number; /** Re-probe a cheaper tier this long after its last failure. Default 24 h. */ reprobeAfterMs?: number; /** Probability of re-probing once eligible. Default 0.1. */ reprobeProbability?: number; /** Consecutive failures before a proxy is banned for a domain. Default 3. */ proxyBanAfter?: number; /** First ban duration; doubles on each further failure. Default 60 s. */ proxyBanBaseMs?: number; /** Ban duration cap. Default 6 h. */ proxyBanMaxMs?: number; /** Delay after the first throttle. Default 1000 ms. */ politenessInitialMs?: number; /** Multiplicative increase factor. Default 2. */ politenessMultiplier?: number; /** Delay cap. Default 60 000 ms. */ politenessMaxMs?: number; /** Additive decrease per success. Default 100 ms. */ politenessDecreaseMs?: number; /** Delay floor. Default 0. */ politenessMinMs?: number; /** Millisecond clock. Default `Date.now`. */ clock?: () => number; /** Uniform [0, 1) RNG for Thompson sampling and exploration. Default `Math.random`. */ random?: () => number; } export type StartTierSource = /** No attempt recorded for the domain. */ | "unknown" /** Cheapest tier with enough evidence and EWMA >= threshold. */ | "known-good" /** Cheapest tier that has succeeded and is not known-bad. */ | "best-tier" /** First tier above the most expensive known-bad tier. */ | "above-known-bad" /** Some attempts recorded, none conclusive. */ | "insufficient-evidence" /** Exploration: the nearest cheaper tier that failed, re-probed after the TTL. */ | "reprobe"; export interface StartTierDecision { /** eTLD+1 the decision was made for. */ domain: string; tier: EscalationStep; source: StartTierSource; /** Tier chosen without exploration. */ exploitTier: EscalationStep; } export interface DomainTierSnapshot { tier: string; successes: number; failures: number; ewmaSuccess: number; ewmaLatencyMs: number | null; lastOutcomeAt: string | null; lastSuccessAt: string | null; lastFailureAt: string | null; } export interface DomainProxySnapshot { proxy: string; attempts: number; successes: number; ewmaSuccess: number; consecutiveFailures: number; bannedUntil: string | null; lastUsedAt: string | null; } export interface DomainBlockSignatureSnapshot { signature: string; reason: string | null; count: number; firstSeen: string; lastSeen: string; } export interface DomainSnapshot { domain: string; known: boolean; bestTier: string | null; startTier: EscalationStep; startSource: StartTierSource; fingerprint: string | null; politenessDelayMs: number; retryAfterUntil: string | null; lastBlockAt: string | null; updatedAt: string | null; tiers: DomainTierSnapshot[]; proxies: DomainProxySnapshot[]; blockSignatures: DomainBlockSignatureSnapshot[]; } export interface DomainMemoryStats { path: string; domains: number; blockedDomains: number; tierRows: number; proxyRows: number; bannedProxies: number; blockSignatures: number; } type Bindings = Record; interface DomainRow { etld1: string; best_tier: string | null; tier_stats: string; fingerprint: string | null; politeness_delay_ms: number; retry_after_until: number | null; last_block_at: number | null; updated_at: number; } interface TierRow { tier: string; successes: number; failures: number; ewma_success: number; ewma_latency_ms: number | null; last_outcome_at: number | null; last_success_at: number | null; last_failure_at: number | null; } interface ProxyRow { proxy: string; ewma_success: number; attempts: number; successes: number; consecutive_failures: number; banned_until: number | null; last_used_at: number | null; } interface SignatureRow { signature: string; reason: string | null; count: number; first_seen: number; last_seen: number; } const OUTCOMES: ReadonlySet = new Set(["success", "blocked", "error", "throttled"]); const SCHEMA = ` CREATE TABLE IF NOT EXISTS domains ( etld1 TEXT PRIMARY KEY, best_tier TEXT, tier_stats TEXT NOT NULL DEFAULT '{}', fingerprint TEXT, politeness_delay_ms REAL NOT NULL DEFAULT 0, retry_after_until INTEGER, last_block_at INTEGER, updated_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS domain_tier_stats ( etld1 TEXT NOT NULL, tier TEXT NOT NULL, successes INTEGER NOT NULL DEFAULT 0, failures INTEGER NOT NULL DEFAULT 0, ewma_success REAL NOT NULL DEFAULT 0, ewma_latency_ms REAL, last_outcome_at INTEGER, last_success_at INTEGER, last_failure_at INTEGER, PRIMARY KEY (etld1, tier) ) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS domain_proxy_scores ( etld1 TEXT NOT NULL, proxy TEXT NOT NULL, ewma_success REAL NOT NULL DEFAULT 0, attempts INTEGER NOT NULL DEFAULT 0, successes INTEGER NOT NULL DEFAULT 0, consecutive_failures INTEGER NOT NULL DEFAULT 0, banned_until INTEGER, last_used_at INTEGER, PRIMARY KEY (etld1, proxy) ) WITHOUT ROWID; CREATE TABLE IF NOT EXISTS domain_block_signatures ( etld1 TEXT NOT NULL, signature TEXT NOT NULL, reason TEXT, count INTEGER NOT NULL DEFAULT 0, first_seen INTEGER NOT NULL, last_seen INTEGER NOT NULL, PRIMARY KEY (etld1, signature) ) WITHOUT ROWID; `; /** Default on-disk location: `$BXC_DOMAIN_MEMORY_PATH` or `~/.bxc/domain-memory.sqlite`. */ export function defaultDomainMemoryPath(): string { const override = Bun.env.BXC_DOMAIN_MEMORY_PATH; if (override && override.trim()) return override.trim(); return join(homedir(), ".bxc", "domain-memory.sqlite"); } /** * Parses a `Retry-After` header value (delta-seconds or HTTP-date) into a * non-negative delay in milliseconds. Returns `undefined` when absent or invalid. */ export function parseRetryAfter( value: string | number | null | undefined, now: number = Date.now(), ): number | undefined { if (value === null || value === undefined) return undefined; if (typeof value === "number") { return Number.isFinite(value) && value >= 0 ? Math.round(value * 1000) : undefined; } const trimmed = value.trim(); if (!trimmed) return undefined; if (/^\d+(?:\.\d+)?$/.test(trimmed)) { return Math.round(Number(trimmed) * 1000); } // HTTP-date must contain letters (IMF-fixdate, RFC 850 or asctime). if (!/[a-z]/i.test(trimmed)) return undefined; const at = Date.parse(trimmed); if (!Number.isFinite(at)) return undefined; return Math.max(0, at - now); } /** Deterministic uniform [0, 1) generator (mulberry32) for tests and replays. */ export function createSeededRandom(seed: number): () => number { let state = seed >>> 0; return () => { state = (state + 0x6d2b79f5) >>> 0; let t = state; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } function uniformOpen(random: () => number): number { const u = random(); return Math.min(1 - 1e-12, Math.max(1e-12, u)); } /** * Draws from Beta(a, b) for a, b >= 1 using closed forms when a or b is 1 and * Cheng's BB algorithm (1978) otherwise. O(1) expected time for any counts. */ export function sampleBeta(a: number, b: number, random: () => number = Math.random): number { if (!(a > 0 && b > 0)) throw new RangeError(`Beta parameters must be > 0 (got ${a}, ${b})`); if (a === 1 && b === 1) return uniformOpen(random); if (a === 1) return 1 - uniformOpen(random) ** (1 / b); if (b === 1) return uniformOpen(random) ** (1 / a); if (a < 1 || b < 1) { // Not needed for count-based priors; fall back to the mean. return a / (a + b); } const lo = Math.min(a, b); const hi = Math.max(a, b); const alpha = lo + hi; const beta = Math.sqrt((alpha - 2) / (2 * lo * hi - alpha)); const gamma = lo + 1 / beta; let w = 0; for (let i = 0; i < 1000; i++) { const u1 = uniformOpen(random); const u2 = uniformOpen(random); const v = beta * Math.log(u1 / (1 - u1)); w = lo * Math.exp(v); const z = u1 * u1 * u2; const r = gamma * v - 1.3862944; const s = lo + r - w; if (s + 2.609438 >= 5 * z) break; const t = Math.log(z); if (s > t) break; if (r + alpha * Math.log(alpha / (hi + w)) >= t) break; } return lo === a ? w / (hi + w) : hi / (hi + w); } function iso(ms: number | null | undefined): string | null { return ms === null || ms === undefined ? null : new Date(ms).toISOString(); } function redactProxy(proxy: string): string { return proxy.replace(/\/\/[^/@\s]*@/, "//***@"); } function round(value: number, digits = 3): number { const f = 10 ** digits; return Math.round(value * f) / f; } let sharedInstance: DomainMemory | undefined; export class DomainMemory { readonly path: string; readonly #db: Database; readonly #alpha: number; readonly #threshold: number; readonly #minEvidence: number; readonly #reprobeAfterMs: number; readonly #reprobeProbability: number; readonly #banAfter: number; readonly #banBaseMs: number; readonly #banMaxMs: number; readonly #politeInitialMs: number; readonly #politeMultiplier: number; readonly #politeMaxMs: number; readonly #politeDecreaseMs: number; readonly #politeMinMs: number; readonly #clock: () => number; readonly #random: () => number; readonly #selDomain: Statement; readonly #selTiers: Statement; readonly #upsertTier: Statement; readonly #upsertDomain: Statement; readonly #selProxies: Statement; readonly #selProxy: Statement; readonly #upsertProxy: Statement; readonly #touchProxy: Statement; readonly #upsertSignature: Statement; readonly #selSignatures: Statement; readonly #record: (url: string, attempt: AttemptRecord) => void; constructor(options: DomainMemoryOptions = {}) { this.path = options.path ?? defaultDomainMemoryPath(); this.#alpha = Math.min(1, Math.max(1e-6, options.alpha ?? 0.3)); this.#threshold = options.successThreshold ?? 0.6; this.#minEvidence = Math.max(1, options.minEvidence ?? 2); this.#reprobeAfterMs = options.reprobeAfterMs ?? 24 * 60 * 60_000; this.#reprobeProbability = options.reprobeProbability ?? 0.1; this.#banAfter = Math.max(1, options.proxyBanAfter ?? 3); this.#banBaseMs = options.proxyBanBaseMs ?? 60_000; this.#banMaxMs = options.proxyBanMaxMs ?? 6 * 60 * 60_000; this.#politeInitialMs = options.politenessInitialMs ?? 1000; this.#politeMultiplier = options.politenessMultiplier ?? 2; this.#politeMaxMs = options.politenessMaxMs ?? 60_000; this.#politeDecreaseMs = options.politenessDecreaseMs ?? 100; this.#politeMinMs = options.politenessMinMs ?? 0; this.#clock = options.clock ?? Date.now; this.#random = options.random ?? Math.random; const inMemory = this.path === ":memory:" || this.path === ""; if (!inMemory && !this.path.startsWith("file:")) { mkdirSync(dirname(this.path), { recursive: true }); } this.#db = new Database(this.path, { create: true, strict: true }); if (!inMemory) this.#db.exec("PRAGMA journal_mode = WAL;"); this.#db.exec("PRAGMA synchronous = NORMAL;"); this.#db.exec("PRAGMA busy_timeout = 5000;"); this.#db.exec(SCHEMA); this.#selDomain = this.#db.prepare("SELECT * FROM domains WHERE etld1 = $etld1"); this.#selTiers = this.#db.prepare( `SELECT tier, successes, failures, ewma_success, ewma_latency_ms, last_outcome_at, last_success_at, last_failure_at FROM domain_tier_stats WHERE etld1 = $etld1`, ); this.#upsertTier = this.#db.prepare( `INSERT INTO domain_tier_stats (etld1, tier, successes, failures, ewma_success, ewma_latency_ms, last_outcome_at, last_success_at, last_failure_at) VALUES ($etld1, $tier, $successes, $failures, $ewma_success, $ewma_latency_ms, $last_outcome_at, $last_success_at, $last_failure_at) ON CONFLICT(etld1, tier) DO UPDATE SET successes = excluded.successes, failures = excluded.failures, ewma_success = excluded.ewma_success, ewma_latency_ms = excluded.ewma_latency_ms, last_outcome_at = excluded.last_outcome_at, last_success_at = excluded.last_success_at, last_failure_at = excluded.last_failure_at`, ); this.#upsertDomain = this.#db.prepare( `INSERT INTO domains (etld1, best_tier, tier_stats, fingerprint, politeness_delay_ms, retry_after_until, last_block_at, updated_at) VALUES ($etld1, $best_tier, $tier_stats, $fingerprint, $politeness_delay_ms, $retry_after_until, $last_block_at, $updated_at) ON CONFLICT(etld1) DO UPDATE SET best_tier = excluded.best_tier, tier_stats = excluded.tier_stats, fingerprint = excluded.fingerprint, politeness_delay_ms = excluded.politeness_delay_ms, retry_after_until = excluded.retry_after_until, last_block_at = excluded.last_block_at, updated_at = excluded.updated_at`, ); const proxyColumns = `proxy, ewma_success, attempts, successes, consecutive_failures, banned_until, last_used_at`; this.#selProxies = this.#db.prepare( `SELECT ${proxyColumns} FROM domain_proxy_scores WHERE etld1 = $etld1`, ); this.#selProxy = this.#db.prepare( `SELECT ${proxyColumns} FROM domain_proxy_scores WHERE etld1 = $etld1 AND proxy = $proxy`, ); this.#upsertProxy = this.#db.prepare( `INSERT INTO domain_proxy_scores (etld1, proxy, ewma_success, attempts, successes, consecutive_failures, banned_until, last_used_at) VALUES ($etld1, $proxy, $ewma_success, $attempts, $successes, $consecutive_failures, $banned_until, $last_used_at) ON CONFLICT(etld1, proxy) DO UPDATE SET ewma_success = excluded.ewma_success, attempts = excluded.attempts, successes = excluded.successes, consecutive_failures = excluded.consecutive_failures, banned_until = excluded.banned_until, last_used_at = excluded.last_used_at`, ); this.#touchProxy = this.#db.prepare( `INSERT INTO domain_proxy_scores (etld1, proxy, last_used_at) VALUES ($etld1, $proxy, $now) ON CONFLICT(etld1, proxy) DO UPDATE SET last_used_at = excluded.last_used_at`, ); this.#upsertSignature = this.#db.prepare( `INSERT INTO domain_block_signatures (etld1, signature, reason, count, first_seen, last_seen) VALUES ($etld1, $signature, $reason, 1, $now, $now) ON CONFLICT(etld1, signature) DO UPDATE SET count = count + 1, reason = COALESCE(excluded.reason, reason), last_seen = excluded.last_seen`, ); this.#selSignatures = this.#db.prepare( `SELECT signature, reason, count, first_seen, last_seen FROM domain_block_signatures WHERE etld1 = $etld1 ORDER BY count DESC, last_seen DESC LIMIT 20`, ); this.#record = this.#db.transaction((url: string, attempt: AttemptRecord) => this.#recordInTransaction(url, attempt), ).immediate; } /** * Process-wide instance. Honours `BXC_DOMAIN_MEMORY_PATH`; under `bun test` * (NODE_ENV=test) without an explicit path it stays in memory so test runs * never write to the user's home directory. Falls back to an in-memory * store when the file cannot be opened. */ static shared(): DomainMemory { if (!sharedInstance) { const explicit = Bun.env.BXC_DOMAIN_MEMORY_PATH?.trim(); const path = explicit || (Bun.env.NODE_ENV === "test" ? ":memory:" : defaultDomainMemoryPath()); try { sharedInstance = new DomainMemory({ path }); } catch { sharedInstance = new DomainMemory({ path: ":memory:" }); } } return sharedInstance; } /** Closes and drops the process-wide instance (tests, path changes). */ static resetShared(): void { sharedInstance?.close(); sharedInstance = undefined; } /** Registrable domain (eTLD+1) used as the memory key for a URL or host. */ domainOf(url: string): string { return registrableDomain(url); } /** Records the outcome of one fetch attempt. */ recordAttempt(url: string, attempt: AttemptRecord): void { if (!OUTCOMES.has(attempt.outcome)) { throw new TypeError(`Unknown attempt outcome: ${String(attempt.outcome)}`); } if (!attempt.tier) throw new TypeError("recordAttempt requires a tier"); this.#record(url, attempt); } #ewma(previous: number, observation: number, hasHistory: boolean): number { return hasHistory ? previous + this.#alpha * (observation - previous) : observation; } #recordInTransaction(url: string, attempt: AttemptRecord): void { const etld1 = registrableDomain(url); if (!etld1) return; const now = this.#clock(); const { outcome, status } = attempt; const success = outcome === "success"; // Throttling is a rate signal, not evidence about the tier's capability. const countsForTier = outcome !== "throttled"; const throttled = outcome === "throttled" || status === 429 || status === 503; // --- Tier statistics ------------------------------------------------- const tiers = this.#selTiers.all({ etld1 }); let tierRow = tiers.find((row) => row.tier === attempt.tier); if (!tierRow) { tierRow = { tier: attempt.tier, successes: 0, failures: 0, ewma_success: 0, ewma_latency_ms: null, last_outcome_at: null, last_success_at: null, last_failure_at: null, }; tiers.push(tierRow); } if (countsForTier) { const history = tierRow.successes + tierRow.failures > 0; tierRow.ewma_success = this.#ewma(tierRow.ewma_success, success ? 1 : 0, history); if (success) { tierRow.successes++; tierRow.last_success_at = now; if (attempt.latencyMs !== undefined && Number.isFinite(attempt.latencyMs) && attempt.latencyMs >= 0) { tierRow.ewma_latency_ms = this.#ewma( tierRow.ewma_latency_ms ?? 0, attempt.latencyMs, tierRow.ewma_latency_ms !== null, ); } } else { tierRow.failures++; tierRow.last_failure_at = now; } } tierRow.last_outcome_at = now; this.#upsertTier.run({ etld1, ...tierRow }); // --- Domain row ------------------------------------------------------ const domain = this.#selDomain.get({ etld1 }); let delay = domain?.politeness_delay_ms ?? this.#politeMinMs; if (throttled) { delay = Math.max(this.#politeInitialMs, delay * this.#politeMultiplier); } else if (success) { delay -= this.#politeDecreaseMs; } delay = Math.min(this.#politeMaxMs, Math.max(this.#politeMinMs, delay)); let retryAfterUntil = domain?.retry_after_until ?? null; if (retryAfterUntil !== null && retryAfterUntil <= now) retryAfterUntil = null; if (attempt.retryAfterMs !== undefined && Number.isFinite(attempt.retryAfterMs) && attempt.retryAfterMs > 0) { retryAfterUntil = Math.max(retryAfterUntil ?? 0, now + attempt.retryAfterMs); } const summary: Record = {}; let bestTier: string | null = null; let bestRank = Number.POSITIVE_INFINITY; for (const row of tiers) { summary[row.tier] = { s: row.successes, f: row.failures, ewma: round(row.ewma_success), latencyMs: row.ewma_latency_ms === null ? null : Math.round(row.ewma_latency_ms), }; const rank = ESCALATION_ORDER.indexOf(row.tier as EscalationStep); if ( row.successes > 0 && row.ewma_success >= this.#threshold && (rank < 0 ? ESCALATION_ORDER.length : rank) < bestRank ) { bestRank = rank < 0 ? ESCALATION_ORDER.length : rank; bestTier = row.tier; } } const blockedOrThrottled = outcome === "blocked" || outcome === "throttled"; this.#upsertDomain.run({ etld1, best_tier: bestTier, tier_stats: JSON.stringify(summary), fingerprint: success && attempt.fingerprint ? attempt.fingerprint : (domain?.fingerprint ?? null), politeness_delay_ms: delay, retry_after_until: retryAfterUntil, last_block_at: blockedOrThrottled ? now : (domain?.last_block_at ?? null), updated_at: now, }); // --- Block signature ------------------------------------------------- if (blockedOrThrottled) { const signature = attempt.signature ?? `${attempt.reason ?? outcome}${status !== undefined ? `@${status}` : ""}`; this.#upsertSignature.run({ etld1, signature: signature.slice(0, 200), reason: attempt.reason ?? outcome, now, }); } // --- Proxy score ----------------------------------------------------- if (attempt.proxy) { const proxy = this.#selProxy.get({ etld1, proxy: attempt.proxy }); const attempts = proxy?.attempts ?? 0; const ewma = this.#ewma(proxy?.ewma_success ?? 0, success ? 1 : 0, attempts > 0); let consecutive = success ? 0 : (proxy?.consecutive_failures ?? 0) + 1; let bannedUntil: number | null = success ? null : (proxy?.banned_until ?? null); if (!success && consecutive >= this.#banAfter) { const exponent = Math.min(30, consecutive - this.#banAfter); bannedUntil = now + Math.min(this.#banMaxMs, this.#banBaseMs * 2 ** exponent); } if (consecutive > 1_000_000) consecutive = 1_000_000; this.#upsertProxy.run({ etld1, proxy: attempt.proxy, ewma_success: ewma, attempts: attempts + 1, successes: (proxy?.successes ?? 0) + (success ? 1 : 0), consecutive_failures: consecutive, banned_until: bannedUntil, last_used_at: now, }); } } /** * Decides where the escalation ladder should start for a URL, with the * reason. See {@link startTier}. */ planStart( url: string, ladder: readonly EscalationStep[] = ESCALATION_ORDER, options: { explore?: boolean } = {}, ): StartTierDecision { const domain = registrableDomain(url); const first = ladder[0] ?? "static"; const unknown: StartTierDecision = { domain, tier: first, source: "unknown", exploitTier: first, }; if (!domain || ladder.length === 0) return unknown; const rows = this.#selTiers.all({ etld1: domain }); if (rows.length === 0) return unknown; const stats = new Map(); for (const row of rows) stats.set(row.tier, row); const evidence = (row: TierRow) => row.successes + row.failures; const isGood = (row: TierRow | undefined) => row !== undefined && evidence(row) >= this.#minEvidence && row.ewma_success >= this.#threshold; const isBad = (row: TierRow | undefined) => row !== undefined && evidence(row) >= this.#minEvidence && row.ewma_success < this.#threshold; let index = ladder.findIndex((tier) => isGood(stats.get(tier))); let source: StartTierSource = "known-good"; if (index < 0) { index = ladder.findIndex((tier) => { const row = stats.get(tier); return row !== undefined && row.successes > 0 && row.ewma_success >= this.#threshold; }); source = "best-tier"; } if (index < 0) { let lastBad = -1; ladder.forEach((tier, i) => { if (isBad(stats.get(tier))) lastBad = i; }); if (lastBad < 0) { index = 0; source = "insufficient-evidence"; } else { index = Math.min(lastBad + 1, ladder.length - 1); source = "above-known-bad"; } } const exploitTier = ladder[index]; if (options.explore !== false && index > 0) { // Nearest cheaper tier that has failed. Never-tried tiers in between are // skipped: when the re-probe fails, the ladder walk reaches them anyway. let probe = index - 1; while (probe >= 0 && (stats.get(ladder[probe])?.last_failure_at ?? null) === null) probe--; const lastFailureAt = probe >= 0 ? stats.get(ladder[probe])?.last_failure_at : null; if ( lastFailureAt !== null && lastFailureAt !== undefined && this.#clock() - lastFailureAt >= this.#reprobeAfterMs && this.#random() < this.#reprobeProbability ) { return { domain, tier: ladder[probe], source: "reprobe", exploitTier }; } } return { domain, tier: exploitTier, source, exploitTier }; } /** * Tier to start the escalation ladder at for a URL: the cheapest tier with * EWMA success >= threshold and enough evidence; else the cheapest tier that * has succeeded; else the first tier above the known-bad ones; the cheapest * tier for unknown domains. Occasionally (`reprobeProbability`) re-probes the * nearest cheaper tier that failed, once `reprobeAfterMs` has elapsed since * that failure, so tiers that start working again are rediscovered. */ startTier(url: string, ladder: readonly EscalationStep[] = ESCALATION_ORDER): EscalationStep { return this.planStart(url, ladder).tier; } /** * Picks a proxy for a URL from `pool` by Thompson sampling on * Beta(successes+1, failures+1), skipping proxies banned for this domain. * When every proxy is banned, returns the least recently used one. */ chooseProxy(url: string, pool: readonly string[]): string | undefined { if (pool.length === 0) return undefined; const etld1 = registrableDomain(url); const now = this.#clock(); const rows = new Map(); for (const row of this.#selProxies.all({ etld1 })) rows.set(row.proxy, row); let chosen: string | undefined; let bestScore = -1; for (const proxy of pool) { const row = rows.get(proxy); if (row?.banned_until !== null && row?.banned_until !== undefined && row.banned_until > now) continue; const successes = row?.successes ?? 0; const failures = Math.max(0, (row?.attempts ?? 0) - successes); const score = sampleBeta(successes + 1, failures + 1, this.#random); if (score > bestScore) { bestScore = score; chosen = proxy; } } if (chosen === undefined) { let oldest = Number.POSITIVE_INFINITY; for (const proxy of pool) { const usedAt = rows.get(proxy)?.last_used_at ?? Number.NEGATIVE_INFINITY; if (usedAt < oldest) { oldest = usedAt; chosen = proxy; } } chosen ??= pool[0]; } if (etld1) this.#touchProxy.run({ etld1, proxy: chosen, now }); return chosen; } /** Proxies currently banned for the URL's domain. */ bannedProxies(url: string): string[] { const now = this.#clock(); return this.#selProxies .all({ etld1: registrableDomain(url) }) .filter((row) => row.banned_until !== null && row.banned_until > now) .map((row) => row.proxy); } /** * Milliseconds to wait before the next request to the URL's domain: the * AIMD delay, or the remaining `Retry-After` window when longer. */ politenessDelayMs(url: string): number { const row = this.#selDomain.get({ etld1: registrableDomain(url) }); if (!row) return this.#politeMinMs; const retryWait = row.retry_after_until === null ? 0 : Math.max(0, row.retry_after_until - this.#clock()); return Math.round(Math.max(row.politeness_delay_ms, retryWait)); } /** Fingerprint of the last successful attempt that reported one. */ rememberedFingerprint(url: string): string | undefined { return this.#selDomain.get({ etld1: registrableDomain(url) })?.fingerprint ?? undefined; } /** JSON-safe summary of everything known about the URL's domain. */ snapshot(url: string): DomainSnapshot { const domain = registrableDomain(url); const row = this.#selDomain.get({ etld1: domain }); const decision = this.planStart(url, ESCALATION_ORDER, { explore: false }); const rank = (tier: string) => { const i = ESCALATION_ORDER.indexOf(tier as EscalationStep); return i < 0 ? ESCALATION_ORDER.length : i; }; const tiers = this.#selTiers .all({ etld1: domain }) .sort((a, b) => rank(a.tier) - rank(b.tier)) .map((tier) => ({ tier: tier.tier, successes: tier.successes, failures: tier.failures, ewmaSuccess: round(tier.ewma_success), ewmaLatencyMs: tier.ewma_latency_ms === null ? null : Math.round(tier.ewma_latency_ms), lastOutcomeAt: iso(tier.last_outcome_at), lastSuccessAt: iso(tier.last_success_at), lastFailureAt: iso(tier.last_failure_at), })); const proxies = this.#selProxies .all({ etld1: domain }) .sort((a, b) => b.ewma_success - a.ewma_success || b.attempts - a.attempts) .map((proxy) => ({ proxy: redactProxy(proxy.proxy), attempts: proxy.attempts, successes: proxy.successes, ewmaSuccess: round(proxy.ewma_success), consecutiveFailures: proxy.consecutive_failures, bannedUntil: iso(proxy.banned_until), lastUsedAt: iso(proxy.last_used_at), })); const blockSignatures = this.#selSignatures.all({ etld1: domain }).map((sig) => ({ signature: sig.signature, reason: sig.reason, count: sig.count, firstSeen: new Date(sig.first_seen).toISOString(), lastSeen: new Date(sig.last_seen).toISOString(), })); return { domain, known: row !== null, bestTier: row?.best_tier ?? null, startTier: decision.tier, startSource: decision.source, fingerprint: row?.fingerprint ?? null, politenessDelayMs: this.politenessDelayMs(url), retryAfterUntil: iso(row?.retry_after_until), lastBlockAt: iso(row?.last_block_at), updatedAt: iso(row?.updated_at), tiers, proxies, blockSignatures, }; } /** Deletes everything known about the URL's domain. Returns true when rows were removed. */ forget(url: string): boolean { const etld1 = registrableDomain(url); let changes = 0; this.#db.transaction(() => { for (const table of [ "domains", "domain_tier_stats", "domain_proxy_scores", "domain_block_signatures", ]) { changes += this.#db.run(`DELETE FROM ${table} WHERE etld1 = ?`, [etld1]).changes; } }).immediate(); return changes > 0; } /** Aggregate counters for doctor-like output. */ stats(): DomainMemoryStats { const now = this.#clock(); const count = (sql: string, ...params: number[]) => (this.#db.query<{ n: number }, number[]>(sql).get(...params)?.n ?? 0); return { path: this.path, domains: count("SELECT COUNT(*) AS n FROM domains"), blockedDomains: count("SELECT COUNT(*) AS n FROM domains WHERE last_block_at IS NOT NULL"), tierRows: count("SELECT COUNT(*) AS n FROM domain_tier_stats"), proxyRows: count("SELECT COUNT(*) AS n FROM domain_proxy_scores"), bannedProxies: count("SELECT COUNT(*) AS n FROM domain_proxy_scores WHERE banned_until > ?", now), blockSignatures: count("SELECT COUNT(*) AS n FROM domain_block_signatures"), }; } /** Closes the underlying database. */ close(): void { if (sharedInstance === this) sharedInstance = undefined; this.#db.close(); } }