/** * 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/extract/selector-cache * * Learned extraction plans persisted per (registrable domain, schema hash) in * the domain-memory SQLite file (own table `extract_selectors`). */ import { Database, type Statement } from "bun:sqlite"; import { mkdirSync } from "node:fs"; import { dirname } from "node:path"; import { defaultDomainMemoryPath } from "../profiles/domain-memory.ts"; import { registrableDomain } from "../profiles/etld.ts"; import type { ExtractionPlan, FieldLocator } from "./field-matcher.ts"; export interface CachedPlan { etld1: string; schemaHash: string; plan: ExtractionPlan; successes: number; failures: number; updatedAt: number; } interface Row { etld1: string; schema_hash: string; record_selector: string; fields_json: string; successes: number; failures: number; updated_at: number; } export interface SelectorCacheOptions { /** SQLite path; `":memory:"` for tests. Default: {@link defaultDomainMemoryPath}. */ path?: string; clock?: () => number; } const SCHEMA = ` CREATE TABLE IF NOT EXISTS extract_selectors ( etld1 TEXT NOT NULL, schema_hash TEXT NOT NULL, record_selector TEXT NOT NULL, fields_json TEXT NOT NULL, successes INTEGER NOT NULL DEFAULT 0, failures INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL, PRIMARY KEY (etld1, schema_hash) ) WITHOUT ROWID; `; /** Registrable domain of a URL, or `null` when it has none (file:, data:, invalid). */ export function cacheDomain(url: string | undefined): string | null { if (!url) return null; try { const parsed = new URL(url); if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null; return registrableDomain(parsed.hostname) || null; } catch { return null; } } export class SelectorCache { readonly path: string; readonly #db: Database; readonly #clock: () => number; readonly #select: Statement; readonly #upsert: Statement; readonly #success: Statement; readonly #failure: Statement; readonly #delete: Statement; constructor(options: SelectorCacheOptions = {}) { this.path = options.path ?? defaultDomainMemoryPath(); this.#clock = options.clock ?? Date.now; 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 }); if (!inMemory) this.#db.exec("PRAGMA journal_mode = WAL;"); this.#db.exec("PRAGMA busy_timeout = 5000;"); this.#db.exec(SCHEMA); this.#select = this.#db.prepare("SELECT * FROM extract_selectors WHERE etld1 = ? AND schema_hash = ?"); this.#upsert = this.#db.prepare( `INSERT INTO extract_selectors (etld1, schema_hash, record_selector, fields_json, successes, failures, updated_at) VALUES (?1, ?2, ?3, ?4, 1, 0, ?5) ON CONFLICT(etld1, schema_hash) DO UPDATE SET record_selector = excluded.record_selector, fields_json = excluded.fields_json, successes = 1, failures = 0, updated_at = excluded.updated_at`, ); this.#success = this.#db.prepare( "UPDATE extract_selectors SET successes = successes + 1, updated_at = ?1 WHERE etld1 = ?2 AND schema_hash = ?3", ); this.#failure = this.#db.prepare( "UPDATE extract_selectors SET failures = failures + 1, updated_at = ?1 WHERE etld1 = ?2 AND schema_hash = ?3", ); this.#delete = this.#db.prepare("DELETE FROM extract_selectors WHERE etld1 = ? AND schema_hash = ?"); } /** Cached plan for the site of `url`, or `null`. */ get(url: string, schemaHash: string): CachedPlan | null { const etld1 = cacheDomain(url); if (!etld1) return null; const row = this.#select.get(etld1, schemaHash); if (!row) return null; try { const stored = JSON.parse(row.fields_json) as { kind: ExtractionPlan["kind"]; span: number; fields: FieldLocator[] }; return { etld1, schemaHash, plan: { version: 1, kind: stored.kind, recordSelector: row.record_selector, span: stored.span, fields: stored.fields }, successes: row.successes, failures: row.failures, updatedAt: row.updated_at, }; } catch { this.#delete.run(etld1, schemaHash); return null; } } /** Store (or replace) the plan for the site of `url`. Returns `false` without a registrable domain. */ put(url: string, schemaHash: string, plan: ExtractionPlan): boolean { const etld1 = cacheDomain(url); if (!etld1) return false; const fields = JSON.stringify({ kind: plan.kind, span: plan.span, fields: plan.fields }); this.#upsert.run(etld1, schemaHash, plan.recordSelector, fields, this.#clock()); return true; } recordSuccess(url: string, schemaHash: string): void { const etld1 = cacheDomain(url); if (etld1) this.#success.run(this.#clock(), etld1, schemaHash); } recordFailure(url: string, schemaHash: string): void { const etld1 = cacheDomain(url); if (etld1) this.#failure.run(this.#clock(), etld1, schemaHash); } delete(url: string, schemaHash: string): void { const etld1 = cacheDomain(url); if (etld1) this.#delete.run(etld1, schemaHash); } close(): void { this.#db.close(); } }