"use strict";
/*
 * Copyright © 2020 Atomist, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRetryingGoalExecutor = exports.createPredicatedGoalExecutor = exports.createPredicatedGoal = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const retry_1 = require("@atomist/automation-client/lib/util/retry");
const GoalWithFulfillment_1 = require("../GoalWithFulfillment");
const DefaultWaitRules = {
    timeoutSeconds: 1,
    retries: 1000,
};
/**
 * Create a goal from the given executor, waiting until a condition is satisfied,
 * with a given timeout.
 * @param {EssentialGoalInfo} egi
 * @param {ExecuteGoal} goalExecutor
 * @param w rules for waiting
 * @return {Goal}
 */
function createPredicatedGoal(egi, goalExecutor, w) {
    return GoalWithFulfillment_1.goal(egi, createPredicatedGoalExecutor(egi.displayName, goalExecutor, w));
}
exports.createPredicatedGoal = createPredicatedGoal;
/**
 * Wrap provided ExecuteGoal instance with WaitRules processing
 * @param {string} uniqueName
 * @param {ExecuteGoal} goalExecutor
 * @param w rules for waiting
 * @return {ExecuteGoal}
 */
function createPredicatedGoalExecutor(uniqueName, goalExecutor, w, unref = true) {
    if (!!w.timeoutSeconds && !!w.timeoutMillis) {
        throw new Error("Invalid combination: Cannot specify timeoutSeconds and timeoutMillis: Choose one");
    }
    const waitRulesToUse = Object.assign(Object.assign({}, DefaultWaitRules), w);
    waitRulesToUse.timeoutMillis = waitRulesToUse.timeoutMillis || 1000 * w.timeoutSeconds;
    return async (gi) => {
        let tries = 1;
        while (true) {
            if (tries > waitRulesToUse.retries) {
                throw new Error(`Goal '${uniqueName}' timed out after max retries: ${JSON.stringify(waitRulesToUse)}`);
            }
            if (await waitRulesToUse.condition(gi)) {
                return goalExecutor(gi);
            }
            tries++;
            logger_1.logger.debug("Waiting %dms for '%s'", waitRulesToUse.timeoutMillis, uniqueName);
            await wait(waitRulesToUse.timeoutMillis, unref);
        }
    };
}
exports.createPredicatedGoalExecutor = createPredicatedGoalExecutor;
function createRetryingGoalExecutor(uniqueName, goalExecutor, retry) {
    return gi => retry_1.doWithRetry(async () => {
        const result = await goalExecutor(gi);
        if (!!result && result.code !== 0) {
            throw new Error(`Goal '${uniqueName}' failed with non-zero code`);
        }
        return result;
    }, `Invoking goal '${uniqueName}'`, Object.assign({ log: false }, retry));
}
exports.createRetryingGoalExecutor = createRetryingGoalExecutor;
function wait(timeoutMillis, unref) {
    return new Promise(resolve => {
        const timer = setTimeout(resolve, timeoutMillis);
        if (unref) {
            timer.unref();
        }
    });
}
//# sourceMappingURL=createGoal.js.map