48 lines · 1.7 KB
import { all, run } from "../db";
import { repoDb } from "../scoped-db";
import { forEachScope } from "../account-scope";

const DELIVERY_RETENTION_MS = 30 * 24 * 60 * 60_000;
const PRUNE_BATCH = 500;

/** Integrations whose repo or org no longer exists hold live credentials for nothing; remove them. */
async function pruneOrphanedIntegrations(): Promise<void> {
  await run(
    `DELETE FROM integrations WHERE id IN (
       SELECT id FROM integrations WHERE scope_type = 'repo' AND scope_id NOT IN (SELECT id FROM repos) LIMIT ?)`,
    PRUNE_BATCH,
  );
  await run(
    `DELETE FROM integrations WHERE id IN (
       SELECT id FROM integrations WHERE scope_type = 'org' AND scope_id NOT IN (SELECT id FROM accounts) LIMIT ?)`,
    PRUNE_BATCH,
  );
}

/** Delivery logs (inbound and outbound, plus legacy webhook deliveries) are kept for 30 days, pruned in batches. */
async function pruneDeliveryLogs(now: number): Promise<void> {
  const cutoff = now - DELIVERY_RETENTION_MS;
  await run(
    "DELETE FROM integration_deliveries WHERE id IN (SELECT id FROM integration_deliveries WHERE created_at < ? LIMIT ?)",
    cutoff,
    PRUNE_BATCH,
  );
  const repos = await all<{ id: string }>("SELECT id FROM repos");
  await forEachScope(
    repos.map((repo) => repo.id),
    async (repoId) => {
      await repoDb(repoId).run(
        "DELETE FROM webhook_deliveries WHERE id IN (SELECT id FROM webhook_deliveries WHERE created_at < ? LIMIT ?)",
        cutoff,
        PRUNE_BATCH,
      );
    },
  );