Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

3.4 KB
Raw Blame
/**
 * Low-level table/artifact purge primitives backing {@link resetUsageHistory}
 * (see `../cleanup.ts`). Split out of `cleanup.ts` to keep that file under the
 * repo's file-size cap — these helpers have no state of their own beyond the
 * shared DB singleton, so they are safe to call from any reset routine that
 * needs generic "wipe" / "wipe before cutoff" semantics.
 *
 * @module lib/db/cleanup/usagePurge
 */
import { getDbInstance } from "../core";
import { cleanupEmptyCallLogDirs, deleteCallArtifact } from "@/lib/usage/callLogArtifacts";

export type DeleteByPeriodTarget = {
  table: string;
  column: string;
  cutoff: "iso" | "date" | "dateHour" | "epochMs" | "epochSeconds";
};

const DELETE_BATCH_SIZE = 10_000;

function cutoffValue(target: DeleteByPeriodTarget, cutoffIso: string): string | number {
  switch (target.cutoff) {
    case "date":
      return cutoffIso.slice(0, 10);
    case "dateHour":
      return `${cutoffIso.slice(0, 10)} ${cutoffIso.slice(11, 13)}:00:00`;
    case "epochMs":
      return new Date(cutoffIso).getTime();
    case "epochSeconds":
      return Math.floor(new Date(cutoffIso).getTime() / 1000);
    case "iso":
    default:
      return cutoffIso;
  }
}

export function tableExists(table: string): boolean {
  const row = getDbInstance()
    .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?")
    .get(table) as { name?: string } | undefined;
  return Boolean(row?.name);
}

export function deleteAllFromTable(table: string): number {
  if (!tableExists(table)) return 0;
  return getDbInstance().prepare(`DELETE FROM ${table}`).run().changes;
}

export function deleteFromTableBefore(target: DeleteByPeriodTarget, cutoffIso: string): number {
  if (!tableExists(target.table)) return 0;

  return getDbInstance()
    .prepare(`DELETE FROM ${target.table} WHERE ${target.column} < ?`)
    .run(cutoffValue(target, cutoffIso)).changes;
}

export async function deleteFromTableBeforeInBatches(
  target: DeleteByPeriodTarget,
  cutoffIso: string
): Promise<number> {
  if (!tableExists(target.table)) return 0;

  const statement = getDbInstance().prepare(
    `DELETE FROM ${target.table}
     WHERE rowid IN (
       SELECT rowid FROM ${target.table}
       WHERE ${target.column} < ?
       LIMIT ?
     )`
  );
  const cutoff = cutoffValue(target, cutoffIso);
  let deleted = 0;

  while (true) {
    const batch = statement.run(cutoff, DELETE_BATCH_SIZE).changes;
    deleted += batch;
    if (batch < DELETE_BATCH_SIZE) return deleted;
    await new Promise<void>((resolve) => setImmediate(resolve));
  }
}

export function collectCallLogArtifactsBefore(cutoffIso: string): string[] {
  if (!tableExists("call_logs")) return [];

  const rows = getDbInstance()
    .prepare(
      "SELECT artifact_relpath FROM call_logs WHERE timestamp < ? AND artifact_relpath IS NOT NULL"
    )
    .all(cutoffIso) as Array<{ artifact_relpath?: string | null }>;

  return rows
    .map((row) => row.artifact_relpath)
    .filter((relPath): relPath is string => typeof relPath === "string" && relPath.length > 0);
}

export function deleteCallLogArtifacts(relativePaths: string[]): {
  deletedArtifacts: number;
  errors: number;
} {
  const result = { deletedArtifacts: 0, errors: 0 };

  for (const relPath of new Set(relativePaths)) {
    if (deleteCallArtifact(relPath)) {
      result.deletedArtifacts++;
    }
  }

  cleanupEmptyCallLogDirs();
  return result;
}