import {
  markStopping
} from "./chunk-4O2KJSKM.js";
import {
  closeDb,
  init_client,
  syncDb
} from "./chunk-TLEKKGH7.js";
import {
  getRuntime
} from "./chunk-UYTSKFGK.js";

// src/shutdown.ts
init_client();
var g = globalThis;
function installShutdownHandlers() {
  if (g.__caShutdownInstalled) return;
  g.__caShutdownInstalled = true;
  process.on("SIGTERM", () => {
    void shutdown("SIGTERM");
  });
  process.on("SIGINT", () => {
    void shutdown("SIGINT");
  });
}
var shuttingDown = false;
async function shutdown(signal) {
  if (shuttingDown) {
    console.log(`[shutdown] forced exit`);
    process.exit(1);
  }
  shuttingDown = true;
  const rt = getRuntime();
  const inflight = rt.inFlightRuns.size;
  if (inflight > 0) {
    console.log(`[shutdown] stopping ${inflight} in-flight turn${inflight > 1 ? "s" : ""}...`);
  } else {
    console.log(`[shutdown] shutting down...`);
  }
  markStopping();
  if (g.__caSweeperHandle) {
    clearInterval(g.__caSweeperHandle);
    g.__caSweeperHandle = void 0;
  }
  for (const run of rt.inFlightRuns.values()) {
    try {
      run.controller.abort(new DOMException("shutting down", "AbortError"));
    } catch {
    }
  }
  if (inflight > 0) {
    await new Promise((r) => setTimeout(r, 5e3));
  }
  syncDb();
  closeDb();
  process.exit(0);
}

export {
  installShutdownHandlers
};
