/** * 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. */ import { Database, type Statement } from "bun:sqlite"; import { join } from "node:path"; import { withDomTree, querySelectBatch, convertFutHtmlToMarkdown, } from "../parser/native.ts"; import { querySelector } from "../../../../src/rust/bridge.ts"; export interface CacheEntry { key: string; value: T; expiresAt: number; } export interface BenchmarkResult { iterations: number; rustFfiTimeMs: number; regexTimeMs: number; ffiSpeedupFactor: number; wyhashOpsPerSec: number; sqliteOpsPerSec: number; } /** * Ultra-fast native cache powered by bun:sqlite, WAL mode, prepared statements, * Bun.hash.wyhash, and transparent Bun.gzipSync compression for large payloads. */ export class FutNativeCache { private db: Database; private stmtGet: Statement; private stmtSet: Statement; private stmtDel: Statement; private stmtPrune: Statement; constructor(dbPath?: string) { const path = dbPath ?? ":memory:"; this.db = new Database(path); this.db.run("PRAGMA journal_mode = WAL;"); this.db.run("PRAGMA synchronous = NORMAL;"); this.db.run(` CREATE TABLE IF NOT EXISTS fut_cache ( hash_key INTEGER PRIMARY KEY, raw_key TEXT NOT NULL, value BLOB NOT NULL, is_compressed INTEGER NOT NULL, expires_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_fut_cache_expires ON fut_cache (expires_at); `); this.stmtGet = this.db.prepare( "SELECT value, is_compressed, expires_at FROM fut_cache WHERE hash_key = $hashKey", ); this.stmtSet = this.db.prepare(` INSERT INTO fut_cache (hash_key, raw_key, value, is_compressed, expires_at) VALUES ($hashKey, $rawKey, $value, $isCompressed, $expiresAt) ON CONFLICT(hash_key) DO UPDATE SET value = excluded.value, is_compressed = excluded.is_compressed, expires_at = excluded.expires_at `); this.stmtDel = this.db.prepare("DELETE FROM fut_cache WHERE hash_key = $hashKey"); this.stmtPrune = this.db.prepare("DELETE FROM fut_cache WHERE expires_at < $now"); } private hashKey(key: string): bigint { return Bun.hash.wyhash(key); } public get(key: string): T | null { const hashKey = this.hashKey(key); const row = this.stmtGet.get({ $hashKey: hashKey }) as { value: Uint8Array | Buffer; is_compressed: number; expires_at: number; } | null; if (!row) return null; const now = Date.now(); if (row.expires_at > 0 && row.expires_at < now) { this.stmtDel.run({ $hashKey: hashKey }); return null; } try { let buf: Uint8Array = row.value; if (row.is_compressed) { buf = Bun.gunzipSync(Buffer.from(buf)); } const text = new TextDecoder().decode(buf); return JSON.parse(text) as T; } catch { return null; } } public set(key: string, value: T, ttlMs = 0): void { const hashKey = this.hashKey(key); const rawKey = key; const expiresAt = ttlMs > 0 ? Date.now() + ttlMs : 0; const jsonText = JSON.stringify(value); let buf: Uint8Array = new TextEncoder().encode(jsonText); let isCompressed = 0; // Compress payloads larger than 1024 bytes with Bun.gzipSync if (buf.length > 1024) { buf = Bun.gzipSync(Buffer.from(buf)); isCompressed = 1; } this.stmtSet.run({ $hashKey: hashKey, $rawKey: rawKey, $value: buf, $isCompressed: isCompressed, $expiresAt: expiresAt, }); } public delete(key: string): void { const hashKey = this.hashKey(key); this.stmtDel.run({ $hashKey: hashKey }); } public prune(): number { const now = Date.now(); const info = this.stmtPrune.run({ $now: now }); return info.changes; } public close(): void { this.db.close(); } } /** * Executes a microsecond-accurate benchmark comparing Rust FFI DOM parsing vs pure JS RegExp * and Bun native utilities. */ export function runNativeFfiBenchmark(iterations = 500): BenchmarkResult { const sampleHtml = `

Kylian Mbappé

91
ST
3,450,000
Real Madrid
France
LALIGA EA SPORTS
97 90 80 92 36 78
View Profile
`; // 1. Rust FFI Benchmark const startFfi = performance.now(); for (let i = 0; i < iterations; i++) { withDomTree(sampleHtml, (tree) => { querySelector(tree, ".player-name"); querySelector(tree, ".player-price"); querySelector(tree, ".stat-pac"); }); } const rustFfiTimeMs = performance.now() - startFfi; // 2. Pure JS Regex Benchmark const startRegex = performance.now(); const reName = /class="player-name">([^<]+)([^<]+)([^<]+)