"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
exports.CobuildLock = void 0;
const node_core_library_1 = require("@rushstack/node-core-library");
const KEY_SEPARATOR = ':';
class CobuildLock {
    constructor(options) {
        const { cobuildConfiguration, operationBuildCache, cobuildClusterId: clusterId, lockExpireTimeInSeconds, packageName, phaseName } = options;
        const { cobuildContextId: contextId, cobuildRunnerId: runnerId } = cobuildConfiguration;
        const { cacheId } = operationBuildCache;
        this.cobuildConfiguration = cobuildConfiguration;
        this.operationBuildCache = operationBuildCache;
        if (!cacheId) {
            // This should never happen
            throw new node_core_library_1.InternalError(`Cache id is require for cobuild lock`);
        }
        if (!contextId) {
            // This should never happen
            throw new node_core_library_1.InternalError(`Cobuild context id is require for cobuild lock`);
        }
        // Example: cobuild:lock:<contextId>:<clusterId>
        const lockKey = ['cobuild', 'lock', contextId, clusterId].join(KEY_SEPARATOR);
        // Example: cobuild:completed:<contextId>:<cacheId>
        const completedStateKey = ['cobuild', 'completed', contextId, cacheId].join(KEY_SEPARATOR);
        this._cobuildContext = {
            contextId,
            clusterId,
            runnerId,
            lockKey,
            completedStateKey,
            packageName,
            phaseName,
            lockExpireTimeInSeconds: lockExpireTimeInSeconds,
            cacheId
        };
    }
    async setCompletedStateAsync(state) {
        await this.cobuildConfiguration
            .getCobuildLockProvider()
            .setCompletedStateAsync(this._cobuildContext, state);
    }
    async getCompletedStateAsync() {
        const state = await this.cobuildConfiguration
            .getCobuildLockProvider()
            .getCompletedStateAsync(this._cobuildContext);
        return state;
    }
    async tryAcquireLockAsync() {
        const acquireLockResult = await this.cobuildConfiguration
            .getCobuildLockProvider()
            .acquireLockAsync(this._cobuildContext);
        if (acquireLockResult) {
            // renew the lock in a redundant way in case of losing the lock
            await this.renewLockAsync();
        }
        return acquireLockResult;
    }
    async renewLockAsync() {
        await this.cobuildConfiguration.getCobuildLockProvider().renewLockAsync(this._cobuildContext);
    }
    get cobuildContext() {
        return this._cobuildContext;
    }
}
exports.CobuildLock = CobuildLock;
//# sourceMappingURL=CobuildLock.js.map