src / swarm / sqlite-visited-cache.ts

import fs from "node:fs";
import path from "node:path";
import type { DatabaseSync, SQLOutputValue } from "node:sqlite";
import { gzipSync, gunzipSync } from "node:zlib";
import type { CrawledSource } from "../types";
import type { CachedVisitedEntry, CacheFileShape, VisitedSearchFilters } from "./visited-cache";

type Row = Record<string, SQLOutputValue>;
const SCHEMA_VERSION = 1;

export function sqliteAvailable(): boolean {
  return process.getBuiltinModule?.("node:sqlite") !== undefined;
}

export function countMatchedTerms(source: CrawledSource, terms: readonly string[]): number {
  const words = new Set(searchWords(source));
  return terms.filter((term) => words.has(term)).length;
}

function searchWords(source: CrawledSource): string[] {
  return `${source.title} ${source.description} ${source.text}`.toLowerCase().match(/[a-z0-9]{4,}/g) ?? [];
}

export function visitedSourceHost(url: string): string {
  try { return new URL(url).hostname.toLowerCase().replace(/^www\./, ""); } catch { return ""; }
}

export class SqliteVisitedCache {
  private readonly indexed: boolean;
  private reportedError = false;
  migratedEntries: number | undefined;

  constructor(
    private readonly file: string,
    private readonly readOnly: boolean,
    loadLegacy: () => CacheFileShape | null,
  ) {
    if (!readOnly) fs.mkdirSync(path.dirname(file), { recursive: true });
    this.indexed = this.withDatabase((db) => {
      if (!readOnly) {
        db.exec("PRAGMA journal_mode = WAL");
        this.transaction(db, () => this.initialize(db, loadLegacy));
      }
      if (db.prepare("PRAGMA user_version").get()?.user_version !== SCHEMA_VERSION) {
        throw new Error("Unsupported visited cache schema");
      }
      return db.prepare("SELECT 1 FROM sqlite_master WHERE name = 'page_terms'").get() !== undefined;
    });
  }

  private withDatabase<T>(operation: (db: DatabaseSync) => T): T {
    const { DatabaseSync } = require("node:sqlite") as typeof import("node:sqlite");
    const db = new DatabaseSync(this.file, { readOnly: this.readOnly });
    try {
      db.exec("PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 250");
      return operation(db);
    } finally {
      db.close();
    }
  }

  private attempt<T>(fallback: T, operation: (db: DatabaseSync) => T): T {
    try {
      return this.withDatabase(operation);
    } catch (error) {
      if (!this.reportedError) console.warn(`[CACHE] SQLite operation failed: ${String(error)}`);
      this.reportedError = true;
      return fallback;
    }
  }

  private transaction(db: DatabaseSync, operation: () => void): void {
    db.exec("BEGIN IMMEDIATE");
    try {
      operation();
      db.exec("COMMIT");
    } catch (error) {
      db.exec("ROLLBACK");
      throw error;
    }
  }

  private initialize(db: DatabaseSync, loadLegacy: () => CacheFileShape | null): void {
    if (db.prepare("PRAGMA user_version").get()?.user_version !== 0) return;
    db.exec(`
      CREATE TABLE pages (
        id INTEGER PRIMARY KEY, url TEXT UNIQUE NOT NULL, cached_at INTEGER NOT NULL,
        source_host TEXT NOT NULL, compressed INTEGER NOT NULL, payload BLOB NOT NULL
      );
      CREATE INDEX pages_cached_at ON pages(cached_at);
      CREATE TABLE aliases (url TEXT PRIMARY KEY, target TEXT NOT NULL REFERENCES pages(url) ON DELETE CASCADE);
      CREATE TABLE rejected (url TEXT PRIMARY KEY, rejected_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, reason TEXT NOT NULL);
    `);
    let indexed = false;
    try {
      db.exec("CREATE VIRTUAL TABLE page_terms USING fts5(terms, content='', contentless_delete=1)");
      indexed = true;
    } catch (error) {
      if (!/no such module|unrecognized option/i.test(String(error))) throw error;
    }

    const legacy = loadLegacy();
    if (legacy) {
      this.migratedEntries = 0;
      for (const [url, entry] of Object.entries(legacy.entries)) {
        const cachedAt = Date.parse(entry.visitedAt);
        if (!Number.isFinite(cachedAt) || typeof entry.source?.text !== "string") continue;
        this.writePage(db, indexed, url, entry.source, cachedAt);
        this.migratedEntries++;
      }
      const alias = db.prepare("INSERT INTO aliases SELECT ?, url FROM pages WHERE url = ?");
      for (const [url, target] of Object.entries(legacy.aliases)) alias.run(url, target);
      const reject = db.prepare("INSERT INTO rejected VALUES (?, ?, ?, ?)");
      for (const [url, entry] of Object.entries(legacy.rejected)) {
        const rejectedAt = Date.parse(entry.rejectedAt);
        if (!Number.isFinite(rejectedAt) || !Number.isFinite(entry.ttlMs)) continue;
        reject.run(url, rejectedAt, rejectedAt + entry.ttlMs, entry.reason);
      }
    }
    db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);
  }

  private writePage(db: DatabaseSync, indexed: boolean, url: string, source: CrawledSource, cachedAt: number): void {
    const raw = Buffer.from(JSON.stringify(source));
    const gzip = raw.length >= 512 ? gzipSync(raw) : raw;
    const compressed = gzip.length < raw.length;
    const row = db.prepare(`
      INSERT INTO pages (url, cached_at, source_host, compressed, payload) VALUES (?, ?, ?, ?, ?)
      ON CONFLICT(url) DO UPDATE SET cached_at=excluded.cached_at, source_host=excluded.source_host,
        compressed=excluded.compressed, payload=excluded.payload RETURNING id
    `).get(url, cachedAt, visitedSourceHost(source.finalUrl ?? source.url), Number(compressed), compressed ? gzip : raw);
    if (indexed && typeof row?.id === "number") {
      db.prepare("DELETE FROM page_terms WHERE rowid=?").run(row.id);
      db.prepare("INSERT INTO page_terms(rowid, terms) VALUES (?, ?)").run(row.id, [...new Set(searchWords(source))].join(" "));
    }
  }

  private decode(row: Row): CachedVisitedEntry | null {
    try {
      if (!(row.payload instanceof Uint8Array) || typeof row.cached_at !== "number") return null;
      const bytes = row.compressed ? gunzipSync(row.payload, { maxOutputLength: 16 * 1024 * 1024 }) : Buffer.from(row.payload);
      return { visitedAt: new Date(row.cached_at).toISOString(), source: JSON.parse(bytes.toString("utf8")) as CrawledSource };
    } catch {
      return null;
    }
  }

  get(url: string, cutoff: number): CachedVisitedEntry | null {
    return this.attempt(null as CachedVisitedEntry | null, (db) => {
      const row = db.prepare(`SELECT * FROM pages WHERE url=COALESCE((SELECT target FROM aliases WHERE url=?), ?) AND cached_at>=?`).get(url, url, cutoff);
      return row ? this.decode(row) : null;
    });
  }

  has(url: string, cutoff: number): boolean {
    return this.attempt(false, (db) => db.prepare(`
      SELECT 1 FROM pages WHERE url=COALESCE((SELECT target FROM aliases WHERE url=?), ?) AND cached_at>=?
    `).get(url, url, cutoff) !== undefined);
  }

  search(terms: readonly string[], limit: number, cutoff: number, filters: VisitedSearchFilters): CachedVisitedEntry[] {
    return this.attempt([] as CachedVisitedEntry[], (db) => {
      const since = Math.max(cutoff, filters.sinceMs ?? 0);
      const host = filters.source ?? "";
      const threshold = Math.max(Math.min(2, terms.length), Math.ceil(terms.length / 2));
      if (!this.indexed) {
        return db.prepare("SELECT * FROM pages WHERE cached_at>=? AND (?='' OR source_host=?) ORDER BY id")
          .all(since, host, host).flatMap((row) => {
            const entry = this.decode(row);
            return entry ? [{ entry, count: countMatchedTerms(entry.source, terms) }] : [];
          }).filter(({ count }) => count >= threshold).sort((a, b) => b.count - a.count)
          .slice(0, limit).map(({ entry }) => entry);
      }
      const postings = terms.map(() => "SELECT rowid FROM page_terms WHERE page_terms MATCH ?").join(" UNION ALL ");
      const rows = db.prepare(`
        WITH postings AS (${postings}), hits AS (
          SELECT rowid, COUNT(*) AS matches FROM postings GROUP BY rowid HAVING COUNT(*) >= ?
        ) SELECT pages.* FROM hits JOIN pages ON pages.id=hits.rowid
          WHERE cached_at>=? AND (?='' OR source_host=?) ORDER BY matches DESC, pages.id LIMIT ?
      `).all(...terms, threshold, since, host, host, limit);
      return rows.flatMap((row) => {
        const entry = this.decode(row);
        return entry ? [entry] : [];
      });
    });
  }

  rejected(url: string, now: number): boolean {
    return this.attempt(false, (db) => db.prepare(`
      SELECT 1 FROM rejected WHERE url=COALESCE((SELECT target FROM aliases WHERE url=?), ?) AND expires_at>=?
        AND reason NOT IN ('off-topic', 'very-off-topic')
    `).get(url, url, now) !== undefined);
  }

  markVisited(source: CrawledSource, now: number, cap: number): void {
    this.attempt(undefined, (db) => this.transaction(db, () => {
      this.writePage(db, this.indexed, source.url, source, now);
      if (source.finalUrl && source.finalUrl !== source.url) {
        db.prepare("INSERT OR REPLACE INTO aliases VALUES (?, ?)").run(source.finalUrl, source.url);
      }
      db.prepare("DELETE FROM rejected WHERE url IN (?, ?)").run(source.url, source.finalUrl ?? source.url);
      this.trimPages(db, 0, cap);
    }));
  }

  markRejected(url: string, now: number, ttl: number, reason: string, cap: number): void {
    this.attempt(undefined, (db) => this.transaction(db, () => {
      db.prepare("INSERT OR REPLACE INTO rejected VALUES (?, ?, ?, ?)").run(url, now, now + ttl, reason);
      db.prepare("DELETE FROM rejected WHERE url IN (SELECT url FROM rejected ORDER BY rejected_at DESC, rowid DESC LIMIT -1 OFFSET ?)").run(cap);
    }));
  }

  prune(cutoff: number, now: number, cap: number): void {
    this.attempt(undefined, (db) => this.transaction(db, () => {
      this.trimPages(db, cutoff, cap);
      db.prepare("DELETE FROM rejected WHERE expires_at < ? OR reason IN ('off-topic', 'very-off-topic')").run(now);
    }));
  }

  private trimPages(db: DatabaseSync, cutoff: number, cap: number): void {
    const pageIds = `SELECT id FROM pages WHERE cached_at < ? UNION SELECT id FROM (
      SELECT id FROM pages ORDER BY cached_at DESC, id DESC LIMIT -1 OFFSET ?
    )`;
    if (this.indexed) db.prepare(`DELETE FROM page_terms WHERE rowid IN (${pageIds})`).run(cutoff, cap);
    db.prepare(`DELETE FROM pages WHERE id IN (${pageIds})`).run(cutoff, cap);
  }

  stats(cutoff: number, now: number): { entries: number; negativeEntries: number; newestCachedAt?: string } {
    return this.attempt({ entries: 0, negativeEntries: 0, newestCachedAt: undefined as string | undefined }, (db) => {
      const pages = db.prepare("SELECT COUNT(*) AS count, MAX(cached_at) AS newest FROM pages WHERE cached_at>=?").get(cutoff);
      const rejected = db.prepare("SELECT COUNT(*) AS count FROM rejected WHERE expires_at>=?").get(now);
      return {
        entries: Number(pages?.count ?? 0), negativeEntries: Number(rejected?.count ?? 0),
        newestCachedAt: typeof pages?.newest === "number" ? new Date(pages.newest).toISOString() : undefined,
      };
    });
  }
}