import { must } from "../../../shared/src/must.js";
import { getNormalizedZeroConfig } from "../config/zero-config.js";
import { initEventSink } from "../observability/events.js";
import { exitAfter, runUntilKilled } from "../services/life-cycle.js";
import { CVRPurger } from "../services/view-syncer/cvr-purger.js";
import { ActiveUsersGauge } from "../services/view-syncer/active-users-gauge.js";
import { initViewSyncerSchema } from "../services/view-syncer/schema/init.js";
import { pgClient } from "../types/pg.js";
import { singleProcessMode, parentWorker } from "../types/processes.js";
import { getShardID } from "../types/shards.js";
import { createLogContext } from "./logging.js";
import { startOtelAuto } from "./otel-start.js";
import { startAnonymousTelemetry } from "./anonymous-otel-start.js";
const MS_PER_HOUR = 1e3 * 60 * 60;
async function runWorker(parent, env, ...argv) {
  const config = getNormalizedZeroConfig({ env, argv });
  startOtelAuto(createLogContext(config, { worker: "reaper" }, false));
  const lc = createLogContext(config, { worker: "reaper" }, true);
  initEventSink(lc, config);
  startAnonymousTelemetry(lc, config);
  const { cvr } = config;
  const shard = getShardID(config);
  const cvrDB = pgClient(lc, cvr.db, {
    connection: { ["application_name"]: `zero-sync-cvr-purger` }
  });
  await initViewSyncerSchema(lc, cvrDB, shard);
  parent.send(["ready", { ready: true }]);
  return runUntilKilled(
    lc,
    parent,
    new CVRPurger(lc, cvrDB, shard, {
      inactivityThresholdMs: cvr.garbageCollectionInactivityThresholdHours * MS_PER_HOUR,
      initialBatchSize: cvr.garbageCollectionInitialBatchSize,
      initialIntervalMs: cvr.garbageCollectionInitialIntervalSeconds * 1e3
    }),
    // Periodically computes and exports active users gauge to anonymous telemetry
    new ActiveUsersGauge(lc, cvrDB, shard, {
      // Default 10minutes refresh; can be made configurable later if needed
      updateIntervalMs: 10 * 60 * 1e3
    })
  );
}
if (!singleProcessMode()) {
  void exitAfter(
    () => runWorker(must(parentWorker), process.env, ...process.argv.slice(2))
  );
}
export {
  runWorker as default
};
//# sourceMappingURL=reaper.js.map
