import { initBgIntervalProcess } from "../bg-interval.js";
import { withWrite } from "../with-transactions.js";
import { ClientStateNotFoundError, getClients, setClients } from "./clients.js";
const HEARTBEAT_INTERVAL = 60 * 1e3;
let latestHeartbeatUpdate;
function startHeartbeats(clientID, dagStore, onClientStateNotFound, heartbeatIntervalMs, lc, signal) {
  initBgIntervalProcess(
    "Heartbeat",
    async () => {
      latestHeartbeatUpdate = writeHeartbeat(clientID, dagStore);
      try {
        return await latestHeartbeatUpdate;
      } catch (e) {
        if (e instanceof ClientStateNotFoundError) {
          onClientStateNotFound();
          return;
        }
        throw e;
      }
    },
    () => heartbeatIntervalMs,
    lc,
    signal
  );
}
function writeHeartbeat(clientID, dagStore) {
  return withWrite(dagStore, async (dagWrite) => {
    const clients = await getClients(dagWrite);
    const client = clients.get(clientID);
    if (!client) {
      throw new ClientStateNotFoundError(clientID);
    }
    const newClient = {
      ...client,
      heartbeatTimestampMs: Date.now()
    };
    const newClients = new Map(clients).set(clientID, newClient);
    await setClients(newClients, dagWrite);
    return newClients;
  });
}
export {
  HEARTBEAT_INTERVAL,
  latestHeartbeatUpdate,
  startHeartbeats,
  writeHeartbeat
};
//# sourceMappingURL=heartbeat.js.map
