import { initBgIntervalProcess } from "../bg-interval.js";
import { addDeletedClients } from "../deleted-clients.js";
import { withWrite } from "../with-transactions.js";
import { getClients, setClients } from "./clients.js";
const CLIENT_MAX_INACTIVE_TIME = 24 * 60 * 60 * 1e3;
const GC_INTERVAL = 5 * 60 * 1e3;
let latestGCUpdate;
function initClientGC(clientID, dagStore, clientMaxInactiveTime, gcInterval, onClientsDeleted, lc, signal) {
  initBgIntervalProcess(
    "ClientGC",
    () => {
      latestGCUpdate = gcClients(
        clientID,
        dagStore,
        clientMaxInactiveTime,
        onClientsDeleted
      );
      return latestGCUpdate;
    },
    () => gcInterval,
    lc,
    signal
  );
}
function gcClients(clientID, dagStore, clientMaxInactiveTime, onClientsDeleted) {
  return withWrite(dagStore, async (dagWrite) => {
    const now = Date.now();
    const clients = await getClients(dagWrite);
    const deletedClients = [];
    const newClients = /* @__PURE__ */ new Map();
    for (const [id, client] of clients) {
      if (id === clientID || now - client.heartbeatTimestampMs <= clientMaxInactiveTime) {
        newClients.set(id, client);
      } else {
        deletedClients.push({
          clientGroupID: client.clientGroupID,
          clientID: id
        });
      }
    }
    if (newClients.size === clients.size) {
      return clients;
    }
    await setClients(newClients, dagWrite);
    const normalizedDeletedClients = await addDeletedClients(
      dagWrite,
      deletedClients
    );
    await onClientsDeleted(normalizedDeletedClients);
    return newClients;
  });
}
export {
  CLIENT_MAX_INACTIVE_TIME,
  GC_INTERVAL,
  initClientGC
};
//# sourceMappingURL=client-gc.js.map
