39 lines
1.3 KiB
TypeScript
39 lines
1.3 KiB
TypeScript
import "server-only";
|
|
import { randomUUID } from "node:crypto";
|
|
import { start } from "workflow/api";
|
|
import { admin, required } from "./supabase";
|
|
import { discordConfiguration } from "./discord-client";
|
|
import { cleanupClosedDiscordParty } from "./discord-cleanup-workflow";
|
|
|
|
export async function scheduleDiscordCleanup(target?: string) {
|
|
const config = discordConfiguration(process.env);
|
|
if (!config.token || !config.origin) return;
|
|
const db = admin(),
|
|
claim = `starting:${randomUUID()}`;
|
|
const jobs = required(
|
|
await db.rpc("claim_discord_cleanup", {
|
|
p_worker: claim,
|
|
p_target: target ?? null,
|
|
}),
|
|
);
|
|
for (const job of jobs) {
|
|
try {
|
|
const run = await start(cleanupClosedDiscordParty, [job.id, claim]);
|
|
required(
|
|
await db
|
|
.from("discord_announcements")
|
|
.update({ cleanup_run_id: run.runId, cleanup_lease_until: null })
|
|
.eq("id", job.id)
|
|
.eq("cleanup_run_id", claim)
|
|
.select("id"),
|
|
);
|
|
} catch {
|
|
// An ambiguous start may already have enqueued a run. Keep the short lease;
|
|
// a replay keeps the persisted grace period and safely repeats deletion.
|
|
console.error(
|
|
"Discord cleanup scheduling paused; the saved announcement will retry.",
|
|
);
|
|
}
|
|
}
|
|
}
|