lib / research-cache.js

import { Worker } from "node:worker_threads";
import { getDbPath } from "./config.js";
import { researchWorker } from "./research-worker.js";
import { log } from "./log.js";

export const RESEARCH_CONTRACT_VERSION = "1.0";
export const RESEARCH_PLUGIN_ID = "mh825/rss-rag-cache";
const TIMEOUT_MS = 5000;

function run(action, args = {}) {
  // The plugin initializes its database at startup. Never create or migrate it
  // from a read operation; all query work is interruptible via the worker.
  return new Promise((resolve, reject) => {
    const started = Date.now();
    const worker = new Worker(`(${researchWorker.toString()})()`, {
      eval: true,
      workerData: { dbPath: getDbPath(), action, args },
      execArgv: [],
    });
    const timer = setTimeout(() => { log.warn("research-cache-timeout", { action, durationMs: Date.now() - started }); worker.terminate(); reject(new Error("Research cache request timed out")); }, TIMEOUT_MS);
    worker.once("message", (message) => { clearTimeout(timer); if (message.ok) { log.debug("research-cache-complete", { action, durationMs: Date.now() - started }); resolve(message.result); } else { log.warn("research-cache-failed", { action, durationMs: Date.now() - started, error: message.error }); reject(new Error(message.error)); } });
    worker.once("error", (error) => { clearTimeout(timer); log.warn("research-cache-worker-error", { action, durationMs: Date.now() - started, error: error.message }); reject(error); });
    worker.once("exit", (code) => { if (code !== 0) { clearTimeout(timer); reject(new Error(`Research cache worker exited (${code})`)); } });
  });
}

export async function cacheInfo() {
  try { return await run("info"); }
  catch { return { contractVersion: RESEARCH_CONTRACT_VERSION, pluginId: RESEARCH_PLUGIN_ID, available: false, newestCachedAt: null }; }
}

export async function searchCache({ query, limit = 10, since, source } = {}) {
  if (typeof query !== "string" || query.length > 500) throw new Error("query must be a string of at most 500 characters");
  const terms = query.match(/[\p{L}\p{N}]+/gu)?.slice(0, 20) || [];
  if (!terms.length) return [];
  const match = terms.map((term) => `"${term}"`).join(" OR ");
  const timestamp = since == null ? null : Date.parse(since);
  if (since != null && !Number.isFinite(timestamp)) throw new Error("since must be a valid date");
  if (source != null && (typeof source !== "string" || source.length > 2048)) throw new Error("source must be at most 2048 characters");
  const count = Number.isFinite(Number(limit)) ? Math.max(1, Math.min(20, Math.trunc(Number(limit)))) : 10;
  return run("search", { match, limit: count, since: timestamp, source });
}

export async function getCachedItem(itemId) {
  if (!/^[1-9]\d*$/.test(String(itemId)) || !Number.isSafeInteger(Number(itemId))) throw new Error("itemId must be a positive entry ID");
  return run("item", { itemId: Number(itemId) });
}