"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.installWithTimeout = void 0;
var _rxjs = require("rxjs");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const INSTALLATION_TIMEOUT = 20 * 60 * 1000; // 20 minutes

const installWithTimeout = async ({
  description,
  installFn,
  pluginStop$,
  logger,
  timeoutMs = INSTALLATION_TIMEOUT
}) => {
  try {
    let timeoutId;
    const install = async () => {
      await installFn();
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
    const throwTimeoutException = () => {
      return new Promise((_, reject) => {
        timeoutId = setTimeout(() => {
          const msg = `Timeout: it took more than ${timeoutMs}ms`;
          reject(new Error(msg));
        }, timeoutMs);
        (0, _rxjs.firstValueFrom)(pluginStop$).then(() => {
          clearTimeout(timeoutId);
          reject(new Error('Server is stopping; must stop all async operations'));
        });
      });
    };
    await Promise.race([install(), throwTimeoutException()]);
  } catch (e) {
    logger.error(e);
    const reason = (e === null || e === void 0 ? void 0 : e.message) || 'Unknown reason';
    throw new Error(`Failure during installation${description ? ` of ${description}` : ''}. ${reason}`);
  }
};
exports.installWithTimeout = installWithTimeout;