Skip to content

Commit b5ad8bc

Browse files
authored
Upgrade ES client to 9.0.0-alpha.4 (#213375)
## Summary Upgrading the ES client to v9.0.0-alpha.4 to test the changes mentioned in elastic/elasticsearch-js#2584 This new version introduces some type changes, most notably, the `FieldValue` is `string | number | boolean | null | undefined` instead of `any`, leading to some new type checks to be implemented (like on aggregation results `bucket.key`, `search_after`, and `sort` options). On top of that, it adds the new behavior where unknown properties are placed in the `body` (when the request has a body). If they must be in as a query parameter, they should be placed under the `querystring` option. cc @JoshMock TODO: - [x] Stabilize the type errors - [x] Address all the query parameters that are now placed in the body (by wrapping them inside the option `querystring: {}`) I will address `// @ts-expect-error [email protected] https://github.com/elastic/elasticsearch-js/issues/2584` in a separate PR to reduce noise. Related #208776
1 parent 5d16e44 commit b5ad8bc

File tree

58 files changed

+128
-106
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+128
-106
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@
123123
"@elastic/datemath": "5.0.3",
124124
"@elastic/ebt": "^1.1.1",
125125
"@elastic/ecs": "^8.11.5",
126-
"@elastic/elasticsearch": "9.0.0-alpha.3",
126+
"@elastic/elasticsearch": "9.0.0-alpha.4",
127127
"@elastic/ems-client": "8.6.3",
128128
"@elastic/eui": "101.0.1",
129129
"@elastic/eui-theme-borealis": "0.1.0",

src/core/packages/elasticsearch/client-server-mocks/src/mocks.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const omittedProps = [
1919
'transport',
2020
'serializer',
2121
'helpers',
22+
'acceptedParams',
2223
] as Array<PublicKeys<Client>>;
2324

2425
export type DeeplyMockedApi<T> = {

src/core/packages/saved-objects/api-server-internal/src/lib/apis/create.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ export const performCreate = async <T>(
159159
refresh,
160160
document: raw._source,
161161
...(overwrite && version ? decodeRequestVersion(version) : {}),
162-
require_alias: true,
162+
querystring: { require_alias: true },
163163
};
164164

165165
const { body, statusCode, headers } =

src/core/packages/saved-objects/api-server-internal/src/lib/apis/update.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,7 @@ export const executeUpdate = async <T>(
194194
refresh,
195195
document: rawUpsert._source,
196196
...(version ? decodeRequestVersion(version) : {}),
197-
// @ts-expect-error
198-
require_alias: true,
197+
querystring: { require_alias: true },
199198
};
200199

201200
const {

src/platform/packages/private/kbn-generate-csv/src/generate_csv.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1424,7 +1424,7 @@ describe('CsvGenerator', () => {
14241424
expect(mockEsClient.asCurrentUser.openPointInTime).toHaveBeenCalledWith(
14251425
{
14261426
ignore_unavailable: true,
1427-
ignore_throttled: false,
1427+
querystring: { ignore_throttled: false },
14281428
index: 'logstash-*',
14291429
keep_alive: '30s',
14301430
},

src/platform/packages/private/kbn-generate-csv/src/lib/search_cursor_pit.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,13 @@ export class SearchCursorPit extends SearchCursor {
4747
index: this.indexPatternTitle,
4848
keep_alive: scroll.duration(taskInstanceFields),
4949
ignore_unavailable: true,
50-
// @ts-expect-error ignore_throttled is not in the type definition, but it is accepted by es
51-
ignore_throttled: includeFrozen ? false : undefined, // "true" will cause deprecation warnings logged in ES
50+
...(includeFrozen ? { querystring: { ignore_throttled: false } } : {}), // "true" will cause deprecation warnings logged in ES
5251
},
5352
{
5453
signal: this.abortController.signal,
5554
requestTimeout: scroll.duration(taskInstanceFields),
5655
maxRetries: 0,
56+
// @ts-expect-error not documented in the types. Is this still supported?
5757
maxConcurrentShardRequests,
5858
}
5959
);

src/platform/packages/shared/content-management/favorites/favorites_server/src/favorites_usage_collection.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -115,11 +115,12 @@ export function registerFavoritesUsageCollection({
115115
[]) as estypes.AggregationsStringTermsBucket[];
116116

117117
typesBuckets.forEach((bucket) => {
118-
favoritesUsage[bucket.key] = {
119-
total: bucket.stats.sum,
120-
total_users_spaces: bucket.stats.count,
121-
avg_per_user_per_space: bucket.stats.avg,
122-
max_per_user_per_space: bucket.stats.max,
118+
const stats = bucket.stats as estypes.AggregationsStatsAggregate;
119+
favoritesUsage[`${bucket.key}`] = {
120+
total: stats.sum,
121+
total_users_spaces: stats.count,
122+
avg_per_user_per_space: stats.avg!,
123+
max_per_user_per_space: stats.max!,
123124
};
124125
});
125126

src/platform/packages/shared/kbn-rule-data-utils/src/alerts_as_data_rbac.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,17 +51,19 @@ export const isValidFeatureId = (a: unknown): a is ValidFeatureId =>
5151
* @param sortIds estypes.SortResults | undefined
5252
* @returns SortResults
5353
*/
54-
export const getSafeSortIds = (sortIds: estypes.SortResults | null | undefined) => {
54+
export const getSafeSortIds = (
55+
sortIds: estypes.SortResults | null | undefined
56+
): Array<string | number> | undefined => {
5557
if (sortIds == null) {
56-
return sortIds;
58+
return sortIds as undefined;
5759
}
5860
return sortIds.map((sortId) => {
5961
// haven't determined when we would receive a null value for a sort id
6062
// but in case we do, default to sending the stringified Java max_int
61-
if (sortId == null || sortId === '' || sortId >= Number.MAX_SAFE_INTEGER) {
63+
if (sortId == null || sortId === '' || Number(sortId) >= Number.MAX_SAFE_INTEGER) {
6264
return '9223372036854775807';
6365
}
64-
return sortId;
66+
return sortId as string | number;
6567
});
6668
};
6769

src/platform/plugins/private/kibana_usage_collection/server/collectors/saved_objects_counts/get_saved_object_counts/get_saved_object_counts.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,16 +80,18 @@ export async function getSavedObjectsCounts(
8080
const nonExpectedTypes: string[] = [];
8181

8282
const perType = buckets.map((perTypeEntry) => {
83-
if (perTypeEntry.key !== MISSING_TYPE_KEY && !soTypes.includes(perTypeEntry.key)) {
83+
const key = perTypeEntry.key as string;
84+
if (key !== MISSING_TYPE_KEY && !soTypes.includes(key)) {
8485
// If the breakdown includes any SO types that are not expected, highlight them in the nonExpectedTypes list.
85-
nonExpectedTypes.push(perTypeEntry.key);
86+
nonExpectedTypes.push(key);
8687
}
8788

8889
return { key: perTypeEntry.key, doc_count: perTypeEntry.doc_count };
8990
});
9091

9192
return {
9293
total: body.total,
94+
// @ts-expect-error `FieldValue` types now claim that bucket keys can be `null`
9395
per_type: perType,
9496
non_expected_types: nonExpectedTypes,
9597
others: body.aggregations?.types?.sum_other_doc_count ?? 0,

src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.test.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,9 @@ describe('ES search strategy', () => {
314314
expect(mockRollupSearchCaller).toHaveBeenCalledWith(
315315
{
316316
index: 'foo-程',
317-
ignore_unavailable: true,
317+
querystring: {
318+
ignore_unavailable: true,
319+
},
318320
max_concurrent_shard_requests: undefined,
319321
timeout: '100ms',
320322
track_total_hits: true,

src/platform/plugins/shared/data/server/search/strategies/ese_search/ese_search_strategy.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,12 +166,20 @@ export const enhancedEsSearchStrategyProvider = (
166166
throw new KbnSearchError(`"params.index" is required when performing a rollup search`, 400);
167167
}
168168

169+
// eslint-disable-next-line @typescript-eslint/naming-convention
170+
const { ignore_unavailable, preference, ...params } = {
171+
...querystring,
172+
...request.params,
173+
index: request.params.index,
174+
};
175+
169176
try {
170177
const esResponse = await client.rollup.rollupSearch(
171178
{
172-
...querystring,
173-
...request.params,
174-
index: request.params.index,
179+
...params,
180+
// Not defined in the spec, and the client places it in the body.
181+
// This workaround allows us to force it as a query parameter.
182+
querystring: { ...params.querystring, ignore_unavailable, preference },
175183
},
176184
{
177185
signal: options?.abortSignal,

src/platform/plugins/shared/saved_objects_management/server/lib/get_saved_objects_counts.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ export const getSavedObjectCounts = async ({
3838
(body.aggregations?.types?.buckets as estypes.AggregationsStringTermsBucketKeys[]) || [];
3939

4040
const counts = buckets.reduce((memo, bucket) => {
41-
memo[bucket.key] = bucket.doc_count;
41+
memo[`${bucket.key}`] = bucket.doc_count;
4242
return memo;
4343
}, {} as Record<string, number>);
4444

x-pack/platform/plugins/private/index_lifecycle_management/__jest__/extend_index_management.test.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,6 @@ const indexWithLifecyclePhaseDefinition: Index = {
162162
step_time_millis: 1544187776208,
163163
phase_execution: {
164164
policy: 'testy',
165-
// @ts-expect-error ILM type is incorrect https://github.com/elastic/elasticsearch-specification/issues/2326
166165
phase_definition: { min_age: '0s', actions: { rollover: { max_size: '1gb' } } },
167166
version: 1,
168167
modified_date_in_millis: 1544031699844,

x-pack/platform/plugins/private/index_lifecycle_management/public/extend_index_management/components/index_lifecycle_summary.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export const IndexLifecycleSummary: FunctionComponent<Props> = ({
8383
defaultMessage: 'Policy name',
8484
}
8585
),
86-
description: ilm.policy,
86+
description: ilm.policy!,
8787
},
8888
{
8989
title: i18n.translate(
@@ -153,7 +153,7 @@ export const IndexLifecycleSummary: FunctionComponent<Props> = ({
153153
<EuiLink
154154
color="primary"
155155
href={getUrlForApp('management', {
156-
path: `data/index_lifecycle_management/${getPolicyEditPath(ilm.policy)}`,
156+
path: `data/index_lifecycle_management/${getPolicyEditPath(ilm.policy!)}`,
157157
})}
158158
target="_blank"
159159
>

x-pack/platform/plugins/private/upgrade_assistant/server/lib/es_deprecations_status/index.test.ts

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
import _ from 'lodash';
99
import { elasticsearchServiceMock } from '@kbn/core/server/mocks';
10-
import type * as estypes from '@elastic/elasticsearch/lib/api/types';
10+
import type { estypes } from '@elastic/elasticsearch';
1111

1212
import fakeDeprecations from '../__fixtures__/fake_deprecations.json';
1313
import * as healthIndicatorsMock from '../__fixtures__/health_indicators';
@@ -126,7 +126,6 @@ describe('getESUpgradeStatus', () => {
126126
],
127127
},
128128
data_streams: {},
129-
// @ts-expect-error not in types yet
130129
ilm_policies: {},
131130
templates: {},
132131
});
@@ -148,7 +147,7 @@ describe('getESUpgradeStatus', () => {
148147
...esMigrationsMock.getMockEsDeprecations(),
149148
...esMigrationsMock.getMockMlSettingsDeprecations(),
150149
};
151-
// @ts-ignore missing property definitions in ES resolve_during_rolling_upgrade and _meta
150+
// @ts-expect-error missing property definitions in ES resolve_during_rolling_upgrade and _meta
152151
esClient.migration.deprecations.mockResponse(mockResponse);
153152

154153
const enabledUpgradeStatus = await getESUpgradeStatus(esClient, {
@@ -217,7 +216,6 @@ describe('getESUpgradeStatus', () => {
217216
message: 'Index created before 7.0',
218217
url: 'https: //www.elastic.co/guide/en/elasticsearch/reference/master/breaking-changes-8.0.html',
219218
details: 'This index was created using version: 6.8.13',
220-
// @ts-ignore
221219
resolve_during_rolling_upgrade: false,
222220
_meta: {
223221
reindex_required: true,
@@ -228,7 +226,6 @@ describe('getESUpgradeStatus', () => {
228226
message: 'Index created before 7.0',
229227
url: 'https: //www.elastic.co/guide/en/elasticsearch/reference/master/breaking-changes-8.0.html',
230228
details: 'This index was created using version: 6.8.13',
231-
// @ts-ignore
232229
resolve_during_rolling_upgrade: false,
233230
_meta: {
234231
reindex_required: true,
@@ -238,7 +235,6 @@ describe('getESUpgradeStatus', () => {
238235
ml_settings: [],
239236
index_settings: {},
240237
data_streams: {},
241-
// @ts-expect-error not in types yet
242238
ilm_policies: {},
243239
templates: {},
244240
});
@@ -313,7 +309,6 @@ describe('getESUpgradeStatus', () => {
313309
},
314310
],
315311
},
316-
// @ts-expect-error not in types yet
317312
ilm_policies: {},
318313
templates: {},
319314
});
@@ -369,7 +364,6 @@ describe('getESUpgradeStatus', () => {
369364
],
370365
},
371366
data_streams: {},
372-
// @ts-expect-error not in types yet
373367
ilm_policies: {},
374368
templates: {},
375369
});
@@ -398,7 +392,6 @@ describe('getESUpgradeStatus', () => {
398392
message: 'Index created before 7.0',
399393
url: 'https: //www.elastic.co/guide/en/elasticsearch/reference/master/breaking-changes-8.0.html',
400394
details: 'This index was created using version: 6.8.13',
401-
// @ts-ignore
402395
resolve_during_rolling_upgrade: false,
403396
_meta: {
404397
reindex_required: true,
@@ -408,7 +401,6 @@ describe('getESUpgradeStatus', () => {
408401
ml_settings: [],
409402
index_settings: {},
410403
data_streams: {},
411-
// @ts-expect-error not in types yet
412404
ilm_policies: {},
413405
templates: {},
414406
});
@@ -417,7 +409,7 @@ describe('getESUpgradeStatus', () => {
417409
cluster_name: 'mock',
418410
indicators: {
419411
disk: healthIndicatorsMock.diskIndicatorGreen,
420-
// @ts-ignore
412+
// @ts-expect-error
421413
shards_capacity: healthIndicatorsMock.shardCapacityIndicatorRed,
422414
},
423415
});

x-pack/platform/plugins/shared/actions/server/lib/get_execution_log_aggregation.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ function formatExecutionLogAggBucket(bucket: IExecutionUuidAggBucket): IExecutio
324324
const connectorId = outcomeAndMessage?.kibana?.action?.id ?? '';
325325
const timedOut = (bucket?.timeoutMessage?.doc_count ?? 0) > 0;
326326
return {
327-
id: bucket?.key ?? '',
327+
id: bucket?.key ? `${bucket.key}` : '',
328328
timestamp: bucket?.actionExecution?.executeStartTime.value_as_string ?? '',
329329
duration_ms: durationUs / Millis2Nanos,
330330
status,

x-pack/platform/plugins/shared/alerting/server/lib/get_execution_log_aggregation.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,7 @@ function formatExecutionLogAggBucket(bucket: IExecutionUuidAggBucket): IExecutio
530530
? outcomeMessageAndMaintenanceWindow.rule?.name ?? ''
531531
: '';
532532
return {
533-
id: bucket?.key ?? '',
533+
id: bucket?.key ? `${bucket.key}` : '', // `key` can be a number, this way we stringify it.
534534
timestamp: bucket?.ruleExecution?.executeStartTime.value_as_string ?? '',
535535
duration_ms: durationUs / Millis2Nanos,
536536
status,

x-pack/platform/plugins/shared/alerting/server/lib/rule_gaps/find_gaps.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ export const findGapsSearchAfter = async ({
101101
return {
102102
total: gapsResponse.total,
103103
data: transformToGap(gapsResponse),
104-
searchAfter: gapsResponse.search_after,
104+
searchAfter: gapsResponse.search_after as SortResults[] | undefined,
105105
pitId: gapsResponse.pit_id,
106106
};
107107
} catch (err) {

x-pack/platform/plugins/shared/alerting/server/lib/wrap_scoped_cluster_client.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ function getWrappedEqlSearchFn(opts: WrapEsClientOpts) {
253253
requestTimeout ? ` and ${requestTimeout}ms requestTimeout` : ''
254254
}`
255255
);
256-
const result = (await originalEqlSearch.call(opts.esClient, params, {
256+
const result = (await originalEqlSearch.call(opts.esClient.eql, params, {
257257
...searchOptions,
258258
...(requestTimeout
259259
? {

x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_event_log.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ export function parseRuleTypeBucket(
340340
alertsPercentilesByType: { p50: {}, p90: {}, p99: {} },
341341
};
342342
for (const bucket of buckets ?? []) {
343-
const ruleType: string = replaceDotSymbols(bucket?.key) ?? '';
343+
const ruleType: string = replaceDotSymbols(`${bucket?.key ?? ''}`);
344344
const numExecutions: number = bucket?.doc_count ?? 0;
345345
const avgExecutionTimeNanos = bucket?.avg_execution_time?.value ?? 0;
346346
const avgEsSearchTimeMillis = bucket?.avg_es_search_duration?.value ?? 0;
@@ -391,7 +391,7 @@ export function parseExecutionFailureByRuleType(
391391
const executionFailuresWithRuleTypeBuckets: FlattenedExecutionFailureBucket[] = flatMap(
392392
buckets ?? [],
393393
(bucket) => {
394-
const ruleType: string = replaceDotSymbols(bucket.key);
394+
const ruleType: string = replaceDotSymbols(`${bucket.key}`);
395395

396396
/**
397397
* Execution failure bucket format
@@ -409,7 +409,7 @@ export function parseExecutionFailureByRuleType(
409409

410410
const executionFailuresBuckets = bucket?.execution_failures?.by_reason
411411
?.buckets as AggregationsStringTermsBucketKeys[];
412-
return (executionFailuresBuckets ?? []).map((b) => ({ ...b, ruleType }));
412+
return (executionFailuresBuckets ?? []).map((b) => ({ ...b, key: `${b.key}`, ruleType }));
413413
}
414414
);
415415

@@ -548,7 +548,7 @@ export function parseExecutionCountAggregationResults(results: {
548548
countTotalFailedExecutions: results?.execution_failures?.doc_count ?? 0,
549549
countFailedExecutionsByReason: executionFailuresByReasonBuckets.reduce<Record<string, number>>(
550550
(acc, bucket: AggregationsStringTermsBucketKeys) => {
551-
const reason: string = bucket.key;
551+
const reason: string = `${bucket.key}`;
552552
acc[reason] = bucket.doc_count ?? 0;
553553
return acc;
554554
},

x-pack/platform/plugins/shared/alerting/server/usage/lib/get_telemetry_from_task_manager.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,12 +163,14 @@ export function parseBucket(
163163
> {
164164
return (buckets ?? []).reduce(
165165
(summary, bucket) => {
166-
const status: string = bucket.key;
166+
const status: string = `${bucket.key}`;
167167
const taskTypeBuckets = bucket?.by_task_type?.buckets as AggregationsStringTermsBucketKeys[];
168168

169169
const byTaskType = (taskTypeBuckets ?? []).reduce<Record<string, number>>(
170170
(acc, taskTypeBucket: AggregationsStringTermsBucketKeys) => {
171-
const taskType: string = replaceDotSymbols(taskTypeBucket.key.replace('alerting:', ''));
171+
const taskType: string = replaceDotSymbols(
172+
`${taskTypeBucket.key}`.replace('alerting:', '')
173+
);
172174
acc[taskType] = taskTypeBucket.doc_count ?? 0;
173175
return acc;
174176
},

x-pack/platform/plugins/shared/alerting/server/usage/lib/parse_simple_rule_type_bucket.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export function parseSimpleRuleTypeBucket(
1616
) {
1717
const buckets = ruleTypeBuckets as AggregationsStringTermsBucketKeys[];
1818
return (buckets ?? []).reduce((acc, bucket: AggregationsStringTermsBucketKeys) => {
19-
const ruleType: string = replaceDotSymbols(bucket.key);
19+
const ruleType: string = replaceDotSymbols(`${bucket.key}`);
2020
acc[ruleType] = bucket.doc_count ?? 0;
2121
return acc;
2222
}, {} as Record<string, number>);

0 commit comments

Comments
 (0)