Skip to content

Commit

Permalink
Cleanup outdated @elastic/elasticsearch client type errors (#101741)
Browse files Browse the repository at this point in the history
* fix errors and update comments in Core

* fix errors or update comments in Security plugin

* update spaces test

* update task_manager files

* update comments in monitoring plugin

* fix errors in update comments in security_solutions

* fix errors and update comments in data_enhanced

* update fleet code

* update infra code

* update comment in trigger_actions_ui

* update comment in lens

* update comments in ES-UI code

* update typings for search

* update monitoring

* remove outdated export
# Conflicts:
#	x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/evaluate_condition.ts
#	x-pack/plugins/snapshot_restore/server/routes/api/snapshots.ts
  • Loading branch information
mshustov committed Jun 21, 2021
1 parent e6f8083 commit ab1d8f2
Show file tree
Hide file tree
Showing 45 changed files with 100 additions and 103 deletions.
14 changes: 6 additions & 8 deletions src/core/server/core_usage_data/core_usage_data_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,14 +126,12 @@ export class CoreUsageDataService implements CoreService<CoreUsageDataSetup, Cor
const stats = body[0];
return {
alias: kibanaOrTaskManagerIndex(index, this.kibanaConfig!.index),
// @ts-expect-error @elastic/elasticsearch declares it 'docs.count' as optional
docsCount: parseInt(stats['docs.count'], 10),
// @ts-expect-error @elastic/elasticsearch declares it 'docs.deleted' as optional
docsDeleted: parseInt(stats['docs.deleted'], 10),
// @ts-expect-error @elastic/elasticsearch declares it 'store.size' as string | number
storeSizeBytes: parseInt(stats['store.size'], 10),
// @ts-expect-error @elastic/elasticsearch declares it 'pri.store.size' as string | number
primaryStoreSizeBytes: parseInt(stats['pri.store.size'], 10),
docsCount: stats['docs.count'] ? parseInt(stats['docs.count'], 10) : 0,
docsDeleted: stats['docs.deleted'] ? parseInt(stats['docs.deleted'], 10) : 0,
storeSizeBytes: stats['store.size'] ? parseInt(stats['store.size'], 10) : 0,
primaryStoreSizeBytes: stats['pri.store.size']
? parseInt(stats['pri.store.size'], 10)
: 0,
};
});
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,8 @@ async function migrateSourceToDest(context: Context) {
await Index.write(
client,
dest.indexName,
await migrateRawDocs(
serializer,
documentMigrator.migrateAndConvert,
// @ts-expect-error @elastic/elasticsearch `Hit._id` may be a string | number in ES, but we always expect strings in the SO index.
docs
)
// @ts-expect-error @elastic/elasticsearch _source is optional
await migrateRawDocs(serializer, documentMigrator.migrateAndConvert, docs)
);
}
}
4 changes: 2 additions & 2 deletions src/core/server/saved_objects/service/lib/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -897,10 +897,10 @@ export class SavedObjectsRepository {
total: body.hits.total,
saved_objects: body.hits.hits.map(
(hit: estypes.SearchHit<SavedObjectsRawDocSource>): SavedObjectsFindResult => ({
// @ts-expect-error @elastic/elasticsearch declared Id as string | number
// @ts-expect-error @elastic/elasticsearch _source is optional
...this._rawToSavedObject(hit),
score: hit._score!,
// @ts-expect-error @elastic/elasticsearch declared sort as string | number
// @ts-expect-error @elastic/elasticsearch _source is optional
sort: hit.sort,
})
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@ export async function getSavedObjectsCounts(
},
};
const { body } = await esClient.search(savedObjectCountSearchParams);
// @ts-expect-error @elastic/elasticsearch Aggregate does not include `buckets`
// @ts-expect-error declare type for aggregations explicitly
return body.aggregations?.types?.buckets || [];
}
18 changes: 7 additions & 11 deletions src/plugins/security_oss/server/check_cluster_data.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,19 @@ describe('checkClusterForUserData', () => {
it('returns false if data only exists in system indices', async () => {
const esClient = elasticsearchServiceMock.createElasticsearchClient();
esClient.cat.indices.mockResolvedValue(
// @ts-expect-error @elastic/elasticsearch ES types don't support array response format
elasticsearchServiceMock.createApiResponse({
body: [
{
index: '.kibana',
'docs.count': 500,
'docs.count': '500',
},
{
index: 'kibana_sample_ecommerce_data',
'docs.count': 20,
'docs.count': '20',
},
{
index: '.somethingElse',
'docs.count': 20,
'docs.count': '20',
},
],
})
Expand All @@ -56,16 +55,15 @@ describe('checkClusterForUserData', () => {
it('returns true if data exists in non-system indices', async () => {
const esClient = elasticsearchServiceMock.createElasticsearchClient();
esClient.cat.indices.mockResolvedValue(
// @ts-expect-error @elastic/elasticsearch ES types don't support array response format
elasticsearchServiceMock.createApiResponse({
body: [
{
index: '.kibana',
'docs.count': 500,
'docs.count': '500',
},
{
index: 'some_real_index',
'docs.count': 20,
'docs.count': '20',
},
],
})
Expand All @@ -87,23 +85,21 @@ describe('checkClusterForUserData', () => {
)
.mockRejectedValueOnce(new Error('something terrible happened'))
.mockResolvedValueOnce(
// @ts-expect-error @elastic/elasticsearch ES types don't support array response format
elasticsearchServiceMock.createApiResponse({
body: [
{
index: '.kibana',
'docs.count': 500,
'docs.count': '500',
},
],
})
)
.mockResolvedValueOnce(
// @ts-expect-error @elastic/elasticsearch ES types don't support array response format
elasticsearchServiceMock.createApiResponse({
body: [
{
index: 'some_real_index',
'docs.count': 20,
'docs.count': '20',
},
],
})
Expand Down
2 changes: 2 additions & 0 deletions typings/elasticsearch/search.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,9 @@ export type AggregateOf<
{
key: string;
from?: number;
from_as_string?: string;
to?: number;
to_as_string?: string;
doc_count: number;
},
TAggregationContainer extends { range: { ranges: Array<infer TRangeType> } }
Expand Down
10 changes: 7 additions & 3 deletions x-pack/plugins/data_enhanced/server/collectors/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 { Observable } from 'rxjs';
import { first } from 'rxjs/operators';
import { SearchResponse } from 'elasticsearch';
Expand Down Expand Up @@ -36,8 +36,12 @@ export function fetchProvider(config$: Observable<SharedGlobalConfig>, logger: L
},
});

// @ts-expect-error @elastic/elasticsearch no way to declare a type for aggregations
const buckets: SessionPersistedTermsBucket[] = esResponse.aggregations!.persisted.buckets;
const aggs = esResponse.aggregations as Record<
string,
estypes.AggregationsMultiBucketAggregate<SessionPersistedTermsBucket>
>;

const buckets = aggs.persisted.buckets;
if (!buckets.length) {
return { transientCount: 0, persistedCount: 0, totalCount: 0 };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function getSearchStatus(
): Promise<Pick<SearchSessionRequestInfo, 'status' | 'error'>> {
// TODO: Handle strategies other than the default one
try {
// @ts-expect-error @elastic/elasticsearch status method is not defined
// @ts-expect-error start_time_in_millis: EpochMillis is string | number
const apiResponse: ApiResponse<AsyncSearchStatusResponse> = await client.asyncSearch.status({
id: asyncId,
});
Expand Down
12 changes: 7 additions & 5 deletions x-pack/plugins/fleet/server/routes/data_streams/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 { keyBy, keys, merge } from 'lodash';
import type { RequestHandler, SavedObjectsBulkGetObject } from 'src/core/server';

Expand Down Expand Up @@ -140,10 +140,7 @@ export const getListHandler: RequestHandler = async (context, request, response)

// Query backing indices to extract data stream dataset, namespace, and type values
const {
body: {
// @ts-expect-error @elastic/elasticsearch aggregations are not typed
aggregations: { dataset, namespace, type },
},
body: { aggregations: dataStreamAggs },
} = await esClient.search({
index: dataStream.indices.map((index) => index.index_name),
body: {
Expand Down Expand Up @@ -187,6 +184,11 @@ export const getListHandler: RequestHandler = async (context, request, response)
},
});

const { dataset, namespace, type } = dataStreamAggs as Record<
string,
estypes.AggregationsMultiBucketAggregate<{ key?: string }>
>;

// Set values from backing indices query
dataStreamResponse.dataset = dataset.buckets[0]?.key || '';
dataStreamResponse.namespace = namespace.buckets[0]?.key || '';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export async function listEnrollmentApiKeys(
body: query ? { query } : undefined,
});

// @ts-expect-error @elastic/elasticsearch
// @ts-expect-error @elastic/elasticsearch _source is optional
const items = res.body.hits.hits.map(esDocToEnrollmentApiKey);

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ const getData = async (
const client = async <Hit = {}, Aggregation = undefined>(
options: CallWithRequestParams
): Promise<InfraDatabaseSearchResponse<Hit, Aggregation>> =>
// @ts-expect-error @elastic/elasticsearch SearchResponse.body.timeout is not required
(await esClient.search(options as any)).body as InfraDatabaseSearchResponse<Hit, Aggregation>;
// @ts-expect-error SearchResponse.body.timeout is optional
(await esClient.search(options)).body as InfraDatabaseSearchResponse<Hit, Aggregation>;

const metrics = [
metric === 'custom' ? (customMetric as SnapshotCustomMetricInput) : { type: metric },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export const logEntrySearchStrategyProvider = ({
tiebreakerField,
runtimeMappings,
}): IEsSearchRequest => ({
// @ts-expect-error @elastic/elasticsearch declares indices_boost as Record<string, number>
// @ts-expect-error `Field` is not assignable to `SearchRequest.docvalue_fields`
params: createGetLogEntryQuery(
indices,
params.logEntryId,
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/lens/server/usage/visualization_counts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export async function getVisualizationCounts(
},
});

// @ts-expect-error @elastic/elasticsearch no way to declare aggregations for search response
// @ts-expect-error specify aggregations type explicitly
const buckets = results.aggregations.groups.buckets;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export async function fetchCCRReadExceptions(

const { body: response } = await esClient.search(params);
const stats: CCRReadExceptionsStats[] = [];
// @ts-expect-error @elastic/elasticsearch Aggregate does not specify buckets
// @ts-expect-error declare aggegations type explicitly
const { buckets: remoteClusterBuckets = [] } = response.aggregations?.remote_clusters;

if (!remoteClusterBuckets?.length) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('fetchCpuUsageNodeStats', () => {

it('fetch normal stats', async () => {
esClient.search.mockReturnValue(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
// @ts-expect-error not full response interface
elasticsearchClientMock.createSuccessTransportRequestPromise({
aggregations: {
clusters: {
Expand Down Expand Up @@ -79,7 +79,7 @@ describe('fetchCpuUsageNodeStats', () => {

it('fetch container stats', async () => {
esClient.search.mockReturnValue(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
// @ts-expect-error not full response interface
elasticsearchClientMock.createSuccessTransportRequestPromise({
aggregations: {
clusters: {
Expand Down Expand Up @@ -146,7 +146,7 @@ describe('fetchCpuUsageNodeStats', () => {

it('fetch properly return ccs', async () => {
esClient.search.mockReturnValue(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
// @ts-expect-error not full response interface
elasticsearchClientMock.createSuccessTransportRequestPromise({
aggregations: {
clusters: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('fetchDiskUsageNodeStats', () => {

it('fetch normal stats', async () => {
esClient.search.mockReturnValue(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
// @ts-expect-error not full response interface
elasticsearchClientMock.createSuccessTransportRequestPromise({
aggregations: {
clusters: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export async function fetchDiskUsageNodeStats(

const { body: response } = await esClient.search(params);
const stats: AlertDiskUsageNodeStats[] = [];
// @ts-expect-error @elastic/elasticsearch Aggregate does not define buckets
// @ts-expect-error declare type for aggregations explicitly
const { buckets: clusterBuckets } = response.aggregations?.clusters;

if (!clusterBuckets?.length) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export async function fetchIndexShardSize(
};

const { body: response } = await esClient.search(params);
// @ts-expect-error @elastic/elasticsearch Aggregate does not specify buckets
// @ts-expect-error declare aggegations type explicitly
const { buckets: clusterBuckets } = response.aggregations?.clusters;
const stats: IndexShardSizeStats[] = [];
if (!clusterBuckets?.length) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe('fetchKibanaVersions', () => {

it('fetch as expected', async () => {
esClient.search.mockReturnValue(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
// @ts-expect-error not full response interface
elasticsearchClientMock.createSuccessTransportRequestPromise({
aggregations: {
index: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe('fetchLogstashVersions', () => {

it('fetch as expected', async () => {
esClient.search.mockReturnValue(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
// @ts-expect-error not full response interface
elasticsearchClientMock.createSuccessTransportRequestPromise({
aggregations: {
index: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export async function fetchMemoryUsageNodeStats(

const { body: response } = await esClient.search(params);
const stats: AlertMemoryUsageNodeStats[] = [];
// @ts-expect-error @elastic/elasticsearch Aggregate does not define buckets
// @ts-expect-error declare type for aggregations explicitly
const { buckets: clusterBuckets } = response.aggregations?.clusters;

if (!clusterBuckets?.length) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ describe('fetchMissingMonitoringData', () => {
];

esClient.search.mockReturnValue(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
// @ts-expect-error not full response interface
elasticsearchClientMock.createSuccessTransportRequestPromise({
aggregations: {
clusters: {
Expand Down Expand Up @@ -115,7 +115,7 @@ describe('fetchMissingMonitoringData', () => {
},
];
esClient.search.mockReturnValue(
// @ts-expect-error @elastic/elasticsearch Aggregate only allows unknown values
// @ts-expect-error not full response interface
elasticsearchClientMock.createSuccessTransportRequestPromise({
aggregations: {
clusters: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export async function fetchNodesFromClusterStats(

const { body: response } = await esClient.search(params);
const nodes: AlertClusterStatsNodes[] = [];
// @ts-expect-error @elastic/elasticsearch Aggregate does not define buckets
// @ts-expect-error declare type for aggregations explicitly
const clusterBuckets = response.aggregations?.clusters?.buckets;
if (!clusterBuckets?.length) {
return nodes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export async function fetchThreadPoolRejectionStats(

const { body: response } = await esClient.search(params);
const stats: AlertThreadPoolRejectionsStats[] = [];
// @ts-expect-error @elastic/elasticsearch Aggregate does not specify buckets
// @ts-expect-error declare type for aggregations explicitly
const { buckets: clusterBuckets } = response.aggregations?.clusters;

if (!clusterBuckets?.length) {
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/security/common/model/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

export interface User {
username: string;
email: string;
full_name: string;
email?: string;
full_name?: string;
roles: readonly string[];
enabled: boolean;
metadata?: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ export const THROTTLE_USERS_WAIT = 10000;

export interface UserFormValues {
username?: string;
full_name: string;
email: string;
full_name?: string;
email?: string;
password?: string;
confirm_password?: string;
roles: readonly string[];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ export class APIKeys {
try {
result = (
await this.clusterClient.asInternalUser.security.grantApiKey({
// @ts-expect-error @elastic/elasticsearch api_key.role_descriptors
// @ts-expect-error @elastic/elasticsearch api_key.role_descriptors doesn't support `Record<string, any>`
body: params,
})
).body;
Expand Down
Loading

0 comments on commit ab1d8f2

Please sign in to comment.