"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.timeoutInProcessGoals = exports.manageGoalSets = exports.manageGoalSetsTrigger = void 0;
const configuration_1 = require("@atomist/automation-client/lib/configuration");
const WebSocketMessageClient_1 = require("@atomist/automation-client/lib/internal/transport/websocket/WebSocketMessageClient");
const namespace = require("@atomist/automation-client/lib/internal/util/cls");
const string_1 = require("@atomist/automation-client/lib/internal/util/string");
const GraphClient_1 = require("@atomist/automation-client/lib/spi/graph/GraphClient");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const _ = require("lodash");
const fetchGoalsOnCommit_1 = require("../../api-helper/goal/fetchGoalsOnCommit");
const storeGoals_1 = require("../../api-helper/goal/storeGoals");
const time_1 = require("../../core/util/misc/time");
const types_1 = require("../../typings/types");
const cancelGoals_1 = require("./cancelGoals");
/**
 * TriggeredListener that queries pending goal sets and updates their state according to state of
 * goals
 */
function manageGoalSetsTrigger(options) {
    return async (li) => {
        const workspaceIds = li.sdm.configuration.workspaceIds;
        if (!!workspaceIds && workspaceIds.length > 0) {
            for (const workspaceId of workspaceIds) {
                const ses = namespace.create();
                ses.run(async () => {
                    const id = string_1.guid();
                    namespace.set({
                        invocationId: id,
                        correlationId: id,
                        workspaceName: workspaceId,
                        workspaceId,
                        operation: "ManagePendingGoalSets",
                        ts: Date.now(),
                        name: li.sdm.configuration.name,
                        version: li.sdm.configuration.version,
                    });
                    try {
                        const graphClient = li.sdm.configuration.graphql.client.factory.create(workspaceId, li.sdm.configuration);
                        const messageClient = new TriggeredMessageClient(li.sdm.configuration.ws.lifecycle, workspaceId, li.sdm.configuration);
                        const ctx = {
                            graphClient,
                            messageClient,
                            workspaceId,
                            correlationId: id,
                            invocationId: id,
                            context: {
                                name: li.sdm.configuration.name,
                                version: li.sdm.configuration.version,
                                operation: "ManagePendingGoalSets",
                                ts: Date.now(),
                                workspaceId,
                                workspaceName: workspaceId,
                                correlationId: id,
                                invocationId: id,
                            },
                        };
                        await manageGoalSets(li.sdm, ctx);
                        await timeoutInProcessGoals(li.sdm, ctx, options);
                    }
                    catch (e) {
                        logger_1.logger.debug("Error managing pending goal sets: %s", e.stack);
                    }
                });
            }
        }
    };
}
exports.manageGoalSetsTrigger = manageGoalSetsTrigger;
async function manageGoalSets(sdm, ctx) {
    const pgs = await cancelGoals_1.pendingGoalSets(ctx, sdm.configuration.name, 0, 100);
    for (const goalSet of pgs) {
        const goals = await fetchGoalsOnCommit_1.fetchGoalsForCommit(ctx, {
            owner: goalSet.repo.owner,
            repo: goalSet.repo.name,
            sha: goalSet.sha,
            branch: goalSet.branch,
        }, goalSet.repo.providerId, goalSet.goalSetId);
        const state = storeGoals_1.goalSetState(goals || []);
        if (state !== goalSet.state) {
            const newGoalSet = Object.assign(Object.assign({}, goalSet), { state });
            logger_1.logger.debug(`Goal set '${goalSet.goalSetId}' now in state '${state}'`);
            await storeGoals_1.storeGoalSet(ctx, newGoalSet);
        }
    }
}
exports.manageGoalSets = manageGoalSets;
async function timeoutInProcessGoals(sdm, ctx, options) {
    const timeout = !!options && !!options.timeout
        ? options.timeout
        : _.get(sdm.configuration, "sdm.goal.inProcessTimeout", 1000 * 60 * 60);
    const end = Date.now() - timeout;
    const gs = (await ctx.graphClient.query({
        name: "InProcessSdmGoals",
        variables: {
            registration: [sdm.configuration.name],
        },
        options: Object.assign(Object.assign({}, GraphClient_1.QueryNoCacheOptions), { log: configuration_1.configurationValue("sdm.query.logging", false) }),
    })).SdmGoal;
    const state = !!options && !!options.state ? options.state : types_1.SdmGoalState.canceled;
    for (const goal of gs) {
        if (goal.ts < end) {
            logger_1.logger.debug(`Canceling goal '${goal.uniqueName}' of goal set '${goal.goalSetId}' because it timed out after '${time_1.formatDuration(timeout)}'`);
            let description = `${state === types_1.SdmGoalState.canceled ? "Canceled" : "Failed"}: ${goal.name}`;
            if (!!goal.descriptions) {
                if (state === types_1.SdmGoalState.canceled && !!goal.descriptions.canceled) {
                    description = goal.descriptions.canceled;
                }
                else if (state === types_1.SdmGoalState.failure && !!goal.descriptions.failed) {
                    description = goal.descriptions.failed;
                }
            }
            await storeGoals_1.updateGoal(ctx, goal, {
                state,
                description,
                phase: `${time_1.formatDuration(timeout)} timeout`,
            });
        }
    }
}
exports.timeoutInProcessGoals = timeoutInProcessGoals;
class TriggeredMessageClient extends WebSocketMessageClient_1.AbstractWebSocketMessageClient {
    constructor(ws, workspaceId, configuration) {
        super(ws, {}, string_1.guid(), { id: workspaceId }, {}, configuration);
    }
}
//# sourceMappingURL=manageGoalSets.js.map