"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.readWithPit = void 0;
var Either = _interopRequireWildcard(require("fp-ts/lib/Either"));
var _elasticsearch = require("@elastic/elasticsearch");
var _catch_retryable_es_client_errors = require("./catch_retryable_es_client_errors");
var _open_pit = require("./open_pit");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

/** @internal */

/** @internal */

/*
 * Requests documents from the index using PIT mechanism.
 * */
const readWithPit = ({
  client,
  pitId,
  query,
  batchSize,
  searchAfter,
  seqNoPrimaryTerm,
  maxResponseSizeBytes
}) => () => {
  return client.search({
    seq_no_primary_term: seqNoPrimaryTerm,
    // Fail if the index being searched doesn't exist or is closed
    // allow_no_indices: false,
    // By default ES returns a 200 with partial results if there are shard
    // request timeouts or shard failures which can lead to data loss for
    // migrations
    allow_partial_search_results: false,
    // Sort fields are required to use searchAfter so we sort by the
    // natural order of the index which is the most efficient option
    // as order is not important for the migration
    sort: '_shard_doc:asc',
    pit: {
      id: pitId,
      keep_alive: _open_pit.DEFAULT_PIT_KEEP_ALIVE
    },
    size: batchSize,
    search_after: searchAfter,
    /**
     * We want to know how many documents we need to process so we can log the progress.
     * But we also want to increase the performance of these requests,
     * so we ask ES to report the total count only on the first request (when searchAfter does not exist)
     */
    track_total_hits: typeof searchAfter === 'undefined',
    query
  }, {
    maxResponseSize: maxResponseSizeBytes
  }).then(body => {
    var _body$hits$total;
    const totalHits = typeof body.hits.total === 'number' ? body.hits.total // This format is to be removed in 8.0
    : (_body$hits$total = body.hits.total) === null || _body$hits$total === void 0 ? void 0 : _body$hits$total.value;
    const hits = body.hits.hits;
    if (hits.length > 0) {
      return Either.right({
        // @ts-expect-error @elastic/elasticsearch _source is optional
        outdatedDocuments: hits,
        lastHitSortValue: hits[hits.length - 1].sort,
        totalHits
      });
    }
    return Either.right({
      outdatedDocuments: [],
      lastHitSortValue: undefined,
      totalHits
    });
  }).catch(e => {
    if (e instanceof _elasticsearch.errors.RequestAbortedError && /The content length \(\d+\) is bigger than the maximum/.test(e.message)) {
      var _e$message$match$, _e$message$match;
      return Either.left({
        type: 'es_response_too_large',
        contentLength: Number.parseInt((_e$message$match$ = (_e$message$match = e.message.match(/The content length \((\d+)\) is bigger than the maximum/)) === null || _e$message$match === void 0 ? void 0 : _e$message$match[1]) !== null && _e$message$match$ !== void 0 ? _e$message$match$ : '-1', 10)
      });
    } else {
      throw e;
    }
  }).catch(_catch_retryable_es_client_errors.catchRetryableEsClientErrors);
};
exports.readWithPit = readWithPit;