"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BuildIdNotFoundError = exports.decodeTaskReachability = exports.encodeTaskReachability = exports.ReachabilityType = exports.TaskQueueClient = exports.UnversionedBuildId = void 0;
exports.reachabilityResponseFromProto = reachabilityResponseFromProto;
const grpc_js_1 = require("@grpc/grpc-js");
const type_helpers_1 = require("@temporalio/common/lib/type-helpers");
const internal_workflow_1 = require("@temporalio/common/lib/internal-workflow");
const base_client_1 = require("./base-client");
const build_id_types_1 = require("./build-id-types");
const errors_1 = require("./errors");
const helpers_1 = require("./helpers");
/**
 * A stand-in for a Build Id for unversioned Workers
 *
 * @deprecated Worker Versioning is now deprecated. Please use the Worker Deployment API instead: https://docs.temporal.io/worker-deployments
 */
exports.UnversionedBuildId = Symbol.for('__temporal_unversionedBuildId');
/**
 * Client for starting Workflow executions and creating Workflow handles
 *
 * @deprecated Worker Versioning is now deprecated. Please use the Worker Deployment API instead: https://docs.temporal.io/worker-deployments
 */
class TaskQueueClient extends base_client_1.BaseClient {
    options;
    constructor(options) {
        super(options);
        this.options = {
            ...(0, base_client_1.defaultBaseClientOptions)(),
            ...(0, internal_workflow_1.filterNullAndUndefined)(options ?? {}),
            loadedDataConverter: this.dataConverter,
        };
    }
    /**
     * Raw gRPC access to the Temporal service.
     *
     * **NOTE**: The namespace provided in {@link options} is **not** automatically set on requests
     * using this service attribute.
     */
    get workflowService() {
        return this.connection.workflowService;
    }
    /**
     * Used to add new Build Ids or otherwise update the relative compatibility of Build Ids as
     * defined on a specific task queue for the Worker Versioning feature. For more on this feature,
     * see https://docs.temporal.io/workers#worker-versioning
     *
     * @param taskQueue The task queue to make changes to.
     * @param operation The operation to be performed.
     *
     * @deprecated Worker Versioning is now deprecated. Please use the Worker Deployment API instead: https://docs.temporal.io/worker-deployments
     */
    async updateBuildIdCompatibility(taskQueue, operation) {
        const request = {
            namespace: this.options.namespace,
            taskQueue,
        };
        switch (operation.operation) {
            case 'addNewIdInNewDefaultSet':
                request.addNewBuildIdInNewDefaultSet = operation.buildId;
                break;
            case 'addNewCompatibleVersion':
                request.addNewCompatibleBuildId = {
                    newBuildId: operation.buildId,
                    existingCompatibleBuildId: operation.existingCompatibleBuildId,
                };
                break;
            case 'promoteSetByBuildId':
                request.promoteSetByBuildId = operation.buildId;
                break;
            case 'promoteBuildIdWithinSet':
                request.promoteBuildIdWithinSet = operation.buildId;
                break;
            case 'mergeSets':
                request.mergeSets = {
                    primarySetBuildId: operation.primaryBuildId,
                    secondarySetBuildId: operation.secondaryBuildId,
                };
                break;
            default:
                (0, type_helpers_1.assertNever)('Unknown build id update operation', operation);
        }
        try {
            await this.workflowService.updateWorkerBuildIdCompatibility(request);
        }
        catch (e) {
            this.rethrowGrpcError(e, 'Unexpected error updating Build Id compatibility');
        }
    }
    /**
     * Fetch the sets of compatible Build Ids for a given task queue.
     *
     * @param taskQueue The task queue to fetch the compatibility information for.
     * @returns The sets of compatible Build Ids for the given task queue, or undefined if the queue
     *          has no Build Ids defined on it.
     *
     * @deprecated Worker Versioning is now deprecated. Please use the Worker Deployment API instead: https://docs.temporal.io/worker-deployments
     */
    async getBuildIdCompatability(taskQueue) {
        let resp;
        try {
            resp = await this.workflowService.getWorkerBuildIdCompatibility({
                taskQueue,
                namespace: this.options.namespace,
            });
        }
        catch (e) {
            this.rethrowGrpcError(e, 'Unexpected error fetching Build Id compatibility');
        }
        if (resp.majorVersionSets == null || resp.majorVersionSets.length === 0) {
            return undefined;
        }
        return (0, build_id_types_1.versionSetsFromProto)(resp);
    }
    /**
     * Fetches task reachability to determine whether a worker may be retired. The request may specify
     * task queues to query for or let the server fetch all task queues mapped to the given build IDs.
     *
     * When requesting a large number of task queues or all task queues associated with the given
     * build ids in a namespace, all task queues will be listed in the response but some of them may
     * not contain reachability information due to a server enforced limit. When reaching the limit,
     * task queues that reachability information could not be retrieved for will be marked with a
     * `NotFetched` entry in {@link BuildIdReachability.taskQueueReachability}. The caller may issue
     * another call to get the reachability for those task queues.
     *
     * @deprecated Worker Versioning is now deprecated. Please use the Worker Deployment API instead: https://docs.temporal.io/worker-deployments
     */
    async getReachability(options) {
        let resp;
        const buildIds = options.buildIds?.map((bid) => {
            if (bid === exports.UnversionedBuildId) {
                return '';
            }
            return bid;
        });
        try {
            resp = await this.workflowService.getWorkerTaskReachability({
                namespace: this.options.namespace,
                taskQueues: options.taskQueues,
                buildIds,
                reachability: (0, exports.encodeTaskReachability)(options.reachability),
            });
        }
        catch (e) {
            this.rethrowGrpcError(e, 'Unexpected error fetching Build Id reachability');
        }
        return reachabilityResponseFromProto(resp);
    }
    rethrowGrpcError(err, fallbackMessage) {
        if ((0, errors_1.isGrpcServiceError)(err)) {
            (0, helpers_1.rethrowKnownErrorTypes)(err);
            if (err.code === grpc_js_1.status.NOT_FOUND) {
                throw new BuildIdNotFoundError(err.details ?? 'Build Id not found');
            }
            throw new errors_1.ServiceError(fallbackMessage, { cause: err });
        }
        throw new errors_1.ServiceError('Unexpected error while making gRPC request');
    }
}
exports.TaskQueueClient = TaskQueueClient;
/**
 * There are different types of reachability:
 *   - `NEW_WORKFLOWS`: The Build Id might be used by new workflows
 *   - `EXISTING_WORKFLOWS` The Build Id might be used by open workflows and/or closed workflows.
 *   - `OPEN_WORKFLOWS` The Build Id might be used by open workflows
 *   - `CLOSED_WORKFLOWS` The Build Id might be used by closed workflows
 *
 * @deprecated Worker Versioning is now deprecated. Please use the Worker Deployment API instead: https://docs.temporal.io/worker-deployments
 */
exports.ReachabilityType = {
    /** The Build Id might be used by new workflows. */
    NEW_WORKFLOWS: 'NEW_WORKFLOWS',
    /** The Build Id might be used by open workflows and/or closed workflows. */
    EXISTING_WORKFLOWS: 'EXISTING_WORKFLOWS',
    /** The Build Id might be used by open workflows. */
    OPEN_WORKFLOWS: 'OPEN_WORKFLOWS',
    /** The Build Id might be used by closed workflows. */
    CLOSED_WORKFLOWS: 'CLOSED_WORKFLOWS',
};
_a = (0, internal_workflow_1.makeProtoEnumConverters)({
    [exports.ReachabilityType.NEW_WORKFLOWS]: 1,
    [exports.ReachabilityType.EXISTING_WORKFLOWS]: 2,
    [exports.ReachabilityType.OPEN_WORKFLOWS]: 3,
    [exports.ReachabilityType.CLOSED_WORKFLOWS]: 4,
    UNSPECIFIED: 0,
}, 'TASK_REACHABILITY_'), exports.encodeTaskReachability = _a[0], exports.decodeTaskReachability = _a[1];
function reachabilityResponseFromProto(resp) {
    return {
        buildIdReachability: Object.fromEntries(resp.buildIdReachability.map((bir) => {
            const taskQueueReachability = {};
            if (bir.taskQueueReachability != null) {
                for (const tqr of bir.taskQueueReachability) {
                    if (tqr.taskQueue == null) {
                        continue;
                    }
                    if (tqr.reachability == null) {
                        taskQueueReachability[tqr.taskQueue] = [];
                        continue;
                    }
                    taskQueueReachability[tqr.taskQueue] = tqr.reachability.map((x) => (0, exports.decodeTaskReachability)(x) ?? 'NOT_FETCHED');
                }
            }
            let bid;
            if (bir.buildId) {
                bid = bir.buildId;
            }
            else {
                bid = exports.UnversionedBuildId;
            }
            return [bid, { taskQueueReachability }];
        })),
    };
}
/**
 * Thrown when one or more Build Ids are not found while using the {@link TaskQueueClient}.
 *
 * It could be because:
 * - Id passed is incorrect
 * - Build Id has been scavenged by the server.
 *
 * @deprecated Worker Versioning is now deprecated. Please use the Worker Deployment API instead: https://docs.temporal.io/worker-deployments
 */
let BuildIdNotFoundError = class BuildIdNotFoundError extends Error {
};
exports.BuildIdNotFoundError = BuildIdNotFoundError;
exports.BuildIdNotFoundError = BuildIdNotFoundError = __decorate([
    (0, type_helpers_1.SymbolBasedInstanceOfError)('BuildIdNotFoundError')
], BuildIdNotFoundError);
//# sourceMappingURL=task-queue-client.js.map