"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "startSnapshotWhenCapacityAvailable", {
    enumerable: true,
    get: function() {
        return startSnapshotWhenCapacityAvailable;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _sleepAsync = require("@tamanu/utils/sleepAsync");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const startSnapshotIfCapacityAvailable = async (sequelize, sessionId)=>{
    // work out how many sessions are currently in the snapshot phase
    const [, affectedRows] = await sequelize.query(`
    WITH in_flight_snapshots AS (
      SELECT COUNT(*) AS count FROM sync_sessions
      WHERE snapshot_started_at IS NOT NULL
      AND snapshot_completed_at IS NULL
      AND errors IS NULL
      AND completed_at IS NULL
    )
    UPDATE sync_sessions
    SET snapshot_started_at = NOW()
    FROM in_flight_snapshots
    WHERE id = :sessionId
    AND in_flight_snapshots.count < :numberConcurrentPullSnapshots;
    `, {
        replacements: {
            sessionId,
            numberConcurrentPullSnapshots: _config.default.sync.numberConcurrentPullSnapshots
        },
        type: sequelize.QueryTypes.UPDATE
    });
    const success = affectedRows === 1;
    return success;
};
const startSnapshotWhenCapacityAvailable = async (sequelize, sessionId)=>{
    // wait for there to be enough capacity to start a snapshot
    while(!await startSnapshotIfCapacityAvailable(sequelize, sessionId)){
        await (0, _sleepAsync.sleepAsync)(500); // wait for half a second
    }
};

//# sourceMappingURL=startSnapshotWhenCapacityAvailable.js.map