diff --git a/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md b/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md
index 279262aa6a5ec..f6190fb3bc055 100644
--- a/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md
+++ b/docs/development/core/server/kibana-plugin-core-server.elasticsearchclient.md
@@ -9,9 +9,9 @@ Client used to query the elasticsearch cluster.
Signature:
```typescript
-export declare type ElasticsearchClient = Omit & {
+export declare type ElasticsearchClient = Omit & {
transport: {
- request(params: TransportRequestParams, options?: TransportRequestOptions): TransportRequestPromise;
+ request(params: TransportRequestParams, options?: TransportRequestOptions): Promise>;
};
};
```
diff --git a/docs/development/core/server/kibana-plugin-core-server.elasticsearcherrordetails.error.md b/docs/development/core/server/kibana-plugin-core-server.elasticsearcherrordetails.error.md
new file mode 100644
index 0000000000000..7191caea54929
--- /dev/null
+++ b/docs/development/core/server/kibana-plugin-core-server.elasticsearcherrordetails.error.md
@@ -0,0 +1,14 @@
+
+
+[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ElasticsearchErrorDetails](./kibana-plugin-core-server.elasticsearcherrordetails.md) > [error](./kibana-plugin-core-server.elasticsearcherrordetails.error.md)
+
+## ElasticsearchErrorDetails.error property
+
+Signature:
+
+```typescript
+error?: {
+ type: string;
+ reason?: string;
+ };
+```
diff --git a/docs/development/core/server/kibana-plugin-core-server.elasticsearcherrordetails.md b/docs/development/core/server/kibana-plugin-core-server.elasticsearcherrordetails.md
new file mode 100644
index 0000000000000..7dbf9e89f9b7c
--- /dev/null
+++ b/docs/development/core/server/kibana-plugin-core-server.elasticsearcherrordetails.md
@@ -0,0 +1,19 @@
+
+
+[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [ElasticsearchErrorDetails](./kibana-plugin-core-server.elasticsearcherrordetails.md)
+
+## ElasticsearchErrorDetails interface
+
+
+Signature:
+
+```typescript
+export interface ElasticsearchErrorDetails
+```
+
+## Properties
+
+| Property | Type | Description |
+| --- | --- | --- |
+| [error](./kibana-plugin-core-server.elasticsearcherrordetails.error.md) | {
type: string;
reason?: string;
}
| |
+
diff --git a/docs/development/core/server/kibana-plugin-core-server.md b/docs/development/core/server/kibana-plugin-core-server.md
index 3970cf005abe4..f22a0fb8283d7 100644
--- a/docs/development/core/server/kibana-plugin-core-server.md
+++ b/docs/development/core/server/kibana-plugin-core-server.md
@@ -71,6 +71,7 @@ The plugin integrates with the core system via lifecycle events: `setup`
| [DeprecationsServiceSetup](./kibana-plugin-core-server.deprecationsservicesetup.md) | The deprecations service provides a way for the Kibana platform to communicate deprecated features and configs with its users. These deprecations are only communicated if the deployment is using these features. Allowing for a user tailored experience for upgrading the stack version.The Deprecation service is consumed by the upgrade assistant to assist with the upgrade experience.If a deprecated feature can be resolved without manual user intervention. Using correctiveActions.api allows the Upgrade Assistant to use this api to correct the deprecation upon a user trigger. |
| [DiscoveredPlugin](./kibana-plugin-core-server.discoveredplugin.md) | Small container object used to expose information about discovered plugins that may or may not have been started. |
| [ElasticsearchConfigPreboot](./kibana-plugin-core-server.elasticsearchconfigpreboot.md) | A limited set of Elasticsearch configuration entries exposed to the preboot
plugins at setup
. |
+| [ElasticsearchErrorDetails](./kibana-plugin-core-server.elasticsearcherrordetails.md) | |
| [ElasticsearchServicePreboot](./kibana-plugin-core-server.elasticsearchservicepreboot.md) | |
| [ElasticsearchServiceSetup](./kibana-plugin-core-server.elasticsearchservicesetup.md) | |
| [ElasticsearchServiceStart](./kibana-plugin-core-server.elasticsearchservicestart.md) | |
diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectserrorhelpers.creategenericnotfoundesunavailableerror.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectserrorhelpers.creategenericnotfoundesunavailableerror.md
deleted file mode 100644
index e17877a537d00..0000000000000
--- a/docs/development/core/server/kibana-plugin-core-server.savedobjectserrorhelpers.creategenericnotfoundesunavailableerror.md
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsErrorHelpers](./kibana-plugin-core-server.savedobjectserrorhelpers.md) > [createGenericNotFoundEsUnavailableError](./kibana-plugin-core-server.savedobjectserrorhelpers.creategenericnotfoundesunavailableerror.md)
-
-## SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError() method
-
-Signature:
-
-```typescript
-static createGenericNotFoundEsUnavailableError(type?: string | null, id?: string | null): DecoratedError;
-```
-
-## Parameters
-
-| Parameter | Type | Description |
-| --- | --- | --- |
-| type | string | null
| |
-| id | string | null
| |
-
-Returns:
-
-`DecoratedError`
-
diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectserrorhelpers.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectserrorhelpers.md
index 67056c8a3cb50..2dc78f2df3a83 100644
--- a/docs/development/core/server/kibana-plugin-core-server.savedobjectserrorhelpers.md
+++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectserrorhelpers.md
@@ -18,7 +18,6 @@ export declare class SavedObjectsErrorHelpers
| [createBadRequestError(reason)](./kibana-plugin-core-server.savedobjectserrorhelpers.createbadrequesterror.md) | static
| |
| [createConflictError(type, id, reason)](./kibana-plugin-core-server.savedobjectserrorhelpers.createconflicterror.md) | static
| |
| [createGenericNotFoundError(type, id)](./kibana-plugin-core-server.savedobjectserrorhelpers.creategenericnotfounderror.md) | static
| |
-| [createGenericNotFoundEsUnavailableError(type, id)](./kibana-plugin-core-server.savedobjectserrorhelpers.creategenericnotfoundesunavailableerror.md) | static
| |
| [createIndexAliasNotFoundError(alias)](./kibana-plugin-core-server.savedobjectserrorhelpers.createindexaliasnotfounderror.md) | static
| |
| [createInvalidVersionError(versionInput)](./kibana-plugin-core-server.savedobjectserrorhelpers.createinvalidversionerror.md) | static
| |
| [createTooManyRequestsError(type, id)](./kibana-plugin-core-server.savedobjectserrorhelpers.createtoomanyrequestserror.md) | static
| |
diff --git a/package.json b/package.json
index 1f2102f3aff2e..37590371bde73 100644
--- a/package.json
+++ b/package.json
@@ -100,7 +100,7 @@
"@elastic/apm-rum-react": "^1.3.1",
"@elastic/charts": "38.0.1",
"@elastic/datemath": "link:bazel-bin/packages/elastic-datemath",
- "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.21",
+ "@elastic/elasticsearch": "npm:@elastic/elasticsearch-canary@^8.0.0-canary.35",
"@elastic/ems-client": "7.16.0",
"@elastic/eui": "40.0.0",
"@elastic/filesaver": "1.1.2",
diff --git a/packages/elastic-apm-synthtrace/src/scripts/utils/clean_write_targets.ts b/packages/elastic-apm-synthtrace/src/scripts/utils/clean_write_targets.ts
index efa24f164d51e..3c514e1097b31 100644
--- a/packages/elastic-apm-synthtrace/src/scripts/utils/clean_write_targets.ts
+++ b/packages/elastic-apm-synthtrace/src/scripts/utils/clean_write_targets.ts
@@ -35,7 +35,7 @@ export async function cleanWriteTargets({
wait_for_completion: false,
});
- const task = response.body.task;
+ const task = response.task;
if (task) {
await new Promise((resolve, reject) => {
@@ -45,13 +45,13 @@ export async function cleanWriteTargets({
});
logger.debug(
- `Polled for task:\n${JSON.stringify(taskResponse.body, ['completed', 'error'], 2)}`
+ `Polled for task:\n${JSON.stringify(taskResponse, ['completed', 'error'], 2)}`
);
- if (taskResponse.body.completed) {
+ if (taskResponse.completed) {
resolve();
- } else if (taskResponse.body.error) {
- reject(taskResponse.body.error);
+ } else if (taskResponse.error) {
+ reject(taskResponse.error);
} else {
setTimeout(pollForTaskCompletion, 2500);
}
diff --git a/packages/elastic-apm-synthtrace/src/scripts/utils/get_write_targets.ts b/packages/elastic-apm-synthtrace/src/scripts/utils/get_write_targets.ts
index 3640e4efaf796..3ad11a8fb049a 100644
--- a/packages/elastic-apm-synthtrace/src/scripts/utils/get_write_targets.ts
+++ b/packages/elastic-apm-synthtrace/src/scripts/utils/get_write_targets.ts
@@ -24,16 +24,15 @@ export async function getWriteTargets({
]);
function getDataStreamName(filter: string) {
- return datastreamsResponse.body.data_streams.find((stream) => stream.name.includes(filter))
- ?.name;
+ return datastreamsResponse.data_streams.find((stream) => stream.name.includes(filter))?.name;
}
function getAlias(filter: string) {
- return Object.keys(indicesResponse.body)
+ return Object.keys(indicesResponse)
.map((key) => {
return {
key,
- writeIndexAlias: Object.entries(indicesResponse.body[key].aliases).find(
+ writeIndexAlias: Object.entries(indicesResponse[key].aliases).find(
([_, alias]) => alias.is_write_index
)?.[0],
};
diff --git a/packages/elastic-apm-synthtrace/src/scripts/utils/upload_events.ts b/packages/elastic-apm-synthtrace/src/scripts/utils/upload_events.ts
index 89cf4d4602177..63d0e451a3af6 100644
--- a/packages/elastic-apm-synthtrace/src/scripts/utils/upload_events.ts
+++ b/packages/elastic-apm-synthtrace/src/scripts/utils/upload_events.ts
@@ -52,7 +52,7 @@ export function uploadEvents({
)
.then((results) => {
const errors = results
- .flatMap((result) => result.body.items)
+ .flatMap((result) => result.items)
.filter((item) => !!item.index?.error)
.map((item) => item.index?.error);
diff --git a/packages/kbn-apm-config-loader/src/init_apm.test.ts b/packages/kbn-apm-config-loader/src/init_apm.test.ts
index 95f0a15a448c8..6781b1b8b807e 100644
--- a/packages/kbn-apm-config-loader/src/init_apm.test.ts
+++ b/packages/kbn-apm-config-loader/src/init_apm.test.ts
@@ -11,7 +11,8 @@ import { mockLoadConfiguration } from './init_apm.test.mocks';
import { initApm } from './init_apm';
import apm from 'elastic-apm-node';
-describe('initApm', () => {
+// TODO: unskip when https://github.com/elastic/kibana/issues/116109 is fixed
+describe.skip('initApm', () => {
let apmAddFilterSpy: jest.SpyInstance;
let apmStartSpy: jest.SpyInstance;
let getConfig: jest.Mock;
diff --git a/packages/kbn-apm-config-loader/src/init_apm.ts b/packages/kbn-apm-config-loader/src/init_apm.ts
index 21c40c8b39419..33609c2493396 100644
--- a/packages/kbn-apm-config-loader/src/init_apm.ts
+++ b/packages/kbn-apm-config-loader/src/init_apm.ts
@@ -14,6 +14,9 @@ export const initApm = (
isDistributable: boolean,
serviceName: string
) => {
+ // TODO: re-enabled when https://github.com/elastic/kibana/issues/116109 is fixed
+ return;
+
const apmConfigLoader = loadConfiguration(argv, rootDir, isDistributable);
const apmConfig = apmConfigLoader.getConfig(serviceName);
diff --git a/packages/kbn-es-archiver/src/actions/empty_kibana_index.ts b/packages/kbn-es-archiver/src/actions/empty_kibana_index.ts
index 24a1de10b2b1d..96b5b5f8e98e5 100644
--- a/packages/kbn-es-archiver/src/actions/empty_kibana_index.ts
+++ b/packages/kbn-es-archiver/src/actions/empty_kibana_index.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { ToolingLog } from '@kbn/dev-utils';
import { KbnClient } from '@kbn/test';
@@ -17,7 +17,7 @@ export async function emptyKibanaIndexAction({
log,
kbnClient,
}: {
- client: KibanaClient;
+ client: Client;
log: ToolingLog;
kbnClient: KbnClient;
}) {
diff --git a/packages/kbn-es-archiver/src/actions/load.ts b/packages/kbn-es-archiver/src/actions/load.ts
index 673fa7e7d96c8..619c946f0c988 100644
--- a/packages/kbn-es-archiver/src/actions/load.ts
+++ b/packages/kbn-es-archiver/src/actions/load.ts
@@ -11,7 +11,7 @@ import { createReadStream } from 'fs';
import { Readable } from 'stream';
import { ToolingLog, REPO_ROOT } from '@kbn/dev-utils';
import { KbnClient } from '@kbn/test';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { createPromiseFromStreams, concatStreamProviders } from '@kbn/utils';
import { ES_CLIENT_HEADERS } from '../client_headers';
@@ -47,7 +47,7 @@ export async function loadAction({
inputDir: string;
skipExisting: boolean;
useCreate: boolean;
- client: KibanaClient;
+ client: Client;
log: ToolingLog;
kbnClient: KbnClient;
}) {
diff --git a/packages/kbn-es-archiver/src/actions/save.ts b/packages/kbn-es-archiver/src/actions/save.ts
index da0966920de24..07ed2b206c1dd 100644
--- a/packages/kbn-es-archiver/src/actions/save.ts
+++ b/packages/kbn-es-archiver/src/actions/save.ts
@@ -9,7 +9,7 @@
import { resolve, relative } from 'path';
import { createWriteStream, mkdirSync } from 'fs';
import { Readable, Writable } from 'stream';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { ToolingLog, REPO_ROOT } from '@kbn/dev-utils';
import { createListStream, createPromiseFromStreams } from '@kbn/utils';
@@ -31,7 +31,7 @@ export async function saveAction({
}: {
outputDir: string;
indices: string | string[];
- client: KibanaClient;
+ client: Client;
log: ToolingLog;
raw: boolean;
query?: Record;
diff --git a/packages/kbn-es-archiver/src/actions/unload.ts b/packages/kbn-es-archiver/src/actions/unload.ts
index 98bae36095b88..1c5f4cd5d7d03 100644
--- a/packages/kbn-es-archiver/src/actions/unload.ts
+++ b/packages/kbn-es-archiver/src/actions/unload.ts
@@ -9,7 +9,7 @@
import { resolve, relative } from 'path';
import { createReadStream } from 'fs';
import { Readable, Writable } from 'stream';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { ToolingLog, REPO_ROOT } from '@kbn/dev-utils';
import { KbnClient } from '@kbn/test';
import { createPromiseFromStreams } from '@kbn/utils';
@@ -31,7 +31,7 @@ export async function unloadAction({
kbnClient,
}: {
inputDir: string;
- client: KibanaClient;
+ client: Client;
log: ToolingLog;
kbnClient: KbnClient;
}) {
diff --git a/packages/kbn-es-archiver/src/cli.ts b/packages/kbn-es-archiver/src/cli.ts
index 8e4a879282765..db54a3bade74b 100644
--- a/packages/kbn-es-archiver/src/cli.ts
+++ b/packages/kbn-es-archiver/src/cli.ts
@@ -19,7 +19,7 @@ import Fs from 'fs';
import { RunWithCommands, createFlagError, CA_CERT_PATH } from '@kbn/dev-utils';
import { readConfigFile, KbnClient } from '@kbn/test';
-import { Client } from '@elastic/elasticsearch';
+import { Client, HttpConnection } from '@elastic/elasticsearch';
import { EsArchiver } from './es_archiver';
@@ -106,7 +106,8 @@ export function runCli() {
const client = new Client({
node: esUrl,
- ssl: esCa ? { ca: esCa } : undefined,
+ tls: esCa ? { ca: esCa } : undefined,
+ Connection: HttpConnection,
});
addCleanupTask(() => client.close());
diff --git a/packages/kbn-es-archiver/src/es_archiver.ts b/packages/kbn-es-archiver/src/es_archiver.ts
index 06a56b79e3012..ed27bc0afcf34 100644
--- a/packages/kbn-es-archiver/src/es_archiver.ts
+++ b/packages/kbn-es-archiver/src/es_archiver.ts
@@ -9,7 +9,7 @@
import Fs from 'fs';
import Path from 'path';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { ToolingLog, REPO_ROOT } from '@kbn/dev-utils';
import { KbnClient } from '@kbn/test';
@@ -23,14 +23,14 @@ import {
} from './actions';
interface Options {
- client: KibanaClient;
+ client: Client;
baseDir?: string;
log: ToolingLog;
kbnClient: KbnClient;
}
export class EsArchiver {
- private readonly client: KibanaClient;
+ private readonly client: Client;
private readonly baseDir: string;
private readonly log: ToolingLog;
private readonly kbnClient: KbnClient;
diff --git a/packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.test.ts b/packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.test.ts
index da7ed4c81b666..2902812f51493 100644
--- a/packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.test.ts
+++ b/packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.test.ts
@@ -99,10 +99,8 @@ it('transforms each input index to a stream of docs using scrollSearch helper',
Array [
Object {
"_source": "true",
- "body": Object {
- "query": undefined,
- },
"index": "bar",
+ "query": undefined,
"rest_total_hits_as_int": true,
"scroll": "1m",
"size": 1000,
@@ -116,10 +114,8 @@ it('transforms each input index to a stream of docs using scrollSearch helper',
Array [
Object {
"_source": "true",
- "body": Object {
- "query": undefined,
- },
"index": "foo",
+ "query": undefined,
"rest_total_hits_as_int": true,
"scroll": "1m",
"size": 1000,
diff --git a/packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.ts b/packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.ts
index 88e167b3705cb..a0636d6a3f76a 100644
--- a/packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.ts
+++ b/packages/kbn-es-archiver/src/lib/docs/generate_doc_records_stream.ts
@@ -7,7 +7,7 @@
*/
import { Transform } from 'stream';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { Stats } from '../stats';
import { Progress } from '../progress';
import { ES_CLIENT_HEADERS } from '../../client_headers';
@@ -21,7 +21,7 @@ export function createGenerateDocRecordsStream({
progress,
query,
}: {
- client: KibanaClient;
+ client: Client;
stats: Stats;
progress: Progress;
query?: Record;
@@ -37,9 +37,7 @@ export function createGenerateDocRecordsStream({
scroll: SCROLL_TIMEOUT,
size: SCROLL_SIZE,
_source: 'true',
- body: {
- query,
- },
+ query,
rest_total_hits_as_int: true,
},
{
diff --git a/packages/kbn-es-archiver/src/lib/docs/index_doc_records_stream.ts b/packages/kbn-es-archiver/src/lib/docs/index_doc_records_stream.ts
index 028ff16c9afb2..749bfd0872353 100644
--- a/packages/kbn-es-archiver/src/lib/docs/index_doc_records_stream.ts
+++ b/packages/kbn-es-archiver/src/lib/docs/index_doc_records_stream.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import AggregateError from 'aggregate-error';
import { Writable } from 'stream';
import { Stats } from '../stats';
@@ -14,7 +14,7 @@ import { Progress } from '../progress';
import { ES_CLIENT_HEADERS } from '../../client_headers';
export function createIndexDocRecordsStream(
- client: KibanaClient,
+ client: Client,
stats: Stats,
progress: Progress,
useCreate: boolean = false
diff --git a/packages/kbn-es-archiver/src/lib/indices/__mocks__/stubs.ts b/packages/kbn-es-archiver/src/lib/indices/__mocks__/stubs.ts
index 7dde4075dc3f2..ded56ddfdf0de 100644
--- a/packages/kbn-es-archiver/src/lib/indices/__mocks__/stubs.ts
+++ b/packages/kbn-es-archiver/src/lib/indices/__mocks__/stubs.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import sinon from 'sinon';
import { ToolingLog } from '@kbn/dev-utils';
import { Stats } from '../../stats';
@@ -67,7 +67,7 @@ const createEsClientError = (errorType: string) => {
const indexAlias = (aliases: Record, index: string) =>
Object.keys(aliases).find((k) => aliases[k] === index);
-type StubClient = KibanaClient;
+type StubClient = Client;
export const createStubClient = (
existingIndices: string[] = [],
diff --git a/packages/kbn-es-archiver/src/lib/indices/create_index_stream.test.ts b/packages/kbn-es-archiver/src/lib/indices/create_index_stream.test.ts
index 28c8ccd1c28a8..3a8180b724e07 100644
--- a/packages/kbn-es-archiver/src/lib/indices/create_index_stream.test.ts
+++ b/packages/kbn-es-archiver/src/lib/indices/create_index_stream.test.ts
@@ -71,6 +71,7 @@ describe('esArchiver: createCreateIndexStream()', () => {
"ignore": Array [
404,
],
+ "meta": true,
},
],
]
diff --git a/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts b/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts
index fba3df24e896f..50d13fc728c79 100644
--- a/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts
+++ b/packages/kbn-es-archiver/src/lib/indices/create_index_stream.ts
@@ -9,8 +9,8 @@
import { Transform, Readable } from 'stream';
import { inspect } from 'util';
-import { estypes } from '@elastic/elasticsearch';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import type { Client } from '@elastic/elasticsearch';
import { ToolingLog } from '@kbn/dev-utils';
import { Stats } from '../stats';
@@ -31,7 +31,7 @@ export function createCreateIndexStream({
skipExisting = false,
log,
}: {
- client: KibanaClient;
+ client: Client;
stats: Stats;
skipExisting?: boolean;
log: ToolingLog;
diff --git a/packages/kbn-es-archiver/src/lib/indices/delete_index.ts b/packages/kbn-es-archiver/src/lib/indices/delete_index.ts
index d3d6f85d7a360..3bba96d32ba95 100644
--- a/packages/kbn-es-archiver/src/lib/indices/delete_index.ts
+++ b/packages/kbn-es-archiver/src/lib/indices/delete_index.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { ToolingLog } from '@kbn/dev-utils';
import { Stats } from '../stats';
import { ES_CLIENT_HEADERS } from '../../client_headers';
@@ -15,7 +15,7 @@ import { ES_CLIENT_HEADERS } from '../../client_headers';
const PENDING_SNAPSHOT_STATUSES = ['INIT', 'STARTED', 'WAITING'];
export async function deleteIndex(options: {
- client: KibanaClient;
+ client: Client;
stats: Stats;
index: string | string[];
log: ToolingLog;
@@ -32,6 +32,7 @@ export async function deleteIndex(options: {
{
ignore: [404],
headers: ES_CLIENT_HEADERS,
+ meta: true,
}
);
@@ -84,15 +85,13 @@ export function isDeleteWhileSnapshotInProgressError(error: any) {
* snapshotting this index to complete.
*/
export async function waitForSnapshotCompletion(
- client: KibanaClient,
+ client: Client,
index: string | string[],
log: ToolingLog
) {
const isSnapshotPending = async (repository: string, snapshot: string) => {
const {
- body: {
- snapshots: [status],
- },
+ snapshots: [status],
} = await client.snapshot.status(
{
repository,
@@ -108,9 +107,7 @@ export async function waitForSnapshotCompletion(
};
const getInProgressSnapshots = async (repository: string) => {
- const {
- body: { snapshots: inProgressSnapshots },
- } = await client.snapshot.get(
+ const { snapshots: inProgressSnapshots } = await client.snapshot.get(
{
repository,
snapshot: '_current',
@@ -123,7 +120,7 @@ export async function waitForSnapshotCompletion(
return inProgressSnapshots;
};
- const { body: repositoryMap } = await client.snapshot.getRepository({} as any);
+ const repositoryMap = await client.snapshot.getRepository({});
for (const repository of Object.keys(repositoryMap)) {
const allInProgress = await getInProgressSnapshots(repository);
const found = allInProgress?.find((s: any) => s.indices.includes(index));
diff --git a/packages/kbn-es-archiver/src/lib/indices/delete_index_stream.ts b/packages/kbn-es-archiver/src/lib/indices/delete_index_stream.ts
index 7765419bb9d15..e7763ca251e6f 100644
--- a/packages/kbn-es-archiver/src/lib/indices/delete_index_stream.ts
+++ b/packages/kbn-es-archiver/src/lib/indices/delete_index_stream.ts
@@ -7,14 +7,14 @@
*/
import { Transform } from 'stream';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { ToolingLog } from '@kbn/dev-utils';
import { Stats } from '../stats';
import { deleteIndex } from './delete_index';
import { cleanKibanaIndices } from './kibana_index';
-export function createDeleteIndexStream(client: KibanaClient, stats: Stats, log: ToolingLog) {
+export function createDeleteIndexStream(client: Client, stats: Stats, log: ToolingLog) {
return new Transform({
readableObjectMode: true,
writableObjectMode: true,
diff --git a/packages/kbn-es-archiver/src/lib/indices/generate_index_records_stream.ts b/packages/kbn-es-archiver/src/lib/indices/generate_index_records_stream.ts
index 6619f1b3a601e..d647a4fe5f501 100644
--- a/packages/kbn-es-archiver/src/lib/indices/generate_index_records_stream.ts
+++ b/packages/kbn-es-archiver/src/lib/indices/generate_index_records_stream.ts
@@ -6,12 +6,12 @@
* Side Public License, v 1.
*/
+import type { Client } from '@elastic/elasticsearch';
import { Transform } from 'stream';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
import { Stats } from '../stats';
import { ES_CLIENT_HEADERS } from '../../client_headers';
-export function createGenerateIndexRecordsStream(client: KibanaClient, stats: Stats) {
+export function createGenerateIndexRecordsStream(client: Client, stats: Stats) {
return new Transform({
writableObjectMode: true,
readableObjectMode: true,
@@ -37,9 +37,10 @@ export function createGenerateIndexRecordsStream(client: KibanaClient, stats: St
},
{
headers: ES_CLIENT_HEADERS,
+ meta: true,
}
)
- ).body as Record;
+ ).body;
for (const [index, { settings, mappings }] of Object.entries(resp)) {
const {
@@ -50,6 +51,7 @@ export function createGenerateIndexRecordsStream(client: KibanaClient, stats: St
{ index },
{
headers: ES_CLIENT_HEADERS,
+ meta: true,
}
);
diff --git a/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts b/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts
index 635e432468846..069db636c596b 100644
--- a/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts
+++ b/packages/kbn-es-archiver/src/lib/indices/kibana_index.ts
@@ -8,7 +8,7 @@
import { inspect } from 'util';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { Client } from '@elastic/elasticsearch';
import { ToolingLog } from '@kbn/dev-utils';
import { KbnClient } from '@kbn/test';
import { Stats } from '../stats';
@@ -23,7 +23,7 @@ export async function deleteKibanaIndices({
stats,
log,
}: {
- client: KibanaClient;
+ client: Client;
stats: Stats;
log: ToolingLog;
}) {
@@ -35,7 +35,7 @@ export async function deleteKibanaIndices({
await client.indices.putSettings(
{
index: indexNames,
- body: { settings: { blocks: { read_only: false } } },
+ body: { blocks: { read_only: false } },
},
{
headers: ES_CLIENT_HEADERS,
@@ -75,7 +75,7 @@ function isKibanaIndex(index?: string): index is string {
);
}
-async function fetchKibanaIndices(client: KibanaClient) {
+async function fetchKibanaIndices(client: Client) {
const resp = await client.cat.indices(
{ index: '.kibana*', format: 'json' },
{
@@ -83,11 +83,11 @@ async function fetchKibanaIndices(client: KibanaClient) {
}
);
- if (!Array.isArray(resp.body)) {
- throw new Error(`expected response to be an array ${inspect(resp.body)}`);
+ if (!Array.isArray(resp)) {
+ throw new Error(`expected response to be an array ${inspect(resp)}`);
}
- return resp.body.map((x: { index?: string }) => x.index).filter(isKibanaIndex);
+ return resp.map((x: { index?: string }) => x.index).filter(isKibanaIndex);
}
const delay = (delayInMs: number) => new Promise((resolve) => setTimeout(resolve, delayInMs));
@@ -97,7 +97,7 @@ export async function cleanKibanaIndices({
stats,
log,
}: {
- client: KibanaClient;
+ client: Client;
stats: Stats;
log: ToolingLog;
}) {
@@ -123,11 +123,11 @@ export async function cleanKibanaIndices({
}
);
- if (resp.body.total !== resp.body.deleted) {
+ if (resp.total !== resp.deleted) {
log.warning(
'delete by query deleted %d of %d total documents, trying again',
- resp.body.deleted,
- resp.body.total
+ resp.deleted,
+ resp.total
);
await delay(200);
continue;
@@ -144,13 +144,7 @@ export async function cleanKibanaIndices({
stats.deletedIndex('.kibana');
}
-export async function createDefaultSpace({
- index,
- client,
-}: {
- index: string;
- client: KibanaClient;
-}) {
+export async function createDefaultSpace({ index, client }: { index: string; client: Client }) {
await client.create(
{
index,
diff --git a/packages/kbn-es-query/src/es_query/decorate_query.ts b/packages/kbn-es-query/src/es_query/decorate_query.ts
index e5bcf01a45915..a58eca575f4bf 100644
--- a/packages/kbn-es-query/src/es_query/decorate_query.ts
+++ b/packages/kbn-es-query/src/es_query/decorate_query.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SerializableRecord } from '@kbn/utility-types';
import { extend, defaults } from 'lodash';
import { getTimeZoneFromSettings } from '../utils';
diff --git a/packages/kbn-es-query/src/es_query/from_filters.ts b/packages/kbn-es-query/src/es_query/from_filters.ts
index ac6c8a4a6b2b8..28d8653246e3d 100644
--- a/packages/kbn-es-query/src/es_query/from_filters.ts
+++ b/packages/kbn-es-query/src/es_query/from_filters.ts
@@ -7,7 +7,7 @@
*/
import { isUndefined } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { migrateFilter } from './migrate_filter';
import { filterMatchesIndex } from './filter_matches_index';
import { Filter, cleanFilter, isFilterDisabled } from '../filters';
diff --git a/packages/kbn-es-query/src/es_query/lucene_string_to_dsl.ts b/packages/kbn-es-query/src/es_query/lucene_string_to_dsl.ts
index 91a912a5da0e3..07b56f281e80e 100644
--- a/packages/kbn-es-query/src/es_query/lucene_string_to_dsl.ts
+++ b/packages/kbn-es-query/src/es_query/lucene_string_to_dsl.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { isString } from 'lodash';
/**
diff --git a/packages/kbn-es-query/src/es_query/types.ts b/packages/kbn-es-query/src/es_query/types.ts
index 75ea320b3431f..9e9888f5d14f6 100644
--- a/packages/kbn-es-query/src/es_query/types.ts
+++ b/packages/kbn-es-query/src/es_query/types.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
/**
* A field's sub type
diff --git a/packages/kbn-es-query/src/filters/build_filters/custom_filter.ts b/packages/kbn-es-query/src/filters/build_filters/custom_filter.ts
index 72b775bc688cc..77356006d98ef 100644
--- a/packages/kbn-es-query/src/filters/build_filters/custom_filter.ts
+++ b/packages/kbn-es-query/src/filters/build_filters/custom_filter.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Filter, FilterMeta, FILTERS, FilterStateStore } from './types';
/** @public */
diff --git a/packages/kbn-es-query/src/filters/build_filters/match_all_filter.ts b/packages/kbn-es-query/src/filters/build_filters/match_all_filter.ts
index 2d14ee8096f13..5e8083c1d1415 100644
--- a/packages/kbn-es-query/src/filters/build_filters/match_all_filter.ts
+++ b/packages/kbn-es-query/src/filters/build_filters/match_all_filter.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { has } from 'lodash';
import type { Filter, FilterMeta } from './types';
diff --git a/packages/kbn-es-query/src/filters/build_filters/phrase_filter.test.ts b/packages/kbn-es-query/src/filters/build_filters/phrase_filter.test.ts
index 13f18ad0cc7ea..87a7812165a66 100644
--- a/packages/kbn-es-query/src/filters/build_filters/phrase_filter.test.ts
+++ b/packages/kbn-es-query/src/filters/build_filters/phrase_filter.test.ts
@@ -14,7 +14,7 @@ import {
} from './phrase_filter';
import { fields, getField } from '../stubs';
import { DataViewBase } from '../../es_query';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
describe('Phrase filter builder', () => {
let indexPattern: DataViewBase;
diff --git a/packages/kbn-es-query/src/filters/build_filters/phrase_filter.ts b/packages/kbn-es-query/src/filters/build_filters/phrase_filter.ts
index 1e123900463b5..4c1827dc58c04 100644
--- a/packages/kbn-es-query/src/filters/build_filters/phrase_filter.ts
+++ b/packages/kbn-es-query/src/filters/build_filters/phrase_filter.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { get, has, isPlainObject } from 'lodash';
import type { Filter, FilterMeta } from './types';
import type { IndexPatternFieldBase, IndexPatternBase } from '../../es_query';
diff --git a/packages/kbn-es-query/src/filters/build_filters/phrases_filter.ts b/packages/kbn-es-query/src/filters/build_filters/phrases_filter.ts
index 0e09a191fd549..fe895bbd60a74 100644
--- a/packages/kbn-es-query/src/filters/build_filters/phrases_filter.ts
+++ b/packages/kbn-es-query/src/filters/build_filters/phrases_filter.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Filter, FilterMeta, FILTERS } from './types';
import { getPhraseScript, PhraseFilterValue } from './phrase_filter';
import type { IndexPatternFieldBase, IndexPatternBase } from '../../es_query';
diff --git a/packages/kbn-es-query/src/filters/build_filters/range_filter.ts b/packages/kbn-es-query/src/filters/build_filters/range_filter.ts
index e559e4d7e1d80..51e8fefe95f70 100644
--- a/packages/kbn-es-query/src/filters/build_filters/range_filter.ts
+++ b/packages/kbn-es-query/src/filters/build_filters/range_filter.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { map, reduce, mapValues, has, get, keys, pickBy } from 'lodash';
import type { Filter, FilterMeta } from './types';
import type { IndexPatternBase, IndexPatternFieldBase } from '../../es_query';
diff --git a/packages/kbn-es-query/src/kuery/ast/ast.ts b/packages/kbn-es-query/src/kuery/ast/ast.ts
index c1b4380ecbfe3..683de9f193901 100644
--- a/packages/kbn-es-query/src/kuery/ast/ast.ts
+++ b/packages/kbn-es-query/src/kuery/ast/ast.ts
@@ -7,7 +7,7 @@
*/
import { JsonObject } from '@kbn/utility-types';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { nodeTypes } from '../node_types/index';
import { KQLSyntaxError } from '../kuery_syntax_error';
import { KueryNode, KueryParseOptions, KueryQueryOptions } from '../types';
diff --git a/packages/kbn-es-query/src/kuery/functions/exists.ts b/packages/kbn-es-query/src/kuery/functions/exists.ts
index d1d0cb7835bca..a0d779c4c7d49 100644
--- a/packages/kbn-es-query/src/kuery/functions/exists.ts
+++ b/packages/kbn-es-query/src/kuery/functions/exists.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IndexPatternFieldBase, IndexPatternBase, KueryNode, KueryQueryOptions } from '../..';
import * as literal from '../node_types/literal';
diff --git a/packages/kbn-es-query/src/kuery/functions/geo_bounding_box.test.ts b/packages/kbn-es-query/src/kuery/functions/geo_bounding_box.test.ts
index 9c4a33f50020f..7580765d59282 100644
--- a/packages/kbn-es-query/src/kuery/functions/geo_bounding_box.test.ts
+++ b/packages/kbn-es-query/src/kuery/functions/geo_bounding_box.test.ts
@@ -109,7 +109,6 @@ describe('kuery functions', () => {
const node = nodeTypes.function.buildNode('geoBoundingBox', 'geo', params);
const result = geoBoundingBox.toElasticsearchQuery(node, indexPattern);
- // @ts-expect-error @elastic/elasticsearch doesn't support ignore_unmapped in QueryDslGeoBoundingBoxQuery
expect(result.geo_bounding_box!.ignore_unmapped).toBe(true);
});
diff --git a/packages/kbn-es-query/src/kuery/functions/geo_bounding_box.ts b/packages/kbn-es-query/src/kuery/functions/geo_bounding_box.ts
index 1dae0b40ff08e..1808b7a2c0106 100644
--- a/packages/kbn-es-query/src/kuery/functions/geo_bounding_box.ts
+++ b/packages/kbn-es-query/src/kuery/functions/geo_bounding_box.ts
@@ -7,7 +7,7 @@
*/
import _ from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { nodeTypes } from '../node_types';
import * as ast from '../ast';
import { IndexPatternBase, KueryNode, KueryQueryOptions, LatLon } from '../..';
@@ -53,7 +53,6 @@ export function toElasticsearchQuery(
}
return {
- // @ts-expect-error @elastic/elasticsearch doesn't support ignore_unmapped in QueryDslGeoBoundingBoxQuery
geo_bounding_box: {
[fieldName]: queryParams,
ignore_unmapped: true,
diff --git a/packages/kbn-es-query/src/kuery/functions/geo_polygon.ts b/packages/kbn-es-query/src/kuery/functions/geo_polygon.ts
index cf0bcdafa04c7..0cc95f8012a42 100644
--- a/packages/kbn-es-query/src/kuery/functions/geo_polygon.ts
+++ b/packages/kbn-es-query/src/kuery/functions/geo_polygon.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { nodeTypes } from '../node_types';
import * as ast from '../ast';
import { IndexPatternBase, KueryNode, KueryQueryOptions, LatLon } from '../..';
@@ -49,7 +49,6 @@ export function toElasticsearchQuery(
}
return {
- // @ts-expect-error @elastic/elasticsearch doesn't support ignore_unmapped in QueryDslGeoPolygonQuery
geo_polygon: {
[fieldName]: queryParams,
ignore_unmapped: true,
diff --git a/packages/kbn-es-query/src/kuery/functions/is.test.ts b/packages/kbn-es-query/src/kuery/functions/is.test.ts
index fbc6011331dbb..2ec53629b9dca 100644
--- a/packages/kbn-es-query/src/kuery/functions/is.test.ts
+++ b/packages/kbn-es-query/src/kuery/functions/is.test.ts
@@ -11,7 +11,7 @@ import { fields } from '../../filters/stubs';
import * as is from './is';
import { DataViewBase } from '../..';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
jest.mock('../grammar');
diff --git a/packages/kbn-es-query/src/kuery/functions/is.ts b/packages/kbn-es-query/src/kuery/functions/is.ts
index 38a62309721a2..854dcd95dc7aa 100644
--- a/packages/kbn-es-query/src/kuery/functions/is.ts
+++ b/packages/kbn-es-query/src/kuery/functions/is.ts
@@ -7,7 +7,7 @@
*/
import { isUndefined } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { getPhraseScript } from '../../filters';
import { getFields } from './utils/get_fields';
import { getTimeZoneFromSettings, getDataViewFieldSubtypeNested } from '../../utils';
diff --git a/packages/kbn-es-query/src/kuery/functions/nested.ts b/packages/kbn-es-query/src/kuery/functions/nested.ts
index e59f7a6acc07d..3a466e9ddca02 100644
--- a/packages/kbn-es-query/src/kuery/functions/nested.ts
+++ b/packages/kbn-es-query/src/kuery/functions/nested.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as ast from '../ast';
import * as literal from '../node_types/literal';
import { IndexPatternBase, KueryNode, KueryQueryOptions } from '../..';
diff --git a/packages/kbn-es-query/src/kuery/functions/not.ts b/packages/kbn-es-query/src/kuery/functions/not.ts
index 01ec89e9b499d..91954c6a09fc4 100644
--- a/packages/kbn-es-query/src/kuery/functions/not.ts
+++ b/packages/kbn-es-query/src/kuery/functions/not.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as ast from '../ast';
import { IndexPatternBase, KueryNode, KueryQueryOptions } from '../..';
diff --git a/packages/kbn-es-query/src/kuery/functions/or.ts b/packages/kbn-es-query/src/kuery/functions/or.ts
index d48ddb4c32d73..d06f51d2918bd 100644
--- a/packages/kbn-es-query/src/kuery/functions/or.ts
+++ b/packages/kbn-es-query/src/kuery/functions/or.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as ast from '../ast';
import { IndexPatternBase, KueryNode, KueryQueryOptions } from '../..';
diff --git a/packages/kbn-es-query/src/kuery/functions/range.test.ts b/packages/kbn-es-query/src/kuery/functions/range.test.ts
index c541b26ce176f..2a97a74ac385d 100644
--- a/packages/kbn-es-query/src/kuery/functions/range.test.ts
+++ b/packages/kbn-es-query/src/kuery/functions/range.test.ts
@@ -13,7 +13,7 @@ import { DataViewBase } from '../..';
import { RangeFilterParams } from '../../filters';
import * as range from './range';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
jest.mock('../grammar');
describe('kuery functions', () => {
diff --git a/packages/kbn-es-query/src/kuery/functions/range.ts b/packages/kbn-es-query/src/kuery/functions/range.ts
index c5f24a1afdd6f..e016feb908bc7 100644
--- a/packages/kbn-es-query/src/kuery/functions/range.ts
+++ b/packages/kbn-es-query/src/kuery/functions/range.ts
@@ -7,7 +7,7 @@
*/
import { pick, map, mapValues } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { nodeTypes } from '../node_types';
import * as ast from '../ast';
import { getRangeScript, RangeFilterParams } from '../../filters';
diff --git a/packages/kbn-es-query/src/kuery/index.ts b/packages/kbn-es-query/src/kuery/index.ts
index 15f3a768ebbd3..6e03b3cb18f4c 100644
--- a/packages/kbn-es-query/src/kuery/index.ts
+++ b/packages/kbn-es-query/src/kuery/index.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { toElasticsearchQuery as astToElasticsearchQuery } from './ast';
/**
diff --git a/packages/kbn-es-query/src/kuery/types.ts b/packages/kbn-es-query/src/kuery/types.ts
index 1ab2d07a60a11..c074fa6d90845 100644
--- a/packages/kbn-es-query/src/kuery/types.ts
+++ b/packages/kbn-es-query/src/kuery/types.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SerializableRecord } from '@kbn/utility-types';
import { NodeTypes } from './node_types';
diff --git a/packages/kbn-es/src/utils/native_realm.js b/packages/kbn-es/src/utils/native_realm.js
index c1682e0d18002..5c81d1e1147d1 100644
--- a/packages/kbn-es/src/utils/native_realm.js
+++ b/packages/kbn-es/src/utils/native_realm.js
@@ -16,7 +16,7 @@ exports.NativeRealm = class NativeRealm {
const auth = { username: 'elastic', password: elasticPassword };
this._client = new Client(
ssl
- ? { node: `https://localhost:${port}`, ssl: { ca: caCert, rejectUnauthorized: true }, auth }
+ ? { node: `https://localhost:${port}`, tls: { ca: caCert, rejectUnauthorized: true }, auth }
: { node: `http://localhost:${port}`, auth }
);
this._elasticPassword = elasticPassword;
@@ -67,9 +67,7 @@ exports.NativeRealm = class NativeRealm {
async getReservedUsers(retryOpts = {}) {
return await this._autoRetry(retryOpts, async () => {
const resp = await this._client.security.getUser();
- const usernames = Object.keys(resp.body).filter(
- (user) => resp.body[user].metadata._reserved === true
- );
+ const usernames = Object.keys(resp).filter((user) => resp[user].metadata._reserved === true);
if (!usernames?.length) {
throw new Error('no reserved users found, unable to set native realm passwords');
@@ -82,9 +80,7 @@ exports.NativeRealm = class NativeRealm {
async isSecurityEnabled(retryOpts = {}) {
try {
return await this._autoRetry(retryOpts, async () => {
- const {
- body: { features },
- } = await this._client.xpack.info({ categories: 'features' });
+ const { features } = await this._client.xpack.info({ categories: 'features' });
return features.security && features.security.enabled && features.security.available;
});
} catch (error) {
diff --git a/packages/kbn-es/src/utils/native_realm.test.js b/packages/kbn-es/src/utils/native_realm.test.js
index 6d07b1e73b547..e3cb6aee84198 100644
--- a/packages/kbn-es/src/utils/native_realm.test.js
+++ b/packages/kbn-es/src/utils/native_realm.test.js
@@ -38,12 +38,10 @@ afterAll(() => {
function mockXPackInfo(available, enabled) {
mockClient.xpack.info.mockImplementation(() => ({
- body: {
- features: {
- security: {
- available,
- enabled,
- },
+ features: {
+ security: {
+ available,
+ enabled,
},
},
}));
@@ -97,31 +95,29 @@ describe('setPasswords', () => {
mockXPackInfo(true, true);
mockClient.security.getUser.mockImplementation(() => ({
- body: {
- kibana_system: {
- metadata: {
- _reserved: true,
- },
+ kibana_system: {
+ metadata: {
+ _reserved: true,
},
- non_native: {
- metadata: {
- _reserved: false,
- },
+ },
+ non_native: {
+ metadata: {
+ _reserved: false,
},
- logstash_system: {
- metadata: {
- _reserved: true,
- },
+ },
+ logstash_system: {
+ metadata: {
+ _reserved: true,
},
- elastic: {
- metadata: {
- _reserved: true,
- },
+ },
+ elastic: {
+ metadata: {
+ _reserved: true,
},
- beats_system: {
- metadata: {
- _reserved: true,
- },
+ },
+ beats_system: {
+ metadata: {
+ _reserved: true,
},
},
}));
@@ -176,21 +172,19 @@ Array [
describe('getReservedUsers', () => {
it('returns array of reserved usernames', async () => {
mockClient.security.getUser.mockImplementation(() => ({
- body: {
- kibana_system: {
- metadata: {
- _reserved: true,
- },
+ kibana_system: {
+ metadata: {
+ _reserved: true,
},
- non_native: {
- metadata: {
- _reserved: false,
- },
+ },
+ non_native: {
+ metadata: {
+ _reserved: false,
},
- logstash_system: {
- metadata: {
- _reserved: true,
- },
+ },
+ logstash_system: {
+ metadata: {
+ _reserved: true,
},
},
}));
diff --git a/packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts b/packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts
index d167b17b83f23..d68f6df5cc4d2 100644
--- a/packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts
+++ b/packages/kbn-rule-data-utils/src/alerts_as_data_rbac.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { EsQueryConfig } from '@kbn/es-query';
/**
diff --git a/packages/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts b/packages/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts
index 6a177f5caac21..973fe27ad7537 100644
--- a/packages/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/create_boostrap_index/index.ts
@@ -16,15 +16,18 @@ export const createBootstrapIndex = async (
index: string
): Promise => {
return (
- await esClient.indices.create({
- index: `${index}-000001`,
- body: {
- aliases: {
- [index]: {
- is_write_index: true,
+ await esClient.indices.create(
+ {
+ index: `${index}-000001`,
+ body: {
+ aliases: {
+ [index]: {
+ is_write_index: true,
+ },
},
},
},
- })
+ { meta: true }
+ )
).body;
};
diff --git a/packages/kbn-securitysolution-es-utils/src/decode_version/index.ts b/packages/kbn-securitysolution-es-utils/src/decode_version/index.ts
index d58c7add67a27..8b3fb6f63d59a 100644
--- a/packages/kbn-securitysolution-es-utils/src/decode_version/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/decode_version/index.ts
@@ -23,8 +23,8 @@ export const decodeVersion = (
const parsed = JSON.parse(decoded);
if (Array.isArray(parsed) && Number.isInteger(parsed[0]) && Number.isInteger(parsed[1])) {
return {
- ifPrimaryTerm: parsed[1],
- ifSeqNo: parsed[0],
+ if_primary_term: parsed[1],
+ if_seq_no: parsed[0],
};
} else {
return {};
diff --git a/packages/kbn-securitysolution-es-utils/src/delete_all_index/index.ts b/packages/kbn-securitysolution-es-utils/src/delete_all_index/index.ts
index 580c104752aea..2ff93f668ea27 100644
--- a/packages/kbn-securitysolution-es-utils/src/delete_all_index/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/delete_all_index/index.ts
@@ -25,7 +25,7 @@ export const deleteAllIndex = async (
{
index: pattern,
},
- { ignore: [404] }
+ { ignore: [404], meta: true }
);
// @ts-expect-error status doesn't exist on response
diff --git a/packages/kbn-securitysolution-es-utils/src/delete_policy/index.ts b/packages/kbn-securitysolution-es-utils/src/delete_policy/index.ts
index 60a15f6d4625d..af6dca4619004 100644
--- a/packages/kbn-securitysolution-es-utils/src/delete_policy/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/delete_policy/index.ts
@@ -10,10 +10,7 @@ import type { ElasticsearchClient } from '../elasticsearch_client';
export const deletePolicy = async (
esClient: ElasticsearchClient,
- policy: string
+ name: string
): Promise => {
- return (
- // @ts-expect-error policy_id is required by mistake. fixed in the v8.0
- (await esClient.ilm.deleteLifecycle({ policy })).body
- );
+ return (await esClient.ilm.deleteLifecycle({ name }, { meta: true })).body;
};
diff --git a/packages/kbn-securitysolution-es-utils/src/delete_template/index.ts b/packages/kbn-securitysolution-es-utils/src/delete_template/index.ts
index 86565a0c43b3a..92eeadfff860a 100644
--- a/packages/kbn-securitysolution-es-utils/src/delete_template/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/delete_template/index.ts
@@ -13,8 +13,11 @@ export const deleteTemplate = async (
name: string
): Promise => {
return (
- await esClient.indices.deleteTemplate({
- name,
- })
+ await esClient.indices.deleteTemplate(
+ {
+ name,
+ },
+ { meta: true }
+ )
).body;
};
diff --git a/packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts b/packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts
index a1fb3ff3ecf31..95fa040142c15 100644
--- a/packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/elasticsearch_client/index.ts
@@ -9,7 +9,7 @@
// Copied from src/core/server/elasticsearch/client/types.ts
// as these types aren't part of any package yet. Once they are, remove this completely
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
/**
* Client used to query the elasticsearch cluster.
@@ -18,5 +18,5 @@ import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
*/
export type ElasticsearchClient = Omit<
KibanaClient,
- 'connectionPool' | 'transport' | 'serializer' | 'extend' | 'child' | 'close'
+ 'connectionPool' | 'transport' | 'serializer' | 'extend' | 'child' | 'close' | 'diagnostic'
>;
diff --git a/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts b/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts
index ba00c1144edfc..9a0d0fed1b63e 100644
--- a/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/get_index_aliases/index.ts
@@ -39,9 +39,12 @@ export const getIndexAliases = async ({
esClient: ElasticsearchClient;
alias: string;
}): Promise => {
- const response = await esClient.indices.getAlias({
- name: alias,
- });
+ const response = await esClient.indices.getAlias(
+ {
+ name: alias,
+ },
+ { meta: true }
+ );
return Object.keys(response.body).map((index) => ({
alias,
diff --git a/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts b/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts
index b1dcd4fd0ad9b..59cae505bfded 100644
--- a/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/get_index_count/index.ts
@@ -23,9 +23,12 @@ export const getIndexCount = async ({
esClient: ElasticsearchClient;
index: string;
}): Promise => {
- const response = await esClient.count<{ count: number }>({
- index,
- });
+ const response = await esClient.count<{ count: number }>(
+ {
+ index,
+ },
+ { meta: true }
+ );
return response.body.count;
};
diff --git a/packages/kbn-securitysolution-es-utils/src/get_index_exists/index.ts b/packages/kbn-securitysolution-es-utils/src/get_index_exists/index.ts
index 9208773048474..50ba298d10259 100644
--- a/packages/kbn-securitysolution-es-utils/src/get_index_exists/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/get_index_exists/index.ts
@@ -13,14 +13,17 @@ export const getIndexExists = async (
index: string
): Promise => {
try {
- const { body: response } = await esClient.search({
- index,
- size: 0,
- allow_no_indices: true,
- body: {
- terminate_after: 1,
+ const { body: response } = await esClient.search(
+ {
+ index,
+ size: 0,
+ allow_no_indices: true,
+ body: {
+ terminate_after: 1,
+ },
},
- });
+ { meta: true }
+ );
return response._shards.total > 0;
} catch (err) {
if (err.body != null && err.body.status === 404) {
diff --git a/packages/kbn-securitysolution-es-utils/src/get_policy_exists/index.ts b/packages/kbn-securitysolution-es-utils/src/get_policy_exists/index.ts
index 8172cfb2abaa0..a62ea6e224e7d 100644
--- a/packages/kbn-securitysolution-es-utils/src/get_policy_exists/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/get_policy_exists/index.ts
@@ -9,11 +9,11 @@ import type { ElasticsearchClient } from '../elasticsearch_client';
export const getPolicyExists = async (
esClient: ElasticsearchClient,
- policy: string
+ name: string
): Promise => {
try {
await esClient.ilm.getLifecycle({
- policy,
+ name,
});
// Return true that there exists a policy which is not 404 or some error
// Since there is not a policy exists API, this is how we create one by calling
diff --git a/packages/kbn-securitysolution-es-utils/src/get_template_exists/index.ts b/packages/kbn-securitysolution-es-utils/src/get_template_exists/index.ts
index 72a3a93654482..a310d1d6e9e0e 100644
--- a/packages/kbn-securitysolution-es-utils/src/get_template_exists/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/get_template_exists/index.ts
@@ -13,8 +13,11 @@ export const getTemplateExists = async (
template: string
): Promise => {
return (
- await esClient.indices.existsTemplate({
- name: template,
- })
+ await esClient.indices.existsTemplate(
+ {
+ name: template,
+ },
+ { meta: true }
+ )
).body;
};
diff --git a/packages/kbn-securitysolution-es-utils/src/read_index/index.ts b/packages/kbn-securitysolution-es-utils/src/read_index/index.ts
index 206a4208b2ecc..a1112f8fceb64 100644
--- a/packages/kbn-securitysolution-es-utils/src/read_index/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/read_index/index.ts
@@ -9,7 +9,10 @@
import type { ElasticsearchClient } from '../elasticsearch_client';
export const readIndex = async (esClient: ElasticsearchClient, index: string): Promise => {
- return esClient.indices.get({
- index,
- });
+ return esClient.indices.get(
+ {
+ index,
+ },
+ { meta: true }
+ );
};
diff --git a/packages/kbn-securitysolution-es-utils/src/read_privileges/index.ts b/packages/kbn-securitysolution-es-utils/src/read_privileges/index.ts
index 772a6afa18c95..614eb55297980 100644
--- a/packages/kbn-securitysolution-es-utils/src/read_privileges/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/read_privileges/index.ts
@@ -13,60 +13,63 @@ export const readPrivileges = async (
index: string
): Promise => {
return (
- await esClient.security.hasPrivileges({
- body: {
- cluster: [
- 'all',
- 'create_snapshot',
- 'manage',
- 'manage_api_key',
- 'manage_ccr',
- 'manage_transform',
- 'manage_ilm',
- 'manage_index_templates',
- 'manage_ingest_pipelines',
- 'manage_ml',
- 'manage_own_api_key',
- 'manage_pipeline',
- 'manage_rollup',
- 'manage_saml',
- 'manage_security',
- 'manage_token',
- 'manage_watcher',
- 'monitor',
- 'monitor_transform',
- 'monitor_ml',
- 'monitor_rollup',
- 'monitor_watcher',
- 'read_ccr',
- 'read_ilm',
- 'transport_client',
- ],
- index: [
- {
- names: [index],
- privileges: [
- 'all',
- 'create',
- 'create_doc',
- 'create_index',
- 'delete',
- 'delete_index',
- 'index',
- 'manage',
- 'maintenance',
- 'manage_follow_index',
- 'manage_ilm',
- 'manage_leader_index',
- 'monitor',
- 'read',
- 'read_cross_cluster',
- 'view_index_metadata',
- 'write',
- ],
- },
- ],
+ await esClient.security.hasPrivileges(
+ {
+ body: {
+ cluster: [
+ 'all',
+ 'create_snapshot',
+ 'manage',
+ 'manage_api_key',
+ 'manage_ccr',
+ 'manage_transform',
+ 'manage_ilm',
+ 'manage_index_templates',
+ 'manage_ingest_pipelines',
+ 'manage_ml',
+ 'manage_own_api_key',
+ 'manage_pipeline',
+ 'manage_rollup',
+ 'manage_saml',
+ 'manage_security',
+ 'manage_token',
+ 'manage_watcher',
+ 'monitor',
+ 'monitor_transform',
+ 'monitor_ml',
+ 'monitor_rollup',
+ 'monitor_watcher',
+ 'read_ccr',
+ 'read_ilm',
+ 'transport_client',
+ ],
+ index: [
+ {
+ names: [index],
+ privileges: [
+ 'all',
+ 'create',
+ 'create_doc',
+ 'create_index',
+ 'delete',
+ 'delete_index',
+ 'index',
+ 'manage',
+ 'maintenance',
+ 'manage_follow_index',
+ 'manage_ilm',
+ 'manage_leader_index',
+ 'monitor',
+ 'read',
+ 'read_cross_cluster',
+ 'view_index_metadata',
+ 'write',
+ ],
+ },
+ ],
+ },
},
- })
+ { meta: true }
+ )
).body;
};
diff --git a/packages/kbn-securitysolution-es-utils/src/set_policy/index.ts b/packages/kbn-securitysolution-es-utils/src/set_policy/index.ts
index f6c2dcf7c3c3a..091155e491e05 100644
--- a/packages/kbn-securitysolution-es-utils/src/set_policy/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/set_policy/index.ts
@@ -9,13 +9,16 @@ import type { ElasticsearchClient } from '../elasticsearch_client';
export const setPolicy = async (
esClient: ElasticsearchClient,
- policy: string,
+ name: string,
body: Record
): Promise => {
return (
- await esClient.ilm.putLifecycle({
- policy,
- body,
- })
+ await esClient.ilm.putLifecycle(
+ {
+ name,
+ body,
+ },
+ { meta: true }
+ )
).body;
};
diff --git a/packages/kbn-securitysolution-es-utils/src/set_template/index.ts b/packages/kbn-securitysolution-es-utils/src/set_template/index.ts
index 20f6fd5719d51..7e1d6a4fb0a1e 100644
--- a/packages/kbn-securitysolution-es-utils/src/set_template/index.ts
+++ b/packages/kbn-securitysolution-es-utils/src/set_template/index.ts
@@ -14,9 +14,12 @@ export const setTemplate = async (
body: Record
): Promise => {
return (
- await esClient.indices.putTemplate({
- name,
- body,
- })
+ await esClient.indices.putTemplate(
+ {
+ name,
+ body,
+ },
+ { meta: true }
+ )
).body;
};
diff --git a/packages/kbn-securitysolution-list-utils/src/build_exception_filter/index.ts b/packages/kbn-securitysolution-list-utils/src/build_exception_filter/index.ts
index 2aa4cf64073ab..dc00314ece266 100644
--- a/packages/kbn-securitysolution-list-utils/src/build_exception_filter/index.ts
+++ b/packages/kbn-securitysolution-list-utils/src/build_exception_filter/index.ts
@@ -23,7 +23,7 @@ import {
} from '@kbn/securitysolution-io-ts-list-types';
import { Filter } from '@kbn/es-query';
-import { QueryDslBoolQuery, QueryDslNestedQuery } from '@elastic/elasticsearch/api/types';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { hasLargeValueList } from '../has_large_value_list';
type NonListEntry = EntryMatch | EntryMatchAny | EntryNested | EntryExists;
@@ -40,11 +40,11 @@ export type ExceptionItemSansLargeValueLists =
| CreateExceptionListItemNonLargeList;
export interface BooleanFilter {
- bool: QueryDslBoolQuery;
+ bool: estypes.QueryDslBoolQuery;
}
export interface NestedFilter {
- nested: QueryDslNestedQuery;
+ nested: estypes.QueryDslNestedQuery;
}
export const chunkExceptions = (
diff --git a/packages/kbn-test/src/es/client_to_kibana_client.ts b/packages/kbn-test/src/es/client_to_kibana_client.ts
new file mode 100644
index 0000000000000..778ee0a7705b3
--- /dev/null
+++ b/packages/kbn-test/src/es/client_to_kibana_client.ts
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
+import type {
+ Client,
+ TransportRequestParams,
+ TransportRequestOptions,
+ TransportResult,
+} from '@elastic/elasticsearch';
+import { Transport } from '@elastic/elasticsearch';
+
+// remove once https://github.com/elastic/kibana/issues/116095 is addressed
+class KibanaTransport extends Transport {
+ request(params: TransportRequestParams, options?: TransportRequestOptions) {
+ const opts: TransportRequestOptions = options || {};
+ // Enforce the client to return TransportResult.
+ // It's required for bwc with responses in 7.x version.
+ if (opts?.meta === undefined) {
+ opts.meta = true;
+ }
+ return super.request(params, opts) as Promise>;
+ }
+}
+
+export function convertToKibanaClient(esClient: Client): KibanaClient {
+ // @ts-expect-error @elastic/elasticsearch fix discrepancy between clients
+ return esClient.child({
+ Transport: KibanaTransport,
+ });
+}
diff --git a/packages/kbn-test/src/es/index.ts b/packages/kbn-test/src/es/index.ts
index ccfec67dae848..0c19a6b903742 100644
--- a/packages/kbn-test/src/es/index.ts
+++ b/packages/kbn-test/src/es/index.ts
@@ -9,3 +9,4 @@
export { createTestEsCluster } from './test_es_cluster';
export type { CreateTestEsClusterOptions, EsTestCluster, ICluster } from './test_es_cluster';
export { esTestConfig } from './es_test_config';
+export { convertToKibanaClient } from './client_to_kibana_client';
diff --git a/packages/kbn-test/src/es/test_es_cluster.ts b/packages/kbn-test/src/es/test_es_cluster.ts
index 0d31ffdb99cc2..575fc965962eb 100644
--- a/packages/kbn-test/src/es/test_es_cluster.ts
+++ b/packages/kbn-test/src/es/test_es_cluster.ts
@@ -11,11 +11,12 @@ import { format } from 'url';
import del from 'del';
// @ts-expect-error in js
import { Cluster } from '@kbn/es';
-import { Client } from '@elastic/elasticsearch';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import { Client, HttpConnection } from '@elastic/elasticsearch';
+import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import type { ToolingLog } from '@kbn/dev-utils';
import { CI_PARALLEL_PROCESS_PREFIX } from '../ci_parallel_process_prefix';
import { esTestConfig } from './es_test_config';
+import { convertToKibanaClient } from './client_to_kibana_client';
import { KIBANA_ROOT } from '../';
@@ -51,7 +52,8 @@ export interface ICluster {
start: () => Promise;
stop: () => Promise;
cleanup: () => Promise;
- getClient: () => KibanaClient;
+ getClient: () => Client;
+ getKibanaEsClient: () => KibanaClient;
getHostUrls: () => string[];
}
@@ -280,12 +282,20 @@ export function createTestEsCluster<
/**
* Returns an ES Client to the configured cluster
*/
- getClient(): KibanaClient {
+ getClient(): Client {
return new Client({
node: this.getHostUrls()[0],
+ Connection: HttpConnection,
});
}
+ /**
+ * Returns an ES Client to the configured cluster
+ */
+ getKibanaEsClient(): KibanaClient {
+ return convertToKibanaClient(this.getClient());
+ }
+
getUrl() {
if (this.nodes.length > 1) {
throw new Error(
diff --git a/packages/kbn-test/src/failed_tests_reporter/report_failures_to_es.ts b/packages/kbn-test/src/failed_tests_reporter/report_failures_to_es.ts
index 754ce2567cb80..a96ca5822775d 100644
--- a/packages/kbn-test/src/failed_tests_reporter/report_failures_to_es.ts
+++ b/packages/kbn-test/src/failed_tests_reporter/report_failures_to_es.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { Client } from '@elastic/elasticsearch';
+import { Client, HttpConnection } from '@elastic/elasticsearch';
import { createFailError, ToolingLog } from '@kbn/dev-utils';
import { TestFailure } from './get_failures';
@@ -34,6 +34,7 @@ export async function reportFailuresToEs(log: ToolingLog, failures: TestFailure[
username: process.env.TEST_FAILURES_ES_USERNAME,
password: process.env.TEST_FAILURES_ES_PASSWORD,
},
+ Connection: HttpConnection,
});
const body = failures.flatMap((failure) => [
@@ -59,7 +60,7 @@ export async function reportFailuresToEs(log: ToolingLog, failures: TestFailure[
},
]);
- const resp = await client.bulk({ body });
+ const resp = await client.bulk({ body }, { meta: true });
if (resp?.body?.errors) {
log.error(JSON.stringify(resp.body.items, null, 2));
}
diff --git a/packages/kbn-test/src/index.ts b/packages/kbn-test/src/index.ts
index dea2ec9d1035e..0ef9fbfed07a0 100644
--- a/packages/kbn-test/src/index.ts
+++ b/packages/kbn-test/src/index.ts
@@ -31,6 +31,7 @@ export {
CreateTestEsClusterOptions,
EsTestCluster,
ICluster,
+ convertToKibanaClient,
} from './es';
export { kbnTestConfig, kibanaServerTestUser, kibanaTestUser, adminTestUser } from './kbn';
diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md
index 1992b2d9686ac..cf0b526aa9fd9 100644
--- a/src/core/public/public.api.md
+++ b/src/core/public/public.api.md
@@ -5,12 +5,11 @@
```ts
import { Action } from 'history';
-import { ApiResponse } from '@elastic/elasticsearch/lib/Transport';
import Boom from '@hapi/boom';
import { ConfigPath } from '@kbn/config';
import { DetailedPeerCertificate } from 'tls';
import { EnvironmentMode } from '@kbn/config';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { EuiBreadcrumb } from '@elastic/eui';
import { EuiButtonEmptyProps } from '@elastic/eui';
import { EuiConfirmModalProps } from '@elastic/eui';
@@ -20,7 +19,7 @@ import { History } from 'history';
import { Href } from 'history';
import { IconType } from '@elastic/eui';
import { IncomingHttpHeaders } from 'http';
-import { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import { Location } from 'history';
import { LocationDescriptorObject } from 'history';
import { Logger } from '@kbn/logging';
@@ -38,9 +37,9 @@ import { RecursiveReadonly } from '@kbn/utility-types';
import { Request } from '@hapi/hapi';
import * as Rx from 'rxjs';
import { SchemaTypeError } from '@kbn/config-schema';
-import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport';
-import { TransportRequestParams } from '@elastic/elasticsearch/lib/Transport';
-import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport';
+import { TransportRequestOptions } from '@elastic/elasticsearch';
+import { TransportRequestParams } from '@elastic/elasticsearch';
+import { TransportResult } from '@elastic/elasticsearch';
import { Type } from '@kbn/config-schema';
import { TypeOf } from '@kbn/config-schema';
import { UiCounterMetricType } from '@kbn/analytics';
diff --git a/src/core/server/core_usage_data/core_usage_data_service.ts b/src/core/server/core_usage_data/core_usage_data_service.ts
index 22dafc7e44e06..2e76bc08658a2 100644
--- a/src/core/server/core_usage_data/core_usage_data_service.ts
+++ b/src/core/server/core_usage_data/core_usage_data_service.ts
@@ -17,7 +17,7 @@ import {
AggregationsFiltersAggregate,
AggregationsFiltersBucketItem,
SearchTotalHits,
-} from '@elastic/elasticsearch/api/types';
+} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { CoreContext } from '../core_context';
import { ElasticsearchConfigType } from '../elasticsearch/elasticsearch_config';
import { HttpConfigType, InternalHttpServiceSetup } from '../http';
diff --git a/src/core/server/elasticsearch/client/client_config.test.ts b/src/core/server/elasticsearch/client/client_config.test.ts
index af8e2d64cb6a2..8158b7d116c4b 100644
--- a/src/core/server/elasticsearch/client/client_config.test.ts
+++ b/src/core/server/elasticsearch/client/client_config.test.ts
@@ -328,10 +328,10 @@ describe('parseClientOptions', () => {
});
});
- describe('ssl config', () => {
- it('does not generate ssl option is ssl config is not set', () => {
- expect(parseClientOptions(createConfig({}), false).ssl).toBeUndefined();
- expect(parseClientOptions(createConfig({}), true).ssl).toBeUndefined();
+ describe('tls config', () => {
+ it('does not generate tls option is ssl config is not set', () => {
+ expect(parseClientOptions(createConfig({}), false).tls).toBeUndefined();
+ expect(parseClientOptions(createConfig({}), true).tls).toBeUndefined();
});
it('handles the `certificateAuthorities` option', () => {
@@ -341,7 +341,7 @@ describe('parseClientOptions', () => {
ssl: { verificationMode: 'full', certificateAuthorities: ['content-of-ca-path'] },
}),
false
- ).ssl!.ca
+ ).tls!.ca
).toEqual(['content-of-ca-path']);
expect(
parseClientOptions(
@@ -349,7 +349,7 @@ describe('parseClientOptions', () => {
ssl: { verificationMode: 'full', certificateAuthorities: ['content-of-ca-path'] },
}),
true
- ).ssl!.ca
+ ).tls!.ca
).toEqual(['content-of-ca-path']);
});
@@ -363,7 +363,7 @@ describe('parseClientOptions', () => {
},
}),
false
- ).ssl
+ ).tls
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
@@ -380,7 +380,7 @@ describe('parseClientOptions', () => {
},
}),
false
- ).ssl
+ ).tls
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
@@ -398,7 +398,7 @@ describe('parseClientOptions', () => {
},
}),
false
- ).ssl
+ ).tls
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
@@ -416,7 +416,7 @@ describe('parseClientOptions', () => {
},
}),
false
- ).ssl
+ ).tls
).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: unknown"`);
});
it('throws for undefined values', () => {
@@ -429,7 +429,7 @@ describe('parseClientOptions', () => {
},
}),
false
- ).ssl
+ ).tls
).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: undefined"`);
});
});
@@ -446,7 +446,7 @@ describe('parseClientOptions', () => {
},
}),
false
- ).ssl
+ ).tls
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
@@ -466,7 +466,7 @@ describe('parseClientOptions', () => {
},
}),
false
- ).ssl
+ ).tls
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
@@ -487,7 +487,7 @@ describe('parseClientOptions', () => {
},
}),
false
- ).ssl
+ ).tls
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
@@ -511,7 +511,7 @@ describe('parseClientOptions', () => {
},
}),
true
- ).ssl
+ ).tls
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
@@ -531,7 +531,7 @@ describe('parseClientOptions', () => {
},
}),
true
- ).ssl
+ ).tls
).toMatchInlineSnapshot(`
Object {
"ca": undefined,
diff --git a/src/core/server/elasticsearch/client/client_config.ts b/src/core/server/elasticsearch/client/client_config.ts
index 24c48012346da..1cb81fd0a417a 100644
--- a/src/core/server/elasticsearch/client/client_config.ts
+++ b/src/core/server/elasticsearch/client/client_config.ts
@@ -9,7 +9,7 @@
import { ConnectionOptions as TlsConnectionOptions } from 'tls';
import { URL } from 'url';
import { Duration } from 'moment';
-import { ClientOptions, NodeOptions } from '@elastic/elasticsearch';
+import type { ClientOptions } from '@elastic/elasticsearch/lib/client';
import { ElasticsearchConfig } from '../elasticsearch_config';
import { DEFAULT_HEADERS } from '../default_headers';
@@ -93,7 +93,7 @@ export function parseClientOptions(
clientOptions.nodes = config.hosts.map((host) => convertHost(host));
if (config.ssl) {
- clientOptions.ssl = generateSslConfig(
+ clientOptions.tls = generateSslConfig(
config.ssl,
scoped && !config.ssl.alwaysPresentCertificate
);
@@ -141,7 +141,7 @@ const generateSslConfig = (
return ssl;
};
-const convertHost = (host: string): NodeOptions => {
+const convertHost = (host: string): { url: URL } => {
const url = new URL(host);
const isHTTPS = url.protocol === 'https:';
url.port = url.port || (isHTTPS ? '443' : '80');
diff --git a/src/core/server/elasticsearch/client/cluster_client.ts b/src/core/server/elasticsearch/client/cluster_client.ts
index f81b651843013..1f3118c77aa0f 100644
--- a/src/core/server/elasticsearch/client/cluster_client.ts
+++ b/src/core/server/elasticsearch/client/cluster_client.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { Client } from '@elastic/elasticsearch';
+import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import { Logger } from '../../logging';
import { GetAuthHeaders, Headers, isKibanaRequest, isRealRequest } from '../../http';
import { ensureRawRequest, filterHeaders } from '../../http/router';
@@ -52,8 +52,8 @@ export interface ICustomClusterClient extends IClusterClient {
/** @internal **/
export class ClusterClient implements ICustomClusterClient {
- public readonly asInternalUser: Client;
- private readonly rootScopedClient: Client;
+ public readonly asInternalUser: KibanaClient;
+ private readonly rootScopedClient: KibanaClient;
private readonly allowListHeaders: string[];
private isClosed = false;
diff --git a/src/core/server/elasticsearch/client/configure_client.test.ts b/src/core/server/elasticsearch/client/configure_client.test.ts
index 35fcb5819d015..7988e81045d17 100644
--- a/src/core/server/elasticsearch/client/configure_client.test.ts
+++ b/src/core/server/elasticsearch/client/configure_client.test.ts
@@ -9,13 +9,13 @@
import { Buffer } from 'buffer';
import { Readable } from 'stream';
-import { RequestEvent, errors } from '@elastic/elasticsearch';
-import type { Client } from '@elastic/elasticsearch';
+import { errors } from '@elastic/elasticsearch';
import type {
TransportRequestOptions,
TransportRequestParams,
+ DiagnosticResult,
RequestBody,
-} from '@elastic/elasticsearch/lib/Transport';
+} from '@elastic/elasticsearch';
import { parseClientOptionsMock, ClientMock } from './configure_client.test.mocks';
import { loggingSystemMock } from '../../logging/logging_system.mock';
@@ -36,7 +36,7 @@ const createFakeClient = () => {
const client = new actualEs.Client({
nodes: ['http://localhost'], // Enforcing `nodes` because it's mandatory
});
- jest.spyOn(client, 'on');
+ jest.spyOn(client.diagnostic, 'on');
return client;
};
@@ -54,7 +54,7 @@ const createApiResponse = ({
warnings?: string[];
params?: TransportRequestParams;
requestOptions?: TransportRequestOptions;
-}): RequestEvent => {
+}): DiagnosticResult => {
return {
body,
statusCode,
@@ -70,14 +70,6 @@ const createApiResponse = ({
};
};
-function getProductCheckValue(client: Client) {
- const tSymbol = Object.getOwnPropertySymbols(client.transport || client).filter(
- (symbol) => symbol.description === 'product check'
- )[0];
- // @ts-expect-error `tSymbol` is missing in the index signature of Transport
- return (client.transport || client)[tSymbol];
-}
-
describe('configureClient', () => {
let logger: ReturnType;
let config: ElasticsearchClientConfig;
@@ -124,26 +116,8 @@ describe('configureClient', () => {
it('listens to client on `response` events', () => {
const client = configureClient(config, { logger, type: 'test', scoped: false });
- expect(client.on).toHaveBeenCalledTimes(1);
- expect(client.on).toHaveBeenCalledWith('response', expect.any(Function));
- });
-
- describe('Product check', () => {
- it('should not skip the product check for the unscoped client', () => {
- const client = configureClient(config, { logger, type: 'test', scoped: false });
- expect(getProductCheckValue(client)).toBe(0);
- });
-
- it('should skip the product check for the scoped client', () => {
- const client = configureClient(config, { logger, type: 'test', scoped: true });
- expect(getProductCheckValue(client)).toBe(2);
- });
-
- it('should skip the product check for the children of the scoped client', () => {
- const client = configureClient(config, { logger, type: 'test', scoped: true });
- const asScoped = client.child({ headers: { 'x-custom-header': 'Custom value' } });
- expect(getProductCheckValue(asScoped)).toBe(2);
- });
+ expect(client.diagnostic.on).toHaveBeenCalledTimes(1);
+ expect(client.diagnostic.on).toHaveBeenCalledWith('response', expect.any(Function));
});
describe('Client logging', () => {
@@ -176,7 +150,7 @@ describe('configureClient', () => {
},
});
- client.emit('response', null, response);
+ client.diagnostic.emit('response', null, response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
Array [
@@ -201,7 +175,7 @@ describe('configureClient', () => {
})
);
- client.emit('response', null, response);
+ client.diagnostic.emit('response', null, response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
Array [
@@ -228,7 +202,7 @@ describe('configureClient', () => {
)
);
- client.emit('response', null, response);
+ client.diagnostic.emit('response', null, response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
Array [
@@ -255,7 +229,7 @@ describe('configureClient', () => {
)
);
- client.emit('response', null, response);
+ client.diagnostic.emit('response', null, response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
Array [
@@ -273,7 +247,7 @@ describe('configureClient', () => {
const response = createResponseWithBody();
- client.emit('response', null, response);
+ client.diagnostic.emit('response', null, response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
Array [
@@ -298,7 +272,7 @@ describe('configureClient', () => {
},
});
- client.emit('response', null, response);
+ client.diagnostic.emit('response', null, response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
@@ -333,7 +307,7 @@ describe('configureClient', () => {
},
},
});
- client.emit('response', new errors.ResponseError(response), response);
+ client.diagnostic.emit('response', new errors.ResponseError(response), response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
@@ -351,7 +325,7 @@ describe('configureClient', () => {
const client = configureClient(createFakeConfig(), { logger, type: 'test', scoped: false });
const response = createApiResponse({ body: {} });
- client.emit('response', new errors.TimeoutError('message', response), response);
+ client.diagnostic.emit('response', new errors.TimeoutError('message', response), response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
@@ -381,7 +355,7 @@ describe('configureClient', () => {
},
},
});
- client.emit('response', new errors.ResponseError(response), response);
+ client.diagnostic.emit('response', new errors.ResponseError(response), response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
@@ -397,7 +371,7 @@ describe('configureClient', () => {
it('logs default error info when the error response body is empty', () => {
const client = configureClient(createFakeConfig(), { logger, type: 'test', scoped: false });
- let response: RequestEvent = createApiResponse({
+ let response: DiagnosticResult = createApiResponse({
statusCode: 400,
headers: {},
params: {
@@ -408,7 +382,7 @@ describe('configureClient', () => {
error: {},
},
});
- client.emit('response', new errors.ResponseError(response), response);
+ client.diagnostic.emit('response', new errors.ResponseError(response), response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
@@ -431,7 +405,7 @@ describe('configureClient', () => {
},
body: undefined,
});
- client.emit('response', new errors.ResponseError(response), response);
+ client.diagnostic.emit('response', new errors.ResponseError(response), response);
expect(loggingSystemMock.collect(logger).debug).toMatchInlineSnapshot(`
Array [
@@ -461,7 +435,7 @@ describe('configureClient', () => {
error: {},
},
});
- client.emit('response', null, response);
+ client.diagnostic.emit('response', null, response);
expect(loggingSystemMock.collect(logger).debug[0][1]).toMatchInlineSnapshot(`
Object {
@@ -487,7 +461,7 @@ describe('configureClient', () => {
},
body: {} as any,
});
- client.emit('response', new errors.ResponseError(response), response);
+ client.diagnostic.emit('response', new errors.ResponseError(response), response);
expect(loggingSystemMock.collect(logger).debug[0][1]).toMatchInlineSnapshot(`
Object {
diff --git a/src/core/server/elasticsearch/client/configure_client.ts b/src/core/server/elasticsearch/client/configure_client.ts
index 93c404593af3f..fc8a06660cc5e 100644
--- a/src/core/server/elasticsearch/client/configure_client.ts
+++ b/src/core/server/elasticsearch/client/configure_client.ts
@@ -8,14 +8,19 @@
import { Buffer } from 'buffer';
import { stringify } from 'querystring';
-import { ApiError, Client, RequestEvent, errors, Transport } from '@elastic/elasticsearch';
+import { Client, errors, Transport, HttpConnection } from '@elastic/elasticsearch';
+import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import type {
- RequestBody,
TransportRequestParams,
TransportRequestOptions,
-} from '@elastic/elasticsearch/lib/Transport';
+ TransportResult,
+ DiagnosticResult,
+ RequestBody,
+} from '@elastic/elasticsearch';
+
import { Logger } from '../../logging';
import { parseClientOptions, ElasticsearchClientConfig } from './client_config';
+import type { ElasticsearchErrorDetails } from './types';
const noop = () => undefined;
@@ -32,30 +37,33 @@ export const configureClient = (
scoped?: boolean;
getExecutionContext?: () => string | undefined;
}
-): Client => {
+): KibanaClient => {
const clientOptions = parseClientOptions(config, scoped);
class KibanaTransport extends Transport {
request(params: TransportRequestParams, options?: TransportRequestOptions) {
- const opts = options || {};
+ const opts: TransportRequestOptions = options || {};
const opaqueId = getExecutionContext();
if (opaqueId && !opts.opaqueId) {
// rewrites headers['x-opaque-id'] if it presents
opts.opaqueId = opaqueId;
}
- return super.request(params, opts);
+ // Enforce the client to return TransportResult.
+ // It's required for bwc with responses in 7.x version.
+ if (opts.meta === undefined) {
+ opts.meta = true;
+ }
+ return super.request(params, opts) as Promise>;
}
}
- const client = new Client({ ...clientOptions, Transport: KibanaTransport });
+ const client = new Client({
+ ...clientOptions,
+ Transport: KibanaTransport,
+ Connection: HttpConnection,
+ });
addLogging(client, logger.get('query', type));
- // --------------------------------------------------------------------------------- //
- // Hack to disable the "Product check" only in the scoped clients while we //
- // come up with a better approach in https://github.com/elastic/kibana/issues/110675 //
- if (scoped) skipProductCheck(client);
- // --------------------------------------------------------------------------------- //
-
- return client;
+ return client as KibanaClient;
};
const convertQueryString = (qs: string | Record | undefined): string => {
@@ -76,9 +84,10 @@ function ensureString(body: RequestBody): string {
* Returns a debug message from an Elasticsearch error in the following format:
* [error type] error reason
*/
-export function getErrorMessage(error: ApiError): string {
+export function getErrorMessage(error: errors.ElasticsearchClientError): string {
if (error instanceof errors.ResponseError) {
- return `[${error.meta.body?.error?.type}]: ${error.meta.body?.error?.reason ?? error.message}`;
+ const errorBody = error.meta.body as ElasticsearchErrorDetails;
+ return `[${errorBody?.error?.type}]: ${errorBody?.error?.reason ?? error.message}`;
}
return `[${error.name}]: ${error.message}`;
}
@@ -92,7 +101,7 @@ export function getErrorMessage(error: ApiError): string {
*
* so it could be copy-pasted into the Dev console
*/
-function getResponseMessage(event: RequestEvent): string {
+function getResponseMessage(event: DiagnosticResult): string {
const errorMeta = getRequestDebugMeta(event);
const body = errorMeta.body ? `\n${errorMeta.body}` : '';
return `${errorMeta.statusCode}\n${errorMeta.method} ${errorMeta.url}${body}`;
@@ -102,7 +111,7 @@ function getResponseMessage(event: RequestEvent): string {
* Returns stringified debug information from an Elasticsearch request event
* useful for logging in case of an unexpected failure.
*/
-export function getRequestDebugMeta(event: RequestEvent): {
+export function getRequestDebugMeta(event: DiagnosticResult): {
url: string;
body: string;
statusCode: number | null;
@@ -115,12 +124,12 @@ export function getRequestDebugMeta(event: RequestEvent): {
url: `${params.path}${querystring ? `?${querystring}` : ''}`,
body: params.body ? `${ensureString(params.body)}` : '',
method: params.method,
- statusCode: event.statusCode,
+ statusCode: event.statusCode!,
};
}
const addLogging = (client: Client, logger: Logger) => {
- client.on('response', (error, event) => {
+ client.diagnostic.on('response', (error, event) => {
if (event) {
const opaqueId = event.meta.request.options.opaqueId;
const meta = opaqueId
@@ -140,21 +149,3 @@ const addLogging = (client: Client, logger: Logger) => {
}
});
};
-
-/**
- * Hack to skip the Product Check performed by the Elasticsearch-js client.
- * We noticed that the scoped clients are always performing this check because
- * of the way we initialize the clients. We'll discuss changing this in the issue
- * https://github.com/elastic/kibana/issues/110675. In the meanwhile, let's skip
- * it for the scoped clients.
- *
- * The hack is copied from the test/utils in the elasticsearch-js repo
- * (https://github.com/elastic/elasticsearch-js/blob/master/test/utils/index.js#L45-L56)
- */
-function skipProductCheck(client: Client) {
- const tSymbol = Object.getOwnPropertySymbols(client.transport || client).filter(
- (symbol) => symbol.description === 'product check'
- )[0];
- // @ts-expect-error `tSymbol` is missing in the index signature of Transport
- (client.transport || client)[tSymbol] = 2;
-}
diff --git a/src/core/server/elasticsearch/client/errors.test.ts b/src/core/server/elasticsearch/client/errors.test.ts
index a27a1fa794a97..59c4296d2bbb2 100644
--- a/src/core/server/elasticsearch/client/errors.test.ts
+++ b/src/core/server/elasticsearch/client/errors.test.ts
@@ -6,12 +6,8 @@
* Side Public License, v 1.
*/
-import {
- ResponseError,
- ConnectionError,
- ConfigurationError,
-} from '@elastic/elasticsearch/lib/errors';
-import { ApiResponse } from '@elastic/elasticsearch';
+import { errors } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
import { isResponseError, isUnauthorizedError } from './errors';
const createApiResponseError = ({
@@ -22,7 +18,7 @@ const createApiResponseError = ({
statusCode?: number;
headers?: Record;
body?: Record;
-} = {}): ApiResponse => {
+} = {}): TransportResult => {
return {
body,
statusCode,
@@ -34,38 +30,42 @@ const createApiResponseError = ({
describe('isResponseError', () => {
it('returns `true` when the input is a `ResponseError`', () => {
- expect(isResponseError(new ResponseError(createApiResponseError()))).toBe(true);
+ expect(isResponseError(new errors.ResponseError(createApiResponseError()))).toBe(true);
});
it('returns `false` when the input is not a `ResponseError`', () => {
expect(isResponseError(new Error('foo'))).toBe(false);
- expect(isResponseError(new ConnectionError('error', createApiResponseError()))).toBe(false);
- expect(isResponseError(new ConfigurationError('foo'))).toBe(false);
+ expect(isResponseError(new errors.ConnectionError('error', createApiResponseError()))).toBe(
+ false
+ );
+ expect(isResponseError(new errors.ConfigurationError('foo'))).toBe(false);
});
});
describe('isUnauthorizedError', () => {
it('returns true when the input is a `ResponseError` and statusCode === 401', () => {
expect(
- isUnauthorizedError(new ResponseError(createApiResponseError({ statusCode: 401 })))
+ isUnauthorizedError(new errors.ResponseError(createApiResponseError({ statusCode: 401 })))
).toBe(true);
});
it('returns false when the input is a `ResponseError` and statusCode !== 401', () => {
expect(
- isUnauthorizedError(new ResponseError(createApiResponseError({ statusCode: 200 })))
+ isUnauthorizedError(new errors.ResponseError(createApiResponseError({ statusCode: 200 })))
).toBe(false);
expect(
- isUnauthorizedError(new ResponseError(createApiResponseError({ statusCode: 403 })))
+ isUnauthorizedError(new errors.ResponseError(createApiResponseError({ statusCode: 403 })))
).toBe(false);
expect(
- isUnauthorizedError(new ResponseError(createApiResponseError({ statusCode: 500 })))
+ isUnauthorizedError(new errors.ResponseError(createApiResponseError({ statusCode: 500 })))
).toBe(false);
});
it('returns `false` when the input is not a `ResponseError`', () => {
expect(isUnauthorizedError(new Error('foo'))).toBe(false);
- expect(isUnauthorizedError(new ConnectionError('error', createApiResponseError()))).toBe(false);
- expect(isUnauthorizedError(new ConfigurationError('foo'))).toBe(false);
+ expect(isUnauthorizedError(new errors.ConnectionError('error', createApiResponseError()))).toBe(
+ false
+ );
+ expect(isUnauthorizedError(new errors.ConfigurationError('foo'))).toBe(false);
});
});
diff --git a/src/core/server/elasticsearch/client/errors.ts b/src/core/server/elasticsearch/client/errors.ts
index 356c2e370c471..21452af770ff4 100644
--- a/src/core/server/elasticsearch/client/errors.ts
+++ b/src/core/server/elasticsearch/client/errors.ts
@@ -6,14 +6,14 @@
* Side Public License, v 1.
*/
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
-export type UnauthorizedError = ResponseError & {
+export type UnauthorizedError = errors.ResponseError & {
statusCode: 401;
};
-export function isResponseError(error: unknown): error is ResponseError {
- return error instanceof ResponseError;
+export function isResponseError(error: unknown): error is errors.ResponseError {
+ return error instanceof errors.ResponseError;
}
export function isUnauthorizedError(error: unknown): error is UnauthorizedError {
diff --git a/src/core/server/elasticsearch/client/index.ts b/src/core/server/elasticsearch/client/index.ts
index 29f8b85695190..2cf5a0229a489 100644
--- a/src/core/server/elasticsearch/client/index.ts
+++ b/src/core/server/elasticsearch/client/index.ts
@@ -14,6 +14,7 @@ export type {
SearchResponse,
GetResponse,
DeleteDocumentResponse,
+ ElasticsearchErrorDetails,
} from './types';
export { ScopedClusterClient } from './scoped_cluster_client';
export type { IScopedClusterClient } from './scoped_cluster_client';
diff --git a/src/core/server/elasticsearch/client/mocks.test.ts b/src/core/server/elasticsearch/client/mocks.test.ts
index e3619e094c8cb..30b50e19f6c7e 100644
--- a/src/core/server/elasticsearch/client/mocks.test.ts
+++ b/src/core/server/elasticsearch/client/mocks.test.ts
@@ -39,9 +39,9 @@ describe('Mocked client', () => {
});
it('used EventEmitter functions should be mocked', () => {
- expectMocked(client.on);
- expectMocked(client.off);
- expectMocked(client.once);
+ expectMocked(client.diagnostic.on);
+ expectMocked(client.diagnostic.off);
+ expectMocked(client.diagnostic.once);
});
it('`child` should be mocked and return a mocked Client', () => {
diff --git a/src/core/server/elasticsearch/client/mocks.ts b/src/core/server/elasticsearch/client/mocks.ts
index 7c4cde1ae424d..16eaf6c49a735 100644
--- a/src/core/server/elasticsearch/client/mocks.ts
+++ b/src/core/server/elasticsearch/client/mocks.ts
@@ -6,36 +6,33 @@
* Side Public License, v 1.
*/
-import type { Client, ApiResponse } from '@elastic/elasticsearch';
-import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport';
+import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
+import type { TransportResult } from '@elastic/elasticsearch';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
+import type { PublicKeys } from '@kbn/utility-types';
import { ElasticsearchClient } from './types';
import { ICustomClusterClient } from './cluster_client';
-import { PRODUCT_RESPONSE_HEADER } from '../supported_server_response_check';
+
+const omittedProps = [
+ 'diagnostic',
+ 'name',
+ 'connectionPool',
+ 'transport',
+ 'serializer',
+ 'helpers',
+] as Array>;
+
+// the product header expected in every response from es
+const PRODUCT_RESPONSE_HEADER = 'x-elastic-product';
// use jest.requireActual() to prevent weird errors when people mock @elastic/elasticsearch
const { Client: UnmockedClient } = jest.requireActual('@elastic/elasticsearch');
-
-const createInternalClientMock = (
- res?: MockedTransportRequestPromise
-): DeeplyMockedKeys => {
+const createInternalClientMock = (res?: Promise): DeeplyMockedKeys => {
// we mimic 'reflection' on a concrete instance of the client to generate the mocked functions.
const client = new UnmockedClient({
- node: 'http://localhost',
+ node: 'http://127.0.0.1',
});
- const omittedProps = [
- '_events',
- '_eventsCount',
- '_maxListeners',
- 'constructor',
- 'name',
- 'serializer',
- 'connectionPool',
- 'transport',
- 'helpers',
- ];
-
const getAllPropertyDescriptors = (obj: Record) => {
const descriptors = Object.entries(Object.getOwnPropertyDescriptors(obj));
let prototype = Object.getPrototypeOf(obj);
@@ -77,21 +74,21 @@ const createInternalClientMock = (
};
// `on`, `off`, and `once` are properties without a setter.
- // We can't `client.on = jest.fn()` because the following error will be thrown:
+ // We can't `client.diagnostic.on = jest.fn()` because the following error will be thrown:
// TypeError: Cannot set property on of # which has only a getter
- mockGetter(client, 'on');
- mockGetter(client, 'off');
- mockGetter(client, 'once');
+ mockGetter(client.diagnostic, 'on');
+ mockGetter(client.diagnostic, 'off');
+ mockGetter(client.diagnostic, 'once');
client.transport = {
request: jest.fn(),
};
- return client as DeeplyMockedKeys;
+ return client as DeeplyMockedKeys;
};
export type ElasticsearchClientMock = DeeplyMockedKeys;
-const createClientMock = (res?: MockedTransportRequestPromise): ElasticsearchClientMock =>
+const createClientMock = (res?: Promise): ElasticsearchClientMock =>
createInternalClientMock(res) as unknown as ElasticsearchClientMock;
export interface ScopedClusterClientMock {
@@ -139,31 +136,23 @@ const createCustomClusterClientMock = () => {
return mock;
};
-export type MockedTransportRequestPromise = TransportRequestPromise & {
- abort: jest.MockedFunction<() => undefined>;
-};
-
const createSuccessTransportRequestPromise = (
body: T,
{ statusCode = 200 }: { statusCode?: number } = {},
headers: Record = { [PRODUCT_RESPONSE_HEADER]: 'Elasticsearch' }
-): MockedTransportRequestPromise> => {
+): Promise> => {
const response = createApiResponse({ body, statusCode, headers });
- const promise = Promise.resolve(response);
- (promise as MockedTransportRequestPromise>).abort = jest.fn();
- return promise as MockedTransportRequestPromise>;
+ return Promise.resolve(response) as Promise>;
};
-const createErrorTransportRequestPromise = (err: any): MockedTransportRequestPromise => {
- const promise = Promise.reject(err);
- (promise as MockedTransportRequestPromise).abort = jest.fn();
- return promise as MockedTransportRequestPromise;
+const createErrorTransportRequestPromise = (err: any): Promise> => {
+ return Promise.reject(err);
};
function createApiResponse>(
- opts: Partial> = {}
-): ApiResponse {
+ opts: Partial> = {}
+): TransportResult {
return {
body: {} as any,
statusCode: 200,
diff --git a/src/core/server/elasticsearch/client/types.ts b/src/core/server/elasticsearch/client/types.ts
index f5a6fa1f0b1fd..e168a4a4a9c21 100644
--- a/src/core/server/elasticsearch/client/types.ts
+++ b/src/core/server/elasticsearch/client/types.ts
@@ -6,13 +6,12 @@
* Side Public License, v 1.
*/
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import type {
- ApiResponse,
+ TransportResult,
TransportRequestOptions,
TransportRequestParams,
- TransportRequestPromise,
-} from '@elastic/elasticsearch/lib/Transport';
+} from '@elastic/elasticsearch';
/**
* Client used to query the elasticsearch cluster.
@@ -21,13 +20,13 @@ import type {
*/
export type ElasticsearchClient = Omit<
KibanaClient,
- 'connectionPool' | 'transport' | 'serializer' | 'extend' | 'child' | 'close'
+ 'connectionPool' | 'transport' | 'serializer' | 'extend' | 'child' | 'close' | 'diagnostic'
> & {
transport: {
- request(
+ request(
params: TransportRequestParams,
options?: TransportRequestOptions
- ): TransportRequestPromise;
+ ): Promise>;
};
};
@@ -133,3 +132,10 @@ export interface DeleteDocumentResponse {
type: string;
};
}
+
+/**
+ * @public
+ */
+export interface ElasticsearchErrorDetails {
+ error?: { type: string; reason?: string };
+}
diff --git a/src/core/server/elasticsearch/index.ts b/src/core/server/elasticsearch/index.ts
index 7f0620a03e5f4..cf7d8a0ce0de2 100644
--- a/src/core/server/elasticsearch/index.ts
+++ b/src/core/server/elasticsearch/index.ts
@@ -35,10 +35,6 @@ export type {
ShardsResponse,
GetResponse,
DeleteDocumentResponse,
+ ElasticsearchErrorDetails,
} from './client';
export { getRequestDebugMeta, getErrorMessage } from './client';
-export {
- isSupportedEsServer,
- isNotFoundFromUnsupportedServer,
- PRODUCT_RESPONSE_HEADER,
-} from './supported_server_response_check';
diff --git a/src/core/server/elasticsearch/integration_tests/client.test.ts b/src/core/server/elasticsearch/integration_tests/client.test.ts
index f3c9cf27d3b29..05100564dac03 100644
--- a/src/core/server/elasticsearch/integration_tests/client.test.ts
+++ b/src/core/server/elasticsearch/integration_tests/client.test.ts
@@ -52,17 +52,6 @@ describe('elasticsearch clients', () => {
);
expect(resp2.headers).not.toHaveProperty('warning');
});
-
- it('returns deprecation warning when x-elastic-product-orign header is not set', async () => {
- const resp =
- await kibanaServer.coreStart.elasticsearch.client.asInternalUser.indices.getSettings(
- { index: '.kibana' },
- { headers: { 'x-elastic-product-origin': null } }
- );
-
- expect(resp.headers).toHaveProperty('warning');
- expect(resp.headers!.warning).toMatch('system indices');
- });
});
function createFakeElasticsearchServer() {
diff --git a/src/core/server/elasticsearch/is_scripting_enabled.test.ts b/src/core/server/elasticsearch/is_scripting_enabled.test.ts
index 6dfb4b13edb9f..dd84c29818556 100644
--- a/src/core/server/elasticsearch/is_scripting_enabled.test.ts
+++ b/src/core/server/elasticsearch/is_scripting_enabled.test.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { elasticsearchServiceMock } from './elasticsearch_service.mock';
import { isInlineScriptingEnabled } from './is_scripting_enabled';
diff --git a/src/core/server/elasticsearch/supported_server_response_check.test.ts b/src/core/server/elasticsearch/supported_server_response_check.test.ts
deleted file mode 100644
index 589e947142fc3..0000000000000
--- a/src/core/server/elasticsearch/supported_server_response_check.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-
-import { isNotFoundFromUnsupportedServer } from './supported_server_response_check';
-
-describe('#isNotFoundFromUnsupportedServer', () => {
- it('returns true with not found response from unsupported server', () => {
- const rawResponse = {
- statusCode: 404,
- headers: {},
- };
-
- const result = isNotFoundFromUnsupportedServer(rawResponse);
- expect(result).toBe(true);
- });
-
- it('returns false with not found response from supported server', async () => {
- const rawResponse = {
- statusCode: 404,
- headers: { 'x-elastic-product': 'Elasticsearch' },
- };
-
- const result = isNotFoundFromUnsupportedServer(rawResponse);
- expect(result).toBe(false);
- });
-
- it('returns false when not a 404', async () => {
- const rawResponse = {
- statusCode: 200,
- headers: { 'x-elastic-product': 'Elasticsearch' },
- };
-
- const result = isNotFoundFromUnsupportedServer(rawResponse);
- expect(result).toBe(false);
- });
-});
diff --git a/src/core/server/elasticsearch/supported_server_response_check.ts b/src/core/server/elasticsearch/supported_server_response_check.ts
deleted file mode 100644
index 85235d04caf5c..0000000000000
--- a/src/core/server/elasticsearch/supported_server_response_check.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.
- */
-export const PRODUCT_RESPONSE_HEADER = 'x-elastic-product';
-/**
- * Response headers check to determine if the response is from Elasticsearch
- * @param headers Response headers
- * @returns boolean
- */
-// This check belongs to the elasticsearch service as a dedicated helper method.
-export const isSupportedEsServer = (headers: Record | null) => {
- return !!headers && headers[PRODUCT_RESPONSE_HEADER] === 'Elasticsearch';
-};
-
-/**
- * Check to ensure that a 404 response does not come from Elasticsearch
- *
- * WARNING: This is a hack to work around for 404 responses returned from a proxy.
- * We're aiming to minimise the risk of data loss when consumers act on Not Found errors
- *
- * @param response response from elasticsearch client call
- * @returns boolean 'true' if the status code is 404 and the Elasticsearch product header is missing/unexpected value
- */
-export const isNotFoundFromUnsupportedServer = (args: {
- statusCode: number | null;
- headers: Record | null;
-}): boolean => {
- return args.statusCode === 404 && !isSupportedEsServer(args.headers);
-};
diff --git a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts
index 70166704679fe..c9bb82d5da65c 100644
--- a/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts
+++ b/src/core/server/elasticsearch/version_check/ensure_es_version.test.ts
@@ -139,6 +139,7 @@ describe('pollEsNodesVersion', () => {
});
const nodeInfosSuccessOnce = (infos: NodesInfo) => {
+ // @ts-expect-error not full interface
internalClient.nodes.info.mockImplementationOnce(() => createEsSuccess(infos));
};
const nodeInfosErrorOnce = (error: any) => {
diff --git a/src/core/server/http/integration_tests/core_services.test.ts b/src/core/server/http/integration_tests/core_services.test.ts
index 84eed0511cb23..4bf64a96cf773 100644
--- a/src/core/server/http/integration_tests/core_services.test.ts
+++ b/src/core/server/http/integration_tests/core_services.test.ts
@@ -8,7 +8,7 @@
import { MockElasticsearchClient } from './core_service.test.mocks';
import { elasticsearchClientMock } from '../../elasticsearch/client/mocks';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import * as kbnTestServer from '../../../test_helpers/kbn_server';
import { InternalElasticsearchServiceStart } from '../../elasticsearch';
@@ -205,7 +205,7 @@ describe('http service', () => {
esClient.ping.mockImplementation(() =>
elasticsearchClientMock.createErrorTransportRequestPromise(
- new ResponseError({
+ new errors.ResponseError({
statusCode: 401,
body: {
error: {
@@ -243,7 +243,7 @@ describe('http service', () => {
esClient.ping.mockImplementation(() =>
elasticsearchClientMock.createErrorTransportRequestPromise(
- new ResponseError({
+ new errors.ResponseError({
statusCode: 401,
body: {
error: {
@@ -279,7 +279,7 @@ describe('http service', () => {
esClient.ping.mockImplementation(() =>
elasticsearchClientMock.createErrorTransportRequestPromise(
- new ResponseError({
+ new errors.ResponseError({
statusCode: 404,
body: {
error: {
diff --git a/src/core/server/http/router/response_adapter.ts b/src/core/server/http/router/response_adapter.ts
index b03449b2ae194..753c11d5f45ae 100644
--- a/src/core/server/http/router/response_adapter.ts
+++ b/src/core/server/http/router/response_adapter.ts
@@ -15,6 +15,7 @@ import Boom from '@hapi/boom';
import * as stream from 'stream';
import { isResponseError as isElasticsearchResponseError } from '../../elasticsearch/client/errors';
+import { ElasticsearchErrorDetails } from '../../elasticsearch';
import {
HttpResponsePayload,
@@ -154,7 +155,9 @@ function getErrorMessage(payload?: ResponseError): string {
if (typeof payload === 'string') return payload;
// for ES response errors include nested error reason message. it doesn't contain sensitive data.
if (isElasticsearchResponseError(payload)) {
- return `[${payload.message}]: ${payload.meta.body?.error?.reason}`;
+ return `[${payload.message}]: ${
+ (payload.meta.body as ElasticsearchErrorDetails)?.error?.reason
+ }`;
}
return getErrorMessage(payload.message);
diff --git a/src/core/server/http/router/router.ts b/src/core/server/http/router/router.ts
index d2d8dfa2cc72f..be3b24d5d19a7 100644
--- a/src/core/server/http/router/router.ts
+++ b/src/core/server/http/router/router.ts
@@ -289,10 +289,10 @@ export class Router {
const getAuthenticateHeaderValue = () => {
- const header = Object.entries(e.headers).find(
+ const header = Object.entries(e.headers || {}).find(
([key]) => key.toLowerCase() === 'www-authenticate'
);
- return header ? header[1] : 'Basic realm="Authorization Required"';
+ return header ? (header[1] as string) : 'Basic realm="Authorization Required"';
};
return {
body: e.message,
diff --git a/src/core/server/index.ts b/src/core/server/index.ts
index c92a91c96da95..bb91b9f9be98f 100644
--- a/src/core/server/index.ts
+++ b/src/core/server/index.ts
@@ -136,6 +136,7 @@ export type {
GetResponse,
DeleteDocumentResponse,
ElasticsearchConfigPreboot,
+ ElasticsearchErrorDetails,
} from './elasticsearch';
export type { IExternalUrlConfig, IExternalUrlPolicy } from './external_url';
diff --git a/src/core/server/saved_objects/deprecations/unknown_object_types.test.ts b/src/core/server/saved_objects/deprecations/unknown_object_types.test.ts
index 3f8fce0bc1c87..5b2687262ab36 100644
--- a/src/core/server/saved_objects/deprecations/unknown_object_types.test.ts
+++ b/src/core/server/saved_objects/deprecations/unknown_object_types.test.ts
@@ -8,7 +8,7 @@
import { getIndexForTypeMock } from './unknown_object_types.test.mocks';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { deleteUnknownTypeObjects, getUnknownTypesDeprecations } from './unknown_object_types';
import { typeRegistryMock } from '../saved_objects_type_registry.mock';
import { elasticsearchClientMock } from '../../elasticsearch/client/mocks';
diff --git a/src/core/server/saved_objects/deprecations/unknown_object_types.ts b/src/core/server/saved_objects/deprecations/unknown_object_types.ts
index 1b34dcad64010..8815065984a27 100644
--- a/src/core/server/saved_objects/deprecations/unknown_object_types.ts
+++ b/src/core/server/saved_objects/deprecations/unknown_object_types.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { i18n } from '@kbn/i18n';
import type { DeprecationsDetails } from '../../deprecations';
import { IScopedClusterClient } from '../../elasticsearch';
diff --git a/src/core/server/saved_objects/mappings/types.ts b/src/core/server/saved_objects/mappings/types.ts
index e2ad2a91fd000..e225d0ff31022 100644
--- a/src/core/server/saved_objects/mappings/types.ts
+++ b/src/core/server/saved_objects/mappings/types.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
/**
* Describe a saved object type mapping.
*
diff --git a/src/core/server/saved_objects/migrations/core/call_cluster.ts b/src/core/server/saved_objects/migrations/core/call_cluster.ts
index d158bf7d131f5..156689c8d96f9 100644
--- a/src/core/server/saved_objects/migrations/core/call_cluster.ts
+++ b/src/core/server/saved_objects/migrations/core/call_cluster.ts
@@ -12,7 +12,7 @@
* funcationality contained here.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export type AliasAction =
| {
diff --git a/src/core/server/saved_objects/migrations/core/elastic_index.test.ts b/src/core/server/saved_objects/migrations/core/elastic_index.test.ts
index 15bd1d46b092b..2cdeb479f50f9 100644
--- a/src/core/server/saved_objects/migrations/core/elastic_index.test.ts
+++ b/src/core/server/saved_objects/migrations/core/elastic_index.test.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import _ from 'lodash';
import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks';
import * as Index from './elastic_index';
@@ -164,7 +164,7 @@ describe('ElasticIndex', () => {
client.tasks.get.mockResolvedValue(
elasticsearchClientMock.createSuccessTransportRequestPromise({
completed: true,
- } as estypes.TaskGetResponse)
+ } as estypes.TasksGetResponse)
);
const info = {
@@ -248,7 +248,7 @@ describe('ElasticIndex', () => {
reason: 'all shards failed',
failed_shards: [],
},
- } as estypes.TaskGetResponse)
+ } as estypes.TasksGetResponse)
);
const info = {
diff --git a/src/core/server/saved_objects/migrations/core/elastic_index.ts b/src/core/server/saved_objects/migrations/core/elastic_index.ts
index dc98139ad513e..64df079897722 100644
--- a/src/core/server/saved_objects/migrations/core/elastic_index.ts
+++ b/src/core/server/saved_objects/migrations/core/elastic_index.ts
@@ -12,7 +12,7 @@
*/
import _ from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { MigrationEsClient } from './migration_es_client';
import { IndexMapping } from '../../mappings';
import { SavedObjectsMigrationVersion } from '../../types';
diff --git a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts
index 64d4fa3609e90..beb0c1d3651c6 100644
--- a/src/core/server/saved_objects/migrations/core/index_migrator.test.ts
+++ b/src/core/server/saved_objects/migrations/core/index_migrator.test.ts
@@ -7,7 +7,7 @@
*/
import _ from 'lodash';
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks';
import { SavedObjectUnsanitizedDoc, SavedObjectsSerializer } from '../../serialization';
import { SavedObjectTypeRegistry } from '../../saved_objects_type_registry';
@@ -450,7 +450,7 @@ function withIndex(
client.tasks.get.mockReturnValue(
elasticsearchClientMock.createSuccessTransportRequestPromise({
completed: true,
- } as estypes.TaskGetResponse)
+ } as estypes.TasksGetResponse)
);
client.search.mockReturnValue(
elasticsearchClientMock.createSuccessTransportRequestPromise(searchResult(0) as any)
diff --git a/src/core/server/saved_objects/migrations/core/migration_es_client.ts b/src/core/server/saved_objects/migrations/core/migration_es_client.ts
index e8dc9c94b7861..243b724eb2a67 100644
--- a/src/core/server/saved_objects/migrations/core/migration_es_client.ts
+++ b/src/core/server/saved_objects/migrations/core/migration_es_client.ts
@@ -5,8 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-
-import type { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport';
+import type { Client, TransportRequestOptions } from '@elastic/elasticsearch';
import { get } from 'lodash';
import { set } from '@elastic/safer-lodash-set';
@@ -58,7 +57,7 @@ export interface MigrationEsClient {
}
export function createMigrationEsClient(
- client: ElasticsearchClient,
+ client: ElasticsearchClient | Client,
log: Logger,
delay?: number
): MigrationEsClient {
@@ -69,7 +68,7 @@ export function createMigrationEsClient(
throw new Error(`unknown ElasticsearchClient client method [${key}]`);
}
return await migrationRetryCallCluster(
- () => fn.call(client, params, { maxRetries: 0, ...options }),
+ () => fn.call(client, params, { maxRetries: 0, meta: true, ...options }),
log,
delay
);
diff --git a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts
index 90274de557fdf..599b5dca0d904 100644
--- a/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts
+++ b/src/core/server/saved_objects/migrations/kibana/kibana_migrator.test.ts
@@ -7,7 +7,7 @@
*/
import { take } from 'rxjs/operators';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks';
import { KibanaMigratorOptions, KibanaMigrator } from './kibana_migrator';
@@ -252,7 +252,7 @@ const mockV2MigrationOptions = () => {
error: undefined,
failures: [],
task: { description: 'task description' } as any,
- } as estypes.TaskGetResponse)
+ } as estypes.TasksGetResponse)
);
options.client.search = jest
diff --git a/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts b/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts
index 9353ede9be6ac..f3ddc0c308970 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/bulk_overwrite_transformed_documents.ts
@@ -8,7 +8,8 @@
import * as Either from 'fp-ts/lib/Either';
import * as TaskEither from 'fp-ts/lib/TaskEither';
-import { errors as esErrors, estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import { errors as esErrors } from '@elastic/elasticsearch';
import { ElasticsearchClient } from '../../../elasticsearch';
import type { SavedObjectsRawDoc } from '../../serialization';
import {
@@ -92,7 +93,7 @@ export const bulkOverwriteTransformedDocuments =
.then((res) => {
// Filter out version_conflict_engine_exception since these just mean
// that another instance already updated these documents
- const errors = (res.body.items ?? [])
+ const errors: estypes.ErrorCause[] = (res.body.items ?? [])
.filter((item) => item.index?.error)
.map((item) => item.index!.error!)
.filter(({ type }) => type !== 'version_conflict_engine_exception');
diff --git a/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts b/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts
index 9ba098d01870f..2b35e3b59e988 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/calculate_exclude_filters.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { withTimeout } from '@kbn/std';
import * as Either from 'fp-ts/lib/Either';
import * as TaskEither from 'fp-ts/lib/TaskEither';
diff --git a/src/core/server/saved_objects/migrationsv2/actions/catch_retryable_es_client_errors.ts b/src/core/server/saved_objects/migrationsv2/actions/catch_retryable_es_client_errors.ts
index 3d9a51e3b1eba..168e3170d30bf 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/catch_retryable_es_client_errors.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/catch_retryable_es_client_errors.ts
@@ -31,7 +31,7 @@ export const catchRetryableEsClientErrors = (
e instanceof EsErrors.ConnectionError ||
e instanceof EsErrors.TimeoutError ||
(e instanceof EsErrors.ResponseError &&
- (retryResponseStatuses.includes(e?.statusCode) ||
+ (retryResponseStatuses.includes(e?.statusCode!) ||
// ES returns a 400 Bad Request when trying to close or delete an
// index while snapshots are in progress. This should have been a 503
// so once https://github.com/elastic/elasticsearch/issues/65883 is
diff --git a/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.test.ts b/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.test.ts
index a52cb2a922968..8a99d28b40de1 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.test.ts
@@ -8,7 +8,8 @@
import * as Either from 'fp-ts/lib/Either';
import { catchRetryableEsClientErrors } from './catch_retryable_es_client_errors';
-import { errors as EsErrors, estypes } from '@elastic/elasticsearch';
+import { errors as EsErrors } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { elasticsearchClientMock } from '../../../elasticsearch/client/mocks';
import { checkForUnknownDocs } from './check_for_unknown_docs';
diff --git a/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts b/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts
index 1db47f0083467..cfeda0548b16a 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/check_for_unknown_docs.ts
@@ -8,7 +8,7 @@
import * as Either from 'fp-ts/lib/Either';
import * as TaskEither from 'fp-ts/lib/TaskEither';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { SavedObjectsRawDocSource } from '../../serialization';
import { ElasticsearchClient } from '../../../elasticsearch';
import {
diff --git a/src/core/server/saved_objects/migrationsv2/actions/create_index.ts b/src/core/server/saved_objects/migrationsv2/actions/create_index.ts
index d5269233344c3..9fa8aebcd7dc1 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/create_index.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/create_index.ts
@@ -9,7 +9,7 @@
import * as Either from 'fp-ts/lib/Either';
import * as TaskEither from 'fp-ts/lib/TaskEither';
import { pipe } from 'fp-ts/lib/pipeable';
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { AcknowledgeResponse } from './index';
import { ElasticsearchClient } from '../../../elasticsearch';
import { IndexMapping } from '../../mappings';
@@ -100,7 +100,7 @@ export const createIndex = ({
* - acknowledged=true, shards_acknowledged=true, index creation complete
*/
return Either.right({
- acknowledged: res.body.acknowledged,
+ acknowledged: Boolean(res.body.acknowledged),
shardsAcknowledged: res.body.shards_acknowledged,
});
})
diff --git a/src/core/server/saved_objects/migrationsv2/actions/es_errors.ts b/src/core/server/saved_objects/migrationsv2/actions/es_errors.ts
index 49b996bb118d8..4f560468bcb0c 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/es_errors.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/es_errors.ts
@@ -5,23 +5,19 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
-export interface EsErrorCause {
- type: string;
- reason: string;
-}
-
-export const isWriteBlockException = ({ type, reason }: EsErrorCause): boolean => {
+export const isWriteBlockException = ({ type, reason }: estypes.ErrorCause): boolean => {
return (
type === 'cluster_block_exception' &&
reason.match(/index \[.+] blocked by: \[FORBIDDEN\/8\/.+ \(api\)\]/) !== null
);
};
-export const isIncompatibleMappingException = ({ type }: EsErrorCause): boolean => {
+export const isIncompatibleMappingException = ({ type }: estypes.ErrorCause): boolean => {
return type === 'strict_dynamic_mapping_exception' || type === 'mapper_parsing_exception';
};
-export const isIndexNotFoundException = ({ type }: EsErrorCause): boolean => {
+export const isIndexNotFoundException = ({ type }: estypes.ErrorCause): boolean => {
return type === 'index_not_found_exception';
};
diff --git a/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts b/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts
index 0a5864dcefac2..3ca3a8505338b 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/integration_tests/actions.test.ts
@@ -38,7 +38,7 @@ import {
} from '../../actions';
import * as Either from 'fp-ts/lib/Either';
import * as Option from 'fp-ts/lib/Option';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { DocumentsTransformFailed, DocumentsTransformSuccess } from '../../../migrations/core';
import { TaskEither } from 'fp-ts/lib/TaskEither';
import Path from 'path';
@@ -61,7 +61,7 @@ describe.skip('migration actions', () => {
beforeAll(async () => {
esServer = await startES();
- client = esServer.es.getClient();
+ client = esServer.es.getKibanaEsClient();
// Create test fixture data:
await createIndex({
@@ -281,7 +281,7 @@ describe.skip('migration actions', () => {
index: 'red_then_yellow_index',
body: {
// Enable all shard allocation so that the index status turns yellow
- settings: { routing: { allocation: { enable: 'all' } } },
+ routing: { allocation: { enable: 'all' } },
},
});
@@ -351,7 +351,7 @@ describe.skip('migration actions', () => {
index: 'clone_red_then_yellow_index',
body: {
// Enable all shard allocation so that the index status goes yellow
- settings: { routing: { allocation: { enable: 'all' } } },
+ routing: { allocation: { enable: 'all' } },
},
});
indexYellow = true;
@@ -413,7 +413,7 @@ describe.skip('migration actions', () => {
await expect(cloneIndexPromise).resolves.toMatchObject({
_tag: 'Left',
left: {
- error: expect.any(ResponseError),
+ error: expect.any(errors.ResponseError),
message: expect.stringMatching(/\"timed_out\":true/),
type: 'retryable_es_client_error',
},
@@ -811,7 +811,7 @@ describe.skip('migration actions', () => {
await expect(task()).resolves.toMatchObject({
_tag: 'Left',
left: {
- error: expect.any(ResponseError),
+ error: expect.any(errors.ResponseError),
message: expect.stringMatching(
/\[timeout_exception\] Timed out waiting for completion of \[org.elasticsearch.index.reindex.BulkByScrollTask/
),
@@ -1170,7 +1170,7 @@ describe.skip('migration actions', () => {
await expect(task()).resolves.toMatchObject({
_tag: 'Left',
left: {
- error: expect.any(ResponseError),
+ error: expect.any(errors.ResponseError),
message: expect.stringMatching(
/\[timeout_exception\] Timed out waiting for completion of \[org.elasticsearch.index.reindex.BulkByScrollTask/
),
@@ -1445,7 +1445,7 @@ describe.skip('migration actions', () => {
index: 'red_then_yellow_index',
body: {
// Disable all shard allocation so that the index status is red
- settings: { routing: { allocation: { enable: 'all' } } },
+ routing: { allocation: { enable: 'all' } },
},
});
indexYellow = true;
diff --git a/src/core/server/saved_objects/migrationsv2/actions/integration_tests/es_errors.test.ts b/src/core/server/saved_objects/migrationsv2/actions/integration_tests/es_errors.test.ts
index e259b375736d5..2473d8d3ae410 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/integration_tests/es_errors.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/integration_tests/es_errors.test.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient } from '../../../../';
import { InternalCoreStart } from '../../../../internal_types';
import * as kbnTestServer from '../../../../../test_helpers/kbn_server';
@@ -100,7 +100,7 @@ describe('Elasticsearch Errors', () => {
],
});
- const cause = res.body.items[0].index!.error!;
+ const cause = res.body.items[0].index!.error! as estypes.ErrorCause;
expect(isWriteBlockException(cause)).toEqual(true);
});
@@ -122,7 +122,7 @@ describe('Elasticsearch Errors', () => {
],
});
- const cause = res.body.items[0].create!.error!;
+ const cause = res.body.items[0].create!.error! as estypes.ErrorCause;
expect(isWriteBlockException(cause)).toEqual(true);
});
diff --git a/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts b/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts
index c8e7d61dce811..0902e206147d3 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/read_with_pit.ts
@@ -8,7 +8,7 @@
import * as Either from 'fp-ts/lib/Either';
import * as TaskEither from 'fp-ts/lib/TaskEither';
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient } from '../../../elasticsearch';
import type { SavedObjectsRawDoc } from '../../serialization';
import {
diff --git a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts
index 92134d2755ac3..e8e054c7a1780 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/reindex.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/reindex.ts
@@ -9,7 +9,7 @@
import * as Either from 'fp-ts/lib/Either';
import * as TaskEither from 'fp-ts/lib/TaskEither';
import * as Option from 'fp-ts/lib/Option';
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient } from '../../../elasticsearch';
import {
catchRetryableEsClientErrors,
diff --git a/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts b/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts
index 77445654d3cc3..cca9ea5e7598e 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/remove_write_block.ts
@@ -41,10 +41,8 @@ export const removeWriteBlock =
// Don't change any existing settings
preserve_existing: true,
body: {
- settings: {
- blocks: {
- write: false,
- },
+ blocks: {
+ write: false,
},
},
},
diff --git a/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts b/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts
index 5a6cb3a3d048d..5a92a7c6cc286 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/search_for_outdated_documents.ts
@@ -8,7 +8,7 @@
import * as Either from 'fp-ts/lib/Either';
import * as TaskEither from 'fp-ts/lib/TaskEither';
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient } from '../../../elasticsearch';
import type { SavedObjectsRawDoc, SavedObjectsRawDocSource } from '../../serialization';
import {
diff --git a/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts b/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts
index db519d0246511..9c40e1b64fae0 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/set_write_block.ts
@@ -6,7 +6,6 @@
* Side Public License, v 1.
*/
-import type { ElasticsearchClientError } from '@elastic/elasticsearch/lib/errors';
import * as Either from 'fp-ts/lib/Either';
import * as TaskEither from 'fp-ts/lib/TaskEither';
import { errors as EsErrors } from '@elastic/elasticsearch';
@@ -61,7 +60,7 @@ export const setWriteBlock =
message: 'set_write_block_failed',
});
})
- .catch((e: ElasticsearchClientError) => {
+ .catch((e: EsErrors.ElasticsearchClientError) => {
if (e instanceof EsErrors.ResponseError) {
if (e.body?.error?.type === 'index_not_found_exception') {
return Either.left({ type: 'index_not_found_exception' as const, index });
diff --git a/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts b/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts
index 212e1ad9c8c81..1a319d17dbce9 100644
--- a/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts
+++ b/src/core/server/saved_objects/migrationsv2/actions/wait_for_task.ts
@@ -5,6 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as Either from 'fp-ts/lib/Either';
import * as TaskEither from 'fp-ts/lib/TaskEither';
import * as Option from 'fp-ts/lib/Option';
@@ -86,7 +87,7 @@ export const waitForTask =
const failures = body.response?.failures ?? [];
return Either.right({
completed: body.completed,
- error: Option.fromNullable(body.error),
+ error: Option.fromNullable(body.error as estypes.ErrorCauseKeys),
failures: failures.length > 0 ? Option.some(failures) : Option.none,
description: body.task.description,
});
diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/7_13_0_failed_action_tasks.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/7_13_0_failed_action_tasks.test.ts
index a4ce95a9e0584..479b1e78e1b72 100644
--- a/src/core/server/saved_objects/migrationsv2/integration_tests/7_13_0_failed_action_tasks.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/integration_tests/7_13_0_failed_action_tasks.test.ts
@@ -55,7 +55,7 @@ describe('migration from 7.13 to 7.14+ with many failed action_tasks', () => {
kibanaIndexName = '.kibana',
taskManagerIndexName = '.kibana_task_manager'
): Promise<{ tasksCount: number; actionTaskParamsCount: number }> => {
- const esClient: ElasticsearchClient = esServer.es.getClient();
+ const esClient: ElasticsearchClient = esServer.es.getKibanaEsClient();
const actionTaskParamsResponse = await esClient.count({
index: kibanaIndexName,
diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/7_13_0_unknown_types.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/7_13_0_unknown_types.test.ts
index a04300ffea626..aea84cea22862 100644
--- a/src/core/server/saved_objects/migrationsv2/integration_tests/7_13_0_unknown_types.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/integration_tests/7_13_0_unknown_types.test.ts
@@ -8,7 +8,7 @@
import Path from 'path';
import fs from 'fs/promises';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as kbnTestServer from '../../../../test_helpers/kbn_server';
import { Root } from '../../../root';
import JSON5 from 'json5';
@@ -114,7 +114,7 @@ describe('migration v2', () => {
);
});
- const client: ElasticsearchClient = esServer.es.getClient();
+ const client: ElasticsearchClient = esServer.es.getKibanaEsClient();
const { body: response } = await client.indices.getSettings({
index: targetIndex,
});
@@ -178,7 +178,7 @@ describe('migration v2', () => {
});
await root.start();
- const client: ElasticsearchClient = esServer.es.getClient();
+ const client: ElasticsearchClient = esServer.es.getKibanaEsClient();
const spacesDocsMigrated = await fetchDocs(client, targetIndex, 'space');
expect(spacesDocsMigrated.map((s) => s.id)).toEqual(
expect.arrayContaining([
diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/batch_size_bytes.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/batch_size_bytes.test.ts
index de25c7b1c6412..e444a3b1a8bdb 100644
--- a/src/core/server/saved_objects/migrationsv2/integration_tests/batch_size_bytes.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/integration_tests/batch_size_bytes.test.ts
@@ -95,7 +95,7 @@ describe('migration v2', () => {
// wait a bit for the count to settle.
await new Promise((resolve) => setTimeout(resolve, 5000));
- const esClient: ElasticsearchClient = esServer.es.getClient();
+ const esClient: ElasticsearchClient = esServer.es.getKibanaEsClient();
// assert that the docs from the original index have been migrated rather than comparing a doc count after startup
const originalDocs = await fetchDocuments(esClient, '.kibana_7.14.0_001');
diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/batch_size_bytes_exceeds_es_content_length.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/batch_size_bytes_exceeds_es_content_length.test.ts
index b47156e3a1e9e..d992193730a34 100644
--- a/src/core/server/saved_objects/migrationsv2/integration_tests/batch_size_bytes_exceeds_es_content_length.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/integration_tests/batch_size_bytes_exceeds_es_content_length.test.ts
@@ -20,7 +20,8 @@ async function removeLogFile() {
await fs.unlink(logFilePath).catch(() => void 0);
}
-describe('migration v2', () => {
+// un-skip after https://github.com/elastic/kibana/issues/116111
+describe.skip('migration v2', () => {
let esServer: kbnTestServer.TestElasticsearchUtils;
let root: Root;
let startES: () => Promise;
diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/cleanup.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/cleanup.test.ts
index c84f72b184261..4f3026c619d3c 100644
--- a/src/core/server/saved_objects/migrationsv2/integration_tests/cleanup.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/integration_tests/cleanup.test.ts
@@ -133,7 +133,7 @@ describe('migration v2', () => {
const pitId = logRecordWithPit.right.pitId;
expect(pitId).toBeTruthy();
- const client = esServer.es.getClient();
+ const client = esServer.es.getKibanaEsClient();
await expect(
client.search({
body: {
diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/multiple_es_nodes.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/multiple_es_nodes.test.ts
index 6956e53ebc7fa..fabc9222b6858 100644
--- a/src/core/server/saved_objects/migrationsv2/integration_tests/multiple_es_nodes.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/integration_tests/multiple_es_nodes.test.ts
@@ -179,7 +179,7 @@ describe('migration v2', () => {
});
await root.start();
- const esClient = esServer.es.getClient();
+ const esClient = esServer.es.getKibanaEsClient();
const migratedFooDocs = await fetchDocs(esClient, migratedIndex, 'foo');
expect(migratedFooDocs.length).toBe(2500);
diff --git a/src/core/server/saved_objects/migrationsv2/integration_tests/multiple_kibana_nodes.test.ts b/src/core/server/saved_objects/migrationsv2/integration_tests/multiple_kibana_nodes.test.ts
index ef92c823182d8..5d0d662a5360b 100644
--- a/src/core/server/saved_objects/migrationsv2/integration_tests/multiple_kibana_nodes.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/integration_tests/multiple_kibana_nodes.test.ts
@@ -182,7 +182,7 @@ describe('migration v2', () => {
await startWithDelay([rootA, rootB, rootC], 0);
- const esClient = esServer.es.getClient();
+ const esClient = esServer.es.getKibanaEsClient();
const migratedDocs = await fetchDocs(esClient, migratedIndex);
expect(migratedDocs.length).toBe(5000);
@@ -201,7 +201,7 @@ describe('migration v2', () => {
await startWithDelay([rootA, rootB, rootC], 1);
- const esClient = esServer.es.getClient();
+ const esClient = esServer.es.getKibanaEsClient();
const migratedDocs = await fetchDocs(esClient, migratedIndex);
expect(migratedDocs.length).toBe(5000);
@@ -220,7 +220,7 @@ describe('migration v2', () => {
await startWithDelay([rootA, rootB, rootC], 5);
- const esClient = esServer.es.getClient();
+ const esClient = esServer.es.getKibanaEsClient();
const migratedDocs = await fetchDocs(esClient, migratedIndex);
expect(migratedDocs.length).toBe(5000);
@@ -239,7 +239,7 @@ describe('migration v2', () => {
await startWithDelay([rootA, rootB, rootC], 20);
- const esClient = esServer.es.getClient();
+ const esClient = esServer.es.getKibanaEsClient();
const migratedDocs = await fetchDocs(esClient, migratedIndex);
expect(migratedDocs.length).toBe(5000);
diff --git a/src/core/server/saved_objects/migrationsv2/migrations_state_action_machine.test.ts b/src/core/server/saved_objects/migrationsv2/migrations_state_action_machine.test.ts
index 338eecf151174..c53bd7bbc53dd 100644
--- a/src/core/server/saved_objects/migrationsv2/migrations_state_action_machine.test.ts
+++ b/src/core/server/saved_objects/migrationsv2/migrations_state_action_machine.test.ts
@@ -12,7 +12,7 @@ import { loggingSystemMock, elasticsearchServiceMock } from '../../mocks';
import { typeRegistryMock } from '../saved_objects_type_registry.mock';
import * as Either from 'fp-ts/lib/Either';
import * as Option from 'fp-ts/lib/Option';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { elasticsearchClientMock } from '../../elasticsearch/client/mocks';
import { LoggerAdapter } from '../../logging/logger_adapter';
import { AllControlStates, State } from './types';
@@ -193,7 +193,7 @@ describe('migrationsStateActionMachine', () => {
logger: mockLogger.get(),
model: transitionModel(['LEGACY_REINDEX', 'LEGACY_DELETE', 'FATAL']),
next: () => {
- throw new ResponseError(
+ throw new errors.ResponseError(
elasticsearchClientMock.createApiResponse({
meta: {
request: { options: {}, id: '', params: { method: 'POST', path: '/mock' } },
diff --git a/src/core/server/saved_objects/migrationsv2/model/model.ts b/src/core/server/saved_objects/migrationsv2/model/model.ts
index 3c36c668f2d99..ff27045dd91ce 100644
--- a/src/core/server/saved_objects/migrationsv2/model/model.ts
+++ b/src/core/server/saved_objects/migrationsv2/model/model.ts
@@ -9,7 +9,7 @@
import * as Either from 'fp-ts/lib/Either';
import * as Option from 'fp-ts/lib/Option';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { AliasAction, isLeftTypeof } from '../actions';
import { AllActionStates, MigrationLog, State } from '../types';
import type { ResponseType } from '../next';
diff --git a/src/core/server/saved_objects/migrationsv2/types.ts b/src/core/server/saved_objects/migrationsv2/types.ts
index 4f6419930c6cc..e68e04e5267cc 100644
--- a/src/core/server/saved_objects/migrationsv2/types.ts
+++ b/src/core/server/saved_objects/migrationsv2/types.ts
@@ -8,7 +8,7 @@
import * as TaskEither from 'fp-ts/lib/TaskEither';
import * as Option from 'fp-ts/lib/Option';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ControlState } from './state_action_machine';
import { AliasAction } from './actions';
import { IndexMapping } from '../mappings';
diff --git a/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts b/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts
index 53f1b5c9d78c5..0296dd25b56ee 100644
--- a/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts
+++ b/src/core/server/saved_objects/service/lib/aggregations/validation.test.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { validateAndConvertAggregations } from './validation';
type AggsMap = Record;
diff --git a/src/core/server/saved_objects/service/lib/aggregations/validation.ts b/src/core/server/saved_objects/service/lib/aggregations/validation.ts
index 5ef89f297a796..445d6b6a7ce22 100644
--- a/src/core/server/saved_objects/service/lib/aggregations/validation.ts
+++ b/src/core/server/saved_objects/service/lib/aggregations/validation.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ObjectType } from '@kbn/config-schema';
import { isPlainObject } from 'lodash';
diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts
index fe97208a6168d..45794e25d00a6 100644
--- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts
+++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.test.ts
@@ -25,7 +25,6 @@ import { savedObjectsPointInTimeFinderMock } from './point_in_time_finder.mock';
import { savedObjectsRepositoryMock } from './repository.mock';
import { PointInTimeFinder } from './point_in_time_finder';
import { ISavedObjectsRepository } from './repository';
-import { SavedObjectsErrorHelpers } from './errors';
const SPACES = ['default', 'another-space'];
const VERSION_PROPS = { _seq_no: 1, _primary_term: 1 };
@@ -319,23 +318,6 @@ describe('collectMultiNamespaceReferences', () => {
// obj3 is excluded from the results
]);
});
- it(`handles 404 responses that don't come from Elasticsearch`, async () => {
- const createEsUnavailableNotFoundError = () => {
- return SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- };
- const obj1 = { type: MULTI_NAMESPACE_OBJ_TYPE_1, id: 'id-1' };
- const params = setup([obj1]);
- client.mget.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { docs: [] },
- { statusCode: 404 },
- {}
- )
- );
- await expect(() => collectMultiNamespaceReferences(params)).rejects.toThrowError(
- createEsUnavailableNotFoundError()
- );
- });
describe('legacy URL aliases', () => {
it('uses the PointInTimeFinder to search for legacy URL aliases', async () => {
diff --git a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts
index 7acbaaea1f5d7..278964c934ba0 100644
--- a/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts
+++ b/src/core/server/saved_objects/service/lib/collect_multi_namespace_references.ts
@@ -7,12 +7,10 @@
*/
import * as esKuery from '@kbn/es-query';
-import { isNotFoundFromUnsupportedServer } from '../../../elasticsearch';
import { LegacyUrlAlias, LEGACY_URL_ALIAS_TYPE } from '../../object_types';
import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry';
import type { SavedObjectsSerializer } from '../../serialization';
import type { SavedObject, SavedObjectsBaseOptions } from '../../types';
-import { SavedObjectsErrorHelpers } from './errors';
import { getRootFields } from './included_fields';
import { getSavedObjectFromSource, rawDocExistsInNamespace } from './internal_utils';
import type {
@@ -199,15 +197,6 @@ async function getObjectsAndReferences({
{ body: { docs: makeBulkGetDocs(bulkGetObjects) } },
{ ignore: [404] }
);
- // exit early if we can't verify a 404 response is from Elasticsearch
- if (
- isNotFoundFromUnsupportedServer({
- statusCode: bulkGetResponse.statusCode,
- headers: bulkGetResponse.headers,
- })
- ) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
const newObjectsToGet = new Set();
for (let i = 0; i < bulkGetObjects.length; i++) {
// For every element in bulkGetObjects, there should be a matching element in bulkGetResponse.body.docs
diff --git a/src/core/server/saved_objects/service/lib/decorate_es_error.test.ts b/src/core/server/saved_objects/service/lib/decorate_es_error.test.ts
index 4e187e85f81a7..e7dd355910362 100644
--- a/src/core/server/saved_objects/service/lib/decorate_es_error.test.ts
+++ b/src/core/server/saved_objects/service/lib/decorate_es_error.test.ts
@@ -53,6 +53,16 @@ describe('savedObjectsClient/decorateEsError', () => {
expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(true);
});
+ it('makes ProductNotSupportedError a SavedObjectsClient/EsUnavailable error', () => {
+ const error = new esErrors.ProductNotSupportedError(
+ 'reason',
+ elasticsearchClientMock.createApiResponse()
+ );
+ expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(false);
+ expect(decorateEsError(error)).toBe(error);
+ expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(true);
+ });
+
it('makes Conflict a SavedObjectsClient/Conflict error', () => {
const error = new esErrors.ResponseError(
elasticsearchClientMock.createApiResponse({ statusCode: 409 })
@@ -109,18 +119,6 @@ describe('savedObjectsClient/decorateEsError', () => {
expect(SavedObjectsErrorHelpers.isNotFoundError(genericError)).toBe(true);
});
- it('makes NotFound errors generic NotFoundEsUnavailableError errors when response is from unsupported server', () => {
- const error = new esErrors.ResponseError(
- // explicitly override the headers
- elasticsearchClientMock.createApiResponse({ statusCode: 404, headers: {} })
- );
- expect(SavedObjectsErrorHelpers.isNotFoundError(error)).toBe(false);
- const genericError = decorateEsError(error);
- expect(genericError).not.toBe(error);
- expect(SavedObjectsErrorHelpers.isNotFoundError(genericError)).toBe(false);
- expect(SavedObjectsErrorHelpers.isEsUnavailableError(genericError)).toBe(true);
- });
-
it('if saved objects index does not exist makes NotFound a SavedObjectsClient/generalError', () => {
const error = new esErrors.ResponseError(
elasticsearchClientMock.createApiResponse({
diff --git a/src/core/server/saved_objects/service/lib/decorate_es_error.ts b/src/core/server/saved_objects/service/lib/decorate_es_error.ts
index 016268ccdf9f4..d8734b141bd9b 100644
--- a/src/core/server/saved_objects/service/lib/decorate_es_error.ts
+++ b/src/core/server/saved_objects/service/lib/decorate_es_error.ts
@@ -8,19 +8,20 @@
import { errors as esErrors } from '@elastic/elasticsearch';
import { get } from 'lodash';
-import { isSupportedEsServer } from '../../../elasticsearch';
+import { ElasticsearchErrorDetails } from '../../../elasticsearch';
const responseErrors = {
- isServiceUnavailable: (statusCode: number) => statusCode === 503,
- isConflict: (statusCode: number) => statusCode === 409,
- isNotAuthorized: (statusCode: number) => statusCode === 401,
- isForbidden: (statusCode: number) => statusCode === 403,
- isRequestEntityTooLarge: (statusCode: number) => statusCode === 413,
- isNotFound: (statusCode: number) => statusCode === 404,
- isBadRequest: (statusCode: number) => statusCode === 400,
- isTooManyRequests: (statusCode: number) => statusCode === 429,
+ isServiceUnavailable: (statusCode?: number) => statusCode === 503,
+ isConflict: (statusCode?: number) => statusCode === 409,
+ isNotAuthorized: (statusCode?: number) => statusCode === 401,
+ isForbidden: (statusCode?: number) => statusCode === 403,
+ isRequestEntityTooLarge: (statusCode?: number) => statusCode === 413,
+ isNotFound: (statusCode?: number) => statusCode === 404,
+ isBadRequest: (statusCode?: number) => statusCode === 400,
+ isTooManyRequests: (statusCode?: number) => statusCode === 429,
};
-const { ConnectionError, NoLivingConnectionsError, TimeoutError } = esErrors;
+const { ConnectionError, NoLivingConnectionsError, TimeoutError, ProductNotSupportedError } =
+ esErrors;
const SCRIPT_CONTEXT_DISABLED_REGEX = /(?:cannot execute scripts using \[)([a-z]*)(?:\] context)/;
const INLINE_SCRIPTS_DISABLED_MESSAGE = 'cannot execute [inline] scripts';
@@ -30,6 +31,7 @@ type EsErrors =
| esErrors.ConnectionError
| esErrors.NoLivingConnectionsError
| esErrors.TimeoutError
+ | esErrors.ProductNotSupportedError
| esErrors.ResponseError;
export function decorateEsError(error: EsErrors) {
@@ -42,6 +44,7 @@ export function decorateEsError(error: EsErrors) {
error instanceof ConnectionError ||
error instanceof NoLivingConnectionsError ||
error instanceof TimeoutError ||
+ error instanceof ProductNotSupportedError ||
responseErrors.isServiceUnavailable(error.statusCode)
) {
return SavedObjectsErrorHelpers.decorateEsUnavailableError(error, reason);
@@ -64,17 +67,12 @@ export function decorateEsError(error: EsErrors) {
}
if (responseErrors.isNotFound(error.statusCode)) {
- const match = error?.meta?.body?.error?.reason?.match(
+ const match = (error?.meta?.body as ElasticsearchErrorDetails)?.error?.reason?.match(
/no such index \[(.+)\] and \[require_alias\] request flag is \[true\] and \[.+\] is not an alias/
);
- if (match?.length > 0) {
+ if (match && match.length > 0) {
return SavedObjectsErrorHelpers.decorateIndexAliasNotFoundError(error, match[1]);
}
- // Throw EsUnavailable error if the 404 is not from elasticsearch
- // Needed here to verify Product support for any non-ignored 404 responses from calls to ES
- if (!isSupportedEsServer(error?.meta?.headers)) {
- return SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
return SavedObjectsErrorHelpers.createGenericNotFoundError();
}
diff --git a/src/core/server/saved_objects/service/lib/errors.test.ts b/src/core/server/saved_objects/service/lib/errors.test.ts
index 3bea693429254..a366dce626ec2 100644
--- a/src/core/server/saved_objects/service/lib/errors.test.ts
+++ b/src/core/server/saved_objects/service/lib/errors.test.ts
@@ -439,45 +439,4 @@ describe('savedObjectsClient/errorTypes', () => {
});
});
});
-
- describe('NotFoundEsUnavailableError', () => {
- it('makes an error identifiable as an EsUnavailable error', () => {
- const error = SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError('foo', 'bar');
- expect(SavedObjectsErrorHelpers.isEsUnavailableError(error)).toBe(true);
- });
-
- it('returns a boom error', () => {
- const error = SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError('foo', 'bar');
- expect(error).toHaveProperty('isBoom', true);
- });
-
- it('decorates the error message with the saved object that was not found', () => {
- const error = SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError('foo', 'bar');
- expect(error.output.payload).toHaveProperty(
- 'message',
- 'x-elastic-product not present or not recognized: Saved object [foo/bar] not found'
- );
- });
-
- describe('error.output', () => {
- it('specifies the saved object that was not found', () => {
- const error = SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError(
- 'foo',
- 'bar'
- );
- expect(error.output.payload).toHaveProperty(
- 'message',
- 'x-elastic-product not present or not recognized: Saved object [foo/bar] not found'
- );
- });
-
- it('sets statusCode to 503', () => {
- const error = SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError(
- 'foo',
- 'bar'
- );
- expect(error.output).toHaveProperty('statusCode', 503);
- });
- });
- });
});
diff --git a/src/core/server/saved_objects/service/lib/errors.ts b/src/core/server/saved_objects/service/lib/errors.ts
index 7412e744f19e7..581145c7c09d1 100644
--- a/src/core/server/saved_objects/service/lib/errors.ts
+++ b/src/core/server/saved_objects/service/lib/errors.ts
@@ -202,16 +202,4 @@ export class SavedObjectsErrorHelpers {
public static isGeneralError(error: Error | DecoratedError) {
return isSavedObjectsClientError(error) && error[code] === CODE_GENERAL_ERROR;
}
-
- public static createGenericNotFoundEsUnavailableError(
- // type and id not available in all operations (e.g. mget)
- type: string | null = null,
- id: string | null = null
- ) {
- const notFoundError = this.createGenericNotFoundError(type, id);
- return this.decorateEsUnavailableError(
- new Error(`${notFoundError.message}`),
- `x-elastic-product not present or not recognized`
- );
- }
}
diff --git a/src/core/server/saved_objects/service/lib/integration_tests/repository_with_proxy.test.ts b/src/core/server/saved_objects/service/lib/integration_tests/repository_with_proxy.test.ts
index 925b23a64f03e..b767b28c90608 100644
--- a/src/core/server/saved_objects/service/lib/integration_tests/repository_with_proxy.test.ts
+++ b/src/core/server/saved_objects/service/lib/integration_tests/repository_with_proxy.test.ts
@@ -289,17 +289,11 @@ describe('404s from proxies', () => {
let repository: ISavedObjectsRepository;
const myTypeDocs: SavedObject[] = [];
- const genericNotFoundEsUnavailableError = (err: any, type?: string, id?: string) => {
+ const SavedObjectsClientEsUnavailable = (err: any) => {
expect(err?.output?.statusCode).toBe(503);
- if (type && id) {
- expect(err?.output?.payload?.message).toBe(
- `x-elastic-product not present or not recognized: Saved object [${type}/${id}] not found`
- );
- } else {
- expect(err?.output?.payload?.message).toBe(
- `x-elastic-product not present or not recognized: Not Found`
- );
- }
+ expect(err?.output?.payload?.message).toBe(
+ `The client noticed that the server is not Elasticsearch and we do not support this unknown product.`
+ );
};
beforeAll(async () => {
@@ -341,7 +335,7 @@ describe('404s from proxies', () => {
} catch (err) {
myError = err;
}
- expect(genericNotFoundEsUnavailableError(myError, 'my_type', 'myTypeId1'));
+ expect(SavedObjectsClientEsUnavailable(myError));
});
it('returns an EsUnavailable error on `update` requests that are interrupted', async () => {
@@ -354,7 +348,7 @@ describe('404s from proxies', () => {
} catch (err) {
updateError = err;
}
- expect(genericNotFoundEsUnavailableError(updateError));
+ expect(SavedObjectsClientEsUnavailable(updateError));
});
it('returns an EsUnavailable error on `bulkCreate` requests with a 404 proxy response and wrong product header', async () => {
@@ -383,7 +377,7 @@ describe('404s from proxies', () => {
} catch (err) {
bulkCreateError = err;
}
- expect(genericNotFoundEsUnavailableError(bulkCreateError));
+ expect(SavedObjectsClientEsUnavailable(bulkCreateError));
});
it('returns an EsUnavailable error on `find` requests with a 404 proxy response and wrong product header', async () => {
@@ -394,7 +388,7 @@ describe('404s from proxies', () => {
} catch (err) {
findErr = err;
}
- expect(genericNotFoundEsUnavailableError(findErr));
+ expect(SavedObjectsClientEsUnavailable(findErr));
expect(findErr?.output?.payload?.error).toBe('Service Unavailable');
});
@@ -405,7 +399,7 @@ describe('404s from proxies', () => {
} catch (err) {
deleteErr = err;
}
- expect(genericNotFoundEsUnavailableError(deleteErr, 'my_type', 'myTypeId1'));
+ expect(SavedObjectsClientEsUnavailable(deleteErr));
});
it('returns an EsUnavailable error on `bulkResolve` requests with a 404 proxy response and wrong product header for an exact match', async () => {
@@ -417,7 +411,7 @@ describe('404s from proxies', () => {
} catch (err) {
testBulkResolveErr = err;
}
- expect(genericNotFoundEsUnavailableError(testBulkResolveErr));
+ expect(SavedObjectsClientEsUnavailable(testBulkResolveErr));
});
it('returns an EsUnavailable error on `resolve` requests with a 404 proxy response and wrong product header for an exact match', async () => {
@@ -428,7 +422,7 @@ describe('404s from proxies', () => {
} catch (err) {
testResolveErr = err;
}
- expect(genericNotFoundEsUnavailableError(testResolveErr));
+ expect(SavedObjectsClientEsUnavailable(testResolveErr));
});
it('returns an EsUnavailable error on `bulkGet` requests with a 404 proxy response and wrong product header', async () => {
@@ -440,7 +434,7 @@ describe('404s from proxies', () => {
} catch (err) {
bulkGetError = err;
}
- expect(genericNotFoundEsUnavailableError(bulkGetError));
+ expect(SavedObjectsClientEsUnavailable(bulkGetError));
});
it('returns an EsUnavailable error on `openPointInTimeForType` requests with a 404 proxy response and wrong product header', async () => {
@@ -451,7 +445,7 @@ describe('404s from proxies', () => {
} catch (err) {
openPitErr = err;
}
- expect(genericNotFoundEsUnavailableError(openPitErr));
+ expect(SavedObjectsClientEsUnavailable(openPitErr));
});
it('returns an EsUnavailable error on `checkConflicts` requests with a 404 proxy response and wrong product header', async () => {
@@ -468,7 +462,7 @@ describe('404s from proxies', () => {
} catch (err) {
checkConflictsErr = err;
}
- expect(genericNotFoundEsUnavailableError(checkConflictsErr));
+ expect(SavedObjectsClientEsUnavailable(checkConflictsErr));
});
it('returns an EsUnavailable error on `deleteByNamespace` requests with a 404 proxy response and wrong product header', async () => {
@@ -479,7 +473,7 @@ describe('404s from proxies', () => {
} catch (err) {
deleteByNamespaceErr = err;
}
- expect(genericNotFoundEsUnavailableError(deleteByNamespaceErr));
+ expect(SavedObjectsClientEsUnavailable(deleteByNamespaceErr));
});
});
});
diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.mock.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.mock.ts
index fbd774f1c10d5..513add01cdd83 100644
--- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.mock.ts
+++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.mock.ts
@@ -7,7 +7,6 @@
*/
import type * as InternalUtils from './internal_utils';
-import type { isNotFoundFromUnsupportedServer } from '../../../elasticsearch';
export const mockGetSavedObjectFromSource = jest.fn() as jest.MockedFunction<
typeof InternalUtils['getSavedObjectFromSource']
@@ -24,14 +23,3 @@ jest.mock('./internal_utils', () => {
rawDocExistsInNamespace: mockRawDocExistsInNamespace,
};
});
-
-export const mockIsNotFoundFromUnsupportedServer = jest.fn() as jest.MockedFunction<
- typeof isNotFoundFromUnsupportedServer
->;
-jest.mock('../../../elasticsearch', () => {
- const actual = jest.requireActual('../../../elasticsearch');
- return {
- ...actual,
- isNotFoundFromUnsupportedServer: mockIsNotFoundFromUnsupportedServer,
- };
-});
diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts
index 5403e146509ae..4120b077a8981 100644
--- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts
+++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.test.ts
@@ -9,7 +9,6 @@
import {
mockGetSavedObjectFromSource,
mockRawDocExistsInNamespace,
- mockIsNotFoundFromUnsupportedServer,
} from './internal_bulk_resolve.test.mock';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
@@ -35,8 +34,6 @@ beforeEach(() => {
);
mockRawDocExistsInNamespace.mockReset();
mockRawDocExistsInNamespace.mockReturnValue(true); // return true by default
- mockIsNotFoundFromUnsupportedServer.mockReset();
- mockIsNotFoundFromUnsupportedServer.mockReturnValue(false);
});
describe('internalBulkResolve', () => {
@@ -173,24 +170,6 @@ describe('internalBulkResolve', () => {
return { saved_object: `mock-obj-for-${id}`, outcome: 'conflict', alias_target_id };
}
- it('throws if mget call results in non-ES-originated 404 error', async () => {
- const objects = [{ type: OBJ_TYPE, id: '1' }];
- const params = setup(objects, { namespace: 'space-x' });
- mockBulkResults(
- { found: false } // fetch alias for obj 1
- );
- mockMgetResults(
- { found: false } // fetch obj 1 (actual result body doesn't matter, just needs statusCode and headers)
- );
- mockIsNotFoundFromUnsupportedServer.mockReturnValue(true);
-
- await expect(() => internalBulkResolve(params)).rejects.toThrow(
- SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError()
- );
- expect(client.bulk).toHaveBeenCalledTimes(1);
- expect(client.mget).toHaveBeenCalledTimes(1);
- });
-
it('returns an empty array if no object args are passed in', async () => {
const params = setup([], { namespace: 'space-x' });
diff --git a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts
index f53a85a9a03ef..19f774fb068b6 100644
--- a/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts
+++ b/src/core/server/saved_objects/service/lib/internal_bulk_resolve.ts
@@ -6,14 +6,13 @@
* Side Public License, v 1.
*/
-import type { MgetHit } from '@elastic/elasticsearch/api/types';
+import type { MgetHit } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
CORE_USAGE_STATS_ID,
CORE_USAGE_STATS_TYPE,
REPOSITORY_RESOLVE_OUTCOME_STATS,
} from '../../../core_usage_data';
-import { isNotFoundFromUnsupportedServer } from '../../../elasticsearch';
import { LegacyUrlAlias, LEGACY_URL_ALIAS_TYPE } from '../../object_types';
import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry';
import type { SavedObjectsRawDocSource, SavedObjectsSerializer } from '../../serialization';
@@ -141,16 +140,6 @@ export async function internalBulkResolve(
{ ignore: [404] }
)
: undefined;
- // exit early if a 404 isn't from elasticsearch
- if (
- bulkGetResponse &&
- isNotFoundFromUnsupportedServer({
- statusCode: bulkGetResponse.statusCode,
- headers: bulkGetResponse.headers,
- })
- ) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
let getResponseIndex = 0;
let aliasTargetIndex = 0;
diff --git a/src/core/server/saved_objects/service/lib/point_in_time_finder.ts b/src/core/server/saved_objects/service/lib/point_in_time_finder.ts
index 9faf5e85085ed..e7f3e9c378e90 100644
--- a/src/core/server/saved_objects/service/lib/point_in_time_finder.ts
+++ b/src/core/server/saved_objects/service/lib/point_in_time_finder.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { Logger } from '../../../logging';
import type { SavedObjectsFindOptions, SavedObjectsClientContract } from '../../types';
import type { SavedObjectsFindResponse } from '../';
diff --git a/src/core/server/saved_objects/service/lib/repository.test.js b/src/core/server/saved_objects/service/lib/repository.test.js
index 985d609f2da59..32b13ba160d5e 100644
--- a/src/core/server/saved_objects/service/lib/repository.test.js
+++ b/src/core/server/saved_objects/service/lib/repository.test.js
@@ -46,8 +46,6 @@ const createGenericNotFoundError = (...args) =>
SavedObjectsErrorHelpers.createGenericNotFoundError(...args).output.payload;
const createUnsupportedTypeError = (...args) =>
SavedObjectsErrorHelpers.createUnsupportedTypeError(...args).output.payload;
-const createGenericNotFoundEsUnavailableError = (...args) =>
- SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError(...args).output.payload;
describe('SavedObjectsRepository', () => {
let client;
@@ -690,29 +688,6 @@ describe('SavedObjectsRepository', () => {
});
};
- const unsupportedProductBulkCreateMgetError = async (objects, options) => {
- const multiNamespaceObjects = objects.filter(
- ({ type, id }) => registry.isMultiNamespace(type) && id
- );
- if (multiNamespaceObjects?.length) {
- const response = getMockMgetResponse(multiNamespaceObjects, options?.namespace);
- client.mget.mockResolvedValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { ...response },
- { statusCode: 404 },
- {}
- )
- );
- }
- const response = getMockBulkCreateResponse(objects, options?.namespace);
- client.bulk.mockResolvedValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
- await expect(savedObjectsRepository.bulkCreate(objects, options)).rejects.toThrowError(
- createGenericNotFoundEsUnavailableError()
- );
- };
-
it(`throws when options.namespace is '*'`, async () => {
await expect(
savedObjectsRepository.bulkCreate([obj3], { namespace: ALL_NAMESPACES_STRING })
@@ -868,13 +843,6 @@ describe('SavedObjectsRepository', () => {
const expectedErrorResult = { type: obj3.type, id: obj3.id, error: 'Oh no, a bulk error!' };
await bulkCreateError(obj3, true, expectedErrorResult);
});
-
- it(`throws when ES mget action returns 404 with missing Elasticsearch header`, async () => {
- const objects = [obj1, { ...obj2, type: MULTI_NAMESPACE_ISOLATED_TYPE }];
- await unsupportedProductBulkCreateMgetError(objects);
- expect(client.mget).toHaveBeenCalledTimes(1);
- expect(client.bulk).toHaveBeenCalledTimes(0);
- });
});
describe('migration', () => {
@@ -1136,21 +1104,6 @@ describe('SavedObjectsRepository', () => {
});
};
- const unsupportedProductBulkGetMgetError = async (objects, options) => {
- const response = getMockMgetResponse(objects, options?.namespace);
- client.mget.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { ...response },
- { statusCode: 404 },
- {}
- )
- );
- await expect(bulkGet(objects, options)).rejects.toThrowError(
- createGenericNotFoundEsUnavailableError()
- );
- expect(client.mget).toHaveBeenCalledTimes(1);
- };
-
it(`throws when options.namespace is '*'`, async () => {
const obj = { type: 'dashboard', id: 'three' };
await expect(
@@ -1218,12 +1171,6 @@ describe('SavedObjectsRepository', () => {
};
await bulkGetError(obj, true, expectErrorNotFound(obj));
});
-
- it(`throws when ES mget action responds with a 404 and a missing Elasticsearch product header`, async () => {
- const getId = (type, id) => `${type}:${id}`;
- await unsupportedProductBulkGetMgetError([obj1, obj2]); // returns 404 without required product header
- _expectClientCallArgs([obj1, obj2], { getId });
- });
});
describe('returns', () => {
@@ -1681,34 +1628,6 @@ describe('SavedObjectsRepository', () => {
saved_objects: [expectSuccess(obj1), expectErrorNotFound(_obj), expectSuccess(obj2)],
});
};
- const unsupportedProductBulkUpdateMgetError = async (objects, options, includeOriginId) => {
- const multiNamespaceObjects = objects.filter(({ type }) => registry.isMultiNamespace(type));
- if (multiNamespaceObjects?.length) {
- const response = getMockMgetResponse(multiNamespaceObjects, options?.namespace);
- client.mget.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { ...response },
- { statusCode: 404 },
- {}
- )
- );
- }
- const response = getMockBulkUpdateResponse(objects, options?.namespace, includeOriginId);
- client.bulk.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(response)
- );
-
- await expect(savedObjectsRepository.bulkUpdate(objects, options)).rejects.toThrowError(
- createGenericNotFoundEsUnavailableError()
- );
- expect(client.mget).toHaveBeenCalledTimes(multiNamespaceObjects?.length ? 1 : 0);
- };
-
- it(`throws when ES mget action responds with a 404 and a missing Elasticsearch product header`, async () => {
- const objects = [obj1, { ...obj2, type: MULTI_NAMESPACE_ISOLATED_TYPE }];
- await unsupportedProductBulkUpdateMgetError(objects);
- expect(client.mget).toHaveBeenCalledTimes(1);
- });
it(`throws when options.namespace is '*'`, async () => {
await expect(
@@ -1910,24 +1829,6 @@ describe('SavedObjectsRepository', () => {
savedObjectsRepository.checkConflicts([obj1], { namespace: ALL_NAMESPACES_STRING })
).rejects.toThrowError(createBadRequestError('"options.namespace" cannot be "*"'));
});
-
- it(`throws when not found responses aren't from Elasticsearch`, async () => {
- const checkConflictsMgetError = async (objects, options) => {
- const response = getMockMgetResponse(objects, options?.namespace);
- client.mget.mockResolvedValue(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { ...response },
- { statusCode: 404 },
- {}
- )
- );
- await expect(checkConflicts(objects, options)).rejects.toThrowError(
- createGenericNotFoundEsUnavailableError()
- );
- expect(client.mget).toHaveBeenCalledTimes(1);
- };
- await checkConflictsMgetError([obj1, obj2], { namespace: 'default' });
- });
});
describe('returns', () => {
@@ -2515,11 +2416,6 @@ describe('SavedObjectsRepository', () => {
createGenericNotFoundError(type, id)
);
};
- const expectNotFoundEsUnavailableError = async (type, id) => {
- await expect(savedObjectsRepository.delete(type, id)).rejects.toThrowError(
- createGenericNotFoundEsUnavailableError(type, id)
- );
- };
it(`throws when options.namespace is '*'`, async () => {
await expect(
@@ -2553,24 +2449,6 @@ describe('SavedObjectsRepository', () => {
expect(client.get).toHaveBeenCalledTimes(1);
});
- it(`throws when ES is unable to find the document during get with missing Elasticsearch header`, async () => {
- client.get.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { found: false },
- { statusCode: 404 },
- {}
- )
- );
- await expectNotFoundEsUnavailableError(MULTI_NAMESPACE_ISOLATED_TYPE, id);
- });
-
- it(`throws when ES is unable to find the index during get with missing Elasticsearch header`, async () => {
- client.get.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }, {})
- );
- await expectNotFoundEsUnavailableError(MULTI_NAMESPACE_ISOLATED_TYPE, id);
- });
-
it(`throws when the type is multi-namespace and the document exists, but not in this namespace`, async () => {
const response = getMockGetResponse({ type: MULTI_NAMESPACE_ISOLATED_TYPE, id }, namespace);
client.get.mockResolvedValueOnce(
@@ -2885,22 +2763,6 @@ describe('SavedObjectsRepository', () => {
savedObjectsRepository.removeReferencesTo(type, id, defaultOptions)
).rejects.toThrowError(createConflictError(type, id));
});
-
- it(`throws on 404 with missing Elasticsearch header`, async () => {
- client.updateByQuery.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- {
- updated: updatedCount,
- },
- { statusCode: 404 },
- {}
- )
- );
- await expect(
- savedObjectsRepository.removeReferencesTo(type, id, defaultOptions)
- ).rejects.toThrowError(createGenericNotFoundEsUnavailableError(type, id));
- expect(client.updateByQuery).toHaveBeenCalledTimes(1);
- });
});
});
@@ -3077,21 +2939,6 @@ describe('SavedObjectsRepository', () => {
});
describe('errors', () => {
- const findNotSupportedServerError = async (options, namespace) => {
- const expectedSearchResults = generateSearchResults(namespace);
- client.search.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { ...expectedSearchResults },
- { statusCode: 404 },
- {}
- )
- );
- await expect(savedObjectsRepository.find(options)).rejects.toThrowError(
- createGenericNotFoundEsUnavailableError()
- );
- expect(getSearchDslNS.getSearchDsl).toHaveBeenCalledTimes(1);
- expect(client.search).toHaveBeenCalledTimes(1);
- };
it(`throws when type is not defined`, async () => {
await expect(savedObjectsRepository.find({})).rejects.toThrowError(
'options.type must be a string or an array of strings'
@@ -3172,11 +3019,6 @@ describe('SavedObjectsRepository', () => {
expect(getSearchDslNS.getSearchDsl).not.toHaveBeenCalled();
expect(client.search).not.toHaveBeenCalled();
});
-
- it(`throws when ES is unable to find with missing Elasticsearch`, async () => {
- await findNotSupportedServerError({ type });
- expect(client.search).toHaveBeenCalledTimes(1);
- });
});
describe('returns', () => {
@@ -3548,11 +3390,6 @@ describe('SavedObjectsRepository', () => {
createGenericNotFoundError(type, id)
);
};
- const expectNotFoundEsUnavailableError = async (type, id) => {
- await expect(savedObjectsRepository.get(type, id)).rejects.toThrowError(
- createGenericNotFoundEsUnavailableError(type, id)
- );
- };
it(`throws when options.namespace is '*'`, async () => {
await expect(
@@ -3596,19 +3433,6 @@ describe('SavedObjectsRepository', () => {
});
expect(client.get).toHaveBeenCalledTimes(1);
});
-
- it(`throws when ES does not return the correct header when finding the document during get`, async () => {
- client.get.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { found: false },
- { statusCode: 404 },
- {}
- )
- );
- await expectNotFoundEsUnavailableError(type, id);
-
- expect(client.get).toHaveBeenCalledTimes(1);
- });
});
describe('returns', () => {
@@ -4279,11 +4103,6 @@ describe('SavedObjectsRepository', () => {
createGenericNotFoundError(type, id)
);
};
- const expectNotFoundEsUnavailableError = async (type, id) => {
- await expect(savedObjectsRepository.update(type, id)).rejects.toThrowError(
- createGenericNotFoundEsUnavailableError(type, id)
- );
- };
it(`throws when options.namespace is '*'`, async () => {
await expect(
@@ -4317,26 +4136,6 @@ describe('SavedObjectsRepository', () => {
expect(client.get).toHaveBeenCalledTimes(1);
});
- it(`throws when ES is unable to find the document during get with missing Elasticsearch header`, async () => {
- client.get.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { found: false },
- { statusCode: 404 },
- {}
- )
- );
- await expectNotFoundEsUnavailableError(MULTI_NAMESPACE_ISOLATED_TYPE, id);
- expect(client.get).toHaveBeenCalledTimes(1);
- });
-
- it(`throws when ES is unable to find the index during get with missing Elasticsearch header`, async () => {
- client.get.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 }, {})
- );
- await expectNotFoundEsUnavailableError(MULTI_NAMESPACE_ISOLATED_TYPE, id);
- expect(client.get).toHaveBeenCalledTimes(1);
- });
-
it(`throws when type is multi-namespace and the document exists, but not in this namespace`, async () => {
const response = getMockGetResponse({ type: MULTI_NAMESPACE_ISOLATED_TYPE, id }, namespace);
client.get.mockResolvedValueOnce(
@@ -4458,21 +4257,6 @@ describe('SavedObjectsRepository', () => {
);
};
- const unsupportedProductExpectNotFoundError = async (type, options) => {
- const results = generateResults();
- client.openPointInTime.mockResolvedValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- { ...results },
- { statusCode: 404 },
- {}
- )
- );
- await expect(
- savedObjectsRepository.openPointInTimeForType(type, options)
- ).rejects.toThrowError(createGenericNotFoundEsUnavailableError());
- expect(client.openPointInTime).toHaveBeenCalledTimes(1);
- };
-
it(`throws when ES is unable to find the index`, async () => {
client.openPointInTime.mockResolvedValueOnce(
elasticsearchClientMock.createSuccessTransportRequestPromise({}, { statusCode: 404 })
@@ -4491,11 +4275,6 @@ describe('SavedObjectsRepository', () => {
await test(HIDDEN_TYPE);
await test(['unknownType', HIDDEN_TYPE]);
});
-
- it(`throws on 404 with missing Elasticsearch product header`, async () => {
- await unsupportedProductExpectNotFoundError(type);
- expect(client.openPointInTime).toHaveBeenCalledTimes(1);
- });
});
describe('returns', () => {
diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts
index 6798f411d87a9..9f69396fac838 100644
--- a/src/core/server/saved_objects/service/lib/repository.ts
+++ b/src/core/server/saved_objects/service/lib/repository.ts
@@ -7,10 +7,9 @@
*/
import { omit, isObject } from 'lodash';
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as esKuery from '@kbn/es-query';
import type { ElasticsearchClient } from '../../../elasticsearch/';
-import { isSupportedEsServer, isNotFoundFromUnsupportedServer } from '../../../elasticsearch';
import type { Logger } from '../../../logging';
import { getRootPropertiesObjects, IndexMapping } from '../../mappings';
import {
@@ -366,15 +365,11 @@ export class SavedObjectsRepository {
require_alias: true,
};
- const { body, statusCode, headers } =
+ const { body } =
id && overwrite
? await this.client.index(requestParams)
: await this.client.create(requestParams);
- // throw if we can't verify a 404 response is from Elasticsearch
- if (isNotFoundFromUnsupportedServer({ statusCode, headers })) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError(id, type);
- }
return this._rawToSavedObject({
...raw,
...body,
@@ -462,16 +457,7 @@ export class SavedObjectsRepository {
{ ignore: [404] }
)
: undefined;
- // throw if we can't verify a 404 response is from Elasticsearch
- if (
- bulkGetResponse &&
- isNotFoundFromUnsupportedServer({
- statusCode: bulkGetResponse.statusCode,
- headers: bulkGetResponse.headers,
- })
- ) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
+
let bulkRequestIndexCounter = 0;
const bulkCreateParams: object[] = [];
const expectedBulkResults: Array, Record>> =
@@ -650,16 +636,7 @@ export class SavedObjectsRepository {
{ ignore: [404] }
)
: undefined;
- // throw if we can't verify a 404 response is from Elasticsearch
- if (
- bulkGetResponse &&
- isNotFoundFromUnsupportedServer({
- statusCode: bulkGetResponse.statusCode,
- headers: bulkGetResponse.headers,
- })
- ) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
+
const errors: SavedObjectsCheckConflictsResponse['errors'] = [];
expectedBulkGetResults.forEach((expectedResult) => {
if (isLeft(expectedResult)) {
@@ -731,7 +708,7 @@ export class SavedObjectsRepository {
}
}
- const { body, statusCode, headers } = await this.client.delete(
+ const { body, statusCode } = await this.client.delete(
{
id: rawId,
index: this.getIndexForType(type),
@@ -741,10 +718,6 @@ export class SavedObjectsRepository {
{ ignore: [404] }
);
- if (isNotFoundFromUnsupportedServer({ statusCode, headers })) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError(type, id);
- }
-
const deleted = body.result === 'deleted';
if (deleted) {
return {};
@@ -793,7 +766,7 @@ export class SavedObjectsRepository {
const match2 = buildNode('not', buildNode('is', 'type', LEGACY_URL_ALIAS_TYPE));
const kueryNode = buildNode('or', [match1, match2]);
- const { body, statusCode, headers } = await this.client.updateByQuery(
+ const { body } = await this.client.updateByQuery(
{
index: this.getIndicesForTypes(typesToUpdate),
refresh: options.refresh,
@@ -822,10 +795,6 @@ export class SavedObjectsRepository {
},
{ ignore: [404] }
);
- // throw if we can't verify a 404 response is from Elasticsearch
- if (isNotFoundFromUnsupportedServer({ statusCode, headers })) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
return body;
}
@@ -970,16 +939,10 @@ export class SavedObjectsRepository {
},
};
- const { body, statusCode, headers } = await this.client.search(
- esOptions,
- {
- ignore: [404],
- }
- );
+ const { body, statusCode } = await this.client.search(esOptions, {
+ ignore: [404],
+ });
if (statusCode === 404) {
- if (!isSupportedEsServer(headers)) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
// 404 is only possible here if the index is missing, which
// we don't want to leak, see "404s from missing index" above
return {
@@ -1086,16 +1049,7 @@ export class SavedObjectsRepository {
{ ignore: [404] }
)
: undefined;
- // fail fast if we can't verify a 404 is from Elasticsearch
- if (
- bulkGetResponse &&
- isNotFoundFromUnsupportedServer({
- statusCode: bulkGetResponse.statusCode,
- headers: bulkGetResponse.headers,
- })
- ) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
+
return {
saved_objects: expectedBulkGetResults.map((expectedResult) => {
if (isLeft(expectedResult)) {
@@ -1186,7 +1140,7 @@ export class SavedObjectsRepository {
throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id);
}
const namespace = normalizeNamespace(options.namespace);
- const { body, statusCode, headers } = await this.client.get(
+ const { body, statusCode } = await this.client.get(
{
id: this._serializer.generateRawId(namespace, type, id),
index: this.getIndexForType(type),
@@ -1194,10 +1148,7 @@ export class SavedObjectsRepository {
{ ignore: [404] }
);
const indexNotFound = statusCode === 404;
- // check if we have the elasticsearch header when index is not found and if we do, ensure it is Elasticsearch
- if (indexNotFound && !isSupportedEsServer(headers)) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError(type, id);
- }
+
if (
!isFoundGetResponse(body) ||
indexNotFound ||
@@ -1326,9 +1277,6 @@ export class SavedObjectsRepository {
require_alias: true,
})
.catch((err) => {
- if (SavedObjectsErrorHelpers.isEsUnavailableError(err)) {
- throw err;
- }
if (SavedObjectsErrorHelpers.isNotFoundError(err)) {
// see "404s from missing index" above
throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id);
@@ -1501,16 +1449,7 @@ export class SavedObjectsRepository {
}
)
: undefined;
- // fail fast if we can't verify a 404 response is from Elasticsearch
- if (
- bulkGetResponse &&
- isNotFoundFromUnsupportedServer({
- statusCode: bulkGetResponse.statusCode,
- headers: bulkGetResponse.headers,
- })
- ) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
+
let bulkUpdateRequestIndexCounter = 0;
const bulkUpdateParams: object[] = [];
const expectedBulkUpdateResults: Array, Record>> =
@@ -1644,7 +1583,7 @@ export class SavedObjectsRepository {
// we need to target all SO indices as all types of objects may have references to the given SO.
const targetIndices = this.getIndicesForTypes(allTypes);
- const { body, statusCode, headers } = await this.client.updateByQuery(
+ const { body } = await this.client.updateByQuery(
{
index: targetIndices,
refresh,
@@ -1677,10 +1616,7 @@ export class SavedObjectsRepository {
},
{ ignore: [404] }
);
- // fail fast if we can't verify a 404 is from Elasticsearch
- if (isNotFoundFromUnsupportedServer({ statusCode, headers })) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError(type, id);
- }
+
if (body.failures?.length) {
throw SavedObjectsErrorHelpers.createConflictError(
type,
@@ -1954,15 +1890,12 @@ export class SavedObjectsRepository {
...(preference ? { preference } : {}),
};
- const { body, statusCode, headers } = await this.client.openPointInTime(esOptions, {
+ const { body, statusCode } = await this.client.openPointInTime(esOptions, {
ignore: [404],
});
+
if (statusCode === 404) {
- if (!isSupportedEsServer(headers)) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- } else {
- throw SavedObjectsErrorHelpers.createGenericNotFoundError();
- }
+ throw SavedObjectsErrorHelpers.createGenericNotFoundError();
}
return {
@@ -2133,7 +2066,7 @@ export class SavedObjectsRepository {
throw new Error(`Cannot make preflight get request for non-multi-namespace type '${type}'.`);
}
- const { body, statusCode, headers } = await this.client.get(
+ const { body, statusCode } = await this.client.get(
{
id: this._serializer.generateRawId(undefined, type, id),
index: this.getIndexForType(type),
@@ -2155,9 +2088,6 @@ export class SavedObjectsRepository {
savedObjectNamespaces: initialNamespaces ?? getSavedObjectNamespaces(namespace, body),
rawDocSource: body,
};
- } else if (isNotFoundFromUnsupportedServer({ statusCode, headers })) {
- // checking if the 404 is from Elasticsearch
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError(type, id);
}
return {
checkResult: 'not_found',
diff --git a/src/core/server/saved_objects/service/lib/repository_es_client.ts b/src/core/server/saved_objects/service/lib/repository_es_client.ts
index 4e8592fa94cca..4c1ae294cc7db 100644
--- a/src/core/server/saved_objects/service/lib/repository_es_client.ts
+++ b/src/core/server/saved_objects/service/lib/repository_es_client.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport';
+import type { TransportRequestOptions } from '@elastic/elasticsearch';
import { ElasticsearchClient } from '../../../elasticsearch/';
import { retryCallCluster } from '../../../elasticsearch/client/retry_call_cluster';
diff --git a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts
index 3196a59ca39ee..f2cf0013dfe08 100644
--- a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts
+++ b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts
@@ -8,7 +8,7 @@
import Boom from '@hapi/boom';
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IndexMapping } from '../../../mappings';
import { SavedObjectsPitParams } from '../../../types';
import { getQueryParams, HasReferenceQueryParams, SearchOperator } from './query_params';
diff --git a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts
index 592110a5413ec..2a3dca2629098 100644
--- a/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts
+++ b/src/core/server/saved_objects/service/lib/search_dsl/sorting_params.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import Boom from '@hapi/boom';
import { getProperty, IndexMapping } from '../../../mappings';
diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts
index ba15fbabfba6b..11dbe6149878c 100644
--- a/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts
+++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.test.ts
@@ -23,7 +23,6 @@ import type {
UpdateObjectsSpacesParams,
} from './update_objects_spaces';
import { updateObjectsSpaces } from './update_objects_spaces';
-import { SavedObjectsErrorHelpers } from './errors';
type SetupParams = Partial<
Pick
@@ -106,32 +105,6 @@ describe('#updateObjectsSpaces', () => {
})
);
}
- /** Mocks the saved objects client so as to test unsupported server responding with 404 */
- function mockMgetResultsNotFound(...results: Array<{ found: boolean }>) {
- client.mget.mockReturnValueOnce(
- elasticsearchClientMock.createSuccessTransportRequestPromise(
- {
- docs: results.map((x) =>
- x.found
- ? {
- _id: 'doesnt-matter',
- _index: 'doesnt-matter',
- _source: { namespaces: [EXISTING_SPACE] },
- ...VERSION_PROPS,
- found: true,
- }
- : {
- _id: 'doesnt-matter',
- _index: 'doesnt-matter',
- found: false,
- }
- ),
- },
- { statusCode: 404 },
- {}
- )
- );
- }
/** Asserts that mget is called for the given objects */
function expectMgetArgs(...objects: SavedObjectsUpdateObjectsSpacesObject[]) {
@@ -267,17 +240,6 @@ describe('#updateObjectsSpaces', () => {
{ ...obj7, spaces: [EXISTING_SPACE, 'foo-space'] },
]);
});
-
- it('throws when mget not found response is missing the Elasticsearch header', async () => {
- const objects = [{ type: SHAREABLE_OBJ_TYPE, id: 'id-1' }];
- const spacesToAdd = ['foo-space'];
- const params = setup({ objects, spacesToAdd });
- mockMgetResultsNotFound({ found: true });
-
- await expect(() => updateObjectsSpaces(params)).rejects.toThrowError(
- SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError()
- );
- });
});
// Note: these test cases do not include requested objects that will result in errors (those are covered above)
diff --git a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts
index 6d7c272c26eec..d88bf700a900e 100644
--- a/src/core/server/saved_objects/service/lib/update_objects_spaces.ts
+++ b/src/core/server/saved_objects/service/lib/update_objects_spaces.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import intersection from 'lodash/intersection';
import type { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry';
@@ -28,7 +28,6 @@ import {
} from './internal_utils';
import { DEFAULT_REFRESH_SETTING } from './repository';
import type { RepositoryEsClient } from './repository_es_client';
-import { isNotFoundFromUnsupportedServer } from '../../../elasticsearch';
/**
* An object that should have its spaces updated.
@@ -188,16 +187,6 @@ export async function updateObjectsSpaces({
)
: undefined;
- // fail fast if we can't verify a 404 response is from Elasticsearch
- if (
- bulkGetResponse &&
- isNotFoundFromUnsupportedServer({
- statusCode: bulkGetResponse.statusCode,
- headers: bulkGetResponse.headers,
- })
- ) {
- throw SavedObjectsErrorHelpers.createGenericNotFoundEsUnavailableError();
- }
const time = new Date().toISOString();
let bulkOperationRequestIndexCounter = 0;
const bulkOperationParams: estypes.BulkOperationContainer[] = [];
@@ -259,7 +248,6 @@ export async function updateObjectsSpaces({
// @ts-expect-error BulkOperation.retry_on_conflict, BulkOperation.routing. BulkOperation.version, and BulkOperation.version_type are optional
bulkOperationParams.push({ update: documentMetadata }, { doc: documentToSave });
} else {
- // @ts-expect-error BulkOperation.retry_on_conflict, BulkOperation.routing. BulkOperation.version, and BulkOperation.version_type are optional
bulkOperationParams.push({ delete: documentMetadata });
}
}
diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts
index dca8814b2914a..68040d9c6e003 100644
--- a/src/core/server/saved_objects/types.ts
+++ b/src/core/server/saved_objects/types.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SavedObjectsClient } from './service/saved_objects_client';
import { SavedObjectsTypeMappingDefinition } from './mappings';
import { SavedObjectMigrationMap } from './migrations';
diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md
index 632fea5c6660d..f135d8caaf54e 100644
--- a/src/core/server/server.api.md
+++ b/src/core/server/server.api.md
@@ -5,11 +5,10 @@
```ts
import { AddConfigDeprecation } from '@kbn/config';
-import { ApiResponse } from '@elastic/elasticsearch/lib/Transport';
import Boom from '@hapi/boom';
import { ByteSizeValue } from '@kbn/config-schema';
import { CliArgs } from '@kbn/config';
-import { ClientOptions } from '@elastic/elasticsearch';
+import { ClientOptions } from '@elastic/elasticsearch/lib/client';
import { ConfigDeprecation } from '@kbn/config';
import { ConfigDeprecationContext } from '@kbn/config';
import { ConfigDeprecationFactory } from '@kbn/config';
@@ -25,9 +24,9 @@ import { EcsEventKind } from '@kbn/logging';
import { EcsEventOutcome } from '@kbn/logging';
import { EcsEventType } from '@kbn/logging';
import { EnvironmentMode } from '@kbn/config';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IncomingHttpHeaders } from 'http';
-import { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import { Logger } from '@kbn/logging';
import { LoggerFactory } from '@kbn/logging';
import { LogLevel } from '@kbn/logging';
@@ -49,9 +48,9 @@ import { ResponseToolkit } from '@hapi/hapi';
import { SchemaTypeError } from '@kbn/config-schema';
import { ShallowPromise } from '@kbn/utility-types';
import { Stream } from 'stream';
-import { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport';
-import { TransportRequestParams } from '@elastic/elasticsearch/lib/Transport';
-import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport';
+import { TransportRequestOptions } from '@elastic/elasticsearch';
+import { TransportRequestParams } from '@elastic/elasticsearch';
+import { TransportResult } from '@elastic/elasticsearch';
import { Type } from '@kbn/config-schema';
import { TypeOf } from '@kbn/config-schema';
import { UiCounterMetricType } from '@kbn/analytics';
@@ -870,9 +869,9 @@ export { EcsEventOutcome }
export { EcsEventType }
// @public
-export type ElasticsearchClient = Omit & {
+export type ElasticsearchClient = Omit & {
transport: {
- request(params: TransportRequestParams, options?: TransportRequestOptions): TransportRequestPromise;
+ request(params: TransportRequestParams, options?: TransportRequestOptions): Promise>;
};
};
@@ -918,6 +917,15 @@ export interface ElasticsearchConfigPreboot {
readonly hosts: string[];
}
+// @public (undocumented)
+export interface ElasticsearchErrorDetails {
+ // (undocumented)
+ error?: {
+ type: string;
+ reason?: string;
+ };
+}
+
// @public (undocumented)
export interface ElasticsearchServicePreboot {
readonly config: Readonly;
@@ -2171,8 +2179,6 @@ export class SavedObjectsErrorHelpers {
// (undocumented)
static createGenericNotFoundError(type?: string | null, id?: string | null): DecoratedError;
// (undocumented)
- static createGenericNotFoundEsUnavailableError(type?: string | null, id?: string | null): DecoratedError;
- // (undocumented)
static createIndexAliasNotFoundError(alias: string): DecoratedError;
// (undocumented)
static createInvalidVersionError(versionInput?: string): DecoratedError;
@@ -3050,7 +3056,7 @@ export const validBodyOutput: readonly ["data", "stream"];
// Warnings were encountered during analysis:
//
-// src/core/server/elasticsearch/client/types.ts:94:7 - (ae-forgotten-export) The symbol "Explanation" needs to be exported by the entry point index.d.ts
+// src/core/server/elasticsearch/client/types.ts:93:7 - (ae-forgotten-export) The symbol "Explanation" needs to be exported by the entry point index.d.ts
// src/core/server/http/router/response.ts:302:3 - (ae-forgotten-export) The symbol "KibanaResponse" needs to be exported by the entry point index.d.ts
// src/core/server/plugins/types.ts:375:3 - (ae-forgotten-export) The symbol "SharedGlobalConfigKeys" needs to be exported by the entry point index.d.ts
// src/core/server/plugins/types.ts:377:3 - (ae-forgotten-export) The symbol "SavedObjectsConfigType" needs to be exported by the entry point index.d.ts
diff --git a/src/core/server/ui_settings/integration_tests/lib/servers.ts b/src/core/server/ui_settings/integration_tests/lib/servers.ts
index 96ba08a0728ab..d94ab98060a27 100644
--- a/src/core/server/ui_settings/integration_tests/lib/servers.ts
+++ b/src/core/server/ui_settings/integration_tests/lib/servers.ts
@@ -8,7 +8,7 @@
import type supertest from 'supertest';
import type { SavedObjectsClientContract, IUiSettingsClient } from 'src/core/server';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
+import type { KibanaClient } from '@elastic/elasticsearch/lib/api/kibana';
import {
createTestServers,
@@ -55,7 +55,7 @@ export function getServices() {
return services;
}
- const esClient = esServer.es.getClient();
+ const esClient = esServer.es.getKibanaEsClient();
const savedObjectsClient = kbn.coreStart.savedObjects.getScopedClient(
httpServerMock.createKibanaRequest()
diff --git a/src/core/types/elasticsearch/index.ts b/src/core/types/elasticsearch/index.ts
index bec611778e6f5..09eff555fc857 100644
--- a/src/core/types/elasticsearch/index.ts
+++ b/src/core/types/elasticsearch/index.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { InferSearchResponseOf, AggregateOf as AggregationResultOf, SearchHit } from './search';
export type ESFilter = estypes.QueryDslQueryContainer;
diff --git a/src/core/types/elasticsearch/search.ts b/src/core/types/elasticsearch/search.ts
index a54f5f3758ce3..2e79bf6fea57c 100644
--- a/src/core/types/elasticsearch/search.ts
+++ b/src/core/types/elasticsearch/search.ts
@@ -7,7 +7,7 @@
*/
import { ValuesType } from 'utility-types';
-import { estypes } from '@elastic/elasticsearch';
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
type InvalidAggregationRequest = unknown;
diff --git a/src/plugins/data/common/search/aggs/agg_configs.ts b/src/plugins/data/common/search/aggs/agg_configs.ts
index 3157735a39967..9a362466c0fd7 100644
--- a/src/plugins/data/common/search/aggs/agg_configs.ts
+++ b/src/plugins/data/common/search/aggs/agg_configs.ts
@@ -11,7 +11,7 @@ import _, { cloneDeep } from 'lodash';
import { i18n } from '@kbn/i18n';
import { Assign } from '@kbn/utility-types';
import { isRangeFilter } from '@kbn/es-query';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
IEsSearchResponse,
diff --git a/src/plugins/data/common/search/aggs/agg_type.ts b/src/plugins/data/common/search/aggs/agg_type.ts
index ebc1705f6c01b..917f80d3b7819 100644
--- a/src/plugins/data/common/search/aggs/agg_type.ts
+++ b/src/plugins/data/common/search/aggs/agg_type.ts
@@ -14,7 +14,7 @@ import { DatatableColumnType } from 'src/plugins/expressions/common';
import type { RequestAdapter } from 'src/plugins/inspector/common';
import type { SerializedFieldFormat } from 'src/plugins/field_formats/common';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { initParams } from './agg_params';
import { AggConfig } from './agg_config';
import { IAggConfigs } from './agg_configs';
diff --git a/src/plugins/data/common/search/aggs/buckets/_terms_other_bucket_helper.ts b/src/plugins/data/common/search/aggs/buckets/_terms_other_bucket_helper.ts
index 436cc5614ac80..ef5066e84f985 100644
--- a/src/plugins/data/common/search/aggs/buckets/_terms_other_bucket_helper.ts
+++ b/src/plugins/data/common/search/aggs/buckets/_terms_other_bucket_helper.ts
@@ -7,7 +7,7 @@
*/
import { isNumber, keys, values, find, each, cloneDeep, flatten } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { buildExistsFilter, buildPhrasesFilter, buildQueryFromFilters } from '@kbn/es-query';
import { AggGroupNames } from '../agg_groups';
import { IAggConfigs } from '../agg_configs';
diff --git a/src/plugins/data/common/search/aggs/utils/time_splits.ts b/src/plugins/data/common/search/aggs/utils/time_splits.ts
index 0510f629540f6..c4a603a383e38 100644
--- a/src/plugins/data/common/search/aggs/utils/time_splits.ts
+++ b/src/plugins/data/common/search/aggs/utils/time_splits.ts
@@ -8,7 +8,7 @@
import moment from 'moment';
import _, { isArray } from 'lodash';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { RangeFilter } from '@kbn/es-query';
import { AggGroupNames } from '../agg_groups';
diff --git a/src/plugins/data/common/search/expressions/es_raw_response.ts b/src/plugins/data/common/search/expressions/es_raw_response.ts
index 2d12af017d88c..61d79939e8635 100644
--- a/src/plugins/data/common/search/expressions/es_raw_response.ts
+++ b/src/plugins/data/common/search/expressions/es_raw_response.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ExpressionTypeDefinition } from '../../../../expressions/common';
const name = 'es_raw_response';
diff --git a/src/plugins/data/common/search/search_source/inspect/inspector_stats.ts b/src/plugins/data/common/search/search_source/inspect/inspector_stats.ts
index 67c23fb16b8de..df32b6ffed2e7 100644
--- a/src/plugins/data/common/search/search_source/inspect/inspector_stats.ts
+++ b/src/plugins/data/common/search/search_source/inspect/inspector_stats.ts
@@ -14,7 +14,7 @@
*/
import { i18n } from '@kbn/i18n';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ISearchSource } from 'src/plugins/data/public';
import type { RequestStatistics } from 'src/plugins/inspector/common';
diff --git a/src/plugins/data/common/search/search_source/search_source.ts b/src/plugins/data/common/search/search_source/search_source.ts
index 7b4537043c31c..50752523403cf 100644
--- a/src/plugins/data/common/search/search_source/search_source.ts
+++ b/src/plugins/data/common/search/search_source/search_source.ts
@@ -71,7 +71,7 @@ import {
tap,
} from 'rxjs/operators';
import { defer, EMPTY, from, Observable } from 'rxjs';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { buildEsQuery, Filter } from '@kbn/es-query';
import { normalizeSortRequest } from './normalize_sort_request';
import { fieldWildcardFilter } from '../../../../kibana_utils/common';
diff --git a/src/plugins/data/common/search/search_source/types.ts b/src/plugins/data/common/search/search_source/types.ts
index a19316c1c8418..c411e53abfcd2 100644
--- a/src/plugins/data/common/search/search_source/types.ts
+++ b/src/plugins/data/common/search/search_source/types.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IAggConfigs } from 'src/plugins/data/public';
import { Query } from '../..';
import { Filter } from '../../es_query';
diff --git a/src/plugins/data/common/search/strategies/eql_search/types.ts b/src/plugins/data/common/search/strategies/eql_search/types.ts
index a30adbaf47c60..7f6ec4809b2c5 100644
--- a/src/plugins/data/common/search/strategies/eql_search/types.ts
+++ b/src/plugins/data/common/search/strategies/eql_search/types.ts
@@ -6,17 +6,17 @@
* Side Public License, v 1.
*/
-import { EqlSearch } from '@elastic/elasticsearch/api/requestParams';
-import { ApiResponse, TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport';
+import type { EqlSearchRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import type { TransportResult, TransportRequestOptions } from '@elastic/elasticsearch';
import { IKibanaSearchRequest, IKibanaSearchResponse } from '../../types';
export const EQL_SEARCH_STRATEGY = 'eql';
-export type EqlRequestParams = EqlSearch>;
+export type EqlRequestParams = EqlSearchRequest;
export interface EqlSearchStrategyRequest extends IKibanaSearchRequest {
options?: TransportRequestOptions;
}
-export type EqlSearchStrategyResponse = IKibanaSearchResponse>;
+export type EqlSearchStrategyResponse = IKibanaSearchResponse>;
diff --git a/src/plugins/data/common/search/strategies/es_search/types.ts b/src/plugins/data/common/search/strategies/es_search/types.ts
index 05df661d466c8..73bf7961fea9b 100644
--- a/src/plugins/data/common/search/strategies/es_search/types.ts
+++ b/src/plugins/data/common/search/strategies/es_search/types.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IKibanaSearchRequest, IKibanaSearchResponse } from '../../types';
diff --git a/src/plugins/data/common/search/tabify/tabify_docs.test.ts b/src/plugins/data/common/search/tabify/tabify_docs.test.ts
index 1964247b09585..8bba487cef9b3 100644
--- a/src/plugins/data/common/search/tabify/tabify_docs.test.ts
+++ b/src/plugins/data/common/search/tabify/tabify_docs.test.ts
@@ -8,7 +8,7 @@
import { tabifyDocs, flattenHit } from './tabify_docs';
import { IndexPattern, DataView } from '../..';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { fieldFormatsMock } from '../../../../field_formats/common/mocks';
import { stubbedSavedObjectIndexPattern } from '../../../../data_views/common/data_view.stub';
diff --git a/src/plugins/data/common/search/tabify/tabify_docs.ts b/src/plugins/data/common/search/tabify/tabify_docs.ts
index 353a0c10ba12a..43b6155f6662f 100644
--- a/src/plugins/data/common/search/tabify/tabify_docs.ts
+++ b/src/plugins/data/common/search/tabify/tabify_docs.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { isPlainObject } from 'lodash';
import { IndexPattern } from '../..';
import { Datatable, DatatableColumn, DatatableColumnType } from '../../../../expressions/common';
diff --git a/src/plugins/data/public/search/errors/types.ts b/src/plugins/data/public/search/errors/types.ts
index 13c5d0c242ed0..d541e53be78f9 100644
--- a/src/plugins/data/public/search/errors/types.ts
+++ b/src/plugins/data/public/search/errors/types.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { KibanaServerError } from '../../../../kibana_utils/common';
export interface FailedShard {
diff --git a/src/plugins/data/public/search/errors/utils.ts b/src/plugins/data/public/search/errors/utils.ts
index cb3e83dc8001c..4373939878d68 100644
--- a/src/plugins/data/public/search/errors/utils.ts
+++ b/src/plugins/data/public/search/errors/utils.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { ErrorCause } from '@elastic/elasticsearch/api/types';
+import type { ErrorCause } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { FailedShard, Reason } from './types';
import { KibanaServerError } from '../../../../kibana_utils/common';
diff --git a/src/plugins/data/public/ui/shard_failure_modal/__mocks__/shard_failure_response.ts b/src/plugins/data/public/ui/shard_failure_modal/__mocks__/shard_failure_response.ts
index e4a31995e47b6..50355a933ec5d 100644
--- a/src/plugins/data/public/ui/shard_failure_modal/__mocks__/shard_failure_response.ts
+++ b/src/plugins/data/public/ui/shard_failure_modal/__mocks__/shard_failure_response.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export const shardFailureResponse: estypes.SearchResponse = {
_shards: {
diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx
index 8e6ad4bc92c8f..e009af4250e6c 100644
--- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx
+++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_modal.tsx
@@ -21,7 +21,7 @@ import {
EuiButtonEmpty,
EuiCallOut,
} from '@elastic/eui';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ShardFailureTable } from './shard_failure_table';
import { ShardFailureRequest } from './shard_failure_types';
diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_open_modal_button.tsx b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_open_modal_button.tsx
index a230378d6c3d3..4ebdd64fede13 100644
--- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_open_modal_button.tsx
+++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_open_modal_button.tsx
@@ -9,7 +9,7 @@
import React from 'react';
import { FormattedMessage } from '@kbn/i18n/react';
import { EuiButton, EuiTextAlign } from '@elastic/eui';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { getOverlays } from '../../services';
import { toMountPoint } from '../../../../kibana_react/public';
diff --git a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts
index 83e4abf55d525..c6533f9f0a850 100644
--- a/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts
+++ b/src/plugins/data/public/ui/shard_failure_modal/shard_failure_types.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export interface ShardFailureRequest {
docvalue_fields: string[];
_source: unknown;
diff --git a/src/plugins/data/server/autocomplete/terms_agg.test.ts b/src/plugins/data/server/autocomplete/terms_agg.test.ts
index dcaa5390f3fe6..eb24b71cae274 100644
--- a/src/plugins/data/server/autocomplete/terms_agg.test.ts
+++ b/src/plugins/data/server/autocomplete/terms_agg.test.ts
@@ -10,9 +10,9 @@ import { coreMock } from '../../../../core/server/mocks';
import { ElasticsearchClient, SavedObjectsClientContract } from 'kibana/server';
import { ConfigSchema } from '../../config';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-import type { ApiResponse } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
import { termsAggSuggestions } from './terms_agg';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { duration } from 'moment';
let savedObjectsClientMock: jest.Mocked;
@@ -32,7 +32,7 @@ const mockResponse = {
},
},
},
-} as ApiResponse>;
+} as TransportResult>;
jest.mock('../data_views');
diff --git a/src/plugins/data/server/autocomplete/terms_agg.ts b/src/plugins/data/server/autocomplete/terms_agg.ts
index 41544b9e01233..20a8a5c212f26 100644
--- a/src/plugins/data/server/autocomplete/terms_agg.ts
+++ b/src/plugins/data/server/autocomplete/terms_agg.ts
@@ -8,11 +8,10 @@
import { get, map } from 'lodash';
import { ElasticsearchClient, SavedObjectsClientContract } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ConfigSchema } from '../../config';
import { IFieldType, getFieldSubtypeNested } from '../../common';
import { findIndexPatternById, getFieldByName } from '../data_views';
-import { shimAbortSignal } from '../search';
export async function termsAggSuggestions(
config: ConfigSchema,
@@ -38,8 +37,12 @@ export async function termsAggSuggestions(
const body = await getBody(autocompleteSearchOptions, field ?? fieldName, query, filters);
- const promise = esClient.search({ index, body });
- const result = await shimAbortSignal(promise, abortSignal);
+ const result = await esClient.search(
+ { index, body },
+ {
+ signal: abortSignal,
+ }
+ );
const buckets =
get(result.body, 'aggregations.suggestions.buckets') ||
diff --git a/src/plugins/data/server/autocomplete/terms_enum.test.ts b/src/plugins/data/server/autocomplete/terms_enum.test.ts
index 444ba4e89c58b..c0750ead5cc0a 100644
--- a/src/plugins/data/server/autocomplete/terms_enum.test.ts
+++ b/src/plugins/data/server/autocomplete/terms_enum.test.ts
@@ -11,8 +11,8 @@ import { coreMock } from '../../../../core/server/mocks';
import { ElasticsearchClient, SavedObjectsClientContract } from 'kibana/server';
import { ConfigSchema } from '../../config';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-import type { ApiResponse } from '@elastic/elasticsearch';
-import { TermsEnumResponse } from '@elastic/elasticsearch/api/types';
+import type { TransportResult } from '@elastic/elasticsearch';
+import { TermsEnumResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
let savedObjectsClientMock: jest.Mocked;
let esClientMock: DeeplyMockedKeys;
@@ -31,7 +31,7 @@ describe('_terms_enum suggestions', () => {
savedObjectsClientMock = requestHandlerContext.savedObjects.client;
esClientMock = requestHandlerContext.elasticsearch.client.asCurrentUser;
esClientMock.termsEnum.mockResolvedValue(
- mockResponse as unknown as ApiResponse
+ mockResponse as unknown as TransportResult
);
});
diff --git a/src/plugins/data/server/autocomplete/terms_enum.ts b/src/plugins/data/server/autocomplete/terms_enum.ts
index 3d7f369233720..201ff32c056ce 100644
--- a/src/plugins/data/server/autocomplete/terms_enum.ts
+++ b/src/plugins/data/server/autocomplete/terms_enum.ts
@@ -7,10 +7,9 @@
*/
import { ElasticsearchClient, SavedObjectsClientContract } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IFieldType } from '../../common';
import { findIndexPatternById, getFieldByName } from '../data_views';
-import { shimAbortSignal } from '../search';
import { ConfigSchema } from '../../config';
export async function termsEnumSuggestions(
@@ -30,26 +29,30 @@ export async function termsEnumSuggestions(
field = indexPattern && getFieldByName(fieldName, indexPattern);
}
- const promise = esClient.termsEnum({
- index,
- body: {
- field: field?.name ?? fieldName,
- string: query,
- index_filter: {
- bool: {
- must: [
- ...(filters ?? []),
- {
- terms: {
- _tier: tiers,
+ const result = await esClient.termsEnum(
+ {
+ index,
+ body: {
+ field: field?.name ?? fieldName,
+ string: query,
+ index_filter: {
+ bool: {
+ must: [
+ ...(filters ?? []),
+ {
+ terms: {
+ _tier: tiers,
+ },
},
- },
- ],
+ ],
+ },
},
},
},
- });
+ {
+ signal: abortSignal,
+ }
+ );
- const result = await shimAbortSignal(promise, abortSignal);
return result.body.terms;
}
diff --git a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts
index 4c75d62f12190..3d9294765cc15 100644
--- a/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts
+++ b/src/plugins/data/server/search/strategies/eql_search/eql_search_strategy.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { ApiResponse } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
import { tap } from 'rxjs/operators';
import type { IScopedClusterClient, Logger } from 'kibana/server';
import {
@@ -18,7 +18,7 @@ import {
import { toEqlKibanaSearchResponse } from './response_utils';
import { EqlSearchResponse } from './types';
import { ISearchStrategy } from '../../types';
-import { getDefaultSearchParams, shimAbortSignal } from '../es_search';
+import { getDefaultSearchParams } from '../es_search';
import { getDefaultAsyncGetParams, getIgnoreThrottled } from '../ese_search/request_utils';
export const eqlSearchStrategyProvider = (
@@ -52,12 +52,15 @@ export const eqlSearchStrategyProvider = (
...getDefaultAsyncGetParams(null, options),
...request.params,
};
- const promise = id
- ? client.get({ ...params, id }, request.options)
- : // @ts-expect-error EqlRequestParams | undefined is not assignable to EqlRequestParams
- client.search(params as EqlSearchStrategyRequest['params'], request.options);
- const response = await shimAbortSignal(promise, options.abortSignal);
- return toEqlKibanaSearchResponse(response as ApiResponse);
+ const response = id
+ ? await client.get({ ...params, id }, { ...request.options, signal: options.abortSignal })
+ : // @ts-expect-error optional key cannot be used since search doesn't expect undefined
+ await client.search(params as EqlSearchStrategyRequest['params'], {
+ ...request.options,
+ abortController: { signal: options.abortSignal },
+ });
+
+ return toEqlKibanaSearchResponse(response as TransportResult);
};
const cancel = async () => {
diff --git a/src/plugins/data/server/search/strategies/eql_search/response_utils.ts b/src/plugins/data/server/search/strategies/eql_search/response_utils.ts
index 11b5a286e709d..f9bdf5bc7de30 100644
--- a/src/plugins/data/server/search/strategies/eql_search/response_utils.ts
+++ b/src/plugins/data/server/search/strategies/eql_search/response_utils.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { ApiResponse } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
import { EqlSearchResponse } from './types';
import { EqlSearchStrategyResponse } from '../../../../common';
@@ -15,7 +15,7 @@ import { EqlSearchStrategyResponse } from '../../../../common';
* (EQL does not provide _shard info, so total/loaded cannot be calculated.)
*/
export function toEqlKibanaSearchResponse(
- response: ApiResponse
+ response: TransportResult
): EqlSearchStrategyResponse {
return {
id: response.body.id,
diff --git a/src/plugins/data/server/search/strategies/eql_search/types.ts b/src/plugins/data/server/search/strategies/eql_search/types.ts
index 4b3c19fda78ea..695490b668e38 100644
--- a/src/plugins/data/server/search/strategies/eql_search/types.ts
+++ b/src/plugins/data/server/search/strategies/eql_search/types.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export interface EqlSearchResponse extends estypes.SearchResponse {
id?: string;
diff --git a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts
index bbbc99d157fe0..c06a75f3148a8 100644
--- a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts
+++ b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.test.ts
@@ -5,18 +5,14 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-
-import {
- elasticsearchClientMock,
- MockedTransportRequestPromise,
- // eslint-disable-next-line @kbn/eslint/no-restricted-paths
-} from '../../../../../../core/server/elasticsearch/client/mocks';
+import type { TransportResult } from '@elastic/elasticsearch';
+import { elasticsearchServiceMock } from '../../../../../../core/server/mocks';
import { pluginInitializerContextConfigMock } from '../../../../../../core/server/mocks';
import { esSearchStrategyProvider } from './es_search_strategy';
import { SearchStrategyDependencies } from '../../types';
import * as indexNotFoundException from '../../../../common/search/test_data/index_not_found_exception.json';
-import { ElasticsearchClientError, ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { KbnServerError } from '../../../../../kibana_utils/server';
describe('ES search strategy', () => {
@@ -27,9 +23,9 @@ describe('ES search strategy', () => {
skipped: 2,
successful: 7,
},
- };
- let mockedApiCaller: MockedTransportRequestPromise;
- let mockApiCaller: jest.Mock<() => MockedTransportRequestPromise>;
+ } as const;
+ let mockedApiCaller: Promise>;
+ let mockApiCaller: jest.Mock<() => TransportResult>;
const mockLogger: any = {
debug: () => {},
};
@@ -37,9 +33,9 @@ describe('ES search strategy', () => {
function getMockedDeps(err?: Record) {
mockApiCaller = jest.fn().mockImplementation(() => {
if (err) {
- mockedApiCaller = elasticsearchClientMock.createErrorTransportRequestPromise(err);
+ mockedApiCaller = elasticsearchServiceMock.createErrorTransportRequestPromise(err);
} else {
- mockedApiCaller = elasticsearchClientMock.createSuccessTransportRequestPromise(
+ mockedApiCaller = elasticsearchServiceMock.createSuccessTransportRequestPromise(
successBody,
{ statusCode: 200 }
);
@@ -108,7 +104,6 @@ describe('ES search strategy', () => {
expect(data.isPartial).toBe(false);
expect(data).toHaveProperty('loaded');
expect(data).toHaveProperty('rawResponse');
- expect(mockedApiCaller.abort).not.toBeCalled();
done();
}));
@@ -127,12 +122,11 @@ describe('ES search strategy', () => {
...params,
track_total_hits: true,
});
- expect(mockedApiCaller.abort).toBeCalled();
});
it('throws normalized error if ResponseError is thrown', async (done) => {
const params = { index: 'logstash-*', ignore_unavailable: false, timeout: '1000ms' };
- const errResponse = new ResponseError({
+ const errResponse = new errors.ResponseError({
body: indexNotFoundException,
statusCode: 404,
headers: {},
@@ -156,7 +150,7 @@ describe('ES search strategy', () => {
it('throws normalized error if ElasticsearchClientError is thrown', async (done) => {
const params = { index: 'logstash-*', ignore_unavailable: false, timeout: '1000ms' };
- const errResponse = new ElasticsearchClientError('This is a general ESClient error');
+ const errResponse = new errors.ElasticsearchClientError('This is a general ESClient error');
try {
await esSearchStrategyProvider(mockConfig$, mockLogger)
diff --git a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.ts b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.ts
index c24aa37082bd8..097e099bf2997 100644
--- a/src/plugins/data/server/search/strategies/es_search/es_search_strategy.ts
+++ b/src/plugins/data/server/search/strategies/es_search/es_search_strategy.ts
@@ -11,7 +11,7 @@ import { first, tap } from 'rxjs/operators';
import type { Logger, SharedGlobalConfig } from 'kibana/server';
import type { ISearchStrategy } from '../../types';
import type { SearchUsage } from '../../collectors';
-import { getDefaultSearchParams, getShardTimeout, shimAbortSignal } from './request_utils';
+import { getDefaultSearchParams, getShardTimeout } from './request_utils';
import { shimHitsTotal, toKibanaSearchResponse } from './response_utils';
import { searchUsageObserver } from '../../collectors/usage';
import { getKbnServerError, KbnServerError } from '../../../../../kibana_utils/server';
@@ -38,13 +38,17 @@ export const esSearchStrategyProvider = (
const search = async () => {
try {
const config = await config$.pipe(first()).toPromise();
+ // @ts-expect-error params fall back to any, but should be valid SearchRequest params
+ const { terminateAfter, ...requestParams } = request.params ?? {};
const params = {
...(await getDefaultSearchParams(uiSettingsClient)),
...getShardTimeout(config),
- ...request.params,
+ ...(terminateAfter ? { terminate_after: terminateAfter } : {}),
+ ...requestParams,
};
- const promise = esClient.asCurrentUser.search(params);
- const { body } = await shimAbortSignal(promise, abortSignal);
+ const { body } = await esClient.asCurrentUser.search(params, {
+ signal: abortSignal,
+ });
const response = shimHitsTotal(body, options);
return toKibanaSearchResponse(response);
} catch (e) {
diff --git a/src/plugins/data/server/search/strategies/es_search/request_utils.test.ts b/src/plugins/data/server/search/strategies/es_search/request_utils.test.ts
index 5d1826d92f182..d6e078c71a87d 100644
--- a/src/plugins/data/server/search/strategies/es_search/request_utils.test.ts
+++ b/src/plugins/data/server/search/strategies/es_search/request_utils.test.ts
@@ -6,19 +6,9 @@
* Side Public License, v 1.
*/
-import { getShardTimeout, getDefaultSearchParams, shimAbortSignal } from './request_utils';
+import { getShardTimeout, getDefaultSearchParams } from './request_utils';
import { IUiSettingsClient, SharedGlobalConfig } from 'kibana/server';
-const createSuccessTransportRequestPromise = (
- body: any,
- { statusCode = 200 }: { statusCode?: number } = {}
-) => {
- const promise = Promise.resolve({ body, statusCode }) as any;
- promise.abort = jest.fn();
-
- return promise;
-};
-
describe('request utils', () => {
describe('getShardTimeout', () => {
test('returns an empty object if the config does not contain a value', () => {
@@ -89,49 +79,4 @@ describe('request utils', () => {
});
});
});
-
- describe('shimAbortSignal', () => {
- test('aborts the promise if the signal is already aborted', async () => {
- const promise = createSuccessTransportRequestPromise({
- success: true,
- });
- const controller = new AbortController();
- controller.abort();
- shimAbortSignal(promise, controller.signal);
-
- expect(promise.abort).toHaveBeenCalled();
- });
-
- test('aborts the promise if the signal is aborted', () => {
- const promise = createSuccessTransportRequestPromise({
- success: true,
- });
- const controller = new AbortController();
- shimAbortSignal(promise, controller.signal);
- controller.abort();
-
- expect(promise.abort).toHaveBeenCalled();
- });
-
- test('returns the original promise', async () => {
- const promise = createSuccessTransportRequestPromise({
- success: true,
- });
- const controller = new AbortController();
- const response = await shimAbortSignal(promise, controller.signal);
-
- expect(response).toEqual(expect.objectContaining({ body: { success: true } }));
- });
-
- test('allows the promise to be aborted manually', () => {
- const promise = createSuccessTransportRequestPromise({
- success: true,
- });
- const controller = new AbortController();
- const enhancedPromise = shimAbortSignal(promise, controller.signal);
-
- enhancedPromise.abort();
- expect(promise.abort).toHaveBeenCalled();
- });
- });
});
diff --git a/src/plugins/data/server/search/strategies/es_search/request_utils.ts b/src/plugins/data/server/search/strategies/es_search/request_utils.ts
index 15cad34065ddc..9a57ac56ce250 100644
--- a/src/plugins/data/server/search/strategies/es_search/request_utils.ts
+++ b/src/plugins/data/server/search/strategies/es_search/request_utils.ts
@@ -6,21 +6,24 @@
* Side Public License, v 1.
*/
-import type { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport';
-import type { Search } from '@elastic/elasticsearch/api/requestParams';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { IUiSettingsClient, SharedGlobalConfig } from 'kibana/server';
import { UI_SETTINGS } from '../../../../common';
-export function getShardTimeout(config: SharedGlobalConfig): Pick {
+export function getShardTimeout(
+ config: SharedGlobalConfig
+): Pick {
const timeout = config.elasticsearch.shardTimeout.asMilliseconds();
return timeout ? { timeout: `${timeout}ms` } : {};
}
export async function getDefaultSearchParams(
uiSettingsClient: Pick
-): Promise<
- Pick
-> {
+): Promise<{
+ max_concurrent_shard_requests?: number;
+ ignore_unavailable: boolean;
+ track_total_hits: boolean;
+}> {
const maxConcurrentShardRequests = await uiSettingsClient.get(
UI_SETTINGS.COURIER_MAX_CONCURRENT_SHARD_REQUESTS
);
@@ -31,25 +34,3 @@ export async function getDefaultSearchParams(
track_total_hits: true,
};
}
-
-/**
- * Temporary workaround until https://github.com/elastic/elasticsearch-js/issues/1297 is resolved.
- * Shims the `AbortSignal` behavior so that, if the given `signal` aborts, the `abort` method on the
- * `TransportRequestPromise` is called, actually performing the cancellation.
- * @internal
- */
-export const shimAbortSignal = (promise: TransportRequestPromise, signal?: AbortSignal) => {
- if (!signal) return promise;
- const abortHandler = () => {
- promise.abort();
- cleanup();
- };
- const cleanup = () => signal.removeEventListener('abort', abortHandler);
- if (signal.aborted) {
- promise.abort();
- } else {
- signal.addEventListener('abort', abortHandler);
- promise.then(cleanup, cleanup);
- }
- return promise;
-};
diff --git a/src/plugins/data/server/search/strategies/es_search/response_utils.test.ts b/src/plugins/data/server/search/strategies/es_search/response_utils.test.ts
index fc35187429a98..043bfd2e518ff 100644
--- a/src/plugins/data/server/search/strategies/es_search/response_utils.test.ts
+++ b/src/plugins/data/server/search/strategies/es_search/response_utils.test.ts
@@ -7,7 +7,7 @@
*/
import { getTotalLoaded, toKibanaSearchResponse, shimHitsTotal } from './response_utils';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
describe('response utils', () => {
describe('getTotalLoaded', () => {
diff --git a/src/plugins/data/server/search/strategies/es_search/response_utils.ts b/src/plugins/data/server/search/strategies/es_search/response_utils.ts
index 0553c015fb2da..4773b6df3bbaf 100644
--- a/src/plugins/data/server/search/strategies/es_search/response_utils.ts
+++ b/src/plugins/data/server/search/strategies/es_search/response_utils.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ISearchOptions } from '../../../../common';
/**
diff --git a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts
index 8d5fbf98db2d3..d4fe74486ee85 100644
--- a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts
+++ b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.test.ts
@@ -8,7 +8,7 @@
import { BehaviorSubject } from 'rxjs';
import { KbnServerError } from '../../../../../kibana_utils/server';
-import { ElasticsearchClientError, ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import * as indexNotFoundException from '../../../../common/search/test_data/index_not_found_exception.json';
import * as xContentParseException from '../../../../common/search/test_data/x_content_parse_exception.json';
import { SearchStrategyDependencies } from '../../types';
@@ -191,7 +191,7 @@ describe('ES search strategy', () => {
});
it('throws normalized error if ResponseError is thrown', async () => {
- const errResponse = new ResponseError({
+ const errResponse = new errors.ResponseError({
body: indexNotFoundException,
statusCode: 404,
headers: {},
@@ -254,7 +254,7 @@ describe('ES search strategy', () => {
});
it('throws normalized error on ResponseError', async () => {
- const errResponse = new ResponseError({
+ const errResponse = new errors.ResponseError({
body: xContentParseException,
statusCode: 400,
headers: {},
@@ -297,7 +297,7 @@ describe('ES search strategy', () => {
});
it('throws normalized error on ElasticsearchClientError', async () => {
- const errResponse = new ElasticsearchClientError('something is wrong with EsClient');
+ const errResponse = new errors.ElasticsearchClientError('something is wrong with EsClient');
mockGetCaller.mockRejectedValue(errResponse);
const id = 'some_other_id';
diff --git a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts
index 75a4ddf051418..e94f1aa44d351 100644
--- a/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts
+++ b/src/plugins/data/server/search/strategies/ese_search/ese_search_strategy.ts
@@ -9,7 +9,7 @@
import type { Observable } from 'rxjs';
import type { IScopedClusterClient, Logger, SharedGlobalConfig } from 'kibana/server';
import { catchError, first, tap } from 'rxjs/operators';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { from } from 'rxjs';
import type { ISearchStrategy, SearchStrategyDependencies } from '../../types';
import type {
@@ -31,7 +31,6 @@ import {
getDefaultSearchParams,
getShardTimeout,
getTotalLoaded,
- shimAbortSignal,
shimHitsTotal,
} from '../es_search';
@@ -68,10 +67,11 @@ export const enhancedEsSearchStrategyProvider = (
)),
...request.params,
};
- const promise = id
- ? client.asyncSearch.get({ ...params, id })
- : client.asyncSearch.submit(params);
- const { body, headers } = await shimAbortSignal(promise, options.abortSignal);
+ const { body, headers } = id
+ ? await client.asyncSearch.get({ ...params, id }, { signal: options.abortSignal })
+ : await client.asyncSearch.submit(params, {
+ signal: options.abortSignal,
+ });
const response = shimHitsTotal(body.response, options);
@@ -115,14 +115,18 @@ export const enhancedEsSearchStrategyProvider = (
};
try {
- const promise = client.transport.request({
- method,
- path,
- body,
- querystring,
- });
+ const esResponse = await client.transport.request(
+ {
+ method,
+ path,
+ body,
+ querystring,
+ },
+ {
+ signal: options?.abortSignal,
+ }
+ );
- const esResponse = await shimAbortSignal(promise, options?.abortSignal);
const response = esResponse.body as estypes.SearchResponse;
return {
rawResponse: shimHitsTotal(response, options),
diff --git a/src/plugins/data/server/search/strategies/ese_search/request_utils.ts b/src/plugins/data/server/search/strategies/ese_search/request_utils.ts
index f8fb54cfd870b..85f9f243ad2b1 100644
--- a/src/plugins/data/server/search/strategies/ese_search/request_utils.ts
+++ b/src/plugins/data/server/search/strategies/ese_search/request_utils.ts
@@ -7,11 +7,8 @@
*/
import { IUiSettingsClient } from 'kibana/server';
-import {
- AsyncSearchGet,
- AsyncSearchSubmit,
- Search,
-} from '@elastic/elasticsearch/api/requestParams';
+import { AsyncSearchGetRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import { AsyncSearchSubmitRequest } from '@elastic/elasticsearch/lib/api/types';
import { ISearchOptions, UI_SETTINGS } from '../../../../common';
import { getDefaultSearchParams } from '../es_search';
import { SearchSessionsConfigSchema } from '../../../../config';
@@ -21,7 +18,7 @@ import { SearchSessionsConfigSchema } from '../../../../config';
*/
export async function getIgnoreThrottled(
uiSettingsClient: Pick
-): Promise> {
+): Promise<{ ignore_throttled?: boolean }> {
const includeFrozen = await uiSettingsClient.get(UI_SETTINGS.SEARCH_INCLUDE_FROZEN);
return includeFrozen ? { ignore_throttled: false } : {};
}
@@ -35,7 +32,7 @@ export async function getDefaultAsyncSubmitParams(
options: ISearchOptions
): Promise<
Pick<
- AsyncSearchSubmit,
+ AsyncSearchSubmitRequest,
| 'batched_reduce_size'
| 'keep_alive'
| 'wait_for_completion_timeout'
@@ -75,7 +72,7 @@ export async function getDefaultAsyncSubmitParams(
export function getDefaultAsyncGetParams(
searchSessionsConfig: SearchSessionsConfigSchema | null,
options: ISearchOptions
-): Pick {
+): Pick {
const useSearchSessions = searchSessionsConfig?.enabled && !!options.sessionId;
return {
diff --git a/src/plugins/data/server/search/strategies/ese_search/types.ts b/src/plugins/data/server/search/strategies/ese_search/types.ts
index 7f21aa3616e4e..4116aa4380339 100644
--- a/src/plugins/data/server/search/strategies/ese_search/types.ts
+++ b/src/plugins/data/server/search/strategies/ese_search/types.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export interface AsyncSearchResponse {
id?: string;
diff --git a/src/plugins/data_views/common/data_views/data_view.ts b/src/plugins/data_views/common/data_views/data_view.ts
index b7823677b70f9..9a597d5ae4471 100644
--- a/src/plugins/data_views/common/data_views/data_view.ts
+++ b/src/plugins/data_views/common/data_views/data_view.ts
@@ -10,7 +10,7 @@
import _, { each, reject } from 'lodash';
import { castEsToKbnFieldTypeName, ES_FIELD_TYPES, KBN_FIELD_TYPES } from '@kbn/field-types';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { FieldAttrs, FieldAttrSet, DataViewAttributes } from '..';
import type { RuntimeField } from '../types';
import { DuplicateField } from '../../../kibana_utils/common';
diff --git a/src/plugins/data_views/common/types.ts b/src/plugins/data_views/common/types.ts
index bbc5ad374636f..3a623f89a72e2 100644
--- a/src/plugins/data_views/common/types.ts
+++ b/src/plugins/data_views/common/types.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { DataViewFieldBase, IFieldSubType, DataViewBase } from '@kbn/es-query';
import { ToastInputFields, ErrorToastOptions } from 'src/core/public/notifications';
// eslint-disable-next-line
diff --git a/src/plugins/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts b/src/plugins/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts
index 6dff343f9e00e..75bede61e10d8 100644
--- a/src/plugins/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts
+++ b/src/plugins/data_views/server/fetcher/lib/field_capabilities/field_caps_response.ts
@@ -7,7 +7,7 @@
*/
import { uniq } from 'lodash';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { castEsToKbnFieldTypeName } from '@kbn/field-types';
import { shouldReadFieldFromDocValues } from './should_read_field_from_doc_values';
import { FieldDescriptor } from '../../../fetcher';
@@ -116,7 +116,6 @@ export function readFieldCapsResponse(
}),
{}
),
- // @ts-expect-error
metadata_field: capsByType[types[0]].metadata_field,
};
// This is intentionally using a "hash" and a "push" to be highly optimized with very large indexes
@@ -133,7 +132,6 @@ export function readFieldCapsResponse(
searchable: isSearchable,
aggregatable: isAggregatable,
readFromDocValues: shouldReadFieldFromDocValues(isAggregatable, esType),
- // @ts-expect-error
metadata_field: capsByType[types[0]].metadata_field,
};
// This is intentionally using a "hash" and a "push" to be highly optimized with very large indexes
diff --git a/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.tsx b/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.tsx
index 2702a232f21ef..a73bc3f175be1 100644
--- a/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.tsx
+++ b/src/plugins/discover/public/application/apps/main/components/doc_table/lib/row_formatter.tsx
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import React, { Fragment } from 'react';
import type { IndexPattern } from 'src/plugins/data/common';
import { MAX_DOC_FIELDS_DISPLAYED } from '../../../../../../../common';
diff --git a/src/plugins/discover/public/application/apps/main/utils/fetch_chart.test.ts b/src/plugins/discover/public/application/apps/main/utils/fetch_chart.test.ts
index 2c050a9391a86..2c9350b457779 100644
--- a/src/plugins/discover/public/application/apps/main/utils/fetch_chart.test.ts
+++ b/src/plugins/discover/public/application/apps/main/utils/fetch_chart.test.ts
@@ -14,7 +14,7 @@ import { ReduxLikeStateContainer } from '../../../../../../kibana_utils/common';
import { AppState } from '../services/discover_state';
import { discoverServiceMock } from '../../../../__mocks__/services';
import { calculateBounds, IKibanaSearchResponse } from '../../../../../../data/common';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
function getDataSubjects() {
return {
diff --git a/src/plugins/discover/public/application/doc_views/doc_views_types.ts b/src/plugins/discover/public/application/doc_views/doc_views_types.ts
index d3e482c0f2e1d..e8faa51bbab40 100644
--- a/src/plugins/discover/public/application/doc_views/doc_views_types.ts
+++ b/src/plugins/discover/public/application/doc_views/doc_views_types.ts
@@ -8,7 +8,7 @@
import { ComponentType } from 'react';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IndexPattern } from '../../../../data/public';
export type ElasticSearchHit = estypes.SearchHit;
diff --git a/src/plugins/discover/public/application/helpers/format_hit.test.ts b/src/plugins/discover/public/application/helpers/format_hit.test.ts
index 2cb46f28dd397..ebf5078238ccf 100644
--- a/src/plugins/discover/public/application/helpers/format_hit.test.ts
+++ b/src/plugins/discover/public/application/helpers/format_hit.test.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { indexPatternMock as dataViewMock } from '../../__mocks__/index_pattern';
import { formatHit } from './format_hit';
import { discoverServiceMock } from '../../__mocks__/services';
diff --git a/src/plugins/discover/public/application/helpers/format_hit.ts b/src/plugins/discover/public/application/helpers/format_hit.ts
index 3890973a3f3e4..1101439515523 100644
--- a/src/plugins/discover/public/application/helpers/format_hit.ts
+++ b/src/plugins/discover/public/application/helpers/format_hit.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { DataView, flattenHit } from '../../../../data/common';
import { MAX_DOC_FIELDS_DISPLAYED } from '../../../common';
import { getServices } from '../../kibana_services';
diff --git a/src/plugins/discover/public/application/helpers/format_value.ts b/src/plugins/discover/public/application/helpers/format_value.ts
index cc33276790372..933309d6dcf8e 100644
--- a/src/plugins/discover/public/application/helpers/format_value.ts
+++ b/src/plugins/discover/public/application/helpers/format_value.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { DataView, DataViewField, KBN_FIELD_TYPES } from '../../../../data/common';
import { getServices } from '../../kibana_services';
diff --git a/src/plugins/discover/public/application/helpers/get_ignored_reason.ts b/src/plugins/discover/public/application/helpers/get_ignored_reason.ts
index 4d2fb85bdb2c4..bf8df6e000d4c 100644
--- a/src/plugins/discover/public/application/helpers/get_ignored_reason.ts
+++ b/src/plugins/discover/public/application/helpers/get_ignored_reason.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { DataViewField, KBN_FIELD_TYPES } from '../../../../data/common';
export enum IgnoredReason {
diff --git a/src/plugins/discover/public/application/services/use_es_doc_search.ts b/src/plugins/discover/public/application/services/use_es_doc_search.ts
index 16a24ff27292b..fa7dce9c7e0a4 100644
--- a/src/plugins/discover/public/application/services/use_es_doc_search.ts
+++ b/src/plugins/discover/public/application/services/use_es_doc_search.ts
@@ -7,7 +7,7 @@
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IndexPattern } from '../../../../data/common';
import { DocProps } from '../apps/doc/components/doc';
import { ElasticRequestState } from '../apps/doc/types';
diff --git a/src/plugins/discover/public/application/types.ts b/src/plugins/discover/public/application/types.ts
index a28c5bbc89aed..f04f3bf77c2f9 100644
--- a/src/plugins/discover/public/application/types.ts
+++ b/src/plugins/discover/public/application/types.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export enum FetchStatus {
UNINITIALIZED = 'uninitialized',
diff --git a/src/plugins/es_ui_shared/__packages_do_not_import__/errors/handle_es_error.ts b/src/plugins/es_ui_shared/__packages_do_not_import__/errors/handle_es_error.ts
index 678c46f69d51f..07a681f002f33 100644
--- a/src/plugins/es_ui_shared/__packages_do_not_import__/errors/handle_es_error.ts
+++ b/src/plugins/es_ui_shared/__packages_do_not_import__/errors/handle_es_error.ts
@@ -6,13 +6,12 @@
* Side Public License, v 1.
*/
-import { ApiError } from '@elastic/elasticsearch';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { IKibanaResponse, KibanaResponseFactory } from 'kibana/server';
import { getEsCause } from './es_error_parser';
interface EsErrorHandlerParams {
- error: ApiError;
+ error: errors.ElasticsearchClientError;
response: KibanaResponseFactory;
handleCustomError?: () => IKibanaResponse;
}
@@ -34,9 +33,9 @@ export const handleEsError = ({
return handleCustomError();
}
- const { statusCode, body } = error as ResponseError;
+ const { statusCode, body } = error as errors.ResponseError;
return response.customError({
- statusCode,
+ statusCode: statusCode!,
body: {
message:
// We use || instead of ?? as the switch here because reason could be an empty string
diff --git a/src/plugins/index_pattern_field_editor/server/routes/field_preview.ts b/src/plugins/index_pattern_field_editor/server/routes/field_preview.ts
index 847dd41e0082b..9ffa5c88df8e8 100644
--- a/src/plugins/index_pattern_field_editor/server/routes/field_preview.ts
+++ b/src/plugins/index_pattern_field_editor/server/routes/field_preview.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { schema } from '@kbn/config-schema';
import { API_BASE_PATH } from '../../common/constants';
diff --git a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts
index 45a59b97b9490..e2657d7111ea6 100644
--- a/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts
+++ b/src/plugins/index_pattern_management/public/components/edit_index_pattern/scripted_fields_table/types.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
/** @internal **/
export interface ScriptedFieldItem {
name: string;
diff --git a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx
index 9509f4fb46e0b..234da4f3bbe05 100644
--- a/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx
+++ b/src/plugins/index_pattern_management/public/components/field_editor/field_editor.tsx
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import React, { PureComponent, Fragment } from 'react';
import { intersection, union, get } from 'lodash';
diff --git a/src/plugins/index_pattern_management/public/scripting_languages/index.ts b/src/plugins/index_pattern_management/public/scripting_languages/index.ts
index aeb38c8172be0..46bb0a359ae89 100644
--- a/src/plugins/index_pattern_management/public/scripting_languages/index.ts
+++ b/src/plugins/index_pattern_management/public/scripting_languages/index.ts
@@ -5,7 +5,7 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { i18n } from '@kbn/i18n';
import { HttpStart, NotificationsStart } from 'src/core/public';
diff --git a/src/plugins/interactive_setup/server/elasticsearch_service.test.ts b/src/plugins/interactive_setup/server/elasticsearch_service.test.ts
index 9baed65db299d..93870578d8cc4 100644
--- a/src/plugins/interactive_setup/server/elasticsearch_service.test.ts
+++ b/src/plugins/interactive_setup/server/elasticsearch_service.test.ts
@@ -289,7 +289,8 @@ describe('ElasticsearchService', () => {
it('treats product check error the same as successful response', async () => {
mockConnectionStatusClient.asInternalUser.ping.mockRejectedValue(
- new errors.ProductNotSupportedError(interactiveSetupMock.createApiResponse({ body: {} }))
+ // @ts-expect-error not full interface
+ new errors.ProductNotSupportedError('product-name', { body: {} })
);
const mockHandler = jest.fn();
@@ -538,7 +539,8 @@ some weird+ca/with
it('fails if host is not supported', async () => {
mockPingClient.asInternalUser.ping.mockRejectedValue(
- new errors.ProductNotSupportedError(interactiveSetupMock.createApiResponse({ body: {} }))
+ // @ts-expect-error not full interface
+ new errors.ProductNotSupportedError('Elasticsearch', { body: {} })
);
await expect(setupContract.ping('http://localhost:9200')).rejects.toMatchInlineSnapshot(
diff --git a/src/plugins/interactive_setup/server/elasticsearch_service.ts b/src/plugins/interactive_setup/server/elasticsearch_service.ts
index b3b25b13c5a9b..5d41f16b01add 100644
--- a/src/plugins/interactive_setup/server/elasticsearch_service.ts
+++ b/src/plugins/interactive_setup/server/elasticsearch_service.ts
@@ -6,8 +6,8 @@
* Side Public License, v 1.
*/
-import type { ApiResponse } from '@elastic/elasticsearch';
import { errors } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
import type { Duration } from 'moment';
import type { Observable } from 'rxjs';
import { from, of, timer } from 'rxjs';
@@ -193,7 +193,7 @@ export class ElasticsearchService {
.asCurrentUser.transport.request({
method: 'GET',
path: '/_security/enroll/kibana',
- })) as ApiResponse<{ token: { name: string; value: string }; http_ca: string }>;
+ })) as TransportResult<{ token: { name: string; value: string }; http_ca: string }>;
} catch (err) {
// We expect that all hosts belong to exactly same node and any non-connection error for one host would mean
// that enrollment will fail for any other host and we should bail out.
diff --git a/src/plugins/interactive_setup/server/errors.ts b/src/plugins/interactive_setup/server/errors.ts
index 5f1d2388b3938..89962e06e0e61 100644
--- a/src/plugins/interactive_setup/server/errors.ts
+++ b/src/plugins/interactive_setup/server/errors.ts
@@ -14,7 +14,7 @@ import { errors } from '@elastic/elasticsearch';
*/
export function getErrorStatusCode(error: any): number {
if (error instanceof errors.ResponseError) {
- return error.statusCode;
+ return error.statusCode!;
}
return error.statusCode || error.status;
diff --git a/src/plugins/interactive_setup/server/mocks.ts b/src/plugins/interactive_setup/server/mocks.ts
index 75b28a502b6d4..eb531e35f8dff 100644
--- a/src/plugins/interactive_setup/server/mocks.ts
+++ b/src/plugins/interactive_setup/server/mocks.ts
@@ -6,15 +6,17 @@
* Side Public License, v 1.
*/
-import type { ApiResponse } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
function createApiResponseMock(
- apiResponse: Pick, 'body'> &
- Partial, 'body'>>
-): ApiResponse {
+ apiResponse: Pick, 'body'> &
+ Partial, 'body'>>
+): TransportResult {
return {
+ // @ts-expect-error null is not supported
statusCode: null,
- headers: null,
+ // @ts-expect-error null is not supported
+ headers: undefined,
warnings: null,
meta: {} as any,
...apiResponse,
diff --git a/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/track_delays.ts b/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/track_delays.ts
index facdb549d0df7..33266cdbd9792 100644
--- a/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/track_delays.ts
+++ b/src/plugins/kibana_usage_collection/server/collectors/event_loop_delays/track_delays.ts
@@ -52,6 +52,10 @@ export function startTrackingEventLoopDelaysUsage(
if (shouldReset) {
eventLoopDelaysMonitor.reset();
}
- await storeHistogram(histogram, internalRepository, instanceUuid);
+ try {
+ await storeHistogram(histogram, internalRepository, instanceUuid);
+ } catch (e) {
+ // do not crash if cannot store a histogram.
+ }
});
}
diff --git a/src/plugins/kibana_usage_collection/server/plugin.ts b/src/plugins/kibana_usage_collection/server/plugin.ts
index 96d37c0303482..19adea4f009a2 100644
--- a/src/plugins/kibana_usage_collection/server/plugin.ts
+++ b/src/plugins/kibana_usage_collection/server/plugin.ts
@@ -108,6 +108,8 @@ export class KibanaUsageCollectionPlugin implements Plugin {
public stop() {
this.metric$.complete();
+
+ this.pluginStop$.next();
this.pluginStop$.complete();
}
diff --git a/src/plugins/kibana_utils/server/report_server_error.ts b/src/plugins/kibana_utils/server/report_server_error.ts
index 9f0bf34eaebb6..57b8c4e207f72 100644
--- a/src/plugins/kibana_utils/server/report_server_error.ts
+++ b/src/plugins/kibana_utils/server/report_server_error.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { KibanaResponseFactory } from 'kibana/server';
import { KbnError } from '../common';
@@ -27,8 +27,8 @@ export function getKbnServerError(e: Error) {
if (e instanceof KbnServerError) return e;
return new KbnServerError(
e.message ?? 'Unknown error',
- e instanceof ResponseError ? e.statusCode : 500,
- e instanceof ResponseError ? e.body : undefined
+ e instanceof errors.ResponseError ? e.statusCode! : 500,
+ e instanceof errors.ResponseError ? e.body : undefined
);
}
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts
index 1a00d0e428016..191e857c777d2 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.test.ts
@@ -7,7 +7,7 @@
*/
import { merge, omit } from 'lodash';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { getLocalStats, handleLocalStats } from './get_local_stats';
import {
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts
index 7860949e098aa..ae2a849ccfa19 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_local_stats.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
StatsGetter,
StatsCollectionContext,
diff --git a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts
index 0d58d80ed5965..a5d4f32b3a62f 100644
--- a/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts
+++ b/src/plugins/telemetry/server/telemetry_collection/get_nodes_usage.ts
@@ -7,7 +7,7 @@
*/
import type { ElasticsearchClient } from 'src/core/server';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { TIMEOUT } from './constants';
/**
diff --git a/src/plugins/vis_types/vega/public/data_model/es_query_parser.ts b/src/plugins/vis_types/vega/public/data_model/es_query_parser.ts
index 7f6ca05df3d7a..f52101212662d 100644
--- a/src/plugins/vis_types/vega/public/data_model/es_query_parser.ts
+++ b/src/plugins/vis_types/vega/public/data_model/es_query_parser.ts
@@ -9,7 +9,7 @@
import moment from 'moment';
import { i18n } from '@kbn/i18n';
import { cloneDeep, isPlainObject } from 'lodash';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Assign } from 'utility-types';
import { TimeCache } from './time_cache';
import { SearchAPI } from './search_api';
diff --git a/src/plugins/vis_types/vega/public/data_model/types.ts b/src/plugins/vis_types/vega/public/data_model/types.ts
index d1568bba6c98c..19efe5a9a4b7d 100644
--- a/src/plugins/vis_types/vega/public/data_model/types.ts
+++ b/src/plugins/vis_types/vega/public/data_model/types.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Assign } from '@kbn/utility-types';
import { Spec } from 'vega';
import { EsQueryParser } from './es_query_parser';
diff --git a/test/api_integration/apis/home/sample_data.ts b/test/api_integration/apis/home/sample_data.ts
index 1e029bc1e04d7..2525cbe330044 100644
--- a/test/api_integration/apis/home/sample_data.ts
+++ b/test/api_integration/apis/home/sample_data.ts
@@ -48,7 +48,7 @@ export default function ({ getService }: FtrProviderContext) {
});
it('should load elasticsearch index containing sample data with dates relative to current time', async () => {
- const { body: resp } = await es.search<{ timestamp: string }>({
+ const resp = await es.search<{ timestamp: string }>({
index: 'kibana_sample_data_flights',
});
@@ -66,7 +66,7 @@ export default function ({ getService }: FtrProviderContext) {
.post(`/api/sample_data/flights?now=${nowString}`)
.set('kbn-xsrf', 'kibana');
- const { body: resp } = await es.search<{ timestamp: string }>({
+ const resp = await es.search<{ timestamp: string }>({
index: 'kibana_sample_data_flights',
});
@@ -85,7 +85,7 @@ export default function ({ getService }: FtrProviderContext) {
});
it('should remove elasticsearch index containing sample data', async () => {
- const { body: resp } = await es.indices.exists({
+ const resp = await es.indices.exists({
index: 'kibana_sample_data_flights',
});
expect(resp).to.be(false);
diff --git a/test/api_integration/apis/index_patterns/has_user_index_pattern/has_user_index_pattern.ts b/test/api_integration/apis/index_patterns/has_user_index_pattern/has_user_index_pattern.ts
index 8dfb892acfd90..8fc4e860e5d9c 100644
--- a/test/api_integration/apis/index_patterns/has_user_index_pattern/has_user_index_pattern.ts
+++ b/test/api_integration/apis/index_patterns/has_user_index_pattern/has_user_index_pattern.ts
@@ -17,11 +17,11 @@ export default function ({ getService }: FtrProviderContext) {
describe('has user index pattern API', () => {
beforeEach(async () => {
await esArchiver.emptyKibanaIndex();
- if ((await es.indices.exists({ index: 'metrics-test' })).body) {
+ if (await es.indices.exists({ index: 'metrics-test' })) {
await es.indices.delete({ index: 'metrics-test' });
}
- if ((await es.indices.exists({ index: 'logs-test' })).body) {
+ if (await es.indices.exists({ index: 'logs-test' })) {
await es.indices.delete({ index: 'logs-test' });
}
});
diff --git a/test/api_integration/apis/kql_telemetry/kql_telemetry.ts b/test/api_integration/apis/kql_telemetry/kql_telemetry.ts
index 5770ed0866a90..4825b454bc42f 100644
--- a/test/api_integration/apis/kql_telemetry/kql_telemetry.ts
+++ b/test/api_integration/apis/kql_telemetry/kql_telemetry.ts
@@ -40,7 +40,7 @@ export default function ({ getService }: FtrProviderContext) {
index: '.kibana',
q: 'type:kql-telemetry',
})
- .then(({ body: response }) => {
+ .then((response) => {
const kqlTelemetryDoc = get(response, 'hits.hits[0]._source.kql-telemetry');
expect(kqlTelemetryDoc.optInCount).to.be(1);
});
@@ -58,7 +58,7 @@ export default function ({ getService }: FtrProviderContext) {
index: '.kibana',
q: 'type:kql-telemetry',
})
- .then(({ body: response }) => {
+ .then((response) => {
const kqlTelemetryDoc = get(response, 'hits.hits[0]._source.kql-telemetry');
expect(kqlTelemetryDoc.optOutCount).to.be(1);
});
diff --git a/test/api_integration/apis/saved_objects/delete_unknown_types.ts b/test/api_integration/apis/saved_objects/delete_unknown_types.ts
index 42caa753683e1..af9e413de0279 100644
--- a/test/api_integration/apis/saved_objects/delete_unknown_types.ts
+++ b/test/api_integration/apis/saved_objects/delete_unknown_types.ts
@@ -31,7 +31,7 @@ export default function ({ getService }: FtrProviderContext) {
});
const fetchIndexContent = async () => {
- const { body } = await es.search<{ type: string }>({
+ const body = await es.search<{ type: string }>({
index: '.kibana',
body: {
size: 100,
diff --git a/test/api_integration/apis/saved_objects/migrations.ts b/test/api_integration/apis/saved_objects/migrations.ts
index 0877998ca6c1f..cba62ee51763d 100644
--- a/test/api_integration/apis/saved_objects/migrations.ts
+++ b/test/api_integration/apis/saved_objects/migrations.ts
@@ -14,7 +14,8 @@ import uuidv5 from 'uuid/v5';
import { set } from '@elastic/safer-lodash-set';
import _ from 'lodash';
import expect from '@kbn/expect';
-import { ElasticsearchClient, SavedObjectsType } from 'src/core/server';
+import { SavedObjectsType } from 'src/core/server';
+import { Client as ElasticsearchClient } from '@elastic/elasticsearch';
import {
DocumentMigrator,
@@ -136,7 +137,7 @@ export default ({ getService }: FtrProviderContext) => {
const migrationATemplate = await esClient.indices.existsTemplate({
name: 'migration_a_template',
});
- expect(migrationATemplate.body).to.be.ok();
+ expect(migrationATemplate).to.be.ok();
const result = await migrateIndex({
esClient,
@@ -150,12 +151,12 @@ export default ({ getService }: FtrProviderContext) => {
name: 'migration_a_template',
});
- expect(migrationATemplateAfter.body).not.to.be.ok();
+ expect(migrationATemplateAfter).not.to.be.ok();
const migrationTestATemplateAfter = await esClient.indices.existsTemplate({
name: 'migration_test_a_template',
});
- expect(migrationTestATemplateAfter.body).to.be.ok();
+ expect(migrationTestATemplateAfter).to.be.ok();
expect(_.omit(result, 'elapsedMs')).to.eql({
destIndex: '.migration-a_2',
sourceIndex: '.migration-a_1',
@@ -451,7 +452,7 @@ export default ({ getService }: FtrProviderContext) => {
{ status: 'skipped', destIndex: undefined },
]);
- const { body } = await esClient.cat.indices({ index: '.migration-c*', format: 'json' });
+ const body = await esClient.cat.indices({ index: '.migration-c*', format: 'json' });
// It only created the original and the dest
expect(_.map(body, 'index').sort()).to.eql(['.migration-c_1', '.migration-c_2']);
@@ -747,7 +748,7 @@ async function migrateIndex({
}
async function fetchDocs(esClient: ElasticsearchClient, index: string) {
- const { body } = await esClient.search({ index });
+ const body = await esClient.search({ index });
return body.hits.hits
.map((h) => ({
diff --git a/test/api_integration/apis/telemetry/telemetry_optin_notice_seen.ts b/test/api_integration/apis/telemetry/telemetry_optin_notice_seen.ts
index a76d09481eca1..a2c48996069b2 100644
--- a/test/api_integration/apis/telemetry/telemetry_optin_notice_seen.ts
+++ b/test/api_integration/apis/telemetry/telemetry_optin_notice_seen.ts
@@ -25,9 +25,7 @@ export default function optInTest({ getService }: FtrProviderContext) {
await supertest.put('/api/telemetry/v2/userHasSeenNotice').set('kbn-xsrf', 'xxx').expect(200);
- const {
- body: { _source },
- } = await client.get<{ telemetry: { userHasSeenNotice: boolean } }>({
+ const { _source } = await client.get<{ telemetry: { userHasSeenNotice: boolean } }>({
index: '.kibana',
id: 'telemetry:telemetry',
});
diff --git a/test/api_integration/apis/ui_metric/ui_metric.ts b/test/api_integration/apis/ui_metric/ui_metric.ts
index 3f0a4c0778911..83f84af4eb9bd 100644
--- a/test/api_integration/apis/ui_metric/ui_metric.ts
+++ b/test/api_integration/apis/ui_metric/ui_metric.ts
@@ -50,7 +50,7 @@ export default function ({ getService }: FtrProviderContext) {
.send({ report })
.expect(200);
- const { body: response } = await es.search({ index: '.kibana', q: 'type:ui-metric' });
+ const response = await es.search({ index: '.kibana', q: 'type:ui-metric' });
const ids = response.hits.hits.map(({ _id }: { _id: string }) => _id);
expect(ids.includes('ui-metric:myApp:myEvent')).to.eql(true);
});
@@ -75,7 +75,7 @@ export default function ({ getService }: FtrProviderContext) {
.send({ report })
.expect(200);
- const { body: response } = await es.search({ index: '.kibana', q: 'type:ui-metric' });
+ const response = await es.search({ index: '.kibana', q: 'type:ui-metric' });
const ids = response.hits.hits.map(({ _id }: { _id: string }) => _id);
expect(ids.includes('ui-metric:myApp:myEvent')).to.eql(true);
expect(ids.includes(`ui-metric:myApp:${uniqueEventName}`)).to.eql(true);
@@ -99,9 +99,7 @@ export default function ({ getService }: FtrProviderContext) {
.expect(200);
const {
- body: {
- hits: { hits },
- },
+ hits: { hits },
} = await es.search({ index: '.kibana', q: 'type:ui-metric' });
const countTypeEvent = hits.find(
diff --git a/test/common/services/elasticsearch.ts b/test/common/services/elasticsearch.ts
index 7b8ff6bd6c8f4..384f98e31bf3c 100644
--- a/test/common/services/elasticsearch.ts
+++ b/test/common/services/elasticsearch.ts
@@ -8,30 +8,31 @@
import { format as formatUrl } from 'url';
import fs from 'fs';
-import { Client } from '@elastic/elasticsearch';
+import { Client, HttpConnection } from '@elastic/elasticsearch';
import { CA_CERT_PATH } from '@kbn/dev-utils';
-import type { KibanaClient } from '@elastic/elasticsearch/api/kibana';
import { FtrProviderContext } from '../ftr_provider_context';
/*
registers Kibana-specific @elastic/elasticsearch client instance.
*/
-export function ElasticsearchProvider({ getService }: FtrProviderContext): KibanaClient {
+export function ElasticsearchProvider({ getService }: FtrProviderContext): Client {
const config = getService('config');
if (process.env.TEST_CLOUD) {
return new Client({
nodes: [formatUrl(config.get('servers.elasticsearch'))],
requestTimeout: config.get('timeouts.esRequestTimeout'),
+ Connection: HttpConnection,
});
} else {
return new Client({
- ssl: {
+ tls: {
ca: fs.readFileSync(CA_CERT_PATH, 'utf-8'),
},
nodes: [formatUrl(config.get('servers.elasticsearch'))],
requestTimeout: config.get('timeouts.esRequestTimeout'),
+ Connection: HttpConnection,
});
}
}
diff --git a/test/common/services/es_delete_all_indices.ts b/test/common/services/es_delete_all_indices.ts
index 3443ef23c8ed0..c0ffa44c2e2c3 100644
--- a/test/common/services/es_delete_all_indices.ts
+++ b/test/common/services/es_delete_all_indices.ts
@@ -37,6 +37,7 @@ export function EsDeleteAllIndicesProvider({ getService }: FtrProviderContext) {
},
{
ignore: [404],
+ meta: true,
}
);
const indices = Object.keys(resp.body) as string[];
diff --git a/test/common/services/saved_object_info/saved_object_info.ts b/test/common/services/saved_object_info/saved_object_info.ts
index 61472ea98d879..3442efcc98438 100644
--- a/test/common/services/saved_object_info/saved_object_info.ts
+++ b/test/common/services/saved_object_info/saved_object_info.ts
@@ -6,7 +6,7 @@
* Side Public License, v 1.
*/
-import { Client } from '@elastic/elasticsearch';
+import { Client, HttpConnection } from '@elastic/elasticsearch';
import url from 'url';
import { Either, fromNullable, chain, getOrElse, toError } from 'fp-ts/Either';
import { flow, pipe } from 'fp-ts/function';
@@ -37,7 +37,7 @@ export const types =
await pipe(
TE.tryCatch(
async () => {
- const { body } = await new Client({ node }).search({
+ const body = await new Client({ node, Connection: HttpConnection }).search({
index,
size: 0,
body: query,
diff --git a/test/functional/apps/management/_field_formatter.ts b/test/functional/apps/management/_field_formatter.ts
index 2377e714418ee..838d20ccdfb50 100644
--- a/test/functional/apps/management/_field_formatter.ts
+++ b/test/functional/apps/management/_field_formatter.ts
@@ -423,7 +423,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
let testDocumentId: string;
before(async () => {
- if ((await es.indices.exists({ index: indexTitle })).body) {
+ if (await es.indices.exists({ index: indexTitle })) {
await es.indices.delete({ index: indexTitle });
}
@@ -447,7 +447,7 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
}, {} as Record),
refresh: 'wait_for',
});
- testDocumentId = docResult.body._id;
+ testDocumentId = docResult._id;
const indexPatternResult = await indexPatterns.create(
{ title: indexTitle },
diff --git a/test/functional/apps/management/_handle_version_conflict.js b/test/functional/apps/management/_handle_version_conflict.js
index 89426805bd503..a04c5d34b2d35 100644
--- a/test/functional/apps/management/_handle_version_conflict.js
+++ b/test/functional/apps/management/_handle_version_conflict.js
@@ -45,13 +45,16 @@ export default function ({ getService, getPageObjects }) {
await PageObjects.settings.clickAddScriptedField();
await PageObjects.settings.setScriptedFieldName(scriptedFiledName);
await PageObjects.settings.setScriptedFieldScript(`doc['bytes'].value`);
- const response = await es.update({
- index: '.kibana',
- id: 'index-pattern:logstash-*',
- body: {
- doc: { 'index-pattern': { fieldFormatMap: '{"geo.src":{"id":"number"}}' } },
+ const response = await es.update(
+ {
+ index: '.kibana',
+ id: 'index-pattern:logstash-*',
+ body: {
+ doc: { 'index-pattern': { fieldFormatMap: '{"geo.src":{"id":"number"}}' } },
+ },
},
- });
+ { meta: true }
+ );
log.debug(JSON.stringify(response));
expect(response.body.result).to.be('updated');
await PageObjects.settings.setFieldFormat('url');
@@ -76,13 +79,16 @@ export default function ({ getService, getPageObjects }) {
).findAllByCssSelector('[data-test-subj="toggle"]')
)[0].click();
await PageObjects.settings.setFieldFormat('url');
- const response = await es.update({
- index: '.kibana',
- id: 'index-pattern:logstash-*',
- body: {
- doc: { 'index-pattern': { fieldFormatMap: '{"geo.dest":{"id":"number"}}' } },
+ const response = await es.update(
+ {
+ index: '.kibana',
+ id: 'index-pattern:logstash-*',
+ body: {
+ doc: { 'index-pattern': { fieldFormatMap: '{"geo.dest":{"id":"number"}}' } },
+ },
},
- });
+ { meta: true }
+ );
log.debug(JSON.stringify(response));
expect(response.body.result).to.be('updated');
await PageObjects.settings.controlChangeSave();
diff --git a/test/interactive_setup_api_integration/tests/enrollment_flow.ts b/test/interactive_setup_api_integration/tests/enrollment_flow.ts
index 9f61529cc3439..53454207b73ed 100644
--- a/test/interactive_setup_api_integration/tests/enrollment_flow.ts
+++ b/test/interactive_setup_api_integration/tests/enrollment_flow.ts
@@ -38,9 +38,7 @@ export default function (context: FtrProviderContext) {
let enrollmentAPIKey: string;
beforeEach(async () => {
const apiResponse = await es.security.createApiKey({ body: { name: 'enrollment_api_key' } });
- enrollmentAPIKey = Buffer.from(`${apiResponse.body.id}:${apiResponse.body.api_key}`).toString(
- 'base64'
- );
+ enrollmentAPIKey = Buffer.from(`${apiResponse.id}:${apiResponse.api_key}`).toString('base64');
});
afterEach(async () => {
diff --git a/x-pack/plugins/actions/server/actions_client.ts b/x-pack/plugins/actions/server/actions_client.ts
index b391e50283ad1..5a5c5b302fad1 100644
--- a/x-pack/plugins/actions/server/actions_client.ts
+++ b/x-pack/plugins/actions/server/actions_client.ts
@@ -6,7 +6,7 @@
*/
import Boom from '@hapi/boom';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { UsageCounter } from 'src/plugins/usage_collection/server';
import { i18n } from '@kbn/i18n';
diff --git a/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts b/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts
index 738fa236f89c0..50a1deba5af20 100644
--- a/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts
+++ b/x-pack/plugins/actions/server/builtin_action_types/es_index.test.ts
@@ -8,7 +8,7 @@
jest.mock('./lib/send_email', () => ({
sendEmail: jest.fn(),
}));
-
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { validateConfig, validateParams } from '../lib';
import { createActionTypeRegistry } from './index.test';
import { actionsMock } from '../mocks';
@@ -216,10 +216,12 @@ describe('execute()', () => {
});
const calls = scopedClusterClient.bulk.mock.calls;
- const timeValue = ((calls[0][0]?.body as unknown[])[1] as Record)
- .field_to_use_for_time;
+ const timeValue = (
+ ((calls[0][0] as estypes.BulkRequest)?.body as unknown[])[1] as Record
+ ).field_to_use_for_time;
expect(timeValue).toBeInstanceOf(Date);
- delete ((calls[0][0]?.body as unknown[])[1] as Record).field_to_use_for_time;
+ delete (((calls[0][0] as estypes.BulkRequest)?.body as unknown[])[1] as Record)
+ .field_to_use_for_time;
expect(calls).toMatchInlineSnapshot(`
Array [
Array [
diff --git a/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts b/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts
index 451e12b9cf29a..b80a8d092118a 100644
--- a/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts
+++ b/x-pack/plugins/actions/server/cleanup_failed_executions/cleanup_tasks.test.ts
@@ -10,7 +10,8 @@ import { loggingSystemMock, elasticsearchServiceMock } from '../../../../../src/
import { spacesMock } from '../../../spaces/server/mocks';
import { CleanupTasksOpts, cleanupTasks } from './cleanup_tasks';
import { TaskInstance } from '../../../task_manager/server';
-import { ApiResponse, estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import { TransportResult } from '@elastic/elasticsearch';
describe('cleanupTasks', () => {
const logger = loggingSystemMock.create().get();
@@ -71,7 +72,7 @@ describe('cleanupTasks', () => {
it('should delete action_task_params and task objects', async () => {
esClient.bulk.mockResolvedValue({
body: { items: [], errors: false, took: 1 },
- } as unknown as ApiResponse);
+ } as unknown as TransportResult);
const result = await cleanupTasks({
...cleanupTasksOpts,
tasks: [taskSO],
@@ -106,7 +107,7 @@ describe('cleanupTasks', () => {
errors: true,
took: 1,
},
- } as unknown as ApiResponse);
+ } as unknown as TransportResult);
const result = await cleanupTasks({
...cleanupTasksOpts,
tasks: [taskSO],
diff --git a/x-pack/plugins/actions/server/cleanup_failed_executions/lib/bulk_delete.ts b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/bulk_delete.ts
index 2e0037d01943d..5bbb48a3d520d 100644
--- a/x-pack/plugins/actions/server/cleanup_failed_executions/lib/bulk_delete.ts
+++ b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/bulk_delete.ts
@@ -6,13 +6,14 @@
*/
import { ElasticsearchClient } from 'kibana/server';
-import { ApiResponse, estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import type { TransportResult } from '@elastic/elasticsearch';
export async function bulkDelete(
esClient: ElasticsearchClient,
index: string,
ids: string[]
-): Promise | undefined> {
+): Promise | undefined> {
if (ids.length === 0) {
return;
}
diff --git a/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts
index 90418c9763a4d..c3b4866f199d3 100644
--- a/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts
+++ b/x-pack/plugins/actions/server/cleanup_failed_executions/lib/extract_bulk_response_delete_failures.ts
@@ -5,12 +5,13 @@
* 2.0.
*/
-import { ApiResponse, estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import type { TransportResult } from '@elastic/elasticsearch';
-type ResponseFailures = Array>;
+type ResponseFailures = Array>;
export function extractBulkResponseDeleteFailures(
- response: ApiResponse
+ response: TransportResult
): ResponseFailures {
const result: ResponseFailures = [];
for (const item of response.body.items) {
diff --git a/x-pack/plugins/actions/server/usage/actions_telemetry.ts b/x-pack/plugins/actions/server/usage/actions_telemetry.ts
index 803a2122fe7f8..ab72352d460e3 100644
--- a/x-pack/plugins/actions/server/usage/actions_telemetry.ts
+++ b/x-pack/plugins/actions/server/usage/actions_telemetry.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/types';
import { ElasticsearchClient } from 'kibana/server';
import { AlertHistoryEsIndexConnectorId } from '../../common';
import { ActionResult, PreConfiguredAction } from '../types';
diff --git a/x-pack/plugins/alerting/server/authorization/alerting_authorization_kuery.ts b/x-pack/plugins/alerting/server/authorization/alerting_authorization_kuery.ts
index 300634af84585..d718373446b60 100644
--- a/x-pack/plugins/alerting/server/authorization/alerting_authorization_kuery.ts
+++ b/x-pack/plugins/alerting/server/authorization/alerting_authorization_kuery.ts
@@ -8,7 +8,7 @@
import { remove } from 'lodash';
import { EsQueryConfig, nodeBuilder, toElasticsearchQuery, KueryNode } from '@kbn/es-query';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { RegistryAlertTypeWithAuth } from './alerting_authorization';
export enum AlertingAuthorizationFilterType {
diff --git a/x-pack/plugins/alerting/server/lib/errors/es_error_parser.ts b/x-pack/plugins/alerting/server/lib/errors/es_error_parser.ts
index 3573da3a52eea..f26fa22f8d730 100644
--- a/x-pack/plugins/alerting/server/lib/errors/es_error_parser.ts
+++ b/x-pack/plugins/alerting/server/lib/errors/es_error_parser.ts
@@ -5,7 +5,6 @@
* 2.0.
*/
-// import { ResponseError } from '@elastic/elasticsearch/lib/errors';
import { ElasticsearchError, ElasticsearchErrorCausedByObject } from './types';
const getEsCause = (
diff --git a/x-pack/plugins/alerting/server/rules_client/rules_client.ts b/x-pack/plugins/alerting/server/rules_client/rules_client.ts
index bde0c35028582..e6f20049bc470 100644
--- a/x-pack/plugins/alerting/server/rules_client/rules_client.ts
+++ b/x-pack/plugins/alerting/server/rules_client/rules_client.ts
@@ -9,7 +9,7 @@ import Semver from 'semver';
import Boom from '@hapi/boom';
import { omit, isEqual, map, uniq, pick, truncate, trim, mapValues } from 'lodash';
import { i18n } from '@kbn/i18n';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
Logger,
SavedObjectsClientContract,
diff --git a/x-pack/plugins/apm/common/search_strategies/field_stats_types.ts b/x-pack/plugins/apm/common/search_strategies/field_stats_types.ts
index d96bb4408f0e8..d63dd7f8d58a1 100644
--- a/x-pack/plugins/apm/common/search_strategies/field_stats_types.ts
+++ b/x-pack/plugins/apm/common/search_strategies/field_stats_types.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SearchStrategyParams } from './types';
export interface FieldStatsCommonRequestParams extends SearchStrategyParams {
diff --git a/x-pack/plugins/apm/common/utils/environment_query.ts b/x-pack/plugins/apm/common/utils/environment_query.ts
index 7b35f90d87691..e2f9a722e3de2 100644
--- a/x-pack/plugins/apm/common/utils/environment_query.ts
+++ b/x-pack/plugins/apm/common/utils/environment_query.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SERVICE_ENVIRONMENT } from '../elasticsearch_fieldnames';
import {
ENVIRONMENT_ALL,
diff --git a/x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx b/x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx
index b3a972bcd59e3..4dc24567259e6 100644
--- a/x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx
+++ b/x-pack/plugins/apm/public/components/shared/kuery_bar/index.tsx
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { i18n } from '@kbn/i18n';
import { uniqueId } from 'lodash';
import React, { useState } from 'react';
diff --git a/x-pack/plugins/apm/public/components/shared/search_bar.tsx b/x-pack/plugins/apm/public/components/shared/search_bar.tsx
index 5f5a25393c7d1..1a6e9a803d735 100644
--- a/x-pack/plugins/apm/public/components/shared/search_bar.tsx
+++ b/x-pack/plugins/apm/public/components/shared/search_bar.tsx
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
EuiFlexGroup,
EuiFlexGroupProps,
diff --git a/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts b/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts
index 3d0f0bd3c3c72..d5cc9a63dbfcd 100644
--- a/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts
+++ b/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts
@@ -135,11 +135,9 @@ export async function aggregateLatencyMetrics() {
destOptions = parseIndexUrl(dest);
destClient = getEsClient({ node: destOptions.node });
- const mappings = (
- await sourceClient.indices.getMapping({
- index: sourceOptions.index,
- })
- ).body;
+ const mappings = await sourceClient.indices.getMapping({
+ index: sourceOptions.index,
+ });
const lastMapping = mappings[Object.keys(mappings)[0]];
diff --git a/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts b/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts
index b9102efee50dc..559f746ab50f2 100644
--- a/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts
+++ b/x-pack/plugins/apm/scripts/create-functional-tests-archive/index.ts
@@ -10,7 +10,7 @@ import { execSync } from 'child_process';
import moment from 'moment';
import path from 'path';
import fs from 'fs';
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { getEsClient } from '../shared/get_es_client';
import { parseIndexUrl } from '../shared/parse_index_url';
@@ -144,6 +144,7 @@ async function run() {
// profile
const indicesWithDocs =
response.body.aggregations?.index.buckets.map(
+ // @ts-expect-error bucket has any type
(bucket) => bucket.key as string
) ?? [];
diff --git a/x-pack/plugins/apm/scripts/shared/create-or-update-index.ts b/x-pack/plugins/apm/scripts/shared/create-or-update-index.ts
index 8bab4df9006f5..39f398354422f 100644
--- a/x-pack/plugins/apm/scripts/shared/create-or-update-index.ts
+++ b/x-pack/plugins/apm/scripts/shared/create-or-update-index.ts
@@ -36,11 +36,9 @@ export async function createOrUpdateIndex({
delete settings?.index?.number_of_shards;
delete settings?.index?.sort;
- const indexExists = (
- await client.indices.exists({
- index: indexName,
- })
- ).body as unknown;
+ const indexExists = await client.indices.exists({
+ index: indexName,
+ });
if (!indexExists) {
await client.indices.create({
diff --git a/x-pack/plugins/apm/scripts/shared/get_es_client.ts b/x-pack/plugins/apm/scripts/shared/get_es_client.ts
index 42833d28adcb2..3ee5642852c06 100644
--- a/x-pack/plugins/apm/scripts/shared/get_es_client.ts
+++ b/x-pack/plugins/apm/scripts/shared/get_es_client.ts
@@ -6,7 +6,7 @@
*/
import { Client } from '@elastic/elasticsearch';
-import { ApiKeyAuth, BasicAuth } from '@elastic/elasticsearch/lib/pool';
+import type { ClientOptions } from '@elastic/elasticsearch/lib/client';
import {
ESSearchResponse,
ESSearchRequest,
@@ -19,11 +19,13 @@ export function getEsClient({
auth,
}: {
node: string;
- auth?: BasicAuth | ApiKeyAuth;
-}) {
+ auth?: ClientOptions['auth'];
+ // Should be refactored
+ // The inferred type of 'getEsClient' references an inaccessible 'unique symbol' type. A type annotation is necessary.
+}): any {
const client = new Client({
node,
- ssl: {
+ tls: {
rejectUnauthorized: false,
},
requestTimeout: 120000,
@@ -36,14 +38,11 @@ export function getEsClient({
TDocument = unknown,
TSearchRequest extends ESSearchRequest = ESSearchRequest
>(request: TSearchRequest) {
- const response = await originalSearch(request);
+ const response = await originalSearch(request);
return {
...response,
- body: response.body as unknown as ESSearchResponse<
- TDocument,
- TSearchRequest
- >,
+ body: response as unknown as ESSearchResponse,
};
}
diff --git a/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts b/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts
index 6397c79ce4ffb..990376ca3e6ba 100644
--- a/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts
+++ b/x-pack/plugins/apm/scripts/upload-telemetry-data/index.ts
@@ -17,7 +17,6 @@ import { argv } from 'yargs';
import { Logger } from 'kibana/server';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { CollectTelemetryParams } from '../../server/lib/apm_telemetry/collect_data_telemetry';
-import { unwrapEsResponse } from '../../../observability/common/utils/unwrap_es_response';
import { downloadTelemetryTemplate } from '../shared/download-telemetry-template';
import { mergeApmTelemetryMapping } from '../../common/apm_telemetry';
import { generateSampleDocuments } from './generate-sample-documents';
@@ -87,18 +86,13 @@ async function uploadData() {
apmAgentConfigurationIndex: '.apm-agent-configuration',
},
search: (body) => {
- return unwrapEsResponse(client.search(body)) as Promise;
+ return client.search(body) as Promise;
},
indicesStats: (body) => {
- return unwrapEsResponse(client.indices.stats(body));
+ return client.indices.stats(body);
},
transportRequest: ((params) => {
- return unwrapEsResponse(
- client.transport.request({
- method: params.method,
- path: params.path,
- })
- );
+ return;
}) as CollectTelemetryParams['transportRequest'],
},
});
diff --git a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts b/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts
index 1359f4b925973..8767b5a60d9b2 100644
--- a/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts
+++ b/x-pack/plugins/apm/server/lib/alerts/chart_preview/get_transaction_duration.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { rangeQuery } from '../../../../../observability/server';
import {
SERVICE_NAME,
diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts
index 698bbcdbdb84a..3500dc8fee921 100644
--- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts
+++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_alert_type.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { schema } from '@kbn/config-schema';
import type {
ALERT_EVALUATION_THRESHOLD as ALERT_EVALUATION_THRESHOLD_TYPED,
diff --git a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts
index 08203646d9004..2809d7feadb37 100644
--- a/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts
+++ b/x-pack/plugins/apm/server/lib/alerts/register_transaction_duration_anomaly_alert_type.ts
@@ -8,7 +8,7 @@
import { schema } from '@kbn/config-schema';
import { compact } from 'lodash';
import { ESSearchResponse } from 'src/core/types/elasticsearch';
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type {
ALERT_EVALUATION_THRESHOLD as ALERT_EVALUATION_THRESHOLD_TYPED,
ALERT_EVALUATION_VALUE as ALERT_EVALUATION_VALUE_TYPED,
diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/index.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/index.ts
index 22a2090dbb6cd..9b5820767690f 100644
--- a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/index.ts
+++ b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/index.ts
@@ -7,7 +7,7 @@
import { merge } from 'lodash';
import { Logger } from 'kibana/server';
-import { IndicesStats } from '@elastic/elasticsearch/api/requestParams';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
ESSearchRequest,
ESSearchResponse,
@@ -22,7 +22,7 @@ type TelemetryTaskExecutor = (params: {
params: TSearchRequest
): Promise>;
indicesStats(
- params: IndicesStats
+ params: estypes.IndicesStatsRequest
// promise returned by client has an abort property
// so we cannot use its ReturnType
): Promise<{
diff --git a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts
index 8764223ad1ebb..f06226c864a98 100644
--- a/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts
+++ b/x-pack/plugins/apm/server/lib/apm_telemetry/collect_data_telemetry/tasks.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
import { flatten, merge, sortBy, sum, pickBy } from 'lodash';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { asMutableArray } from '../../../../common/utils/as_mutable_array';
import { ProcessorEvent } from '../../../../common/processor_event';
import { TelemetryTask } from '.';
@@ -599,7 +599,7 @@ export const tasks: TelemetryTask[] = [
executor: async ({ search, indices }) => {
const response = await search({
index: [indices.transaction, indices.span, indices.error],
- terminateAfter: 1,
+ terminate_after: 1,
body: {
query: {
exists: {
diff --git a/x-pack/plugins/apm/server/lib/connections/exclude_rum_exit_spans_query.ts b/x-pack/plugins/apm/server/lib/connections/exclude_rum_exit_spans_query.ts
index 89a510fe508c6..4e15500a59466 100644
--- a/x-pack/plugins/apm/server/lib/connections/exclude_rum_exit_spans_query.ts
+++ b/x-pack/plugins/apm/server/lib/connections/exclude_rum_exit_spans_query.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { AGENT_NAME } from '../../../common/elasticsearch_fieldnames';
import { RUM_AGENT_NAMES } from '../../../common/agent_name';
diff --git a/x-pack/plugins/apm/server/lib/connections/get_connection_stats/get_destination_map.ts b/x-pack/plugins/apm/server/lib/connections/get_connection_stats/get_destination_map.ts
index be6518708eddb..2eb0ed3db02bd 100644
--- a/x-pack/plugins/apm/server/lib/connections/get_connection_stats/get_destination_map.ts
+++ b/x-pack/plugins/apm/server/lib/connections/get_connection_stats/get_destination_map.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import objectHash from 'object-hash';
import { getOffsetInMs } from '../../../../common/utils/get_offset_in_ms';
import { ENVIRONMENT_NOT_DEFINED } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/connections/get_connection_stats/get_stats.ts b/x-pack/plugins/apm/server/lib/connections/get_connection_stats/get_stats.ts
index 4f48f3388c017..ff46db949d122 100644
--- a/x-pack/plugins/apm/server/lib/connections/get_connection_stats/get_stats.ts
+++ b/x-pack/plugins/apm/server/lib/connections/get_connection_stats/get_stats.ts
@@ -7,7 +7,7 @@
import { sum } from 'lodash';
import objectHash from 'object-hash';
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { AgentName } from '../../../../typings/es_schemas/ui/fields/agent';
import { getOffsetInMs } from '../../../../common/utils/get_offset_in_ms';
import { ENVIRONMENT_NOT_DEFINED } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/connections/get_connection_stats/index.ts b/x-pack/plugins/apm/server/lib/connections/get_connection_stats/index.ts
index 03b94defda6dd..5c1c628762edb 100644
--- a/x-pack/plugins/apm/server/lib/connections/get_connection_stats/index.ts
+++ b/x-pack/plugins/apm/server/lib/connections/get_connection_stats/index.ts
@@ -7,7 +7,7 @@
import { ValuesType } from 'utility-types';
import { merge } from 'lodash';
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { joinByKey } from '../../../../common/utils/join_by_key';
import { Setup } from '../../helpers/setup_request';
import { getStats } from './get_stats';
diff --git a/x-pack/plugins/apm/server/lib/event_metadata/get_event_metadata.ts b/x-pack/plugins/apm/server/lib/event_metadata/get_event_metadata.ts
index 97e2e1356363f..b9e0dee52a42e 100644
--- a/x-pack/plugins/apm/server/lib/event_metadata/get_event_metadata.ts
+++ b/x-pack/plugins/apm/server/lib/event_metadata/get_event_metadata.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
ERROR_ID,
SPAN_ID,
diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/cancel_es_request_on_abort.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/cancel_es_request_on_abort.ts
index a14564fc8e268..41dc33dfa193f 100644
--- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/cancel_es_request_on_abort.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/cancel_es_request_on_abort.ts
@@ -5,24 +5,18 @@
* 2.0.
*/
-import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport';
-import { KibanaRequest } from 'src/core/server';
+import type { KibanaRequest } from 'src/core/server';
-export function cancelEsRequestOnAbort>(
+export function cancelEsRequestOnAbort>(
promise: T,
- request: KibanaRequest
+ request: KibanaRequest,
+ controller: AbortController
) {
const subscription = request.events.aborted$.subscribe(() => {
- promise.abort();
+ controller.abort();
});
- // using .catch() here means unsubscribe will be called
- // after it has thrown an error, so we use .then(onSuccess, onFailure)
- // syntax
- promise.then(
- () => subscription.unsubscribe(),
- () => subscription.unsubscribe()
- );
+ promise.finally(() => subscription.unsubscribe());
return promise;
}
diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts
index 8f03aceef3348..e9280ba3e5976 100644
--- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.test.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-
+import { setTimeout as setTimeoutPromise } from 'timers/promises';
import {
contextServiceMock,
executionContextServiceMock,
@@ -34,17 +34,19 @@ describe('createApmEventClient', () => {
});
const router = createRouter('/');
- const abort = jest.fn();
+ let abortSignal: AbortSignal | undefined;
router.get(
{ path: '/', validate: false },
async (context, request, res) => {
const eventClient = createApmEventClient({
esClient: {
- search: () => {
- return Object.assign(
- new Promise((resolve) => setTimeout(resolve, 3000)),
- { abort }
- );
+ search: async (
+ params: any,
+ { signal }: { signal: AbortSignal }
+ ) => {
+ abortSignal = signal;
+ await setTimeoutPromise(3_000);
+ return {};
},
} as any,
debug: false,
@@ -67,6 +69,8 @@ describe('createApmEventClient', () => {
await server.start();
+ expect(abortSignal?.aborted).toBeFalsy();
+
const incomingRequest = supertest(innerServer.listener)
.get('/')
// end required to send request
@@ -83,6 +87,6 @@ describe('createApmEventClient', () => {
}, 100);
});
- expect(abort).toHaveBeenCalled();
+ expect(abortSignal?.aborted).toBe(true);
});
});
diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts
index b2b2a0b869c80..26b00b075a5c8 100644
--- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_apm_event_client/index.ts
@@ -8,7 +8,7 @@
import type {
TermsEnumRequest,
TermsEnumResponse,
-} from '@elastic/elasticsearch/api/types';
+} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ValuesType } from 'utility-types';
import { withApmSpan } from '../../../../utils/with_apm_span';
import { Profile } from '../../../../../typings/es_schemas/ui/profile';
@@ -110,9 +110,14 @@ export function createApmEventClient({
return callAsyncWithDebug({
cb: () => {
- const searchPromise = withApmSpan(operationName, () =>
- cancelEsRequestOnAbort(esClient.search(searchParams), request)
- );
+ const searchPromise = withApmSpan(operationName, () => {
+ const controller = new AbortController();
+ return cancelEsRequestOnAbort(
+ esClient.search(searchParams, { signal: controller.signal }),
+ request,
+ controller
+ );
+ });
return unwrapEsResponse(searchPromise);
},
@@ -143,15 +148,20 @@ export function createApmEventClient({
return callAsyncWithDebug({
cb: () => {
const { apm, ...rest } = params;
- const termsEnumPromise = withApmSpan(operationName, () =>
- cancelEsRequestOnAbort(
- esClient.termsEnum({
- index: Array.isArray(index) ? index.join(',') : index,
- ...rest,
- }),
- request
- )
- );
+ const termsEnumPromise = withApmSpan(operationName, () => {
+ const controller = new AbortController();
+ return cancelEsRequestOnAbort(
+ esClient.termsEnum(
+ {
+ index: Array.isArray(index) ? index.join(',') : index,
+ ...rest,
+ },
+ { signal: controller.signal }
+ ),
+ request,
+ controller
+ );
+ });
return unwrapEsResponse(termsEnumPromise);
},
diff --git a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts
index 34801cdf94750..621f65f74d9f4 100644
--- a/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/create_es_client/create_internal_es_client/index.ts
@@ -5,8 +5,7 @@
* 2.0.
*/
-import { TransportRequestPromise } from '@elastic/elasticsearch/lib/Transport';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { unwrapEsResponse } from '../../../../../../observability/server';
import { APMRouteHandlerResources } from '../../../../routes/typings';
import {
@@ -39,12 +38,17 @@ export function createInternalESClient({
params,
}: {
requestType: string;
- cb: () => TransportRequestPromise;
+ cb: (signal: AbortSignal) => Promise;
params: Record;
}
) {
return callAsyncWithDebug({
- cb: () => unwrapEsResponse(cancelEsRequestOnAbort(cb(), request)),
+ cb: () => {
+ const controller = new AbortController();
+ return unwrapEsResponse(
+ cancelEsRequestOnAbort(cb(controller.signal), request, controller)
+ );
+ },
getDebugMessage: () => ({
title: getDebugTitle(request),
body: getDebugBody({ params, requestType, operationName }),
@@ -68,14 +72,14 @@ export function createInternalESClient({
): Promise> => {
return callEs(operationName, {
requestType: 'search',
- cb: () => asInternalUser.search(params),
+ cb: (signal) => asInternalUser.search(params, { signal }),
params,
});
},
index: (operationName: string, params: APMIndexDocumentParams) => {
return callEs(operationName, {
requestType: 'index',
- cb: () => asInternalUser.index(params),
+ cb: (signal) => asInternalUser.index(params, { signal }),
params,
});
},
@@ -85,7 +89,7 @@ export function createInternalESClient({
): Promise<{ result: string }> => {
return callEs(operationName, {
requestType: 'delete',
- cb: () => asInternalUser.delete(params),
+ cb: (signal) => asInternalUser.delete(params, { signal }),
params,
});
},
@@ -95,7 +99,7 @@ export function createInternalESClient({
) => {
return callEs(operationName, {
requestType: 'indices.create',
- cb: () => asInternalUser.indices.create(params),
+ cb: (signal) => asInternalUser.indices.create(params, { signal }),
params,
});
},
diff --git a/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts b/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts
index 5bd883c6381d3..52e9e5a8ea74a 100644
--- a/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/setup_request.test.ts
@@ -117,23 +117,28 @@ describe('setupRequest', () => {
expect(
mockResources.context.core.elasticsearch.client.asCurrentUser.search
- ).toHaveBeenCalledWith({
- index: ['apm-*'],
- body: {
- foo: 'bar',
- query: {
- bool: {
- filter: [
- { terms: { 'processor.event': ['transaction'] } },
- { range: { 'observer.version_major': { gte: 7 } } },
- ],
+ ).toHaveBeenCalledWith(
+ {
+ index: ['apm-*'],
+ body: {
+ foo: 'bar',
+ query: {
+ bool: {
+ filter: [
+ { terms: { 'processor.event': ['transaction'] } },
+ { range: { 'observer.version_major': { gte: 7 } } },
+ ],
+ },
},
},
+ ignore_unavailable: true,
+ ignore_throttled: true,
+ preference: 'any',
},
- ignore_unavailable: true,
- ignore_throttled: true,
- preference: 'any',
- });
+ {
+ signal: expect.any(Object),
+ }
+ );
});
it('calls callWithInternalUser', async () => {
@@ -145,12 +150,17 @@ describe('setupRequest', () => {
} as any);
expect(
mockResources.context.core.elasticsearch.client.asInternalUser.search
- ).toHaveBeenCalledWith({
- index: ['apm-*'],
- body: {
- foo: 'bar',
+ ).toHaveBeenCalledWith(
+ {
+ index: ['apm-*'],
+ body: {
+ foo: 'bar',
+ },
},
- });
+ {
+ signal: expect.any(Object),
+ }
+ );
});
});
diff --git a/x-pack/plugins/apm/server/lib/helpers/transactions/__snapshots__/get_is_using_transaction_events.test.ts.snap b/x-pack/plugins/apm/server/lib/helpers/transactions/__snapshots__/get_is_using_transaction_events.test.ts.snap
index 2b629e9849d0d..56d735b5df115 100644
--- a/x-pack/plugins/apm/server/lib/helpers/transactions/__snapshots__/get_is_using_transaction_events.test.ts.snap
+++ b/x-pack/plugins/apm/server/lib/helpers/transactions/__snapshots__/get_is_using_transaction_events.test.ts.snap
@@ -32,7 +32,7 @@ Object {
},
},
},
- "terminateAfter": 1,
+ "terminate_after": 1,
}
`;
@@ -56,7 +56,7 @@ Object {
},
},
},
- "terminateAfter": 1,
+ "terminate_after": 1,
}
`;
@@ -83,7 +83,7 @@ Array [
},
},
},
- "terminateAfter": 1,
+ "terminate_after": 1,
},
],
Array [
@@ -101,7 +101,7 @@ Array [
},
},
},
- "terminateAfter": 1,
+ "terminate_after": 1,
},
],
]
diff --git a/x-pack/plugins/apm/server/lib/helpers/transactions/get_is_using_transaction_events.ts b/x-pack/plugins/apm/server/lib/helpers/transactions/get_is_using_transaction_events.ts
index 66e9697ab7c91..75be545a7e427 100644
--- a/x-pack/plugins/apm/server/lib/helpers/transactions/get_is_using_transaction_events.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/transactions/get_is_using_transaction_events.ts
@@ -83,7 +83,7 @@ async function getHasTransactions({
},
},
},
- terminateAfter: 1,
+ terminate_after: 1,
});
return response.hits.total.value > 0;
diff --git a/x-pack/plugins/apm/server/lib/helpers/transactions/index.ts b/x-pack/plugins/apm/server/lib/helpers/transactions/index.ts
index f16e03ddc3ea4..473d34cd5b6fc 100644
--- a/x-pack/plugins/apm/server/lib/helpers/transactions/index.ts
+++ b/x-pack/plugins/apm/server/lib/helpers/transactions/index.ts
@@ -43,7 +43,7 @@ export async function getHasAggregatedTransactions({
},
},
},
- terminateAfter: 1,
+ terminate_after: 1,
}
);
diff --git a/x-pack/plugins/apm/server/lib/latency/get_overall_latency_distribution.ts b/x-pack/plugins/apm/server/lib/latency/get_overall_latency_distribution.ts
index 787304c3f8dcd..ad1914d921211 100644
--- a/x-pack/plugins/apm/server/lib/latency/get_overall_latency_distribution.ts
+++ b/x-pack/plugins/apm/server/lib/latency/get_overall_latency_distribution.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ProcessorEvent } from '../../../common/processor_event';
diff --git a/x-pack/plugins/apm/server/lib/latency/get_percentile_threshold_value.ts b/x-pack/plugins/apm/server/lib/latency/get_percentile_threshold_value.ts
index 0d417a370e0b6..996e039841b88 100644
--- a/x-pack/plugins/apm/server/lib/latency/get_percentile_threshold_value.ts
+++ b/x-pack/plugins/apm/server/lib/latency/get_percentile_threshold_value.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ProcessorEvent } from '../../../common/processor_event';
diff --git a/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts b/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts
index 3b6993695f3de..f09b67ec98dfb 100644
--- a/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts
+++ b/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts
@@ -19,7 +19,7 @@ export async function getHasData({ setup }: { setup: Setup }) {
ProcessorEvent.metric,
],
},
- terminateAfter: 1,
+ terminate_after: 1,
body: {
size: 0,
},
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_boolean_field_stats.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_boolean_field_stats.ts
index 551ecfe3cd4ea..da5493376426c 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_boolean_field_stats.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_boolean_field_stats.ts
@@ -6,8 +6,8 @@
*/
import { ElasticsearchClient } from 'kibana/server';
-import { SearchRequest } from '@elastic/elasticsearch/api/types';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+
import { buildSamplerAggregation } from '../../utils/field_stats_utils';
import { FieldValuePair } from '../../../../../common/search_strategies/types';
import {
@@ -22,7 +22,7 @@ export const getBooleanFieldStatsRequest = (
params: FieldStatsCommonRequestParams,
fieldName: string,
termFilters?: FieldValuePair[]
-): SearchRequest => {
+): estypes.SearchRequest => {
const query = getQueryWithParams({ params, termFilters });
const { index, samplerShardSize } = params;
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_field_stats.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_field_stats.test.ts
index d3cee1c4ca596..2775d755c9907 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_field_stats.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_field_stats.test.ts
@@ -9,7 +9,7 @@ import { ENVIRONMENT_ALL } from '../../../../../common/environment_filter_values
import { getNumericFieldStatsRequest } from './get_numeric_field_stats';
import { getKeywordFieldStatsRequest } from './get_keyword_field_stats';
import { getBooleanFieldStatsRequest } from './get_boolean_field_stats';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient } from 'kibana/server';
import { fetchFieldsStats } from './get_fields_stats';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_keyword_field_stats.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_keyword_field_stats.ts
index b15449657cba5..a9c727457d0ae 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_keyword_field_stats.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_keyword_field_stats.ts
@@ -6,8 +6,7 @@
*/
import { ElasticsearchClient } from 'kibana/server';
-import { SearchRequest } from '@elastic/elasticsearch/api/types';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { FieldValuePair } from '../../../../../common/search_strategies/types';
import { getQueryWithParams } from '../get_query_with_params';
import { buildSamplerAggregation } from '../../utils/field_stats_utils';
@@ -22,7 +21,7 @@ export const getKeywordFieldStatsRequest = (
params: FieldStatsCommonRequestParams,
fieldName: string,
termFilters?: FieldValuePair[]
-): SearchRequest => {
+): estypes.SearchRequest => {
const query = getQueryWithParams({ params, termFilters });
const { index, samplerShardSize } = params;
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_numeric_field_stats.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_numeric_field_stats.ts
index bab4a1af29b65..c45d4356cfe23 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_numeric_field_stats.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/field_stats/get_numeric_field_stats.ts
@@ -6,9 +6,8 @@
*/
import { ElasticsearchClient } from 'kibana/server';
-import { SearchRequest } from '@elastic/elasticsearch/api/types';
import { find, get } from 'lodash';
-import { estypes } from '@elastic/elasticsearch/index';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
NumericFieldStats,
FieldStatsCommonRequestParams,
@@ -80,7 +79,7 @@ export const fetchNumericFieldStats = async (
field: FieldValuePair,
termFilters?: FieldValuePair[]
): Promise => {
- const request: SearchRequest = getNumericFieldStatsRequest(
+ const request: estypes.SearchRequest = getNumericFieldStatsRequest(
params,
field.fieldName,
termFilters
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/get_query_with_params.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/get_query_with_params.ts
index 31a98b0a6bb18..297fd68a7503f 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/get_query_with_params.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/get_query_with_params.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type {
FieldValuePair,
SearchStrategyParams,
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.test.ts
index 40fcc17444492..6cbf97a163871 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.ts
index 24db25f8afd89..a150d23b27113 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_correlation.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_failure_correlation.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_failure_correlation.ts
index 64249a0f3547e..10a098c4a3ffc 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_failure_correlation.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_failure_correlation.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient } from 'kibana/server';
import { SearchStrategyParams } from '../../../../common/search_strategies/types';
import { EVENT_OUTCOME } from '../../../../common/elasticsearch_fieldnames';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.test.ts
index bae42666e6db0..311016a1b0834 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.ts
index 390243295c4f0..292be1b5817aa 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_candidates.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.test.ts
index ab7a0b4e02072..bb3aa40b328af 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.ts
index 296abfd2d8653..39d6aea2f38bd 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_field_value_pairs.ts
@@ -7,7 +7,7 @@
import type { ElasticsearchClient } from 'src/core/server';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type {
FieldValuePair,
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.test.ts
index 9c704ef7b489a..5c18b21fc029c 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.ts
index ccea480052c9b..555465466498a 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_fractions.ts
@@ -6,7 +6,7 @@
*/
import { ElasticsearchClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SearchStrategyParams } from '../../../../common/search_strategies/types';
import { TRANSACTION_DURATION } from '../../../../common/elasticsearch_fieldnames';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.test.ts
index 7cc6106f671a7..3c5726ee586da 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.ts
index 5fb7ef76fc728..4e40834acccd1 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.test.ts
index 41a2fa9a5039e..3a79b4375e4a5 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.ts
index 439bb9e4b9cd6..176e7befda53b 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histogram_range_steps.ts
@@ -7,7 +7,7 @@
import { scaleLog } from 'd3-scale';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.test.ts
index 00e8c26497eb2..27fd0dc31432d 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.ts
index d526c63c7de34..500714ffdf0d5 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_histograms_generator.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.test.ts
index 57e3e6cadb9bc..67b2f580e3f4d 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.ts
index 70b5b70ce8912..4e1a7b2015614 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_percentiles.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.test.ts
index 7d67e80ae3398..3cafc17e2681b 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.ts b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.ts
index a530c997876c4..8b359c3665eaf 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/queries/query_ranges.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.test.ts b/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.test.ts
index 034bd2a60ad19..ccccdeab5132d 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.test.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/search_strategy_provider.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SearchStrategyDependencies } from 'src/plugins/data/server';
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/utils/compute_expectations_and_ranges.ts b/x-pack/plugins/apm/server/lib/search_strategies/utils/compute_expectations_and_ranges.ts
index 9ab9689fd6d30..1754a35280f86 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/utils/compute_expectations_and_ranges.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/utils/compute_expectations_and_ranges.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { PERCENTILES_STEP } from '../constants';
export const computeExpectationsAndRanges = (
diff --git a/x-pack/plugins/apm/server/lib/search_strategies/utils/field_stats_utils.ts b/x-pack/plugins/apm/server/lib/search_strategies/utils/field_stats_utils.ts
index 2eb67ec501bab..7f98f771c50e2 100644
--- a/x-pack/plugins/apm/server/lib/search_strategies/utils/field_stats_utils.ts
+++ b/x-pack/plugins/apm/server/lib/search_strategies/utils/field_stats_utils.ts
@@ -5,7 +5,8 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+
/*
* Contains utility functions for building and processing queries.
*/
diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts
index 9b2d79dc726ee..2ed1966dcacbd 100644
--- a/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts
+++ b/x-pack/plugins/apm/server/lib/service_map/get_service_anomalies.ts
@@ -7,7 +7,7 @@
import Boom from '@hapi/boom';
import { sortBy, uniqBy } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ESSearchResponse } from '../../../../../../src/core/types/elasticsearch';
import { MlPluginSetup } from '../../../../ml/server';
import { PromiseReturnType } from '../../../../observability/typings/common';
diff --git a/x-pack/plugins/apm/server/lib/services/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/lib/services/__snapshots__/queries.test.ts.snap
index 99891807e689b..d6d6219440dad 100644
--- a/x-pack/plugins/apm/server/lib/services/__snapshots__/queries.test.ts.snap
+++ b/x-pack/plugins/apm/server/lib/services/__snapshots__/queries.test.ts.snap
@@ -12,7 +12,7 @@ Object {
"body": Object {
"size": 0,
},
- "terminateAfter": 1,
+ "terminate_after": 1,
}
`;
@@ -49,7 +49,7 @@ Object {
},
"size": 0,
},
- "terminateAfter": 1,
+ "terminate_after": 1,
}
`;
@@ -99,7 +99,7 @@ Object {
},
"size": 1,
},
- "terminateAfter": 1,
+ "terminate_after": 1,
}
`;
diff --git a/x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts b/x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts
index d44468bb0bb60..ac1c2653bf148 100644
--- a/x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts
+++ b/x-pack/plugins/apm/server/lib/services/annotations/get_stored_annotations.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { ElasticsearchClient, Logger } from 'kibana/server';
import { rangeQuery } from '../../../../../observability/server';
import { environmentQuery } from '../../../../common/utils/environment_query';
@@ -75,7 +75,7 @@ export function getStoredAnnotations({
// so we should handle this error gracefully
if (
error instanceof WrappedElasticsearchClientError &&
- error.originalError instanceof ResponseError
+ error.originalError instanceof errors.ResponseError
) {
const type = error.originalError.body.error.type;
diff --git a/x-pack/plugins/apm/server/lib/services/get_service_agent.ts b/x-pack/plugins/apm/server/lib/services/get_service_agent.ts
index 5ef29437d73d6..4c9ff9f124b10 100644
--- a/x-pack/plugins/apm/server/lib/services/get_service_agent.ts
+++ b/x-pack/plugins/apm/server/lib/services/get_service_agent.ts
@@ -42,7 +42,7 @@ export async function getServiceAgent({
const { apmEventClient } = setup;
const params = {
- terminateAfter: 1,
+ terminate_after: 1,
apm: {
events: [
ProcessorEvent.error,
diff --git a/x-pack/plugins/apm/server/lib/services/get_services/get_legacy_data_status.ts b/x-pack/plugins/apm/server/lib/services/get_services/get_legacy_data_status.ts
index cf80222dc8303..5b94bb2314258 100644
--- a/x-pack/plugins/apm/server/lib/services/get_services/get_legacy_data_status.ts
+++ b/x-pack/plugins/apm/server/lib/services/get_services/get_legacy_data_status.ts
@@ -19,7 +19,7 @@ export async function getLegacyDataStatus(
const { apmEventClient } = setup;
const params = {
- terminateAfter: 1,
+ terminate_after: 1,
apm: {
events: [ProcessorEvent.transaction],
includeLegacyData: true,
diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts b/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts
index f43938891f1f0..a14019f4dbdec 100644
--- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts
+++ b/x-pack/plugins/apm/server/lib/settings/agent_configuration/create_agent_config_index.ts
@@ -36,7 +36,6 @@ const mappings: Mappings = {
dynamic_templates: [
{
// force string to keyword (instead of default of text + keyword)
- // @ts-expect-error @elastic/elasticsearch expects here mapping: MappingPropertyBase
strings: {
match_mapping_type: 'string',
mapping: {
diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_agent_name_by_service.ts b/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_agent_name_by_service.ts
index 0b6dd10b42e25..6ea3e2a578050 100644
--- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_agent_name_by_service.ts
+++ b/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_agent_name_by_service.ts
@@ -20,7 +20,7 @@ export async function getAgentNameByService({
const { apmEventClient } = setup;
const params = {
- terminateAfter: 1,
+ terminate_after: 1,
apm: {
events: [
ProcessorEvent.transaction,
diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/__snapshots__/get_transaction.test.ts.snap b/x-pack/plugins/apm/server/lib/settings/custom_link/__snapshots__/get_transaction.test.ts.snap
index 0649c8c38d29a..921129cf2c1da 100644
--- a/x-pack/plugins/apm/server/lib/settings/custom_link/__snapshots__/get_transaction.test.ts.snap
+++ b/x-pack/plugins/apm/server/lib/settings/custom_link/__snapshots__/get_transaction.test.ts.snap
@@ -44,7 +44,7 @@ Object {
},
},
"size": 1,
- "terminateAfter": 1,
+ "terminate_after": 1,
}
`;
@@ -63,6 +63,6 @@ Object {
},
},
"size": 1,
- "terminateAfter": 1,
+ "terminate_after": 1,
}
`;
diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts
index 085bb2b4be40d..752a7769caea0 100644
--- a/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts
+++ b/x-pack/plugins/apm/server/lib/settings/custom_link/create_custom_link_index.ts
@@ -6,7 +6,7 @@
*/
import { ElasticsearchClient, Logger } from 'src/core/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
createOrUpdateIndex,
Mappings,
diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.ts
index 91bc8c85bc014..1c3d1465527ba 100644
--- a/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.ts
+++ b/x-pack/plugins/apm/server/lib/settings/custom_link/get_transaction.ts
@@ -32,7 +32,7 @@ export async function getTransaction({
);
const params = {
- terminateAfter: 1,
+ terminate_after: 1,
apm: {
events: [ProcessorEvent.transaction as const],
},
diff --git a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts b/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts
index d477da85e0d9b..633545e16acfd 100644
--- a/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts
+++ b/x-pack/plugins/apm/server/lib/settings/custom_link/list_custom_links.ts
@@ -6,7 +6,7 @@
*/
import * as t from 'io-ts';
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
CustomLink,
CustomLinkES,
diff --git a/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts b/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts
index 60a28fd9abdbd..55204786b8e67 100644
--- a/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts
+++ b/x-pack/plugins/apm/server/lib/traces/get_trace_items.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ProcessorEvent } from '../../../common/processor_event';
import {
TRACE_ID,
diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts
index f082483c0c109..200d3d6ac7459 100644
--- a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts
+++ b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { sortBy } from 'lodash';
import moment from 'moment';
import { Unionize } from 'utility-types';
diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts b/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts
index 8769a572e33a0..c79dde721d138 100644
--- a/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts
+++ b/x-pack/plugins/apm/server/lib/transaction_groups/get_transaction_group_stats.ts
@@ -6,7 +6,7 @@
*/
import { merge } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { TRANSACTION_TYPE } from '../../../common/elasticsearch_fieldnames';
import { arrayUnionToCallable } from '../../../common/utils/array_union_to_callable';
import { TransactionGroupRequestBase, TransactionGroupSetup } from './fetcher';
diff --git a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts b/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts
index a61e0614f5b1a..2fcbf5842d746 100644
--- a/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts
+++ b/x-pack/plugins/apm/server/lib/transactions/get_anomaly_data/fetcher.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ESSearchResponse } from '../../../../../../../src/core/types/elasticsearch';
import { PromiseReturnType } from '../../../../../observability/typings/common';
import { rangeQuery } from '../../../../../observability/server';
diff --git a/x-pack/plugins/apm/server/lib/transactions/trace_samples/get_trace_samples/index.ts b/x-pack/plugins/apm/server/lib/transactions/trace_samples/get_trace_samples/index.ts
index 79eebf0813e36..b085c0fc4a839 100644
--- a/x-pack/plugins/apm/server/lib/transactions/trace_samples/get_trace_samples/index.ts
+++ b/x-pack/plugins/apm/server/lib/transactions/trace_samples/get_trace_samples/index.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { withApmSpan } from '../../../../utils/with_apm_span';
import {
SERVICE_NAME,
diff --git a/x-pack/plugins/apm/server/projections/metrics.ts b/x-pack/plugins/apm/server/projections/metrics.ts
index ce5a506752b65..417281f2de487 100644
--- a/x-pack/plugins/apm/server/projections/metrics.ts
+++ b/x-pack/plugins/apm/server/projections/metrics.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
SERVICE_NAME,
SERVICE_NODE_NAME,
diff --git a/x-pack/plugins/apm/server/projections/typings.ts b/x-pack/plugins/apm/server/projections/typings.ts
index 0843fa4c9dd64..d252fd311b4fe 100644
--- a/x-pack/plugins/apm/server/projections/typings.ts
+++ b/x-pack/plugins/apm/server/projections/typings.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { AggregationOptionsByType } from '../../../../../src/core/types/elasticsearch';
import { APMEventESSearchRequest } from '../lib/helpers/create_es_client/create_apm_event_client';
diff --git a/x-pack/plugins/apm/server/routes/historical_data/has_historical_agent_data.ts b/x-pack/plugins/apm/server/routes/historical_data/has_historical_agent_data.ts
index 13591b47a8584..54960c3e48b60 100644
--- a/x-pack/plugins/apm/server/routes/historical_data/has_historical_agent_data.ts
+++ b/x-pack/plugins/apm/server/routes/historical_data/has_historical_agent_data.ts
@@ -13,7 +13,7 @@ export async function hasHistoricalAgentData(setup: Setup) {
const { apmEventClient } = setup;
const params = {
- terminateAfter: 1,
+ terminate_after: 1,
apm: {
events: [
ProcessorEvent.error,
diff --git a/x-pack/plugins/apm/server/routes/register_routes/index.ts b/x-pack/plugins/apm/server/routes/register_routes/index.ts
index d3587f1fcbe4b..576c23dc0882f 100644
--- a/x-pack/plugins/apm/server/routes/register_routes/index.ts
+++ b/x-pack/plugins/apm/server/routes/register_routes/index.ts
@@ -8,7 +8,7 @@
import Boom from '@hapi/boom';
import * as t from 'io-ts';
import { KibanaRequest, RouteRegistrar } from 'src/core/server';
-import { RequestAbortedError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import agent from 'elastic-apm-node';
import { ServerRouteRepository } from '@kbn/server-route-repository';
import { merge } from 'lodash';
@@ -170,7 +170,7 @@ export function registerRoutes({
},
};
- if (error instanceof RequestAbortedError) {
+ if (error instanceof errors.RequestAbortedError) {
return response.custom(merge(opts, CLIENT_CLOSED_REQUEST));
}
diff --git a/x-pack/plugins/canvas/types/strategy.ts b/x-pack/plugins/canvas/types/strategy.ts
index d7115a3e4372f..2cc4c72116cdb 100644
--- a/x-pack/plugins/canvas/types/strategy.ts
+++ b/x-pack/plugins/canvas/types/strategy.ts
@@ -5,8 +5,8 @@
* 2.0.
*/
-import { ApiResponse } from '@elastic/elasticsearch/lib/Transport';
-import { estypes } from '@elastic/elasticsearch';
+import { TransportResult } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IKibanaSearchRequest } from 'src/plugins/data/common';
import { ExpressionValueFilter } from '.';
export interface EssqlSearchStrategyRequest extends IKibanaSearchRequest {
@@ -27,5 +27,5 @@ export interface EssqlSearchStrategyResponse {
}>;
rows: any[];
- rawResponse: ApiResponse;
+ rawResponse: TransportResult;
}
diff --git a/x-pack/plugins/cases/server/services/cases/index.ts b/x-pack/plugins/cases/server/services/cases/index.ts
index 3c76be6d6dd93..4a22793f78af5 100644
--- a/x-pack/plugins/cases/server/services/cases/index.ts
+++ b/x-pack/plugins/cases/server/services/cases/index.ts
@@ -19,7 +19,7 @@ import {
SavedObjectsResolveResponse,
} from 'kibana/server';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { nodeBuilder, KueryNode } from '../../../../../../src/plugins/data/common';
import { SecurityPluginSetup } from '../../../../security/server';
diff --git a/x-pack/plugins/data_enhanced/server/collectors/fetch.ts b/x-pack/plugins/data_enhanced/server/collectors/fetch.ts
index 73dcc89a79b39..f60d6f32871d3 100644
--- a/x-pack/plugins/data_enhanced/server/collectors/fetch.ts
+++ b/x-pack/plugins/data_enhanced/server/collectors/fetch.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Logger } from 'kibana/server';
import { CollectorFetchContext } from '../../../../../src/plugins/usage_collection/server';
import { SEARCH_SESSION_TYPE } from '../../../../../src/plugins/data/common';
diff --git a/x-pack/plugins/data_enhanced/server/search/session/get_search_status.ts b/x-pack/plugins/data_enhanced/server/search/session/get_search_status.ts
index 461c41b46491c..a49dc30b84fb5 100644
--- a/x-pack/plugins/data_enhanced/server/search/session/get_search_status.ts
+++ b/x-pack/plugins/data_enhanced/server/search/session/get_search_status.ts
@@ -6,7 +6,7 @@
*/
import { i18n } from '@kbn/i18n';
-import { ApiResponse } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
import { ElasticsearchClient } from 'src/core/server';
import { SearchStatus } from './types';
import { SearchSessionRequestInfo } from '../../../../../../src/plugins/data/common';
@@ -19,9 +19,11 @@ export async function getSearchStatus(
// TODO: Handle strategies other than the default one
try {
// @ts-expect-error start_time_in_millis: EpochMillis is string | number
- const apiResponse: ApiResponse = await client.asyncSearch.status({
- id: asyncId,
- });
+ const apiResponse: TransportResult = await client.asyncSearch.status(
+ {
+ id: asyncId,
+ }
+ );
const response = apiResponse.body;
if ((response.is_partial && !response.is_running) || response.completion_status >= 400) {
return {
diff --git a/x-pack/plugins/data_visualizer/common/types/indices.ts b/x-pack/plugins/data_visualizer/common/types/indices.ts
index c80b89b4e84c7..dd4bea8602720 100644
--- a/x-pack/plugins/data_visualizer/common/types/indices.ts
+++ b/x-pack/plugins/data_visualizer/common/types/indices.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export interface IndicesOptions {
allow_no_indices?: boolean;
diff --git a/x-pack/plugins/data_visualizer/common/utils/datafeed_utils.ts b/x-pack/plugins/data_visualizer/common/utils/datafeed_utils.ts
index bccd40ed43b0c..5a87d7b01db46 100644
--- a/x-pack/plugins/data_visualizer/common/utils/datafeed_utils.ts
+++ b/x-pack/plugins/data_visualizer/common/utils/datafeed_utils.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export type Datafeed = estypes.MlDatafeed;
export type Aggregation = Record;
diff --git a/x-pack/plugins/data_visualizer/common/utils/query_utils.ts b/x-pack/plugins/data_visualizer/common/utils/query_utils.ts
index d2785072f419d..2aa4cd063d1b1 100644
--- a/x-pack/plugins/data_visualizer/common/utils/query_utils.ts
+++ b/x-pack/plugins/data_visualizer/common/utils/query_utils.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
/*
* Contains utility functions for building and processing queries.
*/
diff --git a/x-pack/plugins/data_visualizer/common/utils/runtime_field_utils.ts b/x-pack/plugins/data_visualizer/common/utils/runtime_field_utils.ts
index fbe4ae5c6faf1..a088685f03f54 100644
--- a/x-pack/plugins/data_visualizer/common/utils/runtime_field_utils.ts
+++ b/x-pack/plugins/data_visualizer/common/utils/runtime_field_utils.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { isPopulatedObject } from './object_utils';
import { RUNTIME_FIELD_TYPES } from '../../../../../src/plugins/data/common';
diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/full_time_range_selector/full_time_range_selector_service.ts b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/full_time_range_selector/full_time_range_selector_service.ts
index 198079c6ec9de..f2d14de9812ca 100644
--- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/full_time_range_selector/full_time_range_selector_service.ts
+++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/components/full_time_range_selector/full_time_range_selector_service.ts
@@ -6,7 +6,7 @@
*/
import moment from 'moment';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Query, TimefilterContract } from 'src/plugins/data/public';
import dateMath from '@elastic/datemath';
import { IndexPattern } from '../../../../../../../../src/plugins/data/public';
diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/data_loader/data_loader.ts b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/data_loader/data_loader.ts
index c4db51dcd81bc..e0a2852a57b29 100644
--- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/data_loader/data_loader.ts
+++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/data_loader/data_loader.ts
@@ -7,7 +7,7 @@
// Maximum number of examples to obtain for text type fields.
import { CoreSetup } from 'kibana/public';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { i18n } from '@kbn/i18n';
import { IndexPattern } from '../../../../../../../src/plugins/data/common';
import { NON_AGGREGATABLE_FIELD_TYPES, OMIT_FIELDS } from '../../../../common/constants';
diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/services/time_field_range.ts b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/services/time_field_range.ts
index 87d4a3b7fb711..58a4bd4520829 100644
--- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/services/time_field_range.ts
+++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/services/time_field_range.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { lazyLoadModules } from '../../../lazy_load_bundle';
import { GetTimeFieldRangeResponse } from '../../../../common/types/time_field_request';
import { Query } from '../../../../../../../src/plugins/data/common/query';
diff --git a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/services/visualizer_stats.ts b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/services/visualizer_stats.ts
index 8db267a1dc837..3653936f3d12e 100644
--- a/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/services/visualizer_stats.ts
+++ b/x-pack/plugins/data_visualizer/public/application/index_data_visualizer/services/visualizer_stats.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { lazyLoadModules } from '../../../lazy_load_bundle';
import type { DocumentCounts, FieldRequestConfig, FieldVisStats } from '../../../../common/types';
import { OverallStats } from '../types/overall_stats';
diff --git a/x-pack/plugins/data_visualizer/server/models/data_visualizer/check_fields_exist.ts b/x-pack/plugins/data_visualizer/server/models/data_visualizer/check_fields_exist.ts
index f0cbffbfa70c3..24b4deeecdddd 100644
--- a/x-pack/plugins/data_visualizer/server/models/data_visualizer/check_fields_exist.ts
+++ b/x-pack/plugins/data_visualizer/server/models/data_visualizer/check_fields_exist.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { get } from 'lodash';
import { IScopedClusterClient } from 'kibana/server';
import { AggCardinality, Aggs, FieldData } from '../../types';
diff --git a/x-pack/plugins/data_visualizer/server/models/data_visualizer/data_visualizer.ts b/x-pack/plugins/data_visualizer/server/models/data_visualizer/data_visualizer.ts
index 003d5a7d86015..42e7f93cc8789 100644
--- a/x-pack/plugins/data_visualizer/server/models/data_visualizer/data_visualizer.ts
+++ b/x-pack/plugins/data_visualizer/server/models/data_visualizer/data_visualizer.ts
@@ -7,7 +7,7 @@
import { IScopedClusterClient } from 'kibana/server';
import { each, last } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { JOB_FIELD_TYPES } from '../../../common';
import type {
BatchStats,
diff --git a/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_field_examples.ts b/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_field_examples.ts
index 69476e254068f..78adfb9e81b95 100644
--- a/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_field_examples.ts
+++ b/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_field_examples.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { get } from 'lodash';
import { IScopedClusterClient } from 'kibana/server';
import { buildBaseFilterCriteria } from '../../../common/utils/query_utils';
diff --git a/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_fields_stats.ts b/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_fields_stats.ts
index 6968aa97ab938..da93719e9ed93 100644
--- a/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_fields_stats.ts
+++ b/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_fields_stats.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { each, find, get } from 'lodash';
import { IScopedClusterClient } from 'kibana/server';
import {
diff --git a/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_histogram_for_fields.ts b/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_histogram_for_fields.ts
index 6621c793c0017..1cbf40a22b056 100644
--- a/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_histogram_for_fields.ts
+++ b/x-pack/plugins/data_visualizer/server/models/data_visualizer/get_histogram_for_fields.ts
@@ -6,7 +6,7 @@
*/
import { IScopedClusterClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { get } from 'lodash';
import { ChartData, ChartRequestAgg, HistogramField, NumericColumnStatsMap } from '../../types';
import { KBN_FIELD_TYPES } from '../../../../../../src/plugins/data/common';
diff --git a/x-pack/plugins/data_visualizer/server/routes/routes.ts b/x-pack/plugins/data_visualizer/server/routes/routes.ts
index 74afae2634636..1ec2eaa242c1c 100644
--- a/x-pack/plugins/data_visualizer/server/routes/routes.ts
+++ b/x-pack/plugins/data_visualizer/server/routes/routes.ts
@@ -6,7 +6,7 @@
*/
import type { CoreSetup, IScopedClusterClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
dataVisualizerFieldHistogramsSchema,
dataVisualizerFieldStatsSchema,
diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts
index f4140298928b6..314a6b9a31ef8 100644
--- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts
+++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts
@@ -16,7 +16,8 @@ import { findOptionsSchema } from '../event_log_client';
import { delay } from '../lib/delay';
import { times } from 'lodash';
import { DeeplyMockedKeys } from '@kbn/utility-types/jest';
-import { estypes, RequestEvent } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/types';
+import type { TransportResult } from '@elastic/elasticsearch';
type MockedLogger = ReturnType;
@@ -399,9 +400,7 @@ describe('setIndexToHidden', () => {
expect(clusterClient.indices.putSettings).toHaveBeenCalledWith({
index: 'foo-bar-000001',
body: {
- settings: {
- 'index.hidden': true,
- },
+ 'index.hidden': true,
},
});
});
@@ -1270,10 +1269,10 @@ type RetryableFunction = () => boolean;
const RETRY_UNTIL_DEFAULT_COUNT = 20;
const RETRY_UNTIL_DEFAULT_WAIT = 1000; // milliseconds
-function asApiResponse(body: T): RequestEvent {
+function asApiResponse(body: T): TransportResult {
return {
body,
- } as RequestEvent;
+ } as TransportResult;
}
async function retryUntil(
diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts
index 7eb3328dddb6b..7246e1ed972ec 100644
--- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts
+++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.ts
@@ -11,7 +11,7 @@ import { reject, isUndefined, isNumber, pick } from 'lodash';
import type { PublicMethodsOf } from '@kbn/utility-types';
import { Logger, ElasticsearchClient } from 'src/core/server';
import util from 'util';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query';
import { IEvent, IValidatedEvent, SAVED_OBJECT_REL_PRIMARY } from '../types';
import { FindOptionsType } from '../event_log_client';
@@ -255,9 +255,7 @@ export class ClusterClientAdapter ({ version: '1.2.3' }));
jest.mock('./init');
@@ -63,6 +63,7 @@ describe('createEsContext', () => {
kibanaVersion: '1.2.3',
elasticsearchClientPromise: Promise.resolve(elasticsearchClient),
});
+
elasticsearchClient.indices.existsTemplate.mockResolvedValue(asApiResponse(false));
elasticsearchClient.indices.existsIndexTemplate.mockResolvedValue(asApiResponse(false));
elasticsearchClient.indices.existsAlias.mockResolvedValue(asApiResponse(false));
@@ -113,8 +114,8 @@ describe('createEsContext', () => {
});
});
-function asApiResponse(body: T): RequestEvent {
+function asApiResponse(body: T): TransportResult {
return {
body,
- } as RequestEvent;
+ } as TransportResult;
}
diff --git a/x-pack/plugins/event_log/server/es/init.ts b/x-pack/plugins/event_log/server/es/init.ts
index f15b9f89887c5..7641404c484ce 100644
--- a/x-pack/plugins/event_log/server/es/init.ts
+++ b/x-pack/plugins/event_log/server/es/init.ts
@@ -5,8 +5,11 @@
* 2.0.
*/
-import { IndicesAlias, IndicesIndexStatePrefixedSettings } from '@elastic/elasticsearch/api/types';
-import { estypes } from '@elastic/elasticsearch';
+import {
+ IndicesAlias,
+ IndicesIndexStatePrefixedSettings,
+} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { asyncForEach } from '@kbn/std';
import { getIlmPolicy, getIndexTemplate } from './documents';
import { EsContext } from './context';
diff --git a/x-pack/plugins/file_upload/common/types.ts b/x-pack/plugins/file_upload/common/types.ts
index 8462f8983a67d..6e72b749bdb61 100644
--- a/x-pack/plugins/file_upload/common/types.ts
+++ b/x-pack/plugins/file_upload/common/types.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ES_FIELD_TYPES } from 'src/plugins/data/common';
export interface InputOverrides {
diff --git a/x-pack/plugins/file_upload/server/get_time_field_range.ts b/x-pack/plugins/file_upload/server/get_time_field_range.ts
index 0e8358f1671d0..1c8e94d5fc301 100644
--- a/x-pack/plugins/file_upload/server/get_time_field_range.ts
+++ b/x-pack/plugins/file_upload/server/get_time_field_range.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
import { IScopedClusterClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { isPopulatedObject } from './utils/runtime_field_utils';
export async function getTimeFieldRange(
diff --git a/x-pack/plugins/file_upload/server/utils/runtime_field_utils.ts b/x-pack/plugins/file_upload/server/utils/runtime_field_utils.ts
index aba6effe175c0..09a473b611ac9 100644
--- a/x-pack/plugins/file_upload/server/utils/runtime_field_utils.ts
+++ b/x-pack/plugins/file_upload/server/utils/runtime_field_utils.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { RUNTIME_FIELD_TYPES } from '../../../../../src/plugins/data/common';
type RuntimeType = typeof RUNTIME_FIELD_TYPES[number];
diff --git a/x-pack/plugins/fleet/common/types/models/epm.ts b/x-pack/plugins/fleet/common/types/models/epm.ts
index 6f107ae44bfa7..078281fec9806 100644
--- a/x-pack/plugins/fleet/common/types/models/epm.ts
+++ b/x-pack/plugins/fleet/common/types/models/epm.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
// Follow pattern from https://github.com/elastic/kibana/pull/52447
// TODO: Update when https://github.com/elastic/kibana/issues/53021 is closed
import type { SavedObject, SavedObjectAttributes, SavedObjectReference } from 'src/core/public';
diff --git a/x-pack/plugins/fleet/server/errors/index.ts b/x-pack/plugins/fleet/server/errors/index.ts
index 22f4b8cd6daab..6075b7e441fdf 100644
--- a/x-pack/plugins/fleet/server/errors/index.ts
+++ b/x-pack/plugins/fleet/server/errors/index.ts
@@ -6,6 +6,8 @@
*/
/* eslint-disable max-classes-per-file */
+import type { ElasticsearchErrorDetails } from 'src/core/server';
+
import { isESClientError } from './utils';
export { defaultIngestErrorHandler, ingestErrorToResponseOptions } from './handlers';
@@ -65,8 +67,8 @@ export class ArtifactsElasticsearchError extends IngestManagerError {
constructor(public readonly meta: Error) {
super(
`${
- isESClientError(meta) && meta.meta.body?.error?.reason
- ? meta.meta.body?.error?.reason
+ isESClientError(meta) && (meta.meta.body as ElasticsearchErrorDetails)?.error?.reason
+ ? (meta.meta.body as ElasticsearchErrorDetails)?.error?.reason
: `Elasticsearch error while working with artifacts: ${meta.message}`
}`
);
diff --git a/x-pack/plugins/fleet/server/errors/utils.ts b/x-pack/plugins/fleet/server/errors/utils.ts
index d58f82b94fcd7..23e92cdcd9f51 100644
--- a/x-pack/plugins/fleet/server/errors/utils.ts
+++ b/x-pack/plugins/fleet/server/errors/utils.ts
@@ -5,10 +5,10 @@
* 2.0.
*/
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
-export function isESClientError(error: unknown): error is ResponseError {
- return error instanceof ResponseError;
+export function isESClientError(error: unknown): error is errors.ResponseError {
+ return error instanceof errors.ResponseError;
}
export function isElasticsearchVersionConflictError(error: Error): boolean {
diff --git a/x-pack/plugins/fleet/server/routes/app/index.ts b/x-pack/plugins/fleet/server/routes/app/index.ts
index 43614f3a286b0..e46e57d3838b4 100644
--- a/x-pack/plugins/fleet/server/routes/app/index.ts
+++ b/x-pack/plugins/fleet/server/routes/app/index.ts
@@ -48,7 +48,10 @@ export const getCheckPermissionsHandler: RequestHandler = async (context, reques
export const generateServiceTokenHandler: RequestHandler = async (context, request, response) => {
const esClient = context.core.elasticsearch.client.asCurrentUser;
try {
- const { body: tokenResponse } = await esClient.transport.request({
+ const { body: tokenResponse } = await esClient.transport.request<{
+ created?: boolean;
+ token?: GenerateServiceTokenResponse;
+ }>({
method: 'POST',
path: `_security/service/elastic/fleet-server/credential/token/token-${Date.now()}`,
});
diff --git a/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts b/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts
index 050b1a2441fed..232df94d7610b 100644
--- a/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts
+++ b/x-pack/plugins/fleet/server/routes/data_streams/handlers.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { keyBy, keys, merge } from 'lodash';
import type { RequestHandler } from 'src/core/server';
diff --git a/x-pack/plugins/fleet/server/services/agents/crud.ts b/x-pack/plugins/fleet/server/services/agents/crud.ts
index 03647c52e05f0..b8d7c284309df 100644
--- a/x-pack/plugins/fleet/server/services/agents/crud.ts
+++ b/x-pack/plugins/fleet/server/services/agents/crud.ts
@@ -6,7 +6,7 @@
*/
import Boom from '@hapi/boom';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { SavedObjectsClientContract, ElasticsearchClient } from 'src/core/server';
import type { KueryNode } from '@kbn/es-query';
@@ -126,10 +126,12 @@ export async function getAgentsByKuery(
index: AGENTS_INDEX,
from: (page - 1) * perPage,
size: perPage,
- sort: `${sortField}:${sortOrder}`,
track_total_hits: true,
ignore_unavailable: true,
- body,
+ body: {
+ ...body,
+ sort: [{ [sortField]: { order: sortOrder } }],
+ },
});
let agents = res.body.hits.hits.map(searchHitToAgent);
@@ -219,6 +221,7 @@ export function isAgentDocument(
}
export type ESAgentDocumentResult = estypes.MgetHit;
+
export async function getAgentDocuments(
esClient: ElasticsearchClient,
agentIds: string[]
@@ -315,10 +318,9 @@ export async function bulkUpdateAgents(
});
return {
- items: res.body.items.map((item: estypes.BulkResponseItemContainer) => ({
+ items: res.body.items.map((item) => ({
id: item.update!._id as string,
success: !item.update!.error,
- // @ts-expect-error ErrorCause is not assignable to Error
error: item.update!.error as Error,
})),
};
diff --git a/x-pack/plugins/fleet/server/services/agents/helpers.ts b/x-pack/plugins/fleet/server/services/agents/helpers.ts
index 195b2567c24ae..609d5ba6c83a0 100644
--- a/x-pack/plugins/fleet/server/services/agents/helpers.ts
+++ b/x-pack/plugins/fleet/server/services/agents/helpers.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { SearchHit } from '../../../../../../src/core/types/elasticsearch';
import type { Agent, AgentSOAttributes, FleetServerAgent } from '../../types';
diff --git a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts
index a87432c639249..71935ffa5f90c 100644
--- a/x-pack/plugins/fleet/server/services/agents/reassign.test.ts
+++ b/x-pack/plugins/fleet/server/services/agents/reassign.test.ts
@@ -6,6 +6,7 @@
*/
import { elasticsearchServiceMock, savedObjectsClientMock } from 'src/core/server/mocks';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { SavedObject } from 'kibana/server';
import type { AgentPolicy } from '../../types';
@@ -47,7 +48,10 @@ describe('reassignAgent (singular)', () => {
expect(esClient.update).toBeCalledTimes(1);
const calledWith = esClient.update.mock.calls[0];
expect(calledWith[0]?.id).toBe(agentInRegularDoc._id);
- expect(calledWith[0]?.body?.doc).toHaveProperty('policy_id', regularAgentPolicySO.id);
+ expect((calledWith[0] as estypes.UpdateRequest)?.body?.doc).toHaveProperty(
+ 'policy_id',
+ regularAgentPolicySO.id
+ );
});
it('cannot reassign from regular agent policy to hosted', async () => {
@@ -85,7 +89,7 @@ describe('reassignAgents (plural)', () => {
// calls ES update with correct values
const calledWith = esClient.bulk.mock.calls[0][0];
// only 1 are regular and bulk write two line per update
- expect(calledWith.body?.length).toBe(2);
+ expect((calledWith as estypes.BulkRequest).body?.length).toBe(2);
// @ts-expect-error
expect(calledWith.body[0].update._id).toEqual(agentInRegularDoc._id);
});
diff --git a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts
index 3621bc5025ab3..7f744ba6a59f4 100644
--- a/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts
+++ b/x-pack/plugins/fleet/server/services/agents/unenroll.test.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { elasticsearchServiceMock, savedObjectsClientMock } from 'src/core/server/mocks';
import type { SavedObject } from 'kibana/server';
@@ -43,7 +43,9 @@ describe('unenrollAgent (singular)', () => {
expect(esClient.update).toBeCalledTimes(1);
const calledWith = esClient.update.mock.calls[0];
expect(calledWith[0]?.id).toBe(agentInRegularDoc._id);
- expect(calledWith[0]?.body).toHaveProperty('doc.unenrollment_started_at');
+ expect((calledWith[0] as estypes.UpdateRequest)?.body).toHaveProperty(
+ 'doc.unenrollment_started_at'
+ );
});
it('cannot unenroll from hosted agent policy by default', async () => {
@@ -71,7 +73,9 @@ describe('unenrollAgent (singular)', () => {
expect(esClient.update).toBeCalledTimes(1);
const calledWith = esClient.update.mock.calls[0];
expect(calledWith[0]?.id).toBe(agentInHostedDoc._id);
- expect(calledWith[0]?.body).toHaveProperty('doc.unenrollment_started_at');
+ expect((calledWith[0] as estypes.UpdateRequest)?.body).toHaveProperty(
+ 'doc.unenrollment_started_at'
+ );
});
it('can unenroll from hosted agent policy with force=true and revoke=true', async () => {
@@ -81,7 +85,7 @@ describe('unenrollAgent (singular)', () => {
expect(esClient.update).toBeCalledTimes(1);
const calledWith = esClient.update.mock.calls[0];
expect(calledWith[0]?.id).toBe(agentInHostedDoc._id);
- expect(calledWith[0]?.body).toHaveProperty('doc.unenrolled_at');
+ expect((calledWith[0] as estypes.UpdateRequest)?.body).toHaveProperty('doc.unenrolled_at');
});
});
@@ -93,10 +97,12 @@ describe('unenrollAgents (plural)', () => {
// calls ES update with correct values
const calledWith = esClient.bulk.mock.calls[1][0];
- const ids = calledWith?.body
+ const ids = (calledWith as estypes.BulkRequest)?.body
?.filter((i: any) => i.update !== undefined)
.map((i: any) => i.update._id);
- const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc);
+ const docs = (calledWith as estypes.BulkRequest)?.body
+ ?.filter((i: any) => i.doc)
+ .map((i: any) => i.doc);
expect(ids).toEqual(idsToUnenroll);
for (const doc of docs!) {
expect(doc).toHaveProperty('unenrollment_started_at');
@@ -111,10 +117,12 @@ describe('unenrollAgents (plural)', () => {
// calls ES update with correct values
const onlyRegular = [agentInRegularDoc._id, agentInRegularDoc2._id];
const calledWith = esClient.bulk.mock.calls[1][0];
- const ids = calledWith?.body
+ const ids = (calledWith as estypes.BulkRequest)?.body
?.filter((i: any) => i.update !== undefined)
.map((i: any) => i.update._id);
- const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc);
+ const docs = (calledWith as estypes.BulkRequest)?.body
+ ?.filter((i: any) => i.doc)
+ .map((i: any) => i.doc);
expect(ids).toEqual(onlyRegular);
for (const doc of docs!) {
expect(doc).toHaveProperty('unenrollment_started_at');
@@ -149,10 +157,12 @@ describe('unenrollAgents (plural)', () => {
// calls ES update with correct values
const onlyRegular = [agentInRegularDoc._id, agentInRegularDoc2._id];
const calledWith = esClient.bulk.mock.calls[0][0];
- const ids = calledWith?.body
+ const ids = (calledWith as estypes.BulkRequest)?.body
?.filter((i: any) => i.update !== undefined)
.map((i: any) => i.update._id);
- const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc);
+ const docs = (calledWith as estypes.BulkRequest)?.body
+ ?.filter((i: any) => i.doc)
+ .map((i: any) => i.doc);
expect(ids).toEqual(onlyRegular);
for (const doc of docs!) {
expect(doc).toHaveProperty('unenrolled_at');
@@ -166,10 +176,12 @@ describe('unenrollAgents (plural)', () => {
// calls ES update with correct values
const calledWith = esClient.bulk.mock.calls[1][0];
- const ids = calledWith?.body
+ const ids = (calledWith as estypes.BulkRequest)?.body
?.filter((i: any) => i.update !== undefined)
.map((i: any) => i.update._id);
- const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc);
+ const docs = (calledWith as estypes.BulkRequest)?.body
+ ?.filter((i: any) => i.doc)
+ .map((i: any) => i.doc);
expect(ids).toEqual(idsToUnenroll);
for (const doc of docs!) {
expect(doc).toHaveProperty('unenrollment_started_at');
@@ -204,10 +216,12 @@ describe('unenrollAgents (plural)', () => {
// calls ES update with correct values
const calledWith = esClient.bulk.mock.calls[0][0];
- const ids = calledWith?.body
+ const ids = (calledWith as estypes.BulkRequest)?.body
?.filter((i: any) => i.update !== undefined)
.map((i: any) => i.update._id);
- const docs = calledWith?.body?.filter((i: any) => i.doc).map((i: any) => i.doc);
+ const docs = (calledWith as estypes.BulkRequest)?.body
+ ?.filter((i: any) => i.doc)
+ .map((i: any) => i.doc);
expect(ids).toEqual(idsToUnenroll);
for (const doc of docs!) {
expect(doc).toHaveProperty('unenrolled_at');
diff --git a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts
index cc2357351f6df..166bd26e0d706 100644
--- a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts
+++ b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts
@@ -8,7 +8,7 @@
import uuid from 'uuid';
import Boom from '@hapi/boom';
import { i18n } from '@kbn/i18n';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import type { SavedObjectsClientContract, ElasticsearchClient } from 'src/core/server';
import { toElasticsearchQuery, fromKueryExpression } from '@kbn/es-query';
@@ -42,10 +42,12 @@ export async function listEnrollmentApiKeys(
index: ENROLLMENT_API_KEYS_INDEX,
from: (page - 1) * perPage,
size: perPage,
- sort: 'created_at:desc',
track_total_hits: true,
ignore_unavailable: true,
- body: query ? { query } : undefined,
+ body: {
+ sort: [{ created_at: { order: 'desc' } }],
+ ...(query ? { query } : {}),
+ },
});
// @ts-expect-error @elastic/elasticsearch _source is optional
@@ -84,7 +86,7 @@ export async function getEnrollmentAPIKey(
// @ts-expect-error esDocToEnrollmentApiKey doesn't accept optional _source
return esDocToEnrollmentApiKey(res.body);
} catch (e) {
- if (e instanceof ResponseError && e.statusCode === 404) {
+ if (e instanceof errors.ResponseError && e.statusCode === 404) {
throw Boom.notFound(`Enrollment api key ${id} not found`);
}
diff --git a/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts b/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts
index b046b41d73722..a0e186aafb79a 100644
--- a/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts
+++ b/x-pack/plugins/fleet/server/services/artifacts/artifacts.test.ts
@@ -7,9 +7,9 @@
import { elasticsearchServiceMock } from 'src/core/server/mocks';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
-import type { ApiResponse } from '@elastic/elasticsearch/lib/Transport';
+import type { TransportResult } from '@elastic/elasticsearch';
import { FLEET_SERVER_ARTIFACTS_INDEX } from '../../../common';
@@ -43,6 +43,7 @@ describe('When using the artifacts services', () => {
describe('and calling `getArtifact()`', () => {
it('should get artifact using id', async () => {
+ // @ts-expect-error not full interface
esClientMock.get.mockImplementation(() => {
return elasticsearchServiceMock.createSuccessTransportRequestPromise(
generateArtifactEsGetSingleHitMock()
@@ -64,7 +65,7 @@ describe('When using the artifacts services', () => {
it('should throw an ArtifactElasticsearchError if one is encountered', async () => {
esClientMock.get.mockImplementation(() => {
return elasticsearchServiceMock.createErrorTransportRequestPromise(
- new ResponseError(generateEsRequestErrorApiResponseMock())
+ new errors.ResponseError(generateEsRequestErrorApiResponseMock())
);
});
@@ -103,9 +104,8 @@ describe('When using the artifacts services', () => {
});
it('should ignore 409 errors from elasticsearch', async () => {
- const error = new ResponseError({ statusCode: 409 } as ApiResponse);
+ const error = new errors.ResponseError({ statusCode: 409 } as TransportResult);
// Unclear why `mockRejectedValue()` has the params value type set to `never`
- // @ts-expect-error
esClientMock.create.mockRejectedValue(error);
await expect(() => createArtifact(esClientMock, newArtifact)).not.toThrow();
});
@@ -140,6 +140,7 @@ describe('When using the artifacts services', () => {
describe('and calling `listArtifacts()`', () => {
beforeEach(() => {
+ // @ts-expect-error not full interface
esClientMock.search.mockImplementation(() => {
return elasticsearchServiceMock.createSuccessTransportRequestPromise(
generateArtifactEsSearchResultHitsMock()
@@ -152,11 +153,13 @@ describe('When using the artifacts services', () => {
expect(esClientMock.search).toHaveBeenCalledWith({
index: FLEET_SERVER_ARTIFACTS_INDEX,
- sort: 'created:asc',
ignore_unavailable: true,
q: '',
from: 0,
size: 20,
+ body: {
+ sort: [{ created: { order: 'asc' } }],
+ },
});
expect(results).toEqual({
@@ -184,11 +187,13 @@ describe('When using the artifacts services', () => {
expect(esClientMock.search).toHaveBeenCalledWith({
index: FLEET_SERVER_ARTIFACTS_INDEX,
- sort: 'identifier:desc',
q: 'packageName:endpoint',
ignore_unavailable: true,
from: 450,
size: 50,
+ body: {
+ sort: [{ identifier: { order: 'desc' } }],
+ },
});
expect(listMeta).toEqual({
diff --git a/x-pack/plugins/fleet/server/services/artifacts/artifacts.ts b/x-pack/plugins/fleet/server/services/artifacts/artifacts.ts
index 6ac23cb1f9ef8..3a6db6fd0d04f 100644
--- a/x-pack/plugins/fleet/server/services/artifacts/artifacts.ts
+++ b/x-pack/plugins/fleet/server/services/artifacts/artifacts.ts
@@ -103,11 +103,13 @@ export const listArtifacts = async (
try {
const searchResult = await esClient.search({
index: FLEET_SERVER_ARTIFACTS_INDEX,
- sort: `${sortField}:${sortOrder}`,
q: kuery,
from: (page - 1) * perPage,
ignore_unavailable: true,
size: perPage,
+ body: {
+ sort: [{ [sortField]: { order: sortOrder } }],
+ },
});
return {
diff --git a/x-pack/plugins/fleet/server/services/artifacts/client.test.ts b/x-pack/plugins/fleet/server/services/artifacts/client.test.ts
index 470f1d4ce0a84..ae875df26371c 100644
--- a/x-pack/plugins/fleet/server/services/artifacts/client.test.ts
+++ b/x-pack/plugins/fleet/server/services/artifacts/client.test.ts
@@ -28,6 +28,7 @@ describe('When using the Fleet Artifacts Client', () => {
singleHit._source.package_name = 'not endpoint';
}
+ // @ts-expect-error not full interface
esClientMock.get.mockImplementation(() => {
return elasticsearchServiceMock.createSuccessTransportRequestPromise(singleHit);
});
@@ -104,6 +105,7 @@ describe('When using the Fleet Artifacts Client', () => {
describe('and calling `listArtifacts()`', () => {
beforeEach(() => {
+ // @ts-expect-error not full interface
esClientMock.search.mockImplementation(() => {
return elasticsearchServiceMock.createSuccessTransportRequestPromise(
generateArtifactEsSearchResultHitsMock()
diff --git a/x-pack/plugins/fleet/server/services/artifacts/mocks.ts b/x-pack/plugins/fleet/server/services/artifacts/mocks.ts
index 2799e1807123d..bc22bff0b29d0 100644
--- a/x-pack/plugins/fleet/server/services/artifacts/mocks.ts
+++ b/x-pack/plugins/fleet/server/services/artifacts/mocks.ts
@@ -6,8 +6,8 @@
*/
import { URL } from 'url';
-import type { ApiResponse } from '@elastic/elasticsearch';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import type { TransportResult } from '@elastic/elasticsearch';
+import { errors } from '@elastic/elasticsearch';
import { elasticsearchServiceMock } from '../../../../../../src/core/server/mocks';
import type { SearchHit, ESSearchResponse } from '../../../../../../src/core/types/elasticsearch';
@@ -69,7 +69,7 @@ export interface GenerateEsRequestErrorApiResponseMockProps {
export const generateEsRequestErrorApiResponseMock = (
{ statusCode = 500 }: GenerateEsRequestErrorApiResponseMockProps = { statusCode: 500 }
-): ApiResponse => {
+): TransportResult => {
return generateEsApiResponseMock(
{
_index: '.fleet-artifacts_1',
@@ -127,8 +127,8 @@ export const generateArtifactEsSearchResultHitsMock = (): ESSearchResponse<
export const generateEsApiResponseMock = >(
body: TBody,
- otherProps: Partial> = {}
-): ApiResponse => {
+ otherProps: Partial> = {}
+): TransportResult => {
return elasticsearchServiceMock.createApiResponse({
body,
headers: {
@@ -148,8 +148,6 @@ export const generateEsApiResponseMock = >(
id: 7160,
},
name: 'elasticsearch-js',
- // There are some properties missing below which is not important for this mock
- // @ts-ignore
connection: {
url: new URL('http://localhost:9200/'),
id: 'http://localhost:9200/',
@@ -158,6 +156,8 @@ export const generateEsApiResponseMock = >(
resurrectTimeout: 0,
_openRequests: 0,
status: 'alive',
+ // There are some properties missing below which is not important for this mock
+ // @ts-expect-error
roles: {
master: true,
data: true,
@@ -182,7 +182,7 @@ export const setEsClientMethodResponseToError = (
) => {
esClientMock[method].mockImplementation(() => {
return elasticsearchServiceMock.createErrorTransportRequestPromise(
- new ResponseError(generateEsRequestErrorApiResponseMock(options))
+ new errors.ResponseError(generateEsRequestErrorApiResponseMock(options))
);
});
};
diff --git a/x-pack/plugins/fleet/server/services/artifacts/utils.ts b/x-pack/plugins/fleet/server/services/artifacts/utils.ts
index bce6b1a1e815b..e3b1be26165e8 100644
--- a/x-pack/plugins/fleet/server/services/artifacts/utils.ts
+++ b/x-pack/plugins/fleet/server/services/artifacts/utils.ts
@@ -8,5 +8,9 @@
import { isESClientError } from '../../errors';
export const isElasticsearchItemNotFoundError = (error: Error): boolean => {
- return isESClientError(error) && error.meta.statusCode === 404 && error.meta.body.found === false;
+ return (
+ isESClientError(error) &&
+ error.meta.statusCode === 404 &&
+ (error.meta.body as any).found === false
+ );
};
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/install.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/install.ts
index 5b85a25f14659..42e1bff6ab370 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/install.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/install.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { TransportRequestOptions } from '@elastic/elasticsearch/lib/Transport';
+import type { TransportRequestOptions } from '@elastic/elasticsearch';
import type { ElasticsearchClient, SavedObjectsClientContract } from 'src/core/server';
import { ElasticsearchAssetType } from '../../../../types';
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/ml_model/install.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/ml_model/install.ts
index d6de59507fbf7..d97081f15aca3 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/ml_model/install.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/ml_model/install.ts
@@ -6,7 +6,7 @@
*/
import type { ElasticsearchClient, SavedObjectsClientContract } from 'kibana/server';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { saveInstalledEsRefs } from '../../packages/install';
import { getPathParts } from '../../archive';
@@ -71,12 +71,13 @@ async function handleMlModelInstall({
model_id: mlModel.installationName,
defer_definition_decompression: true,
timeout: '45s',
+ // @ts-expect-error expects an object not a string
body: mlModel.content,
});
} catch (err) {
// swallow the error if the ml model already exists.
const isAlreadyExistError =
- err instanceof ResponseError &&
+ err instanceof errors.ResponseError &&
err?.body?.error?.type === 'resource_already_exists_exception';
if (!isAlreadyExistError) {
throw err;
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts
index 552e486552a78..2e6365a9913e4 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.test.ts
@@ -5,6 +5,7 @@
* 2.0.
*/
import { elasticsearchServiceMock } from 'src/core/server/mocks';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { createAppContextStartContractMock } from '../../../../mocks';
import { appContextService } from '../../../../services';
@@ -49,14 +50,13 @@ describe('EPM install', () => {
packageName: pkg.name,
});
- const sentTemplate = esClient.indices.putIndexTemplate.mock.calls[0][0]!.body as Record<
- string,
- any
- >;
+ const sentTemplate = (
+ esClient.indices.putIndexTemplate.mock.calls[0][0] as estypes.IndicesPutIndexTemplateRequest
+ ).body;
expect(sentTemplate).toBeDefined();
- expect(sentTemplate.priority).toBe(templatePriorityDatasetIsPrefixUnset);
- expect(sentTemplate.index_patterns).toEqual([templateIndexPatternDatasetIsPrefixUnset]);
+ expect(sentTemplate?.priority).toBe(templatePriorityDatasetIsPrefixUnset);
+ expect(sentTemplate?.index_patterns).toEqual([templateIndexPatternDatasetIsPrefixUnset]);
});
it('tests installPackage to use correct priority and index_patterns for data stream with dataset_is_prefix set to false', async () => {
@@ -90,14 +90,13 @@ describe('EPM install', () => {
packageName: pkg.name,
});
- const sentTemplate = esClient.indices.putIndexTemplate.mock.calls[0][0]!.body as Record<
- string,
- any
- >;
+ const sentTemplate = (
+ esClient.indices.putIndexTemplate.mock.calls[0][0] as estypes.IndicesPutIndexTemplateRequest
+ ).body;
expect(sentTemplate).toBeDefined();
- expect(sentTemplate.priority).toBe(templatePriorityDatasetIsPrefixFalse);
- expect(sentTemplate.index_patterns).toEqual([templateIndexPatternDatasetIsPrefixFalse]);
+ expect(sentTemplate?.priority).toBe(templatePriorityDatasetIsPrefixFalse);
+ expect(sentTemplate?.index_patterns).toEqual([templateIndexPatternDatasetIsPrefixFalse]);
});
it('tests installPackage to use correct priority and index_patterns for data stream with dataset_is_prefix set to true', async () => {
@@ -130,14 +129,14 @@ describe('EPM install', () => {
packageVersion: pkg.version,
packageName: pkg.name,
});
- const sentTemplate = esClient.indices.putIndexTemplate.mock.calls[0][0]!.body as Record<
- string,
- any
- >;
+
+ const sentTemplate = (
+ esClient.indices.putIndexTemplate.mock.calls[0][0] as estypes.IndicesPutIndexTemplateRequest
+ ).body;
expect(sentTemplate).toBeDefined();
- expect(sentTemplate.priority).toBe(templatePriorityDatasetIsPrefixTrue);
- expect(sentTemplate.index_patterns).toEqual([templateIndexPatternDatasetIsPrefixTrue]);
+ expect(sentTemplate?.priority).toBe(templatePriorityDatasetIsPrefixTrue);
+ expect(sentTemplate?.index_patterns).toEqual([templateIndexPatternDatasetIsPrefixTrue]);
});
it('tests installPackage remove the aliases property if the property existed', async () => {
@@ -181,18 +180,16 @@ describe('EPM install', () => {
packageName: pkg.name,
});
- const removeAliases = esClient.indices.putIndexTemplate.mock.calls[0][0]!.body as Record<
- string,
- any
- >;
- expect(removeAliases.template.aliases).not.toBeDefined();
+ const removeAliases = (
+ esClient.indices.putIndexTemplate.mock.calls[0][0] as estypes.IndicesPutIndexTemplateRequest
+ ).body;
+ expect(removeAliases?.template?.aliases).not.toBeDefined();
- const sentTemplate = esClient.indices.putIndexTemplate.mock.calls[1][0]!.body as Record<
- string,
- any
- >;
+ const sentTemplate = (
+ esClient.indices.putIndexTemplate.mock.calls[1][0] as estypes.IndicesPutIndexTemplateRequest
+ ).body;
expect(sentTemplate).toBeDefined();
- expect(sentTemplate.priority).toBe(templatePriorityDatasetIsPrefixUnset);
- expect(sentTemplate.index_patterns).toEqual([templateIndexPatternDatasetIsPrefixUnset]);
+ expect(sentTemplate?.priority).toBe(templatePriorityDatasetIsPrefixUnset);
+ expect(sentTemplate?.index_patterns).toEqual([templateIndexPatternDatasetIsPrefixUnset]);
});
});
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts
index 9dae415838890..67b57dea6e310 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/install.ts
@@ -192,7 +192,6 @@ function putComponentTemplate(
const { name, body, create = false } = params;
return {
clusterPromise: esClient.cluster.putComponentTemplate(
- // @ts-expect-error body is missing required key `settings`. TemplateMapEntry has settings *or* mappings
{ name, body, create },
{ ignore: [404] }
),
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts
index 44d633d5f6e53..16cb4a29bcc7e 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.ts
@@ -505,7 +505,7 @@ const updateExistingDataStream = async ({
try {
await esClient.indices.putSettings({
index: dataStreamName,
- body: { settings: { default_pipeline: settings.index.default_pipeline } },
+ body: { default_pipeline: settings.index.default_pipeline },
});
} catch (err) {
throw new Error(`could not update index template settings for ${dataStreamName}`);
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/install.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/install.ts
index 7d62c0ef41c8d..93181d4f26d02 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/install.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/install.ts
@@ -6,7 +6,7 @@
*/
import type { ElasticsearchClient, SavedObjectsClientContract } from 'kibana/server';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { saveInstalledEsRefs } from '../../packages/install';
import { getPathParts } from '../../archive';
@@ -129,7 +129,7 @@ async function handleTransformInstall({
} catch (err) {
// swallow the error if the transform already exists.
const isAlreadyExistError =
- err instanceof ResponseError &&
+ err instanceof errors.ResponseError &&
err?.body?.error?.type === 'resource_already_exists_exception';
if (!isAlreadyExistError) {
throw err;
diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts
index 34dcd5427d655..5f6f64576ad64 100644
--- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts
+++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts
@@ -18,7 +18,7 @@ jest.mock('./common', () => {
};
});
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
import type { ElasticsearchClient, SavedObject, SavedObjectsClientContract } from 'kibana/server';
@@ -518,7 +518,7 @@ describe('test transform install', () => {
esClient.transport.request.mockImplementationOnce(() =>
elasticsearchClientMock.createErrorTransportRequestPromise(
- new ResponseError(
+ new errors.ResponseError(
elasticsearchClientMock.createApiResponse({
statusCode: 400,
body: { error: { type: 'resource_already_exists_exception' } },
diff --git a/x-pack/plugins/index_lifecycle_management/server/plugin.ts b/x-pack/plugins/index_lifecycle_management/server/plugin.ts
index f511f837b8074..08b1033371ad5 100644
--- a/x-pack/plugins/index_lifecycle_management/server/plugin.ts
+++ b/x-pack/plugins/index_lifecycle_management/server/plugin.ts
@@ -31,11 +31,10 @@ const indexLifecycleDataEnricher = async (
} = await client.asCurrentUser.ilm.explainLifecycle({
index: '*',
});
-
+ // @ts-expect-error IndexLifecyclePolicy is not compatible with IlmExplainLifecycleResponse
return indicesList.map((index: IndexWithoutIlm) => {
return {
...index,
- // @ts-expect-error @elastic/elasticsearch https://github.com/elastic/elasticsearch-specification/issues/531
ilm: { ...(ilmIndicesData[index.name] || {}) },
};
});
diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_create_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_create_route.ts
index bc27a3b909c85..5ac37f4eeb215 100644
--- a/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_create_route.ts
+++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_create_route.ts
@@ -21,7 +21,7 @@ async function createPolicy(
ignore: [404],
};
- return client.ilm.putLifecycle({ policy: name, body }, options);
+ return client.ilm.putLifecycle({ name, body }, options);
}
/**
diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_delete_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_delete_route.ts
index 069adc139a86d..eed36962a78e5 100644
--- a/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_delete_route.ts
+++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_delete_route.ts
@@ -17,8 +17,7 @@ async function deletePolicies(client: ElasticsearchClient, policyName: string):
ignore: [404],
};
- // @ts-expect-error @elastic/elasticsearch DeleteSnapshotLifecycleRequest.policy_id is required
- return client.ilm.deleteLifecycle({ policy: policyName }, options);
+ return client.ilm.deleteLifecycle({ name: policyName }, options);
}
const paramsSchema = schema.object({
diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_fetch_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_fetch_route.ts
index 5c65ff9f6a14b..8cb96e4af0bf3 100644
--- a/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_fetch_route.ts
+++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/policies/register_fetch_route.ts
@@ -6,7 +6,7 @@
*/
import { ElasticsearchClient } from 'kibana/server';
-import { ApiResponse } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
import { PolicyFromES, SerializedPolicy } from '../../../../common/types';
import { RouteDependencies } from '../../../types';
@@ -46,7 +46,7 @@ function formatPolicies(policiesMap: PoliciesMap): PolicyFromES[] {
}, []);
}
-async function fetchPolicies(client: ElasticsearchClient): Promise> {
+async function fetchPolicies(client: ElasticsearchClient): Promise> {
const options = {
// we allow 404 since they may have no policies
ignore: [404],
diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/snapshot_repositories/register_fetch_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/snapshot_repositories/register_fetch_route.ts
index f1fb987c41911..8787be8e936ba 100644
--- a/x-pack/plugins/index_lifecycle_management/server/routes/api/snapshot_repositories/register_fetch_route.ts
+++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/snapshot_repositories/register_fetch_route.ts
@@ -29,7 +29,7 @@ export const registerFetchRoute = ({ router, license }: RouteDependencies) => {
try {
const esResult = await ctx.core.elasticsearch.client.asCurrentUser.snapshot.getRepository({
- repository: '*',
+ name: '*',
});
const repos: ListSnapshotReposResponse = {
repositories: Object.keys(esResult.body),
diff --git a/x-pack/plugins/index_management/server/lib/fetch_indices.ts b/x-pack/plugins/index_management/server/lib/fetch_indices.ts
index f78e666ddfc5f..1dd27dff98c16 100644
--- a/x-pack/plugins/index_management/server/lib/fetch_indices.ts
+++ b/x-pack/plugins/index_management/server/lib/fetch_indices.ts
@@ -54,7 +54,6 @@ async function fetchIndicesCall(
aliases: aliases.length ? aliases : 'none',
// @ts-expect-error @elastic/elasticsearch https://github.com/elastic/elasticsearch-specification/issues/532
hidden: index.settings.index.hidden === 'true',
- // @ts-expect-error @elastic/elasticsearch https://github.com/elastic/elasticsearch-specification/issues/532
data_stream: index.data_stream!,
});
}
diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/register_update_route.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/register_update_route.ts
index 464d73790af2a..c2235b9eb85ab 100644
--- a/x-pack/plugins/index_management/server/routes/api/component_templates/register_update_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/component_templates/register_update_route.ts
@@ -6,7 +6,7 @@
*/
import { schema } from '@kbn/config-schema';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { RouteDependencies } from '../../../types';
import { addBasePath } from '../index';
diff --git a/x-pack/plugins/index_management/server/routes/api/stats/register_stats_route.ts b/x-pack/plugins/index_management/server/routes/api/stats/register_stats_route.ts
index 7458b98f5092f..3335913b81071 100644
--- a/x-pack/plugins/index_management/server/routes/api/stats/register_stats_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/stats/register_stats_route.ts
@@ -6,7 +6,7 @@
*/
import { schema } from '@kbn/config-schema';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { RouteDependencies } from '../../../types';
import { addBasePath } from '../index';
diff --git a/x-pack/plugins/index_management/server/routes/api/templates/lib.ts b/x-pack/plugins/index_management/server/routes/api/templates/lib.ts
index ec8916b0b8d07..413e73ff93d5f 100644
--- a/x-pack/plugins/index_management/server/routes/api/templates/lib.ts
+++ b/x-pack/plugins/index_management/server/routes/api/templates/lib.ts
@@ -51,7 +51,6 @@ export const saveTemplate = async ({
return await client.asCurrentUser.indices.putTemplate({
name: template.name,
- // @ts-expect-error @elastic/elasticsearch https://github.com/elastic/elasticsearch-specification/issues/533
order,
body: {
index_patterns,
diff --git a/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts b/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts
index cd363cbd7d003..e45d86f3e2b27 100644
--- a/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts
+++ b/x-pack/plugins/index_management/server/routes/api/templates/register_simulate_route.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { schema, TypeOf } from '@kbn/config-schema';
import { RouteDependencies } from '../../../types';
@@ -31,7 +31,7 @@ export function registerSimulateRoute({ router, lib: { handleEsError } }: RouteD
// Issue: https://github.com/elastic/elasticsearch/issues/59152
index_patterns: ['a_fake_index_pattern_that_wont_match_any_indices'],
},
- });
+ } as estypes.IndicesSimulateTemplateRequest);
return response.ok({ body: templatePreview });
} catch (error) {
diff --git a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts
index 567acf1fc4134..c6bc10901fcb8 100644
--- a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts
+++ b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { DataView, DataViewsContract } from '../../../../../src/plugins/data_views/common';
import { ObjectEntries } from '../utility_types';
import { ResolveLogSourceConfigurationError } from './errors';
diff --git a/x-pack/plugins/infra/common/search_strategies/log_entries/log_entries.ts b/x-pack/plugins/infra/common/search_strategies/log_entries/log_entries.ts
index cc6d3fbe585e0..4e115cda6a8e6 100644
--- a/x-pack/plugins/infra/common/search_strategies/log_entries/log_entries.ts
+++ b/x-pack/plugins/infra/common/search_strategies/log_entries/log_entries.ts
@@ -6,7 +6,7 @@
*/
import * as rt from 'io-ts';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { logSourceColumnConfigurationRT } from '../../log_sources/log_source_configuration';
import {
logEntryAfterCursorRT,
diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx
index 5aafd9b613d99..ec97d01a1cd6f 100644
--- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx
+++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.test.tsx
@@ -54,6 +54,7 @@ describe('ExpressionChart', () => {
metricAlias: 'metricbeat-*',
inventoryDefaultView: 'host',
metricsExplorerDefaultView: 'host',
+ // @ts-ignore
fields: {
timestamp: '@timestamp',
container: 'container.id',
diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx
index b176e3907228c..6a68c01e26017 100644
--- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx
+++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_chart.tsx
@@ -7,10 +7,11 @@
import React, { useMemo, useCallback } from 'react';
import { Axis, Chart, niceTimeFormatter, Position, Settings } from '@elastic/charts';
-import { first, last } from 'lodash';
import { EuiText } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n/react';
import { DataViewBase } from '@kbn/es-query';
+import { first, last } from 'lodash';
+
import { MetricsSourceConfiguration } from '../../../../common/metrics_sources';
import { Color } from '../../../../common/color_palette';
import { MetricsExplorerRow, MetricsExplorerAggregation } from '../../../../common/http_api';
diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts
index 9de6e574ecb5b..94bb3d8e66cbf 100644
--- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts
+++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_datasets.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { HttpHandler } from 'src/core/public';
import {
LOG_ANALYSIS_VALIDATE_DATASETS_PATH,
diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts
index a211fecc807fa..8a9f960b54afa 100644
--- a/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts
+++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/api/validate_indices.ts
@@ -6,7 +6,7 @@
*/
import type { HttpHandler } from 'src/core/public';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
LOG_ANALYSIS_VALIDATE_INDICES_PATH,
diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts
index 4ae99b95cfff8..4ff8c0c3c08e0 100644
--- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts
+++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts
@@ -6,7 +6,7 @@
*/
import type { HttpHandler } from 'src/core/public';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
ValidateLogEntryDatasetsResponsePayload,
ValidationIndicesResponsePayload,
diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts
index 6823ed173a740..9ef41042302a1 100644
--- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts
+++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { i18n } from '@kbn/i18n';
import type { HttpHandler } from 'src/core/public';
import {
diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx
index 99d4ab4becee5..433a24cffd937 100644
--- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx
+++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx
@@ -6,7 +6,7 @@
*/
import createContainer from 'constate';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { useMemo } from 'react';
import { useLogAnalysisModule } from '../../log_analysis_module';
import { useLogAnalysisModuleConfiguration } from '../../log_analysis_module_configuration';
diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts
index c4c939d0ebb9d..214faaf9a3012 100644
--- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts
+++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts
@@ -6,7 +6,7 @@
*/
import { i18n } from '@kbn/i18n';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { HttpHandler } from 'src/core/public';
import {
bucketSpan,
diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx
index f3e8f7e777597..46587969ca2ab 100644
--- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx
+++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import createContainer from 'constate';
import { useMemo } from 'react';
import { ModuleSourceConfiguration } from '../../log_analysis_module_types';
diff --git a/x-pack/plugins/infra/public/lib/lib.ts b/x-pack/plugins/infra/public/lib/lib.ts
index 4541eb6518788..97a3f8eabbe4e 100644
--- a/x-pack/plugins/infra/public/lib/lib.ts
+++ b/x-pack/plugins/infra/public/lib/lib.ts
@@ -124,7 +124,7 @@ export enum InfraWaffleMapRuleOperator {
}
export interface InfraWaffleMapOptions {
- fields?: MetricsSourceConfigurationProperties['fields'] | null;
+ fields?: Omit | null;
formatter: InfraFormatterType;
formatTemplate: string;
metric: SnapshotMetricInput;
diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts
index 6b7e98912fd49..c0d0b15217df3 100644
--- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts
+++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.ts
@@ -6,9 +6,10 @@
*/
import DateMath from '@elastic/datemath';
-import { isEqual } from 'lodash';
import { useEffect, useState } from 'react';
import { DataViewBase } from '@kbn/es-query';
+import { isEqual } from 'lodash';
+
import { MetricsSourceConfigurationProperties } from '../../../../../common/metrics_sources';
import {
MetricsExplorerResponse,
diff --git a/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts b/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts
index c813bd3dae781..44f65b9e8071a 100644
--- a/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts
+++ b/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts
@@ -6,7 +6,7 @@
*/
import { encode } from 'rison-node';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { FetchData, FetchDataParams, LogsFetchDataResponse } from '../../../observability/public';
import { DEFAULT_SOURCE_ID } from '../../common/constants';
import { callFetchLogSourceConfigurationAPI } from '../containers/logs/log_source/api/fetch_log_source_configuration';
diff --git a/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts b/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts
index 4d4a0ff6320bd..00c52dae7ed3c 100644
--- a/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts
+++ b/x-pack/plugins/infra/server/lib/adapters/framework/adapter_types.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Lifecycle } from '@hapi/hapi';
import { UsageCollectionSetup } from 'src/plugins/usage_collection/server';
import { JsonArray, JsonValue } from '@kbn/utility-types';
diff --git a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts
index b1ea0ce21b3c1..0c0284e328dd3 100644
--- a/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts
+++ b/x-pack/plugins/infra/server/lib/adapters/framework/kibana_framework_adapter.ts
@@ -5,13 +5,8 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
-import {
- IndicesExistsAlias,
- IndicesGet,
- MlGetBuckets,
-} from '@elastic/elasticsearch/api/requestParams';
-import { TransportRequestParams } from '@elastic/elasticsearch/lib/Transport';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import { TransportRequestParams } from '@elastic/elasticsearch';
import { ElasticsearchClient, SavedObjectsClientContract } from 'src/core/server';
import {
CoreSetup,
@@ -181,7 +176,7 @@ export class KibanaFramework {
case 'indices.existsAlias':
apiResult = elasticsearch.client.asCurrentUser.indices.existsAlias({
...params,
- } as IndicesExistsAlias);
+ } as estypes.IndicesExistsAliasRequest);
break;
case 'indices.getAlias':
apiResult = elasticsearch.client.asCurrentUser.indices.getAlias({
@@ -191,7 +186,7 @@ export class KibanaFramework {
case 'indices.get':
apiResult = elasticsearch.client.asCurrentUser.indices.get({
...params,
- } as IndicesGet);
+ } as estypes.IndicesGetRequest);
break;
case 'transport.request':
apiResult = elasticsearch.client.asCurrentUser.transport.request({
@@ -201,7 +196,7 @@ export class KibanaFramework {
case 'ml.getBuckets':
apiResult = elasticsearch.client.asCurrentUser.ml.getBuckets({
...params,
- } as MlGetBuckets);
+ } as estypes.MlGetBucketsRequest);
break;
}
return apiResult ? (await apiResult).body : undefined;
diff --git a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts
index 524658559eadf..75a86ae654d6c 100644
--- a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts
+++ b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts
@@ -10,8 +10,8 @@ import { fold, map } from 'fp-ts/lib/Either';
import { constant, identity } from 'fp-ts/lib/function';
import { pipe } from 'fp-ts/lib/pipeable';
import * as runtimeTypes from 'io-ts';
-import { compact } from 'lodash';
import { JsonArray } from '@kbn/utility-types';
+import { compact } from 'lodash';
import type { InfraPluginRequestHandlerContext } from '../../../types';
import {
LogEntriesAdapter,
@@ -46,7 +46,7 @@ export class InfraKibanaLogEntriesAdapter implements LogEntriesAdapter {
const highlightClause = highlightQuery
? {
highlight: {
- boundary_scanner: 'word',
+ boundary_scanner: 'word' as const,
fields: fields.reduce(
(highlightFieldConfigs, fieldName) => ({
...highlightFieldConfigs,
diff --git a/x-pack/plugins/infra/server/lib/adapters/metrics/lib/check_valid_node.ts b/x-pack/plugins/infra/server/lib/adapters/metrics/lib/check_valid_node.ts
index f2b7691646e48..a1bff361a8067 100644
--- a/x-pack/plugins/infra/server/lib/adapters/metrics/lib/check_valid_node.ts
+++ b/x-pack/plugins/infra/server/lib/adapters/metrics/lib/check_valid_node.ts
@@ -17,7 +17,7 @@ export const checkValidNode = async (
allow_no_indices: true,
ignore_unavailable: true,
index: indexPattern,
- terminateAfter: 1,
+ terminate_after: 1,
body: {
size: 0,
query: {
diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts
index 3dd702126735d..26f2ecbc10197 100644
--- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts
+++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts
@@ -5,10 +5,10 @@
* 2.0.
*/
-import { first, get, last } from 'lodash';
import { i18n } from '@kbn/i18n';
import { ALERT_REASON, ALERT_RULE_PARAMS } from '@kbn/rule-data-utils';
import moment from 'moment';
+import { first, get, last } from 'lodash';
import { getCustomMetricLabel } from '../../../../common/formatters/get_custom_metric_label';
import { toMetricOpt } from '../../../../common/snapshot_metric_i18n';
import { AlertStates } from './types';
diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts
index 1f0521070a1e5..e5d8bab948581 100644
--- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts
+++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts
@@ -24,7 +24,7 @@ import {
GroupedSearchQueryResponse,
} from '../../../../common/alerting/logs/log_threshold/types';
import { alertsMock } from '../../../../../alerting/server/mocks';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
// Mocks //
const numericField = {
diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts
index f99f7a96158c3..6d2b074c45bb0 100644
--- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts
+++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { i18n } from '@kbn/i18n';
import {
ALERT_EVALUATION_THRESHOLD,
diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts
index 5bd7a4947b439..71c18d9f7cf04 100644
--- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts
+++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts
@@ -5,9 +5,9 @@
* 2.0.
*/
-import { mapValues, first, last, isNaN, isNumber, isObject, has } from 'lodash';
import moment from 'moment';
import { ElasticsearchClient } from 'kibana/server';
+import { mapValues, first, last, isNaN, isNumber, isObject, has } from 'lodash';
import {
isTooManyBucketsPreviewException,
TOO_MANY_BUCKETS_PREVIEW_EXCEPTION,
@@ -222,6 +222,7 @@ const getMetric: (
return groupedResults;
}
const { body: result } = await esClient.search({
+ // @ts-expect-error buckets_path is not compatible
body: searchBody,
index,
});
diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts
index 16209e5e4b684..e7b1624206515 100644
--- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts
+++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { JsonObject } from '@kbn/utility-types';
import type { InfraPluginRequestHandlerContext } from '../../../types';
diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts
index 9eae8daa3e74f..4386b6ccef9c1 100644
--- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts
+++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/queries/log_entry_datasets.ts
@@ -6,7 +6,7 @@
*/
import * as rt from 'io-ts';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { commonSearchSuccessResponseFieldsRT } from '../../../../utils/elasticsearch_runtime_types';
diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts
index 3210f01116f76..aca0483037912 100644
--- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts
+++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_anomalies.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { InfraPluginRequestHandlerContext, InfraRequestHandlerContext } from '../../types';
import { TracingSpan, startTracingSpan } from '../../../common/performance_tracing';
import { fetchMlJob, getLogEntryDatasets } from './common';
diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts
index 7023f7007763c..d1d136c741876 100644
--- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts
+++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'src/core/server';
import {
compareDatasetsByMaximumAnomalyScore,
diff --git a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts
index 8b05d7c44e3f5..dd68de4e49d34 100644
--- a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts
+++ b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_category_examples.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as rt from 'io-ts';
import { commonSearchSuccessResponseFieldsRT } from '../../../utils/elasticsearch_runtime_types';
import { defaultRequestParameters } from './common';
diff --git a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts
index d903225facd57..d6099404daa80 100644
--- a/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts
+++ b/x-pack/plugins/infra/server/lib/log_analysis/queries/log_entry_examples.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as rt from 'io-ts';
import { partitionField } from '../../../../common/log_analysis';
import { commonSearchSuccessResponseFieldsRT } from '../../../utils/elasticsearch_runtime_types';
diff --git a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts
index ef789c1b41349..4237ee2ae9abc 100644
--- a/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts
+++ b/x-pack/plugins/infra/server/routes/log_analysis/validation/datasets.ts
@@ -6,7 +6,7 @@
*/
import Boom from '@hapi/boom';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { InfraBackendLibs } from '../../../lib/infra_types';
import {
diff --git a/x-pack/plugins/infra/server/routes/log_sources/configuration.ts b/x-pack/plugins/infra/server/routes/log_sources/configuration.ts
index f0d7b18d91a5d..9a92012c21fe4 100644
--- a/x-pack/plugins/infra/server/routes/log_sources/configuration.ts
+++ b/x-pack/plugins/infra/server/routes/log_sources/configuration.ts
@@ -85,11 +85,13 @@ export const initLogSourceConfigurationRoutes = ({ framework, sources }: InfraBa
? sources.updateSourceConfiguration(
requestContext.core.savedObjects.client,
sourceId,
+ // @ts-ignore
patchedSourceConfigurationProperties
)
: sources.createSourceConfiguration(
requestContext.core.savedObjects.client,
sourceId,
+ // @ts-ignore
patchedSourceConfigurationProperties
));
diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts
index 06035ed40adf1..94becdf6d2811 100644
--- a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts
+++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts
@@ -55,7 +55,7 @@ export const getNodeInfo = async (
const params = {
allow_no_indices: true,
ignore_unavailable: true,
- terminateAfter: 1,
+ terminate_after: 1,
index: sourceConfiguration.metricAlias,
body: {
size: 1,
diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts
index 9bf809ba3b3f4..164d94d9f692f 100644
--- a/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts
+++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_pod_node_name.ts
@@ -24,7 +24,7 @@ export const getPodNodeName = async (
const params = {
allow_no_indices: true,
ignore_unavailable: true,
- terminateAfter: 1,
+ terminate_after: 1,
index: sourceConfiguration.metricAlias,
body: {
size: 1,
diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_dataset_for_field.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_dataset_for_field.ts
index be25bbbf022ee..640d62c366726 100644
--- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_dataset_for_field.ts
+++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_dataset_for_field.ts
@@ -24,7 +24,7 @@ export const getDatasetForField = async (
const params = {
allow_no_indices: true,
ignore_unavailable: true,
- terminateAfter: 1,
+ terminate_after: 1,
index: indexPattern,
body: {
query: {
diff --git a/x-pack/plugins/infra/server/routes/metrics_sources/index.ts b/x-pack/plugins/infra/server/routes/metrics_sources/index.ts
index 0123e4678697c..24ea04e3e14f9 100644
--- a/x-pack/plugins/infra/server/routes/metrics_sources/index.ts
+++ b/x-pack/plugins/infra/server/routes/metrics_sources/index.ts
@@ -88,11 +88,13 @@ export const initMetricsSourceConfigurationRoutes = (libs: InfraBackendLibs) =>
? sources.updateSourceConfiguration(
requestContext.core.savedObjects.client,
sourceId,
+ // @ts-ignore
patchedSourceConfigurationProperties
)
: sources.createSourceConfiguration(
requestContext.core.savedObjects.client,
sourceId,
+ // @ts-ignore
patchedSourceConfigurationProperties
));
diff --git a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.test.ts b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.test.ts
index 85a1b95cf70aa..b0d2eeb987861 100644
--- a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.test.ts
+++ b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { of, throwError } from 'rxjs';
import {
elasticsearchServiceMock,
@@ -230,7 +230,7 @@ describe('LogEntries search strategy', () => {
mockDependencies
);
- await expect(response.toPromise()).rejects.toThrowError(ResponseError);
+ await expect(response.toPromise()).rejects.toThrowError(errors.ResponseError);
});
it('forwards cancellation to the underlying search strategy', async () => {
@@ -307,7 +307,7 @@ const createEsSearchStrategyMock = (esSearchResponse: IEsSearchResponse) => ({
return of(esSearchResponse);
} else {
return throwError(
- new ResponseError({
+ new errors.ResponseError({
body: {},
headers: {},
meta: {} as any,
diff --git a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts
index 651758d9cd976..b401b68d0e3d3 100644
--- a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts
+++ b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts
@@ -113,7 +113,6 @@ export const logEntriesSearchStrategyProvider = ({
messageFormattingRules,
]): IEsSearchRequest => {
return {
- // @ts-expect-error @elastic/elasticsearch declares indices_boost as Record
params: createGetLogEntriesQuery(
indices,
params.startTimestamp,
diff --git a/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.test.ts b/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.test.ts
index ec3d4aa52a6b5..1f03878ba6feb 100644
--- a/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.test.ts
+++ b/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { of, throwError } from 'rxjs';
import {
elasticsearchServiceMock,
@@ -196,7 +196,7 @@ describe('LogEntry search strategy', () => {
mockDependencies
);
- await expect(response.toPromise()).rejects.toThrowError(ResponseError);
+ await expect(response.toPromise()).rejects.toThrowError(errors.ResponseError);
});
it('forwards cancellation to the underlying search strategy', async () => {
@@ -262,7 +262,7 @@ const createEsSearchStrategyMock = (esSearchResponse: IEsSearchResponse) => ({
return of(esSearchResponse);
} else {
return throwError(
- new ResponseError({
+ new errors.ResponseError({
body: {},
headers: {},
meta: {} as any,
diff --git a/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.ts b/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.ts
index 1f0f13eeb6ca9..565318578f990 100644
--- a/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.ts
+++ b/x-pack/plugins/infra/server/services/log_entries/log_entry_search_strategy.ts
@@ -84,7 +84,6 @@ export const logEntrySearchStrategyProvider = ({
tiebreakerField,
runtimeMappings,
}): IEsSearchRequest => ({
- // @ts-expect-error `Field` is not assignable to `SearchRequest.docvalue_fields`
params: createGetLogEntryQuery(
indices,
params.logEntryId,
diff --git a/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts b/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts
index 9022195dce85d..6ca6d5ecd0191 100644
--- a/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts
+++ b/x-pack/plugins/infra/server/services/log_entries/queries/log_entries.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as rt from 'io-ts';
import {
LogEntryAfterCursor,
@@ -53,7 +53,6 @@ export const createGetLogEntriesQuery = (
},
},
fields,
- // @ts-expect-error @elastic/elasticsearch doesn't declare "runtime_mappings" property
runtime_mappings: runtimeMappings,
_source: false,
...createSortClause(sortDirection, timestampField, tiebreakerField),
@@ -87,7 +86,7 @@ const createHighlightClause = (highlightQuery: JsonObject | undefined, fields: s
highlightQuery
? {
highlight: {
- boundary_scanner: 'word',
+ boundary_scanner: 'word' as const,
fields: fields.reduce(
(highlightFieldConfigs, fieldName) => ({
...highlightFieldConfigs,
diff --git a/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts b/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts
index 8da2f1d685db3..856f8b1af9770 100644
--- a/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts
+++ b/x-pack/plugins/infra/server/services/log_entries/queries/log_entry.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as rt from 'io-ts';
import { jsonArrayRT } from '../../../../common/typed_json';
import {
@@ -32,7 +32,6 @@ export const createGetLogEntryQuery = (
},
},
fields: ['*'],
- // @ts-expect-error @elastic/elasticsearch doesn't declare "runtime_mappings" property
runtime_mappings: runtimeMappings,
sort: [{ [timestampField]: 'desc' }, { [tiebreakerField]: 'desc' }],
_source: false,
diff --git a/x-pack/plugins/infra/server/utils/get_all_composite_data.ts b/x-pack/plugins/infra/server/utils/get_all_composite_data.ts
index 1ab290796e36d..b5b4b731472c4 100644
--- a/x-pack/plugins/infra/server/utils/get_all_composite_data.ts
+++ b/x-pack/plugins/infra/server/utils/get_all_composite_data.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { ApiResponse } from '@elastic/elasticsearch/lib/Transport';
+import { TransportResult } from '@elastic/elasticsearch';
import { InfraDatabaseSearchResponse } from '../lib/adapters/framework';
export const getAllCompositeData = async <
@@ -15,7 +15,7 @@ export const getAllCompositeData = async <
>(
esClientSearch: (
options: Options
- ) => Promise>>,
+ ) => Promise>>,
options: Options,
bucketSelector: (response: InfraDatabaseSearchResponse<{}, Aggregation>) => Bucket[],
onAfterKey: (options: Options, response: InfraDatabaseSearchResponse<{}, Aggregation>) => Options,
diff --git a/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts b/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts
index d2669e7c0012b..248797c652c6a 100644
--- a/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts
+++ b/x-pack/plugins/ingest_pipelines/common/lib/pipeline_serialization.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Pipeline, Processor } from '../types';
export function deserializePipelines(pipelinesByName: {
diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts
index 5368b59b35a41..a2882fd7855d6 100644
--- a/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts
+++ b/x-pack/plugins/ingest_pipelines/server/routes/api/privileges.ts
@@ -41,6 +41,7 @@ export const registerPrivilegesRoute = ({ router, config }: RouteDependencies) =
const {
body: { has_all_requested: hasAllPrivileges, cluster },
} = await clusterClient.asCurrentUser.security.hasPrivileges({
+ // @ts-expect-error @elastic/elasticsearch SecurityClusterPrivilege doesn’t contain all the priviledges
body: { cluster: APP_CLUSTER_REQUIRED_PRIVILEGES },
});
diff --git a/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts b/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts
index c133b9237102a..c6d628294a734 100644
--- a/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts
+++ b/x-pack/plugins/ingest_pipelines/server/routes/api/simulate.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { schema } from '@kbn/config-schema';
import { API_BASE_PATH } from '../../../common/constants';
@@ -38,7 +38,7 @@ export const registerSimulateRoute = ({
verbose,
body: {
pipeline,
- docs: documents as estypes.IngestSimulatePipelineDocument[],
+ docs: documents as estypes.IngestSimulateDocument[],
},
});
diff --git a/x-pack/plugins/lens/server/routes/existing_fields.ts b/x-pack/plugins/lens/server/routes/existing_fields.ts
index f35b0a7f23179..704b248faeadb 100644
--- a/x-pack/plugins/lens/server/routes/existing_fields.ts
+++ b/x-pack/plugins/lens/server/routes/existing_fields.ts
@@ -6,7 +6,8 @@
*/
import Boom from '@hapi/boom';
-import { errors, estypes } from '@elastic/elasticsearch';
+import { errors } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { schema } from '@kbn/config-schema';
import { RequestHandlerContext, ElasticsearchClient } from 'src/core/server';
import { CoreSetup, Logger } from 'src/core/server';
diff --git a/x-pack/plugins/lens/server/routes/field_stats.ts b/x-pack/plugins/lens/server/routes/field_stats.ts
index 88e8e600aa906..9e48c00b9d8cb 100644
--- a/x-pack/plugins/lens/server/routes/field_stats.ts
+++ b/x-pack/plugins/lens/server/routes/field_stats.ts
@@ -4,7 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import { errors, estypes } from '@elastic/elasticsearch';
+import { errors } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import DateMath from '@elastic/datemath';
import { schema } from '@kbn/config-schema';
import { CoreSetup } from 'src/core/server';
diff --git a/x-pack/plugins/license_management/server/lib/permissions.ts b/x-pack/plugins/license_management/server/lib/permissions.ts
index 517854fad8e83..06395fb6302b6 100644
--- a/x-pack/plugins/license_management/server/lib/permissions.ts
+++ b/x-pack/plugins/license_management/server/lib/permissions.ts
@@ -20,14 +20,12 @@ export async function getPermissions({ isSecurityEnabled, client }: GetPermissio
};
}
- const options = {
- body: {
- cluster: ['manage'], // License management requires "manage" cluster privileges
- },
- };
-
try {
- const { body: response } = await client.asCurrentUser.security.hasPrivileges(options);
+ const { body: response } = await client.asCurrentUser.security.hasPrivileges({
+ body: {
+ cluster: ['manage'], // License management requires "manage" cluster privileges
+ },
+ });
return {
hasPermission: response.cluster.manage,
};
diff --git a/x-pack/plugins/licensing/server/plugin.test.ts b/x-pack/plugins/licensing/server/plugin.test.ts
index 1fe4bbf238e19..71a98098bb0f5 100644
--- a/x-pack/plugins/licensing/server/plugin.test.ts
+++ b/x-pack/plugins/licensing/server/plugin.test.ts
@@ -6,7 +6,7 @@
*/
import { take, toArray } from 'rxjs/operators';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import moment from 'moment';
import { LicenseType } from '../common/types';
import { ElasticsearchError } from './types';
@@ -102,9 +102,6 @@ describe('licensing plugin', () => {
await license$.pipe(take(1)).toPromise();
expect(esClient.asInternalUser.xpack.info).toHaveBeenCalledTimes(1);
- expect(esClient.asInternalUser.xpack.info).toHaveBeenCalledWith({
- accept_enterprise: true,
- });
});
it('observable receives updated licenses', async () => {
diff --git a/x-pack/plugins/licensing/server/plugin.ts b/x-pack/plugins/licensing/server/plugin.ts
index 00d2ae602fcae..83379fe48ac9e 100644
--- a/x-pack/plugins/licensing/server/plugin.ts
+++ b/x-pack/plugins/licensing/server/plugin.ts
@@ -10,7 +10,7 @@ import moment from 'moment';
import { createHash } from 'crypto';
import stringify from 'json-stable-stringify';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { MaybePromise } from '@kbn/utility-types';
import { isPromise } from '@kbn/std';
import {
diff --git a/x-pack/plugins/lists/server/schemas/common/get_shard.mock.ts b/x-pack/plugins/lists/server/schemas/common/get_shard.mock.ts
index 43511a748ba1a..e7a887d6ca354 100644
--- a/x-pack/plugins/lists/server/schemas/common/get_shard.mock.ts
+++ b/x-pack/plugins/lists/server/schemas/common/get_shard.mock.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export const getShardMock = (): estypes.ShardStatistics => ({
failed: 0,
diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts b/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts
index 2f213ccfbad06..682c77cf5c83b 100644
--- a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts
+++ b/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_item_schema.mock.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
DATE_NOW,
diff --git a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts b/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts
index 2cfbaf26f9d6a..5dde9cc14d4a1 100644
--- a/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts
+++ b/x-pack/plugins/lists/server/schemas/elastic_response/search_es_list_schema.mock.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
DATE_NOW,
diff --git a/x-pack/plugins/lists/server/services/items/find_list_item.mock.ts b/x-pack/plugins/lists/server/services/items/find_list_item.mock.ts
index 1c1ce872a402d..99c2f18877032 100644
--- a/x-pack/plugins/lists/server/services/items/find_list_item.mock.ts
+++ b/x-pack/plugins/lists/server/services/items/find_list_item.mock.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
diff --git a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts
index 1bf337dbd7532..565e8a3e196c5 100644
--- a/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts
+++ b/x-pack/plugins/lists/server/services/items/write_list_items_to_stream.ts
@@ -7,7 +7,7 @@
import { PassThrough } from 'stream';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient } from 'kibana/server';
import { ErrorWithStatusCode } from '../../error_with_status_code';
diff --git a/x-pack/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts b/x-pack/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts
index db667951381b0..8d0d2501475e6 100644
--- a/x-pack/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts
+++ b/x-pack/plugins/lists/server/services/utils/get_query_filter_from_type_value.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { isEmpty, isObject } from 'lodash/fp';
import type { Type } from '@kbn/securitysolution-io-ts-list-types';
diff --git a/x-pack/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts b/x-pack/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts
index 7db46ce1a464c..37794228bd693 100644
--- a/x-pack/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts
+++ b/x-pack/plugins/lists/server/services/utils/get_search_after_with_tie_breaker.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { SortFieldOrUndefined } from '@kbn/securitysolution-io-ts-list-types';
export type TieBreaker = T & {
diff --git a/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts b/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts
index 8a513483f5b5e..e8fae957a5615 100644
--- a/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts
+++ b/x-pack/plugins/lists/server/services/utils/get_sort_with_tie_breaker.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SortFieldOrUndefined, SortOrderOrUndefined } from '@kbn/securitysolution-io-ts-list-types';
export const getSortWithTieBreaker = ({
diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts b/x-pack/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts
index b669b983fe46d..0a3632efe9195 100644
--- a/x-pack/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts
+++ b/x-pack/plugins/lists/server/services/utils/transform_elastic_named_search_to_list_item.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SearchListItemArraySchema, Type } from '@kbn/securitysolution-io-ts-list-types';
import { SearchEsListItemSchema } from '../../schemas/elastic_response';
diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list.ts b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list.ts
index 5b0949d7b79b7..3242742c1cfd6 100644
--- a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list.ts
+++ b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ListArraySchema } from '@kbn/securitysolution-io-ts-list-types';
import { encodeHitVersion } from '@kbn/securitysolution-es-utils';
diff --git a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts
index 65392f8c379d9..3edbab94a0cfd 100644
--- a/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts
+++ b/x-pack/plugins/lists/server/services/utils/transform_elastic_to_list_item.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ListItemArraySchema, Type } from '@kbn/securitysolution-io-ts-list-types';
import { encodeHitVersion } from '@kbn/securitysolution-es-utils';
diff --git a/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts b/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts
index 10c1d1ba24ae0..9fe03cd411b81 100755
--- a/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts
+++ b/x-pack/plugins/logstash/server/models/cluster/cluster.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Cluster } from './cluster';
describe('cluster', () => {
diff --git a/x-pack/plugins/logstash/server/models/cluster/cluster.ts b/x-pack/plugins/logstash/server/models/cluster/cluster.ts
index 2982284879c47..6c1712eb4797e 100755
--- a/x-pack/plugins/logstash/server/models/cluster/cluster.ts
+++ b/x-pack/plugins/logstash/server/models/cluster/cluster.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
/**
* This model deals with a cluster object from ES and converts it to Kibana downstream
diff --git a/x-pack/plugins/logstash/server/routes/pipeline/save.ts b/x-pack/plugins/logstash/server/routes/pipeline/save.ts
index 48a62f83c91ca..83f6ee9b00ba9 100644
--- a/x-pack/plugins/logstash/server/routes/pipeline/save.ts
+++ b/x-pack/plugins/logstash/server/routes/pipeline/save.ts
@@ -47,6 +47,7 @@ export function registerPipelineSaveRoute(
await client.asCurrentUser.logstash.putPipeline({
id: pipeline.id,
+ // @ts-expect-error description is required
body: pipeline.upstreamJSON,
});
diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.tsx b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.tsx
index d038c139a1667..777787d8213f3 100644
--- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.tsx
+++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.tsx
@@ -10,7 +10,7 @@ import React, { ReactElement } from 'react';
import { i18n } from '@kbn/i18n';
import rison from 'rison-node';
import { Feature } from 'geojson';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { makeESBbox } from '../../../../common/elasticsearch_util';
import { convertCompositeRespToGeoJson, convertRegularRespToGeoJson } from './convert_to_geojson';
import { UpdateSourceEditor } from './update_source_editor';
diff --git a/x-pack/plugins/maps/server/plugin.ts b/x-pack/plugins/maps/server/plugin.ts
index 8768580089f31..5d84ee2ef26d2 100644
--- a/x-pack/plugins/maps/server/plugin.ts
+++ b/x-pack/plugins/maps/server/plugin.ts
@@ -73,7 +73,9 @@ export class MapsPlugin implements Plugin {
defaultMessage: 'Map',
});
- home.sampleData.addSavedObjectsToSampleDataset('ecommerce', getEcommerceSavedObjects());
+ // commented out since it registers an SO already registered by home plugin
+ // https://github.com/elastic/kibana/blob/2ddaddc2e958f60c6685ab9f9840cdd86da9d398/src/plugins/home/server/services/sample_data/data_sets/ecommerce/saved_objects.ts#L151
+ // home.sampleData.addSavedObjectsToSampleDataset('ecommerce', getEcommerceSavedObjects());
home.sampleData.addAppLinksToSampleDataset('ecommerce', [
{
diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts
index e1a3f6044587b..ef38504c869fb 100644
--- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts
+++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export type DatafeedId = string;
diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts
index 4e23d97c0d145..3c7f8c51785d1 100644
--- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts
+++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/datafeed_stats.ts
@@ -5,6 +5,6 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export type DatafeedStats = estypes.MlDatafeedStats;
diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts
index dcf18b98e00a0..0e32f4e7a065b 100644
--- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts
+++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export type JobId = string;
export type BucketSpan = string;
diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts
index 5fc8b423a5ac2..995bd1e6a14fc 100644
--- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts
+++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export type JobStats = estypes.MlJobStats;
diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts
index 0bb2162994c37..806aca3eb43ad 100644
--- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts
+++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/model_snapshot.ts
@@ -5,6 +5,6 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export type ModelSnapshot = estypes.MlModelSnapshot;
diff --git a/x-pack/plugins/ml/common/types/data_frame_analytics.ts b/x-pack/plugins/ml/common/types/data_frame_analytics.ts
index 1d2a75069dfe6..92c0c1d06ef93 100644
--- a/x-pack/plugins/ml/common/types/data_frame_analytics.ts
+++ b/x-pack/plugins/ml/common/types/data_frame_analytics.ts
@@ -6,7 +6,7 @@
*/
import Boom from '@hapi/boom';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { RuntimeMappings } from './fields';
import { EsErrorBody } from '../util/errors';
diff --git a/x-pack/plugins/ml/common/types/es_client.ts b/x-pack/plugins/ml/common/types/es_client.ts
index 466075284515e..2a6a1d4c1ffab 100644
--- a/x-pack/plugins/ml/common/types/es_client.ts
+++ b/x-pack/plugins/ml/common/types/es_client.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { isPopulatedObject } from '../util/object_utils';
export function isMultiBucketAggregate(
diff --git a/x-pack/plugins/ml/common/types/fields.ts b/x-pack/plugins/ml/common/types/fields.ts
index 33a4a94e539b8..bf7876570f485 100644
--- a/x-pack/plugins/ml/common/types/fields.ts
+++ b/x-pack/plugins/ml/common/types/fields.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ES_FIELD_TYPES } from '../../../../../src/plugins/data/common';
import {
ML_JOB_AGGREGATION,
diff --git a/x-pack/plugins/ml/common/types/results.ts b/x-pack/plugins/ml/common/types/results.ts
index 74d3286438588..f840f9ad58c01 100644
--- a/x-pack/plugins/ml/common/types/results.ts
+++ b/x-pack/plugins/ml/common/types/results.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { LineAnnotationDatum, RectAnnotationDatum } from '@elastic/charts';
export interface GetStoppedPartitionResult {
diff --git a/x-pack/plugins/ml/common/util/job_utils.ts b/x-pack/plugins/ml/common/util/job_utils.ts
index 6d069cd4383ea..e66d8de5bd15e 100644
--- a/x-pack/plugins/ml/common/util/job_utils.ts
+++ b/x-pack/plugins/ml/common/util/job_utils.ts
@@ -8,7 +8,7 @@
import { each, isEmpty, isEqual, pick } from 'lodash';
import semverGte from 'semver/functions/gte';
import moment, { Duration } from 'moment';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
// @ts-ignore
import numeral from '@elastic/numeral';
import { i18n } from '@kbn/i18n';
diff --git a/x-pack/plugins/ml/common/util/runtime_field_utils.ts b/x-pack/plugins/ml/common/util/runtime_field_utils.ts
index 1fcf8e2e72b15..edda547d363e4 100644
--- a/x-pack/plugins/ml/common/util/runtime_field_utils.ts
+++ b/x-pack/plugins/ml/common/util/runtime_field_utils.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { isPopulatedObject } from './object_utils';
import { RUNTIME_FIELD_TYPES } from '../../../../../src/plugins/data/common';
import type { RuntimeMappings } from '../types/fields';
diff --git a/x-pack/plugins/ml/public/alerting/ml_anomaly_alert_trigger.tsx b/x-pack/plugins/ml/public/alerting/ml_anomaly_alert_trigger.tsx
index 794f4b3b164e9..2be57ddf95431 100644
--- a/x-pack/plugins/ml/public/alerting/ml_anomaly_alert_trigger.tsx
+++ b/x-pack/plugins/ml/public/alerting/ml_anomaly_alert_trigger.tsx
@@ -88,7 +88,7 @@ const MlAnomalyAlertTrigger: FC = ({
const availableResultTypes = useMemo(() => {
if (jobConfigs.length === 0) return Object.values(ANOMALY_RESULT_TYPE);
- return (jobConfigs ?? []).some((v) => v.analysis_config.influencers.length > 0)
+ return (jobConfigs ?? []).some((v) => Boolean(v.analysis_config?.influencers?.length))
? Object.values(ANOMALY_RESULT_TYPE)
: [ANOMALY_RESULT_TYPE.BUCKET, ANOMALY_RESULT_TYPE.RECORD];
}, [jobConfigs]);
diff --git a/x-pack/plugins/ml/public/application/components/data_grid/common.ts b/x-pack/plugins/ml/public/application/components/data_grid/common.ts
index 6fc6f298e73d8..fc6a20e9d4cda 100644
--- a/x-pack/plugins/ml/public/application/components/data_grid/common.ts
+++ b/x-pack/plugins/ml/public/application/components/data_grid/common.ts
@@ -6,7 +6,7 @@
*/
import moment from 'moment-timezone';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { useEffect, useMemo } from 'react';
import {
diff --git a/x-pack/plugins/ml/public/application/components/data_grid/types.ts b/x-pack/plugins/ml/public/application/components/data_grid/types.ts
index 47684ee307e99..01c135000fb0e 100644
--- a/x-pack/plugins/ml/public/application/components/data_grid/types.ts
+++ b/x-pack/plugins/ml/public/application/components/data_grid/types.ts
@@ -7,7 +7,7 @@
import { Dispatch, SetStateAction } from 'react';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
EuiDataGridCellValueElementProps,
EuiDataGridPaginationProps,
diff --git a/x-pack/plugins/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx b/x-pack/plugins/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx
index 5850349ff5fd6..d4ce935cc085f 100644
--- a/x-pack/plugins/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx
+++ b/x-pack/plugins/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx
@@ -6,7 +6,7 @@
*/
import React, { FC, useState, useEffect, useCallback, useMemo } from 'react';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { EuiCallOut, EuiSpacer, EuiLink } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n/react';
diff --git a/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx b/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx
index d64a180bfa8b6..ecaf3515e1634 100644
--- a/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx
+++ b/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx
@@ -7,7 +7,7 @@
import React, { useMemo, useEffect, useState, FC } from 'react';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
EuiCallOut,
diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts
index 920f56b376747..eda63ec4285ea 100644
--- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts
+++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { extractErrorMessage } from '../../../../common/util/errors';
import { EsSorting, UseDataGridReturnType, getProcessedFields } from '../../components/data_grid';
diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts
index 72853ec23fd36..1fe649ee9519a 100644
--- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts
+++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/form_options_validation.ts
@@ -6,7 +6,7 @@
*/
import { i18n } from '@kbn/i18n';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ES_FIELD_TYPES } from '../../../../../../../../../../src/plugins/data/public';
import { EVENT_RATE_FIELD_ID } from '../../../../../../../common/types/fields';
import { ANALYSIS_CONFIG_TYPE } from '../../../../common/analytics';
diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/use_saved_search.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/use_saved_search.ts
index 41973b5ec2d01..ad23c018afbbb 100644
--- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/use_saved_search.ts
+++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/use_saved_search.ts
@@ -12,7 +12,7 @@ import {
luceneStringToDsl,
toElasticsearchQuery,
} from '@kbn/es-query';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { useMlContext } from '../../../../../contexts/ml';
import { SEARCH_QUERY_LANGUAGE } from '../../../../../../../common/constants/search';
import { getQueryFromSavedSearchObject } from '../../../../../util/index_utils';
diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts
index f3779e1968985..69f66832af3c7 100644
--- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts
+++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts
@@ -7,7 +7,7 @@
import { useEffect, useMemo, useState } from 'react';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { EuiDataGridColumn } from '@elastic/eui';
import { CoreSetup } from 'src/core/public';
diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_query_bar/exploration_query_bar.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_query_bar/exploration_query_bar.tsx
index 3639836c6be01..27eb06d7ecd41 100644
--- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_query_bar/exploration_query_bar.tsx
+++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_query_bar/exploration_query_bar.tsx
@@ -11,7 +11,7 @@ import { i18n } from '@kbn/i18n';
import { debounce } from 'lodash';
import { fromKueryExpression, luceneStringToDsl, toElasticsearchQuery } from '@kbn/es-query';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Dictionary } from '../../../../../../../common/types/common';
import { DataView } from '../../../../../../../../../../src/plugins/data_views/common';
import { Query, QueryStringInput } from '../../../../../../../../../../src/plugins/data/public';
diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts
index 3d8c34e0e5967..fd1df5395ff84 100644
--- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts
+++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { SavedSearchSavedObject } from '../../../../../../common/types/kibana';
import { JobCreator } from './job_creator';
diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts
index 607a4fcf9a73c..79bf2f64ca95d 100644
--- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts
+++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts
@@ -83,7 +83,7 @@ export class JobCreator {
this._calendars = [];
this._datafeed_config = createEmptyDatafeed(this._indexPatternTitle);
this._detectors = this._job_config.analysis_config.detectors;
- this._influencers = this._job_config.analysis_config.influencers;
+ this._influencers = this._job_config.analysis_config.influencers!;
if (typeof indexPattern.timeFieldName === 'string') {
this._job_config.data_description.time_field = indexPattern.timeFieldName;
@@ -766,7 +766,7 @@ export class JobCreator {
this._datafeed_config = datafeed;
this._detectors = this._job_config.analysis_config.detectors;
- this._influencers = this._job_config.analysis_config.influencers;
+ this._influencers = this._job_config.analysis_config.influencers!;
if (this._job_config.groups === undefined) {
this._job_config.groups = [];
}
diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx
index f156233dfde85..f6317bcc41e54 100644
--- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx
+++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/advanced_detector_modal/advanced_detector_modal.tsx
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import React, { FC, Fragment, useState, useContext, useEffect } from 'react';
import {
EuiComboBox,
diff --git a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts
index eacfd826868ac..1601a5d6cceea 100644
--- a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts
+++ b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts
@@ -50,7 +50,7 @@ export class AnomalyDetectorService {
}
const influencers = new Set();
for (const job of jobs) {
- for (const influencer of job.analysis_config.influencers) {
+ for (const influencer of job.analysis_config.influencers || []) {
influencers.add(influencer);
}
}
diff --git a/x-pack/plugins/ml/public/application/services/job_service.d.ts b/x-pack/plugins/ml/public/application/services/job_service.d.ts
index 667f23da34aa0..b6575c48b21f2 100644
--- a/x-pack/plugins/ml/public/application/services/job_service.d.ts
+++ b/x-pack/plugins/ml/public/application/services/job_service.d.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { TimeRange } from 'src/plugins/data/common/query/timefilter/types';
import { CombinedJob, Datafeed, Job } from '../../../common/types/anomaly_detection_jobs';
diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts
index 29c2cd8a2408c..854d4b8014b09 100644
--- a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts
+++ b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Observable } from 'rxjs';
import type { HttpStart } from 'kibana/public';
import { HttpService } from '../http_service';
diff --git a/x-pack/plugins/ml/public/embeddables/common/process_filters.ts b/x-pack/plugins/ml/public/embeddables/common/process_filters.ts
index 4ce445eb4c488..1ff8259250019 100644
--- a/x-pack/plugins/ml/public/embeddables/common/process_filters.ts
+++ b/x-pack/plugins/ml/public/embeddables/common/process_filters.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
Filter,
fromKueryExpression,
diff --git a/x-pack/plugins/ml/server/lib/alerts/jobs_health_service.test.ts b/x-pack/plugins/ml/server/lib/alerts/jobs_health_service.test.ts
index 2790ce423c1e7..e824e34a1779b 100644
--- a/x-pack/plugins/ml/server/lib/alerts/jobs_health_service.test.ts
+++ b/x-pack/plugins/ml/server/lib/alerts/jobs_health_service.test.ts
@@ -9,7 +9,7 @@ import { JobsHealthService, jobsHealthServiceProvider } from './jobs_health_serv
import type { DatafeedsService } from '../../models/job_service/datafeeds';
import type { Logger } from 'kibana/server';
import { MlClient } from '../ml_client';
-import { MlJob, MlJobStats } from '@elastic/elasticsearch/api/types';
+import { MlJob, MlJobStats } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { AnnotationService } from '../../models/annotation_service/annotation';
import { JobsHealthExecutorOptions } from './register_jobs_monitoring_rule_type';
import { JobAuditMessagesService } from '../../models/job_audit_messages/job_audit_messages';
diff --git a/x-pack/plugins/ml/server/lib/alerts/jobs_health_service.ts b/x-pack/plugins/ml/server/lib/alerts/jobs_health_service.ts
index 70a8e4a777b69..2fbda6a4b37f6 100644
--- a/x-pack/plugins/ml/server/lib/alerts/jobs_health_service.ts
+++ b/x-pack/plugins/ml/server/lib/alerts/jobs_health_service.ts
@@ -8,7 +8,7 @@
import { groupBy, keyBy, memoize } from 'lodash';
import { KibanaRequest, Logger, SavedObjectsClientContract } from 'kibana/server';
import { i18n } from '@kbn/i18n';
-import { MlJob } from '@elastic/elasticsearch/api/types';
+import { MlJob } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { MlClient } from '../ml_client';
import { JobSelection } from '../../routes/schemas/alerting_schema';
import { datafeedsProvider, DatafeedsService } from '../../models/job_service/datafeeds';
diff --git a/x-pack/plugins/ml/server/lib/alerts/register_jobs_monitoring_rule_type.ts b/x-pack/plugins/ml/server/lib/alerts/register_jobs_monitoring_rule_type.ts
index dcf545fa4060b..5fd21d5372d23 100644
--- a/x-pack/plugins/ml/server/lib/alerts/register_jobs_monitoring_rule_type.ts
+++ b/x-pack/plugins/ml/server/lib/alerts/register_jobs_monitoring_rule_type.ts
@@ -7,7 +7,11 @@
import { i18n } from '@kbn/i18n';
import { KibanaRequest } from 'kibana/server';
-import { MlDatafeedState, MlJobState, MlJobStats } from '@elastic/elasticsearch/api/types';
+import {
+ MlDatafeedState,
+ MlJobState,
+ MlJobStats,
+} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ML_ALERT_TYPES } from '../../../common/constants/alerts';
import { PLUGIN_ID } from '../../../common/constants/app';
import { MINIMUM_FULL_LICENSE } from '../../../common/license';
diff --git a/x-pack/plugins/ml/server/lib/ml_client/search.ts b/x-pack/plugins/ml/server/lib/ml_client/search.ts
index 3062a70d9a975..bdcee216cf669 100644
--- a/x-pack/plugins/ml/server/lib/ml_client/search.ts
+++ b/x-pack/plugins/ml/server/lib/ml_client/search.ts
@@ -7,7 +7,8 @@
import Boom from '@hapi/boom';
import { IScopedClusterClient } from 'kibana/server';
-import { estypes, ApiResponse } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import type { TransportResult } from '@elastic/elasticsearch';
import { JobSavedObjectService } from '../../saved_objects';
import { ML_RESULTS_INDEX_PATTERN } from '../../../common/constants/index_patterns';
@@ -30,7 +31,7 @@ export function searchProvider(
async function anomalySearch(
searchParams: estypes.SearchRequest,
jobIds: string[]
- ): Promise>> {
+ ): Promise, unknown>> {
await jobIdsCheck('anomaly-detector', jobIds);
const { asInternalUser } = client;
const resp = await asInternalUser.search({
diff --git a/x-pack/plugins/ml/server/lib/query_utils.ts b/x-pack/plugins/ml/server/lib/query_utils.ts
index e801130643345..cfaa5abaf7f23 100644
--- a/x-pack/plugins/ml/server/lib/query_utils.ts
+++ b/x-pack/plugins/ml/server/lib/query_utils.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
/*
* Contains utility functions for building and processing queries.
*/
diff --git a/x-pack/plugins/ml/server/models/annotation_service/annotation.ts b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts
index 5807d181cc566..fac35d6255e03 100644
--- a/x-pack/plugins/ml/server/models/annotation_service/annotation.ts
+++ b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts
@@ -9,7 +9,7 @@ import Boom from '@hapi/boom';
import { each, get } from 'lodash';
import { IScopedClusterClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ANNOTATION_EVENT_USER, ANNOTATION_TYPE } from '../../../common/constants/annotations';
import { PARTITION_FIELDS } from '../../../common/constants/anomalies';
import {
diff --git a/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts b/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts
index 760faa8d530fc..4eb2c2421debf 100644
--- a/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts
+++ b/x-pack/plugins/ml/server/models/calculate_model_memory_limit/calculate_model_memory_limit.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import numeral from '@elastic/numeral';
import { IScopedClusterClient } from 'kibana/server';
import { MLCATEGORY } from '../../../common/constants/field_types';
@@ -89,6 +89,7 @@ const cardinalityCheckProvider = (client: IScopedClusterClient) => {
new Set()
);
+ // @ts-expect-error influencers is optional
const normalizedInfluencers: estypes.Field[] = Array.isArray(influencers)
? influencers
: [influencers];
diff --git a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts
index 791ba6d79ab5a..508abcffd0776 100644
--- a/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts
+++ b/x-pack/plugins/ml/server/models/calendar/calendar_manager.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { difference } from 'lodash';
import { EventManager } from './event_manager';
import type { MlClient } from '../../lib/ml_client';
diff --git a/x-pack/plugins/ml/server/models/calendar/event_manager.ts b/x-pack/plugins/ml/server/models/calendar/event_manager.ts
index d30297eab5c15..46ad415167387 100644
--- a/x-pack/plugins/ml/server/models/calendar/event_manager.ts
+++ b/x-pack/plugins/ml/server/models/calendar/event_manager.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { GLOBAL_CALENDAR } from '../../../common/constants/calendars';
import type { MlClient } from '../../lib/ml_client';
diff --git a/x-pack/plugins/ml/server/models/data_frame_analytics/validation.ts b/x-pack/plugins/ml/server/models/data_frame_analytics/validation.ts
index b39debbe664d3..436ca86b5a603 100644
--- a/x-pack/plugins/ml/server/models/data_frame_analytics/validation.ts
+++ b/x-pack/plugins/ml/server/models/data_frame_analytics/validation.ts
@@ -6,7 +6,7 @@
*/
import { i18n } from '@kbn/i18n';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IScopedClusterClient } from 'kibana/server';
import { getAnalysisType } from '../../../common/util/analytics_utils';
import { ANALYSIS_CONFIG_TYPE } from '../../../common/constants/data_frame_analytics';
diff --git a/x-pack/plugins/ml/server/models/filter/filter_manager.ts b/x-pack/plugins/ml/server/models/filter/filter_manager.ts
index a2b71ae572170..3a0d7a706e69c 100644
--- a/x-pack/plugins/ml/server/models/filter/filter_manager.ts
+++ b/x-pack/plugins/ml/server/models/filter/filter_manager.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import Boom from '@hapi/boom';
import type { MlClient } from '../../lib/ml_client';
diff --git a/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.ts b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.ts
index 69f5c8b36f10c..313b60a35aa6d 100644
--- a/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.ts
+++ b/x-pack/plugins/ml/server/models/job_audit_messages/job_audit_messages.ts
@@ -7,8 +7,8 @@
import moment from 'moment';
import type { IScopedClusterClient } from 'kibana/server';
-import type { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
-import type { estypes } from '@elastic/elasticsearch';
+import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ML_NOTIFICATION_INDEX_PATTERN } from '../../../common/constants/index_patterns';
import { MESSAGE_LEVEL } from '../../../common/constants/message_levels';
import type { JobSavedObjectService } from '../../saved_objects';
diff --git a/x-pack/plugins/ml/server/models/job_service/datafeeds.ts b/x-pack/plugins/ml/server/models/job_service/datafeeds.ts
index 8b3f7f4b0b0ee..a699402f9b47a 100644
--- a/x-pack/plugins/ml/server/models/job_service/datafeeds.ts
+++ b/x-pack/plugins/ml/server/models/job_service/datafeeds.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { i18n } from '@kbn/i18n';
import { IScopedClusterClient } from 'kibana/server';
import { JOB_STATE, DATAFEED_STATE } from '../../../common/constants/states';
diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts
index 4f87e4698c032..a5510977d2ade 100644
--- a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts
+++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/examples.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IScopedClusterClient } from 'kibana/server';
import { chunk } from 'lodash';
diff --git a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts
index 87715d9d85dbf..03477b896d7c7 100644
--- a/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts
+++ b/x-pack/plugins/ml/server/models/job_service/new_job/categorization/top_categories.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { CategoryId, Category } from '../../../../../common/types/categories';
import type { MlClient } from '../../../../lib/ml_client';
diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts
index a25b3183362b3..3682245b1b640 100644
--- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts
+++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/field_service.ts
@@ -6,7 +6,7 @@
*/
import { cloneDeep } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { IScopedClusterClient } from 'kibana/server';
import type { Field, FieldId, NewJobCaps, RollupFields } from '../../../../common/types/fields';
import { ES_FIELD_TYPES } from '../../../../../../../src/plugins/data/common';
@@ -113,7 +113,7 @@ class FieldsService {
this._mlClusterClient,
this._dataViewsService
);
- const rollupConfigs: estypes.RollupGetRollupCapabilitiesRollupCapabilitySummary[] | null =
+ const rollupConfigs: estypes.RollupGetRollupCapsRollupCapabilitySummary[] | null =
await rollupService.getRollupJobs();
// if a rollup index has been specified, yet there are no
@@ -137,7 +137,7 @@ class FieldsService {
}
function combineAllRollupFields(
- rollupConfigs: estypes.RollupGetRollupCapabilitiesRollupCapabilitySummary[]
+ rollupConfigs: estypes.RollupGetRollupCapsRollupCapabilitySummary[]
): RollupFields {
const rollupFields: RollupFields = {};
rollupConfigs.forEach((conf) => {
diff --git a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts
index 87504a1bc0e10..f0f9a53879962 100644
--- a/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts
+++ b/x-pack/plugins/ml/server/models/job_service/new_job_caps/rollup.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { IScopedClusterClient } from 'kibana/server';
import type {
DataViewsService,
@@ -29,7 +29,7 @@ export async function rollupServiceProvider(
let jobIndexPatterns: string[] = [indexPattern];
async function getRollupJobs(): Promise<
- estypes.RollupGetRollupCapabilitiesRollupCapabilitySummary[] | null
+ estypes.RollupGetRollupCapsRollupCapabilitySummary[] | null
> {
if (
rollupIndexPatternObject !== null &&
diff --git a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts
index ad67cfb49ca6d..212beb1ebbd4a 100644
--- a/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts
+++ b/x-pack/plugins/ml/server/models/job_validation/validate_influencers.ts
@@ -38,7 +38,7 @@ export async function validateInfluencers(job: CombinedJob) {
// detector using 'count' and no influencers and there shouldn't
// be a warning about that.
if (
- influencers.length === 0 &&
+ influencers?.length === 0 &&
job.analysis_config.detectors.length === 1 &&
detectorFieldNames.length === 0
) {
@@ -46,6 +46,7 @@ export async function validateInfluencers(job: CombinedJob) {
}
if (
+ // @ts-expect-error influencers is optional
influencers.length <= INFLUENCER_LOW_THRESHOLD &&
detectorFieldNames.length >= DETECTOR_FIELD_NAMES_THRESHOLD
) {
@@ -59,8 +60,10 @@ export async function validateInfluencers(job: CombinedJob) {
}
messages.push({ id, influencerSuggestion });
+ // @ts-expect-error influencers is optional
} else if (influencers.length <= INFLUENCER_LOW_THRESHOLD) {
messages.push({ id: 'influencer_low' });
+ // @ts-expect-error influencers is optional
} else if (influencers.length >= INFLUENCER_HIGH_THRESHOLD) {
messages.push({ id: 'influencer_high' });
}
diff --git a/x-pack/plugins/ml/server/routes/anomaly_detectors.ts b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts
index 30aae3c0fb550..4e222e05c1b19 100644
--- a/x-pack/plugins/ml/server/routes/anomaly_detectors.ts
+++ b/x-pack/plugins/ml/server/routes/anomaly_detectors.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { schema } from '@kbn/config-schema';
import { wrapError } from '../client/error_wrapper';
import { RouteInitialization } from '../types';
@@ -221,6 +221,7 @@ export function jobRoutes({ router, routeGuard }: RouteInitialization) {
const { jobId } = request.params;
const { body } = await mlClient.updateJob({
job_id: jobId,
+ // @ts-expect-error MlDetector is not compatible
body: request.body,
});
return response.ok({
diff --git a/x-pack/plugins/ml/server/routes/datafeeds.ts b/x-pack/plugins/ml/server/routes/datafeeds.ts
index 9f908bf61a35d..c3414b2fbc55c 100644
--- a/x-pack/plugins/ml/server/routes/datafeeds.ts
+++ b/x-pack/plugins/ml/server/routes/datafeeds.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { wrapError } from '../client/error_wrapper';
import { RouteInitialization } from '../types';
import {
diff --git a/x-pack/plugins/ml/server/routes/job_service.ts b/x-pack/plugins/ml/server/routes/job_service.ts
index 15b0b4449590c..96ca56baa38da 100644
--- a/x-pack/plugins/ml/server/routes/job_service.ts
+++ b/x-pack/plugins/ml/server/routes/job_service.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { schema } from '@kbn/config-schema';
import { wrapError } from '../client/error_wrapper';
import type { RouteInitialization } from '../types';
diff --git a/x-pack/plugins/ml/server/shared_services/providers/system.ts b/x-pack/plugins/ml/server/shared_services/providers/system.ts
index 85cd73ba010af..b198e5d8345f0 100644
--- a/x-pack/plugins/ml/server/shared_services/providers/system.ts
+++ b/x-pack/plugins/ml/server/shared_services/providers/system.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { KibanaRequest, SavedObjectsClientContract } from 'kibana/server';
import { MlLicense } from '../../../common/license';
diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_es_usage.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_es_usage.ts
index 1fb2ba70f2ab1..884b4e6466e60 100644
--- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_es_usage.ts
+++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_es_usage.ts
@@ -7,7 +7,7 @@
import { ElasticsearchClient } from 'src/core/server';
import { get } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { StackProductUsage } from '../types';
interface ESIndicesBucket {
diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_license_type.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_license_type.ts
index f42623ff851ce..0f0d75546d28d 100644
--- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_license_type.ts
+++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_license_type.ts
@@ -7,7 +7,7 @@
import { get } from 'lodash';
import { ElasticsearchClient } from 'src/core/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { INDEX_PATTERN_ELASTICSEARCH } from '../../../../common/constants';
import { getCcsIndexPattern } from '../../../lib/alerts/get_ccs_index_pattern';
diff --git a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_stack_product_usage.ts b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_stack_product_usage.ts
index 0d3aab8283688..bcb872912394c 100644
--- a/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_stack_product_usage.ts
+++ b/x-pack/plugins/monitoring/server/kibana_monitoring/collectors/lib/fetch_stack_product_usage.ts
@@ -7,7 +7,7 @@
import { get } from 'lodash';
import { ElasticsearchClient } from 'src/core/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { MonitoringConfig } from '../../../config';
// @ts-ignore
import { prefixIndexPattern } from '../../../../common/ccs_utils';
diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts
index ca8270590da54..19d6168dbb5d0 100644
--- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts
+++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_available_ccs.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
import { elasticsearchServiceMock } from 'src/core/server/mocks';
diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_health.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_health.test.ts
index 08ecaef33085b..2739e23245bde 100644
--- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_health.test.ts
+++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_health.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { elasticsearchClientMock } from '../../../../../../src/core/server/elasticsearch/client/mocks';
import { fetchClusterHealth } from './fetch_cluster_health';
diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_clusters.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_clusters.test.ts
index 75991e892d419..c46ec424b2cd3 100644
--- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_clusters.test.ts
+++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_clusters.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { elasticsearchClientMock } from 'src/core/server/elasticsearch/client/mocks';
import { elasticsearchServiceMock } from 'src/core/server/mocks';
diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts
index 8f0083f1f533f..a67a5e679cc33 100644
--- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts
+++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { elasticsearchClientMock } from '../../../../../../src/core/server/elasticsearch/client/mocks';
import { fetchCpuUsageNodeStats } from './fetch_cpu_usage_node_stats';
diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_elasticsearch_versions.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_elasticsearch_versions.test.ts
index d105174853636..515fa3b2442d3 100644
--- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_elasticsearch_versions.test.ts
+++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_elasticsearch_versions.test.ts
@@ -9,7 +9,7 @@
import { elasticsearchClientMock } from '../../../../../../src/core/server/elasticsearch/client/mocks';
import { elasticsearchServiceMock } from 'src/core/server/mocks';
import { fetchElasticsearchVersions } from './fetch_elasticsearch_versions';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
describe('fetchElasticsearchVersions', () => {
const esClient = elasticsearchServiceMock.createScopedClusterClient().asCurrentUser;
diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.test.ts
index 3c12c70bf1713..538e24a764276 100644
--- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.test.ts
+++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.test.ts
@@ -8,7 +8,7 @@ import { fetchLicenses } from './fetch_licenses';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { elasticsearchClientMock } from '../../../../../../src/core/server/elasticsearch/client/mocks';
import { elasticsearchServiceMock } from 'src/core/server/mocks';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
describe('fetchLicenses', () => {
const clusterName = 'MyCluster';
diff --git a/x-pack/plugins/monitoring/server/lib/elasticsearch_settings/cluster.test.ts b/x-pack/plugins/monitoring/server/lib/elasticsearch_settings/cluster.test.ts
index 8b2ea8459e26c..985ad2357648a 100644
--- a/x-pack/plugins/monitoring/server/lib/elasticsearch_settings/cluster.test.ts
+++ b/x-pack/plugins/monitoring/server/lib/elasticsearch_settings/cluster.test.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { ClusterGetSettingsResponse } from '@elastic/elasticsearch/api/types';
+import { ClusterGetSettingsResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { checkClusterSettings } from '.';
import { LegacyRequest } from '../../types';
diff --git a/x-pack/plugins/monitoring/server/lib/elasticsearch_settings/cluster.ts b/x-pack/plugins/monitoring/server/lib/elasticsearch_settings/cluster.ts
index 4f46f65591d62..b474cca59519e 100644
--- a/x-pack/plugins/monitoring/server/lib/elasticsearch_settings/cluster.ts
+++ b/x-pack/plugins/monitoring/server/lib/elasticsearch_settings/cluster.ts
@@ -6,7 +6,7 @@
*/
import { get } from 'lodash';
-import { ClusterGetSettingsResponse } from '@elastic/elasticsearch/api/types';
+import { ClusterGetSettingsResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { findReason } from './find_reason';
import { ClusterSettingsReasonResponse, LegacyRequest } from '../../types';
diff --git a/x-pack/plugins/monitoring/server/lib/errors/auth_errors.test.ts b/x-pack/plugins/monitoring/server/lib/errors/auth_errors.test.ts
index e9f3eb8efc4d7..06883a47f2ca3 100644
--- a/x-pack/plugins/monitoring/server/lib/errors/auth_errors.test.ts
+++ b/x-pack/plugins/monitoring/server/lib/errors/auth_errors.test.ts
@@ -6,7 +6,7 @@
*/
import { forbidden, unauthorized } from '@hapi/boom';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { isAuthError, handleAuthError } from './auth_errors';
describe('Error handling for 401/403 errors', () => {
@@ -59,7 +59,7 @@ describe('Error handling for 401/403 errors', () => {
describe('Elasticsearch errors', () => {
it('handles Forbidden error defined by ElasticsearchJS', () => {
- const err = new ResponseError({
+ const err = new errors.ResponseError({
statusCode: 401,
body: {
error: {
@@ -91,7 +91,7 @@ describe('Error handling for 401/403 errors', () => {
});
it('handles Unauthorized error defined by ElasticsearchJS', () => {
- const err = new ResponseError({
+ const err = new errors.ResponseError({
statusCode: 403,
body: {
error: {
diff --git a/x-pack/plugins/monitoring/server/lib/errors/esclient_errors.ts b/x-pack/plugins/monitoring/server/lib/errors/esclient_errors.ts
index 5994c3048dae8..1b83b8e4e7eb6 100644
--- a/x-pack/plugins/monitoring/server/lib/errors/esclient_errors.ts
+++ b/x-pack/plugins/monitoring/server/lib/errors/esclient_errors.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { ElasticsearchClientError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { boomify } from '@hapi/boom';
import { i18n } from '@kbn/i18n';
import { ErrorTypes } from '../../types';
@@ -38,12 +38,12 @@ const mapTypeMessage: { [key: string]: string } = {
};
export function isESClientError(err: ErrorTypes) {
- if (err instanceof ElasticsearchClientError === false) return false;
+ if (err instanceof errors.ElasticsearchClientError === false) return false;
const knownTypes = Object.keys(mapTypeMessage);
return knownTypes.includes(err.constructor.name);
}
-export function handleESClientError(err: ElasticsearchClientError) {
+export function handleESClientError(err: errors.ElasticsearchClientError) {
err.message = mapTypeMessage[err.constructor.name];
return boomify(err, { statusCode: 503 });
}
diff --git a/x-pack/plugins/monitoring/server/lib/errors/handle_error.ts b/x-pack/plugins/monitoring/server/lib/errors/handle_error.ts
index 3fe3b28034b2c..cc5fde228120e 100644
--- a/x-pack/plugins/monitoring/server/lib/errors/handle_error.ts
+++ b/x-pack/plugins/monitoring/server/lib/errors/handle_error.ts
@@ -6,7 +6,7 @@
*/
import { boomify, isBoom } from '@hapi/boom';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { isCustomError, handleCustomError } from './custom_errors';
import { isAuthError, handleAuthError } from './auth_errors';
import { ErrorTypes, LegacyRequest } from '../../types';
@@ -15,7 +15,7 @@ import { handleESClientError, isESClientError } from './esclient_errors';
export const getStatusCode = (err: ErrorTypes) => {
return isBoom(err)
? err.output.statusCode
- : err instanceof ResponseError
+ : err instanceof errors.ResponseError
? err.statusCode
: undefined;
};
diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts b/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts
index 3cd2b8b73b315..eee6ba98e62c7 100644
--- a/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts
+++ b/x-pack/plugins/monitoring/server/routes/api/v1/elasticsearch_settings/check/internal_monitoring.ts
@@ -7,7 +7,7 @@
import { schema } from '@kbn/config-schema';
import { RequestHandlerContext } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
INDEX_PATTERN_ELASTICSEARCH,
INDEX_PATTERN_KIBANA,
diff --git a/x-pack/plugins/monitoring/server/static_globals.ts b/x-pack/plugins/monitoring/server/static_globals.ts
index fc4ece3231486..ac0cab7a68388 100644
--- a/x-pack/plugins/monitoring/server/static_globals.ts
+++ b/x-pack/plugins/monitoring/server/static_globals.ts
@@ -13,7 +13,7 @@ import {
PluginInitializerContext,
} from 'kibana/server';
import url from 'url';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { MonitoringConfig } from './config';
import { PluginsSetup } from './types';
import { mbSafeQuery } from './lib/mb_safe_query';
diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_beats_stats.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_beats_stats.ts
index 00dba8b727883..8da551a923f04 100644
--- a/x-pack/plugins/monitoring/server/telemetry_collection/get_beats_stats.ts
+++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_beats_stats.ts
@@ -7,7 +7,7 @@
import { get } from 'lodash';
import { ElasticsearchClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { createQuery } from './create_query';
import { INDEX_PATTERN_BEATS } from '../../common/constants';
diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_cluster_uuids.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_cluster_uuids.ts
index 7cf4ca2b94ce0..eda038ac19395 100644
--- a/x-pack/plugins/monitoring/server/telemetry_collection/get_cluster_uuids.ts
+++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_cluster_uuids.ts
@@ -8,7 +8,7 @@
import { get } from 'lodash';
import moment from 'moment';
import { ElasticsearchClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { createQuery } from './create_query';
import {
INDEX_PATTERN_ELASTICSEARCH,
diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_es_stats.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_es_stats.ts
index 92aa48cbe90ef..8155c0080e44e 100644
--- a/x-pack/plugins/monitoring/server/telemetry_collection/get_es_stats.ts
+++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_es_stats.ts
@@ -6,7 +6,7 @@
*/
import { ElasticsearchClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { INDEX_PATTERN_ELASTICSEARCH } from '../../common/constants';
/**
diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_high_level_stats.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_high_level_stats.ts
index 5f14ebb815bab..79c38c4d15a87 100644
--- a/x-pack/plugins/monitoring/server/telemetry_collection/get_high_level_stats.ts
+++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_high_level_stats.ts
@@ -7,7 +7,7 @@
import { get } from 'lodash';
import { ElasticsearchClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { createQuery } from './create_query';
import {
INDEX_PATTERN_KIBANA,
diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.test.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.test.ts
index cd037fa062ed8..5474880986238 100644
--- a/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.test.ts
+++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.test.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
getUsageStats,
combineStats,
diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.ts
index 8313bcc9f5464..df8354716a0c8 100644
--- a/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.ts
+++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_kibana_stats.ts
@@ -7,7 +7,7 @@
import moment from 'moment';
import { isEmpty } from 'lodash';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient } from 'kibana/server';
import { KIBANA_SYSTEM_ID, TELEMETRY_COLLECTION_INTERVAL } from '../../common/constants';
import {
diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_licenses.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_licenses.ts
index 514b04bf1a0e7..d70bfdfd70ad6 100644
--- a/x-pack/plugins/monitoring/server/telemetry_collection/get_licenses.ts
+++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_licenses.ts
@@ -6,7 +6,7 @@
*/
import { ElasticsearchClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ESLicense } from '../../../telemetry_collection_xpack/server';
import { INDEX_PATTERN_ELASTICSEARCH } from '../../common/constants';
diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_logstash_stats.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_logstash_stats.ts
index 306c9b6201557..736c61130bc67 100644
--- a/x-pack/plugins/monitoring/server/telemetry_collection/get_logstash_stats.ts
+++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_logstash_stats.ts
@@ -6,7 +6,7 @@
*/
import { ElasticsearchClient } from 'kibana/server';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { createQuery } from './create_query';
import { mapToList } from './get_high_level_stats';
import { incrementByKey } from './get_high_level_stats';
diff --git a/x-pack/plugins/monitoring/server/types.ts b/x-pack/plugins/monitoring/server/types.ts
index 416d1ac7c3d86..14071aafaea12 100644
--- a/x-pack/plugins/monitoring/server/types.ts
+++ b/x-pack/plugins/monitoring/server/types.ts
@@ -14,7 +14,7 @@ import type {
ElasticsearchClient,
} from 'kibana/server';
import type Boom from '@hapi/boom';
-import { ElasticsearchClientError, ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { UsageCollectionSetup } from 'src/plugins/usage_collection/server';
import { LicenseFeature, ILicense } from '../../licensing/server';
import type {
@@ -180,7 +180,7 @@ export interface ClusterSettingsReasonResponse {
};
}
-export type ErrorTypes = Error | Boom.Boom | ResponseError | ElasticsearchClientError;
+export type ErrorTypes = Error | Boom.Boom | errors.ResponseError | errors.ElasticsearchClientError;
export type Pipeline = {
id: string;
diff --git a/x-pack/plugins/observability/common/utils/unwrap_es_response.ts b/x-pack/plugins/observability/common/utils/unwrap_es_response.ts
index 81f8be4e0f696..d2c97eb0ba25a 100644
--- a/x-pack/plugins/observability/common/utils/unwrap_es_response.ts
+++ b/x-pack/plugins/observability/common/utils/unwrap_es_response.ts
@@ -4,20 +4,20 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import { ElasticsearchClientError, ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import type { UnwrapPromise } from '@kbn/utility-types';
import { inspect } from 'util';
export class WrappedElasticsearchClientError extends Error {
- originalError: ElasticsearchClientError;
- constructor(originalError: ElasticsearchClientError) {
+ originalError: errors.ElasticsearchClientError;
+ constructor(originalError: errors.ElasticsearchClientError) {
super(originalError.message);
const stack = this.stack;
this.originalError = originalError;
- if (originalError instanceof ResponseError) {
+ if (originalError instanceof errors.ResponseError) {
// make sure ES response body is visible when logged to the console
// @ts-expect-error
this.stack = {
diff --git a/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/use_filter_values.ts b/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/use_filter_values.ts
index e84f79f88298c..d27e3ec98287e 100644
--- a/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/use_filter_values.ts
+++ b/x-pack/plugins/observability/public/components/shared/exploratory_view/series_editor/use_filter_values.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
import { ExistsFilter, isExistsFilter } from '@kbn/es-query';
-import { QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { useValuesList } from '../../../../hooks/use_values_list';
import { FilterProps } from './columns/filter_expanded';
import { useAppIndexPatternContext } from '../hooks/use_app_index_pattern';
@@ -25,7 +25,7 @@ export function useFilterValues(
queryFilters.push(qFilter.query);
}
if (isExistsFilter(qFilter)) {
- queryFilters.push({ exists: qFilter.query.exists } as QueryDslQueryContainer);
+ queryFilters.push({ exists: qFilter.query.exists } as estypes.QueryDslQueryContainer);
}
});
diff --git a/x-pack/plugins/observability/public/hooks/use_es_search.ts b/x-pack/plugins/observability/public/hooks/use_es_search.ts
index bf96cf2c1f2c5..94126d6c1540e 100644
--- a/x-pack/plugins/observability/public/hooks/use_es_search.ts
+++ b/x-pack/plugins/observability/public/hooks/use_es_search.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { DataPublicPluginStart } from '../../../../../src/plugins/data/public';
import { ESSearchResponse } from '../../../../../src/core/types/elasticsearch';
import { useKibana } from '../../../../../src/plugins/kibana_react/public';
diff --git a/x-pack/plugins/observability/server/routes/register_routes.ts b/x-pack/plugins/observability/server/routes/register_routes.ts
index 660c38edb8e9d..66d8940b615b3 100644
--- a/x-pack/plugins/observability/server/routes/register_routes.ts
+++ b/x-pack/plugins/observability/server/routes/register_routes.ts
@@ -12,7 +12,7 @@ import {
} from '@kbn/server-route-repository';
import { CoreSetup, CoreStart, Logger, RouteRegistrar } from 'kibana/server';
import Boom from '@hapi/boom';
-import { RequestAbortedError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
import { RuleDataPluginService } from '../../../rule_registry/server';
import { ObservabilityRequestHandlerContext } from '../types';
import { AbstractObservabilityServerRouteRepository } from './types';
@@ -79,7 +79,7 @@ export function registerRoutes({
opts.statusCode = error.output.statusCode;
}
- if (error instanceof RequestAbortedError) {
+ if (error instanceof errors.RequestAbortedError) {
opts.statusCode = 499;
opts.body.message = 'Client closed request';
}
diff --git a/x-pack/plugins/observability/server/utils/create_or_update_index.ts b/x-pack/plugins/observability/server/utils/create_or_update_index.ts
index 7451314ad248c..9cd4cf9c9334f 100644
--- a/x-pack/plugins/observability/server/utils/create_or_update_index.ts
+++ b/x-pack/plugins/observability/server/utils/create_or_update_index.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import pRetry from 'p-retry';
import { Logger, ElasticsearchClient } from 'src/core/server';
diff --git a/x-pack/plugins/observability/server/utils/queries.ts b/x-pack/plugins/observability/server/utils/queries.ts
index 2e05aa6cb3758..953c0021636d4 100644
--- a/x-pack/plugins/observability/server/utils/queries.ts
+++ b/x-pack/plugins/observability/server/utils/queries.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query';
export function rangeQuery(
diff --git a/x-pack/plugins/osquery/common/search_strategy/osquery/actions/index.ts b/x-pack/plugins/osquery/common/search_strategy/osquery/actions/index.ts
index b24e4f28d89f1..22edbf25cc412 100644
--- a/x-pack/plugins/osquery/common/search_strategy/osquery/actions/index.ts
+++ b/x-pack/plugins/osquery/common/search_strategy/osquery/actions/index.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IEsSearchResponse } from '../../../../../../../src/plugins/data/common';
import { Inspect, Maybe, PageInfoPaginated } from '../../common';
diff --git a/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts b/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts
index fb3bd92abb4c9..d0d67c8546b61 100644
--- a/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts
+++ b/x-pack/plugins/osquery/common/search_strategy/osquery/index.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IEsSearchRequest } from '../../../../../../src/plugins/data/common';
import { ESQuery } from '../../typed_json';
import {
diff --git a/x-pack/plugins/osquery/common/search_strategy/osquery/results/index.ts b/x-pack/plugins/osquery/common/search_strategy/osquery/results/index.ts
index ca85f4342c9c1..f08d9f88e705d 100644
--- a/x-pack/plugins/osquery/common/search_strategy/osquery/results/index.ts
+++ b/x-pack/plugins/osquery/common/search_strategy/osquery/results/index.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IEsSearchResponse } from '../../../../../../../src/plugins/data/common';
import { Inspect, Maybe, PageInfoPaginated, SortField } from '../../common';
diff --git a/x-pack/plugins/osquery/public/agents/helpers.ts b/x-pack/plugins/osquery/public/agents/helpers.ts
index 1b9ac9cedcee2..1b0ae182070de 100644
--- a/x-pack/plugins/osquery/public/agents/helpers.ts
+++ b/x-pack/plugins/osquery/public/agents/helpers.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { euiPaletteColorBlindBehindText } from '@elastic/eui';
import {
PaginationInputPaginated,
diff --git a/x-pack/plugins/osquery/public/agents/types.ts b/x-pack/plugins/osquery/public/agents/types.ts
index bfe59c91d007d..9a4d4c7ff18cc 100644
--- a/x-pack/plugins/osquery/public/agents/types.ts
+++ b/x-pack/plugins/osquery/public/agents/types.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { EuiComboBoxOptionOption } from '@elastic/eui';
import { Agent } from '../../common/shared_imports';
diff --git a/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/all/query.all_actions.dsl.ts b/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/all/query.all_actions.dsl.ts
index 8dc8fad02a7c1..5162475529792 100644
--- a/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/all/query.all_actions.dsl.ts
+++ b/x-pack/plugins/osquery/server/search_strategy/osquery/factory/actions/all/query.all_actions.dsl.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ISearchRequestParams } from '../../../../../../../../../src/plugins/data/common';
import { AgentsRequestOptions } from '../../../../../../common/search_strategy';
diff --git a/x-pack/plugins/osquery/server/usage/fetchers.ts b/x-pack/plugins/osquery/server/usage/fetchers.ts
index 3ac7d56acac4d..cbf72f9144b4b 100644
--- a/x-pack/plugins/osquery/server/usage/fetchers.ts
+++ b/x-pack/plugins/osquery/server/usage/fetchers.ts
@@ -10,7 +10,7 @@ import {
AggregationsTopHitsAggregate,
AggregationsValueAggregate,
SearchResponse,
-} from '@elastic/elasticsearch/api/types';
+} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { PackagePolicyServiceInterface } from '../../../fleet/server';
import { getRouteMetric } from '../routes/usage';
import { ElasticsearchClient, SavedObjectsClientContract } from '../../../../../src/core/server';
diff --git a/x-pack/plugins/remote_clusters/server/routes/api/update_route.test.ts b/x-pack/plugins/remote_clusters/server/routes/api/update_route.test.ts
index 129326dea95ec..856b8062e320e 100644
--- a/x-pack/plugins/remote_clusters/server/routes/api/update_route.test.ts
+++ b/x-pack/plugins/remote_clusters/server/routes/api/update_route.test.ts
@@ -164,6 +164,7 @@ describe('UPDATE remote clusters', () => {
test('updates v1 proxy cluster', async () => {
remoteInfoMockFn.mockResolvedValueOnce(
+ // @ts-expect-error not full interface
createApiResponse({
body: {
test: {
diff --git a/x-pack/plugins/reporting/server/deprecations/reporting_role.ts b/x-pack/plugins/reporting/server/deprecations/reporting_role.ts
index a2a7e9c78726d..e4575f9875315 100644
--- a/x-pack/plugins/reporting/server/deprecations/reporting_role.ts
+++ b/x-pack/plugins/reporting/server/deprecations/reporting_role.ts
@@ -8,7 +8,7 @@
import {
SecurityGetRoleMappingResponse,
SecurityGetUserResponse,
-} from '@elastic/elasticsearch/api/types';
+} from '@elastic/elasticsearch/lib/api/types';
import { i18n } from '@kbn/i18n';
import type {
DeprecationsDetails,
diff --git a/x-pack/plugins/reporting/server/export_types/csv/execute_job.test.ts b/x-pack/plugins/reporting/server/export_types/csv/execute_job.test.ts
index 57f030df66e0e..6af186fa6baf6 100644
--- a/x-pack/plugins/reporting/server/export_types/csv/execute_job.test.ts
+++ b/x-pack/plugins/reporting/server/export_types/csv/execute_job.test.ts
@@ -190,7 +190,7 @@ describe('CSV Execute Job', function () {
);
expect(mockEsClient.scroll).toHaveBeenCalledWith(
- expect.objectContaining({ body: { scroll_id: scrollId } })
+ expect.objectContaining({ scroll_id: scrollId })
);
});
@@ -279,7 +279,7 @@ describe('CSV Execute Job', function () {
);
expect(mockEsClient.clearScroll).toHaveBeenCalledWith(
- expect.objectContaining({ body: { scroll_id: lastScrollId } })
+ expect.objectContaining({ scroll_id: lastScrollId })
);
});
@@ -315,7 +315,7 @@ describe('CSV Execute Job', function () {
);
expect(mockEsClient.clearScroll).toHaveBeenCalledWith(
- expect.objectContaining({ body: { scroll_id: lastScrollId } })
+ expect.objectContaining({ scroll_id: lastScrollId })
);
});
});
@@ -788,9 +788,7 @@ describe('CSV Execute Job', function () {
await delay(100);
expect(mockEsClient.clearScroll).toHaveBeenCalledWith(
- expect.objectContaining({
- body: { scroll_id: scrollId },
- })
+ expect.objectContaining({ scroll_id: scrollId })
);
});
});
@@ -1184,7 +1182,7 @@ describe('CSV Execute Job', function () {
await runTask('job123', jobParams, cancellationToken, stream);
expect(mockEsClient.scroll).toHaveBeenCalledWith(
- expect.objectContaining({ body: { scroll: scrollDuration, scroll_id: 'scrollId' } })
+ expect.objectContaining({ scroll: scrollDuration, scroll_id: 'scrollId' })
);
});
});
diff --git a/x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.ts
index 9014e4f85b3b2..f2da8564bebbc 100644
--- a/x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.ts
+++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.ts
@@ -4,18 +4,15 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-
-import { UnwrapPromise } from '@kbn/utility-types';
+import type { TransportResult } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { i18n } from '@kbn/i18n';
import { ElasticsearchClient } from 'src/core/server';
import { CancellationToken } from '../../../../common';
import { LevelLogger } from '../../../lib';
import { ScrollConfig } from '../../../types';
-type SearchResponse = UnwrapPromise>;
-type SearchRequest = Required>[0];
-
-function parseResponse(response: SearchResponse) {
+function parseResponse(response: TransportResult) {
if (!response?.body._scroll_id) {
throw new Error(
i18n.translate('xpack.reporting.exportTypes.csv.hitIterator.expectedScrollIdErrorMessage', {
@@ -44,11 +41,14 @@ export function createHitIterator(logger: LevelLogger) {
return async function* hitIterator(
scrollSettings: ScrollConfig,
elasticsearchClient: ElasticsearchClient,
- searchRequest: SearchRequest,
+ searchRequest: estypes.SearchRequest,
cancellationToken: CancellationToken
) {
logger.debug('executing search request');
- async function search(index: SearchRequest['index'], body: SearchRequest['body']) {
+ async function search(
+ index: estypes.SearchRequest['index'],
+ body: estypes.SearchRequest['body']
+ ) {
return parseResponse(
await elasticsearchClient.search({
index,
@@ -64,10 +64,8 @@ export function createHitIterator(logger: LevelLogger) {
logger.debug('executing scroll request');
return parseResponse(
await elasticsearchClient.scroll({
- body: {
- scroll_id: scrollId,
- scroll: scrollSettings.duration,
- },
+ scroll_id: scrollId,
+ scroll: scrollSettings.duration,
})
);
}
@@ -76,7 +74,7 @@ export function createHitIterator(logger: LevelLogger) {
logger.debug('executing clearScroll request');
try {
await elasticsearchClient.clearScroll({
- body: { scroll_id: scrollId },
+ scroll_id: scrollId,
});
} catch (err) {
// Do not throw the error, as the job can still be completed successfully
diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/generate_csv/generate_csv.test.ts b/x-pack/plugins/reporting/server/export_types/csv_searchsource/generate_csv/generate_csv.test.ts
index 1902c4ed0272e..4d883eb9aefb9 100644
--- a/x-pack/plugins/reporting/server/export_types/csv_searchsource/generate_csv/generate_csv.test.ts
+++ b/x-pack/plugins/reporting/server/export_types/csv_searchsource/generate_csv/generate_csv.test.ts
@@ -345,12 +345,13 @@ it('uses the scrollId to page all the data', async () => {
// `scroll` and `clearScroll` must be called with scroll ID in the post body!
expect(mockEsClient.asCurrentUser.scroll).toHaveBeenCalledTimes(9);
expect(mockEsClient.asCurrentUser.scroll).toHaveBeenCalledWith({
- body: { scroll: '30s', scroll_id: 'awesome-scroll-hero' },
+ scroll: '30s',
+ scroll_id: 'awesome-scroll-hero',
});
expect(mockEsClient.asCurrentUser.clearScroll).toHaveBeenCalledTimes(1);
expect(mockEsClient.asCurrentUser.clearScroll).toHaveBeenCalledWith({
- body: { scroll_id: ['awesome-scroll-hero'] },
+ scroll_id: ['awesome-scroll-hero'],
});
});
diff --git a/x-pack/plugins/reporting/server/export_types/csv_searchsource/generate_csv/generate_csv.ts b/x-pack/plugins/reporting/server/export_types/csv_searchsource/generate_csv/generate_csv.ts
index 77ad4fba1ab60..76172da3e99cf 100644
--- a/x-pack/plugins/reporting/server/export_types/csv_searchsource/generate_csv/generate_csv.ts
+++ b/x-pack/plugins/reporting/server/export_types/csv_searchsource/generate_csv/generate_csv.ts
@@ -7,7 +7,7 @@
import { Writable } from 'stream';
import { i18n } from '@kbn/i18n';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IScopedClusterClient, IUiSettingsClient } from 'src/core/server';
import { IScopedSearchClient } from 'src/plugins/data/server';
import { Datatable } from 'src/plugins/expressions/server';
@@ -109,10 +109,8 @@ export class CsvGenerator {
this.logger.debug(`executing scroll request`);
const results = (
await this.clients.es.asCurrentUser.scroll({
- body: {
- scroll: scrollSettings.duration,
- scroll_id: scrollId,
- },
+ scroll: scrollSettings.duration,
+ scroll_id: scrollId,
})
).body;
return results;
@@ -403,7 +401,7 @@ export class CsvGenerator {
if (scrollId) {
this.logger.debug(`executing clearScroll request`);
try {
- await this.clients.es.asCurrentUser.clearScroll({ body: { scroll_id: [scrollId] } });
+ await this.clients.es.asCurrentUser.clearScroll({ scroll_id: [scrollId] });
} catch (err) {
this.logger.error(err);
}
diff --git a/x-pack/plugins/reporting/server/lib/content_stream.ts b/x-pack/plugins/reporting/server/lib/content_stream.ts
index 3c0fdaa91f32e..9719ac57b119c 100644
--- a/x-pack/plugins/reporting/server/lib/content_stream.ts
+++ b/x-pack/plugins/reporting/server/lib/content_stream.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Duplex } from 'stream';
import { defaults, get } from 'lodash';
import Puid from 'puid';
@@ -22,7 +22,7 @@ import { LevelLogger } from './level_logger';
const REQUEST_SPAN_SIZE_IN_BYTES = 1024;
type Callback = (error?: Error) => void;
-type SearchRequest = Required>[0];
+type SearchRequest = estypes.SearchRequest;
interface ContentStreamDocument {
id: string;
diff --git a/x-pack/plugins/reporting/server/lib/deprecations/check_ilm_migration_status.ts b/x-pack/plugins/reporting/server/lib/deprecations/check_ilm_migration_status.ts
index dc20f92f38c94..629a44ecbcc9e 100644
--- a/x-pack/plugins/reporting/server/lib/deprecations/check_ilm_migration_status.ts
+++ b/x-pack/plugins/reporting/server/lib/deprecations/check_ilm_migration_status.ts
@@ -7,7 +7,7 @@
import type {
IndicesIndexStatePrefixedSettings,
IndicesIndexSettings,
-} from '@elastic/elasticsearch/api/types';
+} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ILM_POLICY_NAME } from '../../../common/constants';
import { IlmPolicyMigrationStatus } from '../../../common/types';
import { IlmPolicyManager } from '../../lib/store/ilm_policy_manager';
diff --git a/x-pack/plugins/reporting/server/lib/deprecations/index.ts b/x-pack/plugins/reporting/server/lib/deprecations/index.ts
index 2d55c3b4c22d8..5d8a95695a129 100644
--- a/x-pack/plugins/reporting/server/lib/deprecations/index.ts
+++ b/x-pack/plugins/reporting/server/lib/deprecations/index.ts
@@ -58,7 +58,7 @@ function deprecationError(title: string, error: Error): DeprecationsDetails[] {
];
}
-function getErrorStatusCode(error: any): number {
+function getErrorStatusCode(error: any): number | undefined {
if (error instanceof errors.ResponseError) {
return error.statusCode;
}
diff --git a/x-pack/plugins/reporting/server/lib/store/ilm_policy_manager/constants.ts b/x-pack/plugins/reporting/server/lib/store/ilm_policy_manager/constants.ts
index bea2ba21c0846..cbbf21094d61f 100644
--- a/x-pack/plugins/reporting/server/lib/store/ilm_policy_manager/constants.ts
+++ b/x-pack/plugins/reporting/server/lib/store/ilm_policy_manager/constants.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { IlmPutLifecycleRequest } from '@elastic/elasticsearch/api/types';
+import type { IlmPutLifecycleRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
export const reportingIlmPolicy: IlmPutLifecycleRequest['body'] = {
policy: {
diff --git a/x-pack/plugins/reporting/server/lib/store/ilm_policy_manager/ilm_policy_manager.ts b/x-pack/plugins/reporting/server/lib/store/ilm_policy_manager/ilm_policy_manager.ts
index ca0a74cae8726..e0569883fbbe2 100644
--- a/x-pack/plugins/reporting/server/lib/store/ilm_policy_manager/ilm_policy_manager.ts
+++ b/x-pack/plugins/reporting/server/lib/store/ilm_policy_manager/ilm_policy_manager.ts
@@ -24,7 +24,7 @@ export class IlmPolicyManager {
public async doesIlmPolicyExist(): Promise {
try {
- await this.client.ilm.getLifecycle({ policy: ILM_POLICY_NAME });
+ await this.client.ilm.getLifecycle({ name: ILM_POLICY_NAME });
return true;
} catch (e) {
if (e.statusCode === 404) {
@@ -39,7 +39,7 @@ export class IlmPolicyManager {
*/
public async createIlmPolicy(): Promise {
await this.client.ilm.putLifecycle({
- policy: ILM_POLICY_NAME,
+ name: ILM_POLICY_NAME,
body: reportingIlmPolicy,
});
}
diff --git a/x-pack/plugins/reporting/server/lib/store/store.test.ts b/x-pack/plugins/reporting/server/lib/store/store.test.ts
index 8c6cb4dcdd7d6..a28197d261ba2 100644
--- a/x-pack/plugins/reporting/server/lib/store/store.test.ts
+++ b/x-pack/plugins/reporting/server/lib/store/store.test.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-
+import * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
import { ElasticsearchClient } from 'src/core/server';
import { elasticsearchServiceMock } from 'src/core/server/mocks';
@@ -262,7 +262,8 @@ describe('ReportingStore', () => {
await store.setReportClaimed(report, { testDoc: 'test' } as any);
const [[updateCall]] = mockEsClient.update.mock.calls;
- const response = updateCall.body?.doc as Report;
+
+ const response = (updateCall as estypes.UpdateRequest).body?.doc as Report;
expect(response.migration_version).toBe(`7.14.0`);
expect(response.status).toBe(`processing`);
expect(updateCall.if_seq_no).toBe(42);
@@ -293,7 +294,7 @@ describe('ReportingStore', () => {
await store.setReportFailed(report, { errors: 'yes' } as any);
const [[updateCall]] = mockEsClient.update.mock.calls;
- const response = updateCall.body?.doc as Report;
+ const response = (updateCall as estypes.UpdateRequest).body?.doc as Report;
expect(response.migration_version).toBe(`7.14.0`);
expect(response.status).toBe(`failed`);
expect(updateCall.if_seq_no).toBe(43);
@@ -324,7 +325,7 @@ describe('ReportingStore', () => {
await store.setReportCompleted(report, { certainly_completed: 'yes' } as any);
const [[updateCall]] = mockEsClient.update.mock.calls;
- const response = updateCall.body?.doc as Report;
+ const response = (updateCall as estypes.UpdateRequest).body?.doc as Report;
expect(response.migration_version).toBe(`7.14.0`);
expect(response.status).toBe(`completed`);
expect(updateCall.if_seq_no).toBe(44);
@@ -360,7 +361,7 @@ describe('ReportingStore', () => {
} as any);
const [[updateCall]] = mockEsClient.update.mock.calls;
- const response = updateCall.body?.doc as Report;
+ const response = (updateCall as estypes.UpdateRequest).body?.doc as Report;
expect(response.migration_version).toBe(`7.14.0`);
expect(response.status).toBe(`completed_with_warnings`);
@@ -401,7 +402,7 @@ describe('ReportingStore', () => {
await store.prepareReportForRetry(report);
const [[updateCall]] = mockEsClient.update.mock.calls;
- const response = updateCall.body?.doc as Report;
+ const response = (updateCall as estypes.UpdateRequest).body?.doc as Report;
expect(response.migration_version).toBe(`7.14.0`);
expect(response.status).toBe(`pending`);
@@ -417,7 +418,7 @@ describe('ReportingStore', () => {
const store = new ReportingStore(mockCore, mockLogger);
await store.start();
- expect(mockEsClient.ilm.getLifecycle).toHaveBeenCalledWith({ policy: 'kibana-reporting' });
+ expect(mockEsClient.ilm.getLifecycle).toHaveBeenCalledWith({ name: 'kibana-reporting' });
expect(mockEsClient.ilm.putLifecycle.mock.calls[0][0]).toMatchInlineSnapshot(`
Object {
"body": Object {
@@ -429,7 +430,7 @@ describe('ReportingStore', () => {
},
},
},
- "policy": "kibana-reporting",
+ "name": "kibana-reporting",
}
`);
});
@@ -440,7 +441,7 @@ describe('ReportingStore', () => {
const store = new ReportingStore(mockCore, mockLogger);
await store.start();
- expect(mockEsClient.ilm.getLifecycle).toHaveBeenCalledWith({ policy: 'kibana-reporting' });
+ expect(mockEsClient.ilm.getLifecycle).toHaveBeenCalledWith({ name: 'kibana-reporting' });
expect(mockEsClient.ilm.putLifecycle).not.toHaveBeenCalled();
});
});
diff --git a/x-pack/plugins/reporting/server/lib/store/store.ts b/x-pack/plugins/reporting/server/lib/store/store.ts
index 01a6f7a3cd06d..43f57da8c21f7 100644
--- a/x-pack/plugins/reporting/server/lib/store/store.ts
+++ b/x-pack/plugins/reporting/server/lib/store/store.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { IndexResponse, UpdateResponse } from '@elastic/elasticsearch/api/types';
+import { IndexResponse, UpdateResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient } from 'src/core/server';
import { LevelLogger, statuses } from '../';
import { ReportingCore } from '../../';
@@ -196,7 +196,7 @@ export class ReportingStore {
await ilmPolicyManager.createIlmPolicy();
} catch (e) {
this.logger.error('Error in start phase');
- this.logger.error(e.body.error);
+ this.logger.error(e.body?.error);
throw e;
}
}
diff --git a/x-pack/plugins/reporting/server/lib/tasks/execute_report.ts b/x-pack/plugins/reporting/server/lib/tasks/execute_report.ts
index 84566eb9c250c..5f885ad127b43 100644
--- a/x-pack/plugins/reporting/server/lib/tasks/execute_report.ts
+++ b/x-pack/plugins/reporting/server/lib/tasks/execute_report.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { UpdateResponse } from '@elastic/elasticsearch/api/types';
+import { UpdateResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import moment from 'moment';
import * as Rx from 'rxjs';
import { timeout } from 'rxjs/operators';
diff --git a/x-pack/plugins/reporting/server/routes/deprecations.ts b/x-pack/plugins/reporting/server/routes/deprecations.ts
index 4a519b7c199f8..521be51d6ccee 100644
--- a/x-pack/plugins/reporting/server/routes/deprecations.ts
+++ b/x-pack/plugins/reporting/server/routes/deprecations.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
import { errors } from '@elastic/elasticsearch';
-import { SecurityHasPrivilegesIndexPrivilegesCheck } from '@elastic/elasticsearch/api/types';
+import { SecurityHasPrivilegesIndexPrivilegesCheck } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { RequestHandler } from 'src/core/server';
import {
API_MIGRATE_ILM_POLICY_URL,
diff --git a/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts b/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts
index 54efe0636536a..ce8b5cf14ac9b 100644
--- a/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts
+++ b/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts
@@ -5,9 +5,14 @@
* 2.0.
*/
-import { ApiResponse } from '@elastic/elasticsearch';
-import { DeleteResponse, SearchHit, SearchResponse } from '@elastic/elasticsearch/api/types';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import type { TransportResult } from '@elastic/elasticsearch';
+import {
+ DeleteResponse,
+ SearchHit,
+ SearchResponse,
+ SearchRequest,
+} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
+import { errors } from '@elastic/elasticsearch';
import { i18n } from '@kbn/i18n';
import { UnwrapPromise } from '@kbn/utility-types';
import { ElasticsearchClient } from 'src/core/server';
@@ -19,8 +24,6 @@ import { statuses } from '../../lib/statuses';
import { Report } from '../../lib/store';
import { ReportingUser } from '../../types';
-type SearchRequest = Required>[0];
-
const defaultSize = 10;
const getUsername = (user: ReportingUser) => (user ? user.username : false);
@@ -50,7 +53,7 @@ interface JobsQueryFactory {
count(jobTypes: string[], user: ReportingUser): Promise;
get(user: ReportingUser, id: string): Promise;
getError(id: string): Promise;
- delete(deleteIndex: string, id: string): Promise>;
+ delete(deleteIndex: string, id: string): Promise>;
}
export function jobsQueryFactory(reportingCore: ReportingCore): JobsQueryFactory {
@@ -66,7 +69,7 @@ export function jobsQueryFactory(reportingCore: ReportingCore): JobsQueryFactory
return await callback(client);
} catch (error) {
- if (error instanceof ResponseError && [401, 403, 404].includes(error.statusCode)) {
+ if (error instanceof errors.ResponseError && [401, 403, 404].includes(error.statusCode!)) {
return;
}
@@ -97,7 +100,7 @@ export function jobsQueryFactory(reportingCore: ReportingCore): JobsQueryFactory
const response = (await execQuery((elasticsearchClient) =>
elasticsearchClient.search({ body, index: getIndex() })
- )) as ApiResponse>;
+ )) as TransportResult>;
return (
response?.body.hits?.hits.map((report: SearchHit) => {
diff --git a/x-pack/plugins/reporting/server/usage/get_reporting_usage.ts b/x-pack/plugins/reporting/server/usage/get_reporting_usage.ts
index b2c6aece924f2..73a4920b350e3 100644
--- a/x-pack/plugins/reporting/server/usage/get_reporting_usage.ts
+++ b/x-pack/plugins/reporting/server/usage/get_reporting_usage.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { ElasticsearchClient } from 'kibana/server';
import { get } from 'lodash';
import type { ReportingConfig } from '../';
diff --git a/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts b/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts
index f929917bd8f75..4833631f09adb 100644
--- a/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts
+++ b/x-pack/plugins/rule_registry/common/mapping_from_field_map.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { set } from '@elastic/safer-lodash-set';
import { FieldMap } from './field_map/types';
diff --git a/x-pack/plugins/rule_registry/common/types.ts b/x-pack/plugins/rule_registry/common/types.ts
index 7b2fde48057a6..8ffbebbc631a1 100644
--- a/x-pack/plugins/rule_registry/common/types.ts
+++ b/x-pack/plugins/rule_registry/common/types.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import * as t from 'io-ts';
diff --git a/x-pack/plugins/rule_registry/server/alert_data_client/alerts_client.ts b/x-pack/plugins/rule_registry/server/alert_data_client/alerts_client.ts
index 16447e6b0f539..6a22e47000d0e 100644
--- a/x-pack/plugins/rule_registry/server/alert_data_client/alerts_client.ts
+++ b/x-pack/plugins/rule_registry/server/alert_data_client/alerts_client.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
import Boom from '@hapi/boom';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { PublicMethodsOf } from '@kbn/utility-types';
import { Filter, buildEsQuery, EsQueryConfig } from '@kbn/es-query';
import { decodeVersion, encodeHitVersion } from '@kbn/securitysolution-es-utils';
@@ -23,7 +23,10 @@ import {
// @ts-expect-error
} from '@kbn/rule-data-utils/target_node/alerts_as_data_rbac';
-import { InlineScript, QueryDslQueryContainer } from '@elastic/elasticsearch/api/types';
+import {
+ InlineScript,
+ QueryDslQueryContainer,
+} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { AlertTypeParams, AlertingAuthorizationFilterType } from '../../../alerting/server';
import {
ReadOperations,
diff --git a/x-pack/plugins/rule_registry/server/rule_data_client/rule_data_client.ts b/x-pack/plugins/rule_registry/server/rule_data_client/rule_data_client.ts
index 2755021e235a8..ba92e9aac3d27 100644
--- a/x-pack/plugins/rule_registry/server/rule_data_client/rule_data_client.ts
+++ b/x-pack/plugins/rule_registry/server/rule_data_client/rule_data_client.ts
@@ -5,8 +5,8 @@
* 2.0.
*/
-import { BulkRequest } from '@elastic/elasticsearch/api/types';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { errors } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Either, isLeft } from 'fp-ts/lib/Either';
import { ElasticsearchClient } from 'kibana/server';
@@ -168,7 +168,7 @@ export class RuleDataClient implements IRuleDataClient {
const prepareForWritingResult = prepareForWriting();
return {
- bulk: async (request: BulkRequest) => {
+ bulk: async (request: estypes.BulkRequest) => {
return prepareForWritingResult
.then((clusterClient) => {
const requestWithDefaultParameters = {
@@ -179,7 +179,7 @@ export class RuleDataClient implements IRuleDataClient {
return clusterClient.bulk(requestWithDefaultParameters).then((response) => {
if (response.body.errors) {
- const error = new ResponseError(response);
+ const error = new errors.ResponseError(response);
throw error;
}
return response;
diff --git a/x-pack/plugins/rule_registry/server/rule_data_client/types.ts b/x-pack/plugins/rule_registry/server/rule_data_client/types.ts
index 7c05945a98b10..5ddbd0035526d 100644
--- a/x-pack/plugins/rule_registry/server/rule_data_client/types.ts
+++ b/x-pack/plugins/rule_registry/server/rule_data_client/types.ts
@@ -5,8 +5,8 @@
* 2.0.
*/
-import { ApiResponse } from '@elastic/elasticsearch';
-import { BulkRequest, BulkResponse } from '@elastic/elasticsearch/api/types';
+import type { TransportResult } from '@elastic/elasticsearch';
+import { BulkRequest, BulkResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ESSearchRequest, ESSearchResponse } from 'src/core/types/elasticsearch';
import { FieldDescriptor } from 'src/plugins/data/server';
@@ -35,5 +35,5 @@ export interface IRuleDataReader {
}
export interface IRuleDataWriter {
- bulk(request: BulkRequest): Promise | undefined>;
+ bulk(request: BulkRequest): Promise | undefined>;
}
diff --git a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index_options.ts b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index_options.ts
index e85331fb02a63..ba0961c7926a1 100644
--- a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index_options.ts
+++ b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/index_options.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ValidFeatureId } from '@kbn/rule-data-utils';
/**
diff --git a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/resource_installer.ts b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/resource_installer.ts
index 160261642ff25..041dfdeed42e0 100644
--- a/x-pack/plugins/rule_registry/server/rule_data_plugin_service/resource_installer.ts
+++ b/x-pack/plugins/rule_registry/server/rule_data_plugin_service/resource_installer.ts
@@ -6,7 +6,7 @@
*/
import { get, isEmpty } from 'lodash';
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { ElasticsearchClient, Logger } from 'kibana/server';
@@ -85,7 +85,7 @@ export class ResourceInstaller {
// We can install them in parallel
await Promise.all([
this.createOrUpdateLifecyclePolicy({
- policy: getResourceName(DEFAULT_ILM_POLICY_ID),
+ name: getResourceName(DEFAULT_ILM_POLICY_ID),
body: defaultLifecyclePolicy,
}),
@@ -116,7 +116,7 @@ export class ResourceInstaller {
if (ilmPolicy != null) {
await this.createOrUpdateLifecyclePolicy({
- policy: indexInfo.getIlmPolicyName(),
+ name: indexInfo.getIlmPolicyName(),
body: { policy: ilmPolicy },
});
}
@@ -385,7 +385,7 @@ export class ResourceInstaller {
const { logger, getClusterClient } = this.options;
const clusterClient = await getClusterClient();
- logger.debug(`Installing lifecycle policy ${policy.policy}`);
+ logger.debug(`Installing lifecycle policy ${policy.name}`);
return clusterClient.ilm.putLifecycle(policy);
}
diff --git a/x-pack/plugins/rule_registry/server/utils/persistence_types.ts b/x-pack/plugins/rule_registry/server/utils/persistence_types.ts
index 5da05d9956d7f..326a8bef49abd 100644
--- a/x-pack/plugins/rule_registry/server/utils/persistence_types.ts
+++ b/x-pack/plugins/rule_registry/server/utils/persistence_types.ts
@@ -5,8 +5,8 @@
* 2.0.
*/
-import { ApiResponse } from '@elastic/elasticsearch';
-import { BulkResponse } from '@elastic/elasticsearch/api/types';
+import type { TransportResult } from '@elastic/elasticsearch';
+import { BulkResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Logger } from '@kbn/logging';
import {
AlertExecutorOptions,
@@ -25,7 +25,7 @@ export type PersistenceAlertService = (
fields: Record;
}>,
refresh: boolean | 'wait_for'
-) => Promise | undefined>;
+) => Promise | undefined>;
export interface PersistenceServices {
alertWithPersistence: PersistenceAlertService;
diff --git a/x-pack/plugins/security/server/authentication/api_keys/api_keys.ts b/x-pack/plugins/security/server/authentication/api_keys/api_keys.ts
index 1707ca710aaf8..65a7972084cb8 100644
--- a/x-pack/plugins/security/server/authentication/api_keys/api_keys.ts
+++ b/x-pack/plugins/security/server/authentication/api_keys/api_keys.ts
@@ -113,11 +113,11 @@ export interface InvalidateAPIKeyResult {
* Details about these errors. This field is not present in the response when error_count is 0.
*/
error_details?: Array<{
- type: string;
- reason: string;
+ type?: string;
+ reason?: string;
caused_by?: {
- type: string;
- reason: string;
+ type?: string;
+ reason?: string;
};
}>;
}
diff --git a/x-pack/plugins/security/server/authorization/check_privileges.ts b/x-pack/plugins/security/server/authorization/check_privileges.ts
index 36c364f1ff7da..81cf3ebc29f43 100644
--- a/x-pack/plugins/security/server/authorization/check_privileges.ts
+++ b/x-pack/plugins/security/server/authorization/check_privileges.ts
@@ -5,6 +5,7 @@
* 2.0.
*/
+import type * as estypes from '@elastic/elasticsearch/lib/api/types';
import { pick, transform, uniq } from 'lodash';
import type { IClusterClient, KibanaRequest } from 'src/core/server';
@@ -60,11 +61,11 @@ export function checkPrivilegesWithRequestFactory(
const clusterClient = await getClusterClient();
const { body } = await clusterClient.asScoped(request).asCurrentUser.security.hasPrivileges({
body: {
- cluster: privileges.elasticsearch?.cluster,
+ cluster: privileges.elasticsearch?.cluster as estypes.SecurityClusterPrivilege[],
index: Object.entries(privileges.elasticsearch?.index ?? {}).map(
([name, indexPrivileges]) => ({
names: [name],
- privileges: indexPrivileges,
+ privileges: indexPrivileges as estypes.SecurityIndexPrivilege[],
})
),
application: [
diff --git a/x-pack/plugins/security/server/deprecations/kibana_user_role.test.ts b/x-pack/plugins/security/server/deprecations/kibana_user_role.test.ts
index da728b12fca91..d971769160df5 100644
--- a/x-pack/plugins/security/server/deprecations/kibana_user_role.test.ts
+++ b/x-pack/plugins/security/server/deprecations/kibana_user_role.test.ts
@@ -6,7 +6,7 @@
*/
import { errors } from '@elastic/elasticsearch';
-import type { SecurityRoleMapping, SecurityUser } from '@elastic/elasticsearch/api/types';
+import type { SecurityRoleMapping, SecurityUser } from '@elastic/elasticsearch/lib/api/types';
import type { PackageInfo, RegisterDeprecationsConfig } from 'src/core/server';
import {
diff --git a/x-pack/plugins/security/server/deprecations/kibana_user_role.ts b/x-pack/plugins/security/server/deprecations/kibana_user_role.ts
index d659ea273f05f..ba32446611a62 100644
--- a/x-pack/plugins/security/server/deprecations/kibana_user_role.ts
+++ b/x-pack/plugins/security/server/deprecations/kibana_user_role.ts
@@ -8,7 +8,7 @@
import type {
SecurityGetRoleMappingResponse,
SecurityGetUserResponse,
-} from '@elastic/elasticsearch/api/types';
+} from '@elastic/elasticsearch/lib/api/types';
import { i18n } from '@kbn/i18n';
import type {
diff --git a/x-pack/plugins/security/server/errors.ts b/x-pack/plugins/security/server/errors.ts
index 25d2aa44f3dc8..2f2573b171ae2 100644
--- a/x-pack/plugins/security/server/errors.ts
+++ b/x-pack/plugins/security/server/errors.ts
@@ -33,7 +33,7 @@ export function wrapIntoCustomErrorResponse(error: any) {
*/
export function getErrorStatusCode(error: any): number {
if (error instanceof errors.ResponseError) {
- return error.statusCode;
+ return error.statusCode!;
}
return Boom.isBoom(error) ? error.output.statusCode : error.statusCode || error.status;
diff --git a/x-pack/plugins/security/server/mocks.ts b/x-pack/plugins/security/server/mocks.ts
index 7cae0d29bf943..491d6cdafa44d 100644
--- a/x-pack/plugins/security/server/mocks.ts
+++ b/x-pack/plugins/security/server/mocks.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { ApiResponse } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
import { licenseMock } from '../common/licensing/index.mock';
import type { MockAuthenticatedUserProps } from '../common/model/authenticated_user.mock';
@@ -53,11 +53,13 @@ function createStartMock() {
}
function createApiResponseMock(
- apiResponse: Pick, 'body'> &
- Partial, 'body'>>
-): ApiResponse {
+ apiResponse: Pick, 'body'> &
+ Partial, 'body'>>
+): TransportResult {
return {
+ // @ts-expect-error null is not supported
statusCode: null,
+ // @ts-expect-error null is not supported
headers: null,
warnings: null,
meta: {} as any,
diff --git a/x-pack/plugins/security/server/routes/deprecations/kibana_user_role.test.ts b/x-pack/plugins/security/server/routes/deprecations/kibana_user_role.test.ts
index b2ae2543bd652..3c9a775d7a054 100644
--- a/x-pack/plugins/security/server/routes/deprecations/kibana_user_role.test.ts
+++ b/x-pack/plugins/security/server/routes/deprecations/kibana_user_role.test.ts
@@ -6,7 +6,7 @@
*/
import { errors } from '@elastic/elasticsearch';
-import type { SecurityRoleMapping, SecurityUser } from '@elastic/elasticsearch/api/types';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { DeeplyMockedKeys } from '@kbn/utility-types/jest';
import type { RequestHandler, RouteConfig } from 'src/core/server';
@@ -18,11 +18,11 @@ import type { SecurityRequestHandlerContext, SecurityRouter } from '../../types'
import { routeDefinitionParamsMock } from '../index.mock';
import { defineKibanaUserRoleDeprecationRoutes } from './kibana_user_role';
-function createMockUser(user: Partial = {}) {
+function createMockUser(user: Partial = {}) {
return { enabled: true, username: 'userA', roles: ['roleA'], metadata: {}, ...user };
}
-function createMockRoleMapping(mapping: Partial = {}) {
+function createMockRoleMapping(mapping: Partial = {}) {
return { enabled: true, roles: ['roleA'], rules: {}, metadata: {}, ...mapping };
}
diff --git a/x-pack/plugins/security/server/routes/deprecations/kibana_user_role.ts b/x-pack/plugins/security/server/routes/deprecations/kibana_user_role.ts
index 21bb9db7329b6..5d5e2a12f86a6 100644
--- a/x-pack/plugins/security/server/routes/deprecations/kibana_user_role.ts
+++ b/x-pack/plugins/security/server/routes/deprecations/kibana_user_role.ts
@@ -5,10 +5,7 @@
* 2.0.
*/
-import type {
- SecurityGetRoleMappingResponse,
- SecurityGetUserResponse,
-} from '@elastic/elasticsearch/api/types';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type { RouteDefinitionParams } from '..';
import { KIBANA_ADMIN_ROLE_NAME, KIBANA_USER_ROLE_NAME } from '../../deprecations';
@@ -29,7 +26,7 @@ export function defineKibanaUserRoleDeprecationRoutes({ router, logger }: RouteD
validate: false,
},
createLicensedRouteHandler(async (context, request, response) => {
- let users: SecurityGetUserResponse;
+ let users: estypes.SecurityGetUserResponse;
try {
users = (await context.core.elasticsearch.client.asCurrentUser.security.getUser()).body;
} catch (err) {
@@ -92,7 +89,7 @@ export function defineKibanaUserRoleDeprecationRoutes({ router, logger }: RouteD
validate: false,
},
createLicensedRouteHandler(async (context, request, response) => {
- let roleMappings: SecurityGetRoleMappingResponse;
+ let roleMappings: estypes.SecurityGetRoleMappingResponse;
try {
roleMappings = (
await context.core.elasticsearch.client.asCurrentUser.security.getRoleMapping()
diff --git a/x-pack/plugins/security/server/routes/indices/get_fields.ts b/x-pack/plugins/security/server/routes/indices/get_fields.ts
index ebfb2b9b3fb95..d6c7778d9ccbf 100644
--- a/x-pack/plugins/security/server/routes/indices/get_fields.ts
+++ b/x-pack/plugins/security/server/routes/indices/get_fields.ts
@@ -39,11 +39,7 @@ export function defineGetFieldsRoutes({ router }: RouteDefinitionParams) {
const mappingValues = Object.values(
// `FieldMapping` type from `TypeFieldMappings` --> `GetFieldMappingResponse` is not correct and
// doesn't have any properties.
- (
- indexMapping.mappings[fieldName] as {
- mapping: Record;
- }
- ).mapping
+ indexMapping.mappings[fieldName]?.mapping as Record
);
const hasMapping = mappingValues.length > 0;
diff --git a/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts b/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts
index 61f71e2ee253b..8f69df325fe42 100644
--- a/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts
+++ b/x-pack/plugins/security_solution/common/endpoint/data_generators/fleet_agent_generator.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { DeepPartial } from 'utility-types';
import { merge } from 'lodash';
import { BaseDataGenerator } from './base_data_generator';
diff --git a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_actions.ts b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_actions.ts
index e4379271315dd..3c8d23e375159 100644
--- a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_actions.ts
+++ b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_actions.ts
@@ -6,7 +6,7 @@
*/
import { Client } from '@elastic/elasticsearch';
-import { DeleteByQueryResponse } from '@elastic/elasticsearch/api/types';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { HostMetadata, LogsEndpointAction, LogsEndpointActionResponse } from '../types';
import { EndpointActionGenerator } from '../data_generators/endpoint_action_generator';
import { wrapErrorAndRejectPromise } from './utils';
@@ -144,8 +144,8 @@ export const indexEndpointActionsForHost = async (
};
export interface DeleteIndexedEndpointActionsResponse {
- endpointActionRequests: DeleteByQueryResponse | undefined;
- endpointActionResponses: DeleteByQueryResponse | undefined;
+ endpointActionRequests: estypes.DeleteByQueryResponse | undefined;
+ endpointActionResponses: estypes.DeleteByQueryResponse | undefined;
}
export const deleteIndexedEndpointActions = async (
@@ -158,55 +158,51 @@ export const deleteIndexedEndpointActions = async (
};
if (indexedData.endpointActions.length) {
- response.endpointActionRequests = (
- await esClient
- .deleteByQuery({
- index: `${indexedData.endpointActionsIndex}-*`,
- wait_for_completion: true,
- body: {
- query: {
- bool: {
- filter: [
- {
- terms: {
- action_id: indexedData.endpointActions.map(
- (action) => action.EndpointActions.action_id
- ),
- },
+ response.endpointActionRequests = await esClient
+ .deleteByQuery({
+ index: `${indexedData.endpointActionsIndex}-*`,
+ wait_for_completion: true,
+ body: {
+ query: {
+ bool: {
+ filter: [
+ {
+ terms: {
+ action_id: indexedData.endpointActions.map(
+ (action) => action.EndpointActions.action_id
+ ),
},
- ],
- },
+ },
+ ],
},
},
- })
- .catch(wrapErrorAndRejectPromise)
- ).body;
+ },
+ })
+ .catch(wrapErrorAndRejectPromise);
}
if (indexedData.endpointActionResponses) {
- response.endpointActionResponses = (
- await esClient
- .deleteByQuery({
- index: `${indexedData.endpointActionResponsesIndex}-*`,
- wait_for_completion: true,
- body: {
- query: {
- bool: {
- filter: [
- {
- terms: {
- action_id: indexedData.endpointActionResponses.map(
- (action) => action.EndpointActions.action_id
- ),
- },
+ response.endpointActionResponses = await esClient
+ .deleteByQuery({
+ index: `${indexedData.endpointActionResponsesIndex}-*`,
+ wait_for_completion: true,
+ body: {
+ query: {
+ bool: {
+ filter: [
+ {
+ terms: {
+ action_id: indexedData.endpointActionResponses.map(
+ (action) => action.EndpointActions.action_id
+ ),
},
- ],
- },
+ },
+ ],
},
},
- })
- .catch(wrapErrorAndRejectPromise)
- ).body;
+ },
+ })
+ .catch(wrapErrorAndRejectPromise);
}
return response;
diff --git a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_hosts.ts b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_hosts.ts
index fdb8416de2ed8..de564019db6d0 100644
--- a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_hosts.ts
+++ b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_endpoint_hosts.ts
@@ -10,7 +10,7 @@ import { cloneDeep, merge } from 'lodash';
import { AxiosResponse } from 'axios';
// eslint-disable-next-line import/no-extraneous-dependencies
import { KbnClient } from '@kbn/test';
-import { DeleteByQueryResponse } from '@elastic/elasticsearch/api/types';
+import { DeleteByQueryResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Agent, CreatePackagePolicyResponse, GetPackagesResponse } from '../../../../fleet/common';
import { EndpointDocGenerator } from '../generate_data';
import { HostMetadata, HostPolicyResponse } from '../types';
@@ -290,15 +290,13 @@ export const deleteIndexedEndpointHosts = async (
},
};
- response.hosts = (
- await esClient
- .deleteByQuery({
- index: indexedData.metadataIndex,
- wait_for_completion: true,
- body,
- })
- .catch(wrapErrorAndRejectPromise)
- ).body;
+ response.hosts = await esClient
+ .deleteByQuery({
+ index: indexedData.metadataIndex,
+ wait_for_completion: true,
+ body,
+ })
+ .catch(wrapErrorAndRejectPromise);
// Delete from the transform destination index
await esClient
@@ -311,29 +309,27 @@ export const deleteIndexedEndpointHosts = async (
}
if (indexedData.policyResponses.length) {
- response.policyResponses = (
- await esClient
- .deleteByQuery({
- index: indexedData.policyResponseIndex,
- wait_for_completion: true,
- body: {
- query: {
- bool: {
- filter: [
- {
- terms: {
- 'agent.id': indexedData.policyResponses.map(
- (policyResponse) => policyResponse.agent.id
- ),
- },
+ response.policyResponses = await esClient
+ .deleteByQuery({
+ index: indexedData.policyResponseIndex,
+ wait_for_completion: true,
+ body: {
+ query: {
+ bool: {
+ filter: [
+ {
+ terms: {
+ 'agent.id': indexedData.policyResponses.map(
+ (policyResponse) => policyResponse.agent.id
+ ),
},
- ],
- },
+ },
+ ],
},
},
- })
- .catch(wrapErrorAndRejectPromise)
- ).body;
+ },
+ })
+ .catch(wrapErrorAndRejectPromise);
}
merge(response, await deleteIndexedFleetAgents(esClient, indexedData));
diff --git a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_actions.ts b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_actions.ts
index 5cc564ee3d41d..34f57c0604fac 100644
--- a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_actions.ts
+++ b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_actions.ts
@@ -6,7 +6,7 @@
*/
import { Client } from '@elastic/elasticsearch';
-import { DeleteByQueryResponse } from '@elastic/elasticsearch/api/types';
+import { DeleteByQueryResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { EndpointAction, EndpointActionResponse, HostMetadata } from '../types';
import { AGENT_ACTIONS_INDEX, AGENT_ACTIONS_RESULTS_INDEX } from '../../../../fleet/common';
import { FleetActionGenerator } from '../data_generators/fleet_action_generator';
@@ -175,47 +175,43 @@ export const deleteIndexedFleetActions = async (
};
if (indexedData.actions.length) {
- response.actions = (
- await esClient
- .deleteByQuery({
- index: `${indexedData.actionsIndex}-*`,
- wait_for_completion: true,
- body: {
- query: {
- bool: {
- filter: [
- { terms: { action_id: indexedData.actions.map((action) => action.action_id) } },
- ],
- },
+ response.actions = await esClient
+ .deleteByQuery({
+ index: `${indexedData.actionsIndex}-*`,
+ wait_for_completion: true,
+ body: {
+ query: {
+ bool: {
+ filter: [
+ { terms: { action_id: indexedData.actions.map((action) => action.action_id) } },
+ ],
},
},
- })
- .catch(wrapErrorAndRejectPromise)
- ).body;
+ },
+ })
+ .catch(wrapErrorAndRejectPromise);
}
if (indexedData.actionResponses) {
- response.responses = (
- await esClient
- .deleteByQuery({
- index: `${indexedData.responsesIndex}-*`,
- wait_for_completion: true,
- body: {
- query: {
- bool: {
- filter: [
- {
- terms: {
- action_id: indexedData.actionResponses.map((action) => action.action_id),
- },
+ response.responses = await esClient
+ .deleteByQuery({
+ index: `${indexedData.responsesIndex}-*`,
+ wait_for_completion: true,
+ body: {
+ query: {
+ bool: {
+ filter: [
+ {
+ terms: {
+ action_id: indexedData.actionResponses.map((action) => action.action_id),
},
- ],
- },
+ },
+ ],
},
},
- })
- .catch(wrapErrorAndRejectPromise)
- ).body;
+ },
+ })
+ .catch(wrapErrorAndRejectPromise);
}
return response;
diff --git a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_agent.ts b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_agent.ts
index 67a261d088f86..263b6bc175688 100644
--- a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_agent.ts
+++ b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_agent.ts
@@ -7,7 +7,7 @@
import { Client } from '@elastic/elasticsearch';
import { AxiosResponse } from 'axios';
-import { DeleteByQueryResponse } from '@elastic/elasticsearch/api/types';
+import { DeleteByQueryResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
// eslint-disable-next-line import/no-extraneous-dependencies
import { KbnClient } from '@kbn/test';
import { HostMetadata } from '../types';
@@ -81,7 +81,7 @@ export const indexFleetAgentForHost = async (
return {
fleetAgentsIndex: agentDoc._index,
agents: [
- await fetchFleetAgent(kbnClient, createdFleetAgent.body._id).catch(wrapErrorAndRejectPromise),
+ await fetchFleetAgent(kbnClient, createdFleetAgent._id).catch(wrapErrorAndRejectPromise),
],
};
};
@@ -110,29 +110,27 @@ export const deleteIndexedFleetAgents = async (
};
if (indexedData.agents.length) {
- response.agents = (
- await esClient
- .deleteByQuery({
- index: `${indexedData.fleetAgentsIndex}-*`,
- wait_for_completion: true,
- body: {
- query: {
- bool: {
- filter: [
- {
- terms: {
- 'local_metadata.elastic.agent.id': indexedData.agents.map(
- (agent) => agent.local_metadata.elastic.agent.id
- ),
- },
+ response.agents = await esClient
+ .deleteByQuery({
+ index: `${indexedData.fleetAgentsIndex}-*`,
+ wait_for_completion: true,
+ body: {
+ query: {
+ bool: {
+ filter: [
+ {
+ terms: {
+ 'local_metadata.elastic.agent.id': indexedData.agents.map(
+ (agent) => agent.local_metadata.elastic.agent.id
+ ),
},
- ],
- },
+ },
+ ],
},
},
- })
- .catch(wrapErrorAndRejectPromise)
- ).body;
+ },
+ })
+ .catch(wrapErrorAndRejectPromise);
}
return response;
diff --git a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_server.ts b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_server.ts
index 7ef827b8ea1f1..ed3e1812b8a63 100644
--- a/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_server.ts
+++ b/x-pack/plugins/security_solution/common/endpoint/data_loaders/index_fleet_server.ts
@@ -17,13 +17,13 @@ import { wrapErrorAndRejectPromise } from './utils';
* @param version
*/
export const enableFleetServerIfNecessary = async (esClient: Client, version: string = '8.0.0') => {
- const res = await esClient.search<{}, {}>({
+ const res = await esClient.search({
index: FLEET_SERVER_SERVERS_INDEX,
ignore_unavailable: true,
rest_total_hits_as_int: true,
});
- if (res.body.hits.total > 0) {
+ if (res.hits.total > 0) {
return;
}
diff --git a/x-pack/plugins/security_solution/common/search_strategy/eql/validation/helpers.mock.ts b/x-pack/plugins/security_solution/common/search_strategy/eql/validation/helpers.mock.ts
index b3a2c9c9a3f62..0c620fbdd348d 100644
--- a/x-pack/plugins/security_solution/common/search_strategy/eql/validation/helpers.mock.ts
+++ b/x-pack/plugins/security_solution/common/search_strategy/eql/validation/helpers.mock.ts
@@ -5,10 +5,10 @@
* 2.0.
*/
-import { ApiResponse } from '@elastic/elasticsearch';
+import type { TransportResult } from '@elastic/elasticsearch';
import { ErrorResponse } from './helpers';
-export const getValidEqlResponse = (): ApiResponse['body'] => ({
+export const getValidEqlResponse = (): TransportResult['body'] => ({
is_partial: false,
is_running: false,
took: 162,
@@ -56,7 +56,7 @@ export const getEqlResponseWithValidationErrors = (): ErrorResponse => ({
},
});
-export const getEqlResponseWithNonValidationError = (): ApiResponse['body'] => ({
+export const getEqlResponseWithNonValidationError = (): TransportResult['body'] => ({
error: {
root_cause: [
{
diff --git a/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts b/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts
index e8578b4c07063..315f6eeb69f34 100644
--- a/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts
+++ b/x-pack/plugins/security_solution/common/search_strategy/security_solution/hosts/details/index.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IEsSearchResponse } from '../../../../../../../../src/plugins/data/common';
import { Inspect, Maybe, TimerangeInput } from '../../../common';
diff --git a/x-pack/plugins/security_solution/common/search_strategy/security_solution/index.ts b/x-pack/plugins/security_solution/common/search_strategy/security_solution/index.ts
index 9a176662fe86b..91a2956e25286 100644
--- a/x-pack/plugins/security_solution/common/search_strategy/security_solution/index.ts
+++ b/x-pack/plugins/security_solution/common/search_strategy/security_solution/index.ts
@@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IEsSearchRequest } from '../../../../../../src/plugins/data/common';
import { ESQuery } from '../../typed_json';
import {
diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx
index 662a3ee770547..82c3fb4c40248 100644
--- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx
+++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx
@@ -6,7 +6,7 @@
*/
import { act, renderHook, RenderHookResult } from '@testing-library/react-hooks';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { coreMock } from '../../../../../../../src/core/public/mocks';
import { KibanaServices } from '../../../common/lib/kibana';
diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx
index 18fce44646909..7cb8b643aa0e8 100644
--- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx
+++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx
@@ -6,7 +6,7 @@
*/
import { useEffect, useRef, useState, useCallback } from 'react';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import type {
ExceptionListItemSchema,
CreateExceptionListItemSchema,
diff --git a/x-pack/plugins/security_solution/public/common/hooks/eql/eql_search_response.mock.ts b/x-pack/plugins/security_solution/public/common/hooks/eql/eql_search_response.mock.ts
index 513bfc654027d..107a691b6dbeb 100644
--- a/x-pack/plugins/security_solution/public/common/hooks/eql/eql_search_response.mock.ts
+++ b/x-pack/plugins/security_solution/public/common/hooks/eql/eql_search_response.mock.ts
@@ -8,7 +8,7 @@
import { EqlSearchStrategyResponse } from '../../../../../../../src/plugins/data/common';
import { Source } from './types';
import { EqlSearchResponse } from '../../../../common/detection_engine/types';
-import { Connection } from '@elastic/elasticsearch';
+import type { Connection } from '@elastic/elasticsearch';
export const getMockEqlResponse = (): EqlSearchStrategyResponse> => ({
id: 'some-id',
diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/alerts/api.ts b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/alerts/api.ts
index 324372edf8623..44f3e22c82ae8 100644
--- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/alerts/api.ts
+++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/alerts/api.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { getCasesFromAlertsUrl } from '../../../../../../cases/common';
import { HostIsolationResponse, HostInfo } from '../../../../../common/endpoint/types';
import {
diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/alerts/use_fetch_ecs_alerts_data.ts b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/alerts/use_fetch_ecs_alerts_data.ts
index 749addcc94930..64b5d6ea9431a 100644
--- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/alerts/use_fetch_ecs_alerts_data.ts
+++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/alerts/use_fetch_ecs_alerts_data.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
import { useEffect, useState } from 'react';
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { isEmpty } from 'lodash';
import {
diff --git a/x-pack/plugins/security_solution/public/hosts/components/authentications_table/mock.ts b/x-pack/plugins/security_solution/public/hosts/components/authentications_table/mock.ts
index f2b004f856cc4..caf441b34ca90 100644
--- a/x-pack/plugins/security_solution/public/hosts/components/authentications_table/mock.ts
+++ b/x-pack/plugins/security_solution/public/hosts/components/authentications_table/mock.ts
@@ -5,7 +5,7 @@
* 2.0.
*/
-import type { estypes } from '@elastic/elasticsearch';
+import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { HostAuthenticationsStrategyResponse } from '../../../../common/search_strategy/security_solution/hosts/authentications';
export const mockData: { Authentications: HostAuthenticationsStrategyResponse } = {
diff --git a/x-pack/plugins/security_solution/public/timelines/containers/index.tsx b/x-pack/plugins/security_solution/public/timelines/containers/index.tsx
index 368a5a02d7167..4ccb90b0ee5ae 100644
--- a/x-pack/plugins/security_solution/public/timelines/containers/index.tsx
+++ b/x-pack/plugins/security_solution/public/timelines/containers/index.tsx
@@ -245,6 +245,7 @@ export const useTimelineEvents = ({
activeTimeline.setEqlRequest(request as TimelineEqlRequestOptions);
activeTimeline.setEqlResponse(newTimelineResponse);
} else {
+ // @ts-expect-error EqlSearchRequest.query is not compatible with QueryDslQueryContainer
activeTimeline.setRequest(request);
activeTimeline.setResponse(newTimelineResponse);
}
diff --git a/x-pack/plugins/security_solution/scripts/endpoint/resolver_generator_script.ts b/x-pack/plugins/security_solution/scripts/endpoint/resolver_generator_script.ts
index 3c267117964ce..da0810bead47e 100644
--- a/x-pack/plugins/security_solution/scripts/endpoint/resolver_generator_script.ts
+++ b/x-pack/plugins/security_solution/scripts/endpoint/resolver_generator_script.ts
@@ -8,8 +8,8 @@
/* eslint-disable no-console */
import yargs from 'yargs';
import fs from 'fs';
-import { Client, ClientOptions } from '@elastic/elasticsearch';
-import { ResponseError } from '@elastic/elasticsearch/lib/errors';
+import { Client, errors } from '@elastic/elasticsearch';
+import type { ClientOptions } from '@elastic/elasticsearch/lib/client';
import { ToolingLog, CA_CERT_PATH } from '@kbn/dev-utils';
import { KbnClient } from '@kbn/test';
import { indexHostsAndAlerts } from '../../common/endpoint/index_data';
@@ -19,7 +19,7 @@ main();
async function deleteIndices(indices: string[], client: Client) {
const handleErr = (err: unknown) => {
- if (err instanceof ResponseError && err.statusCode !== 404) {
+ if (err instanceof errors.ResponseError && err.statusCode !== 404) {
console.log(JSON.stringify(err, null, 2));
// eslint-disable-next-line no-process-exit
process.exit(1);
@@ -196,7 +196,7 @@ async function main() {
url,
certificateAuthorities: [ca],
});
- clientOptions = { node, ssl: { ca: [ca] } };
+ clientOptions = { node, tls: { ca: [ca] } };
} else {
kbnClient = new KbnClient({
log: new ToolingLog({
diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts
index d6599f2686670..277ccf030f808 100644
--- a/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts
+++ b/x-pack/plugins/security_solution/server/endpoint/lib/artifacts/migrate_artifacts_to_fleet.test.ts
@@ -21,7 +21,7 @@ import { createEndpointArtifactClientMock } from '../../services/artifacts/mocks
import { InternalArtifactCompleteSchema } from '../../schemas';
import { generateArtifactEsGetSingleHitMock } from '../../../../../fleet/server/services/artifacts/mocks';
import { NewArtifact } from '../../../../../fleet/server/services';
-import { CreateRequest } from '@elastic/elasticsearch/api/types';
+import { CreateRequest } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
describe('When migrating artifacts to fleet', () => {
let soClient: jest.Mocked;
diff --git a/x-pack/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.test.ts b/x-pack/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.test.ts
index 0510743fdf05b..91bb5c775b74e 100644
--- a/x-pack/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.test.ts
+++ b/x-pack/plugins/security_solution/server/endpoint/lib/metadata/check_metadata_transforms_task.test.ts
@@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
-import { ApiResponse } from '@elastic/elasticsearch';
-import { TransformGetTransformStatsResponse } from '@elastic/elasticsearch/api/types';
+import type { TransportResult } from '@elastic/elasticsearch';
+import { TransformGetTransformStatsResponse } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import {
CheckMetadataTransformsTask,
TYPE,
@@ -102,7 +102,7 @@ describe('check metadata transforms task', () => {
},
],
},
- } as unknown as ApiResponse