Skip to content

Commit

Permalink
[8.x] [Security Solution] Reduce the _review rule upgrade endpoint re…
Browse files Browse the repository at this point in the history
…sponse size (#211045) (#212921)

# Backport

This will backport the following commits from `main` to `8.x`:
- [[Security Solution] Reduce the _review rule upgrade endpoint response
size (#211045)](#211045)

<!--- Backport version: 9.6.6 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sorenlouv/backport)

<!--BACKPORT [{"author":{"name":"Dmitrii
Shevchenko","email":"dmitrii.shevchenko@elastic.co"},"sourceCommit":{"committedDate":"2025-03-03T14:03:07Z","message":"[Security
Solution] Reduce the _review rule upgrade endpoint response size
(#211045)\n\n**Resolves:
https://github.com/elastic/kibana/issues/208361**\n**Resolves:
https://github.com/elastic/kibana/issues/210544**\n\n## Summary\n\nThis
PR introduces significant memory consumption improvements to
the\nprebuilt rule endpoints, ensuring users won't encounter OOM errors
on\nmemory-limited Kibana instances.\n\nMemory consumption testing
results provided
in\nhttps://github.com//pull/211045#issuecomment-2689854328.\n\n##
Details\n\nThis PR implements a number of memory usage optimizations to
the\nprebuilt rule endpoints with the final goal reducing chances of
getting\nOOM errors. The changes are extensive and require thorough
testing\nbefore merging.\n\nThe changes are described by the following
bullets\n\n- The most significant change is the addition of pagination
to the\n`upgrade/_review` endpoint. This endpoint was known for causing
OOM\nerrors due to its large and ever-growing response size. With
pagination,\nit now returns upgrade information for no more than 20-100
rules at a\ntime, significantly reducing its memory footprint.\n- New
backend methods, such
as\n`ruleObjectsClient.fetchInstalledRuleVersions`, have been
introduced.\nThese methods return rule IDs with their corresponding
installed\nversions, allowing to build a map of outdated rules without
loading all\navailable rules into memory. Previously, all installed
rules, along with\ntheir base and target versions, were fetched
unconditionally before\nfiltering for updates.\n- The `stats` data
structure of the review endpoint has been deprecated\n(it can be safely
removed after one Serverless release cycle). Since the\nendpoint now
returns paginated results, building stats is no longer\nfeasible due to
the limited rule set size fetched on the server side. As\nthe side
effect it required removing related Cypress tests asserting\n`Update
All` disabled when rules can't be updated.\n- All changes to the
endpoints are backward-compatible. All previously\nrequired returned
structures still present in response. All newly added\nstructures are
optional.\n- Upgradeable rule tags are now returned from the prebuilt
rule status\nendpoint.\n- The frontend logic has been updated to move
sorting and filtering of\nprebuilt rules from the client side to the
server side.\n- The `upgrade/_perform` endpoint has been rewritten to
use lightweight\nrule version information rather than full rules to
determine upgradeable\nrules. Additionally, upgrades are now performed
in batches of up to 100\nrules, further reducing memory usage.\n- A dry
run option has been added to the upgrade perform endpoint. This\nis
needed for the \"Update all\" rules scenario to determine if any
rules\ncontain conflicts and display a confirmation modal to the
user.\n- An option to skip conflicting rules has been added to the
upgrade\nendpoint when called with the `ALL_RULES` mode.\n- The
`install/_review` endpoint's memory consumption has been optimized\nby
avoiding loading all rules into memory to determine available rules\nfor
installation. Redundant fetching of all base versions has also
been\nremoved, as they do not participate in the
calculation.\n\n---------\n\nCo-authored-by: Maxim Palenov
<maxim.palenov@elastic.co>","sha":"c4a016eda30ae8f224fdd485a634dc6773898e31","branchLabelMapping":{"^v9.1.0$":"main","^v8.19.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["bug","release_note:fix","performance","v9.0.0","Team:Detections
and Resp","Team: SecuritySolution","Team:Detection Rule
Management","Feature:Prebuilt Detection
Rules","backport:version","v8.18.0","v9.1.0","v8.19.0","v8.17.3"],"title":"[Security
Solution] Reduce the _review rule upgrade endpoint response
size","number":211045,"url":"https://github.com/elastic/kibana/pull/211045","mergeCommit":{"message":"[Security
Solution] Reduce the _review rule upgrade endpoint response size
(#211045)\n\n**Resolves:
https://github.com/elastic/kibana/issues/208361**\n**Resolves:
https://github.com/elastic/kibana/issues/210544**\n\n## Summary\n\nThis
PR introduces significant memory consumption improvements to
the\nprebuilt rule endpoints, ensuring users won't encounter OOM errors
on\nmemory-limited Kibana instances.\n\nMemory consumption testing
results provided
in\nhttps://github.com//pull/211045#issuecomment-2689854328.\n\n##
Details\n\nThis PR implements a number of memory usage optimizations to
the\nprebuilt rule endpoints with the final goal reducing chances of
getting\nOOM errors. The changes are extensive and require thorough
testing\nbefore merging.\n\nThe changes are described by the following
bullets\n\n- The most significant change is the addition of pagination
to the\n`upgrade/_review` endpoint. This endpoint was known for causing
OOM\nerrors due to its large and ever-growing response size. With
pagination,\nit now returns upgrade information for no more than 20-100
rules at a\ntime, significantly reducing its memory footprint.\n- New
backend methods, such
as\n`ruleObjectsClient.fetchInstalledRuleVersions`, have been
introduced.\nThese methods return rule IDs with their corresponding
installed\nversions, allowing to build a map of outdated rules without
loading all\navailable rules into memory. Previously, all installed
rules, along with\ntheir base and target versions, were fetched
unconditionally before\nfiltering for updates.\n- The `stats` data
structure of the review endpoint has been deprecated\n(it can be safely
removed after one Serverless release cycle). Since the\nendpoint now
returns paginated results, building stats is no longer\nfeasible due to
the limited rule set size fetched on the server side. As\nthe side
effect it required removing related Cypress tests asserting\n`Update
All` disabled when rules can't be updated.\n- All changes to the
endpoints are backward-compatible. All previously\nrequired returned
structures still present in response. All newly added\nstructures are
optional.\n- Upgradeable rule tags are now returned from the prebuilt
rule status\nendpoint.\n- The frontend logic has been updated to move
sorting and filtering of\nprebuilt rules from the client side to the
server side.\n- The `upgrade/_perform` endpoint has been rewritten to
use lightweight\nrule version information rather than full rules to
determine upgradeable\nrules. Additionally, upgrades are now performed
in batches of up to 100\nrules, further reducing memory usage.\n- A dry
run option has been added to the upgrade perform endpoint. This\nis
needed for the \"Update all\" rules scenario to determine if any
rules\ncontain conflicts and display a confirmation modal to the
user.\n- An option to skip conflicting rules has been added to the
upgrade\nendpoint when called with the `ALL_RULES` mode.\n- The
`install/_review` endpoint's memory consumption has been optimized\nby
avoiding loading all rules into memory to determine available rules\nfor
installation. Redundant fetching of all base versions has also
been\nremoved, as they do not participate in the
calculation.\n\n---------\n\nCo-authored-by: Maxim Palenov
<maxim.palenov@elastic.co>","sha":"c4a016eda30ae8f224fdd485a634dc6773898e31"}},"sourceBranch":"main","suggestedTargetBranches":["9.0","8.18","8.x","8.17"],"targetPullRequestStates":[{"branch":"9.0","label":"v9.0.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"8.18","label":"v8.18.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"main","label":"v9.1.0","branchLabelMappingKey":"^v9.1.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/211045","number":211045,"mergeCommit":{"message":"[Security
Solution] Reduce the _review rule upgrade endpoint response size
(#211045)\n\n**Resolves:
https://github.com/elastic/kibana/issues/208361**\n**Resolves:
https://github.com/elastic/kibana/issues/210544**\n\n## Summary\n\nThis
PR introduces significant memory consumption improvements to
the\nprebuilt rule endpoints, ensuring users won't encounter OOM errors
on\nmemory-limited Kibana instances.\n\nMemory consumption testing
results provided
in\nhttps://github.com//pull/211045#issuecomment-2689854328.\n\n##
Details\n\nThis PR implements a number of memory usage optimizations to
the\nprebuilt rule endpoints with the final goal reducing chances of
getting\nOOM errors. The changes are extensive and require thorough
testing\nbefore merging.\n\nThe changes are described by the following
bullets\n\n- The most significant change is the addition of pagination
to the\n`upgrade/_review` endpoint. This endpoint was known for causing
OOM\nerrors due to its large and ever-growing response size. With
pagination,\nit now returns upgrade information for no more than 20-100
rules at a\ntime, significantly reducing its memory footprint.\n- New
backend methods, such
as\n`ruleObjectsClient.fetchInstalledRuleVersions`, have been
introduced.\nThese methods return rule IDs with their corresponding
installed\nversions, allowing to build a map of outdated rules without
loading all\navailable rules into memory. Previously, all installed
rules, along with\ntheir base and target versions, were fetched
unconditionally before\nfiltering for updates.\n- The `stats` data
structure of the review endpoint has been deprecated\n(it can be safely
removed after one Serverless release cycle). Since the\nendpoint now
returns paginated results, building stats is no longer\nfeasible due to
the limited rule set size fetched on the server side. As\nthe side
effect it required removing related Cypress tests asserting\n`Update
All` disabled when rules can't be updated.\n- All changes to the
endpoints are backward-compatible. All previously\nrequired returned
structures still present in response. All newly added\nstructures are
optional.\n- Upgradeable rule tags are now returned from the prebuilt
rule status\nendpoint.\n- The frontend logic has been updated to move
sorting and filtering of\nprebuilt rules from the client side to the
server side.\n- The `upgrade/_perform` endpoint has been rewritten to
use lightweight\nrule version information rather than full rules to
determine upgradeable\nrules. Additionally, upgrades are now performed
in batches of up to 100\nrules, further reducing memory usage.\n- A dry
run option has been added to the upgrade perform endpoint. This\nis
needed for the \"Update all\" rules scenario to determine if any
rules\ncontain conflicts and display a confirmation modal to the
user.\n- An option to skip conflicting rules has been added to the
upgrade\nendpoint when called with the `ALL_RULES` mode.\n- The
`install/_review` endpoint's memory consumption has been optimized\nby
avoiding loading all rules into memory to determine available rules\nfor
installation. Redundant fetching of all base versions has also
been\nremoved, as they do not participate in the
calculation.\n\n---------\n\nCo-authored-by: Maxim Palenov
<maxim.palenov@elastic.co>","sha":"c4a016eda30ae8f224fdd485a634dc6773898e31"}},{"branch":"8.x","label":"v8.19.0","branchLabelMappingKey":"^v8.19.0$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"8.17","label":"v8.17.3","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"}]}]
BACKPORT-->

Co-authored-by: Dmitrii Shevchenko <dmitrii.shevchenko@elastic.co>
  • Loading branch information
kibanamachine and xcrzx authored Mar 3, 2025
1 parent 336b476 commit dd55c99
Show file tree
Hide file tree
Showing 47 changed files with 1,045 additions and 1,017 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { z } from '@kbn/zod';

export enum RuleCustomizationStatus {
CUSTOMIZED = 'CUSTOMIZED',
NOT_CUSTOMIZED = 'NOT_CUSTOMIZED',
}

export type PrebuiltRulesFilter = z.infer<typeof PrebuiltRulesFilter>;
export const PrebuiltRulesFilter = z.object({
/**
* Tags to filter by
*/
tags: z.array(z.string()).optional(),
/**
* Rule name to filter by
*/
name: z.string().optional(),
/**
* Rule customization status to filter by
*/
customization_status: z.nativeEnum(RuleCustomizationStatus).optional(),
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { z } from '@kbn/zod';
import { PrebuiltRulesFilter } from './prebuilt_rules_filter';

export enum RuleCustomizationStatus {
CUSTOMIZED = 'CUSTOMIZED',
NOT_CUSTOMIZED = 'NOT_CUSTOMIZED',
}

export type ReviewPrebuiltRuleUpgradeFilter = z.infer<typeof ReviewPrebuiltRuleUpgradeFilter>;
export const ReviewPrebuiltRuleUpgradeFilter = PrebuiltRulesFilter.merge(
z.object({
/**
* Rule IDs to return upgrade info for
*/
rule_ids: z.array(z.string()).optional(),
})
);
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@
export interface GetPrebuiltRulesStatusResponseBody {
/** Aggregated info about all prebuilt rules */
stats: PrebuiltRulesStatusStats;

/**
* Aggregated info about upgradeable prebuilt rules. This fields is optional
* for backward compatibility. After one serverless release cycle, it can be
* made required.
* */
aggregated_fields?: {
upgradeable_rules: {
/** List of all tags of the current versions of upgradeable rules */
tags: string[];
};
};
}

export interface PrebuiltRulesStatusStats {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ export * from './model/diff/three_way_diff/three_way_diff_outcome';
export * from './model/diff/three_way_diff/three_way_diff';
export * from './model/diff/three_way_diff/three_way_diff_conflict';
export * from './model/diff/three_way_diff/three_way_merge_outcome';
export * from './common/prebuilt_rules_filter';
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { mapValues } from 'lodash';
import { RuleResponse } from '../../model/rule_schema/rule_schemas.gen';
import { AggregatedPrebuiltRuleError, DiffableAllFields } from '../model';
import { RuleSignatureId, RuleVersion } from '../../model';
import { PrebuiltRulesFilter } from '../common/prebuilt_rules_filter';

export type Mode = z.infer<typeof Mode>;
export const Mode = z.enum(['ALL_RULES', 'SPECIFIC_RULES']);
Expand Down Expand Up @@ -111,21 +112,31 @@ export const RuleUpgradeSpecifier = z.object({
fields: RuleFieldsToUpgrade.optional(),
});

export type UpgradeConflictResolution = z.infer<typeof UpgradeConflictResolution>;
export const UpgradeConflictResolution = z.enum(['SKIP', 'OVERWRITE']);
export type UpgradeConflictResolutionEnum = typeof UpgradeConflictResolution.enum;
export const UpgradeConflictResolutionEnum = UpgradeConflictResolution.enum;

export type UpgradeSpecificRulesRequest = z.infer<typeof UpgradeSpecificRulesRequest>;
export const UpgradeSpecificRulesRequest = z.object({
mode: z.literal('SPECIFIC_RULES'),
rules: z.array(RuleUpgradeSpecifier).min(1),
pick_version: PickVersionValues.optional(),
on_conflict: UpgradeConflictResolution.optional(),
dry_run: z.boolean().optional(),
});

export type UpgradeAllRulesRequest = z.infer<typeof UpgradeAllRulesRequest>;
export const UpgradeAllRulesRequest = z.object({
mode: z.literal('ALL_RULES'),
pick_version: PickVersionValues.optional(),
filter: PrebuiltRulesFilter.optional(),
on_conflict: UpgradeConflictResolution.optional(),
dry_run: z.boolean().optional(),
});

export type SkipRuleUpgradeReason = z.infer<typeof SkipRuleUpgradeReason>;
export const SkipRuleUpgradeReason = z.enum(['RULE_UP_TO_DATE']);
export const SkipRuleUpgradeReason = z.enum(['RULE_UP_TO_DATE', 'CONFLICT']);
export type SkipRuleUpgradeReasonEnum = typeof SkipRuleUpgradeReason.enum;
export const SkipRuleUpgradeReasonEnum = SkipRuleUpgradeReason.enum;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,86 @@
* 2.0.
*/

import type { RuleObjectId, RuleSignatureId, RuleTagArray } from '../../model';
import { z } from '@kbn/zod';
import { SortOrder, type RuleObjectId, type RuleSignatureId, type RuleTagArray } from '../../model';
import type { PartialRuleDiff } from '../model';
import type { RuleResponse } from '../../model/rule_schema';
import type { RuleResponse, RuleVersion } from '../../model/rule_schema';
import { FindRulesSortField } from '../../rule_management';
import { PrebuiltRulesFilter } from '../common/prebuilt_rules_filter';

export type ReviewRuleUpgradeSort = z.infer<typeof ReviewRuleUpgradeSort>;
export const ReviewRuleUpgradeSort = z.object({
/**
* Field to sort by
*/
field: FindRulesSortField.optional(),
/**
* Sort order
*/
order: SortOrder.optional(),
});

export type ReviewRuleUpgradeRequestBody = z.infer<typeof ReviewRuleUpgradeRequestBody>;
export const ReviewRuleUpgradeRequestBody = z
.object({
filter: PrebuiltRulesFilter.optional(),
sort: ReviewRuleUpgradeSort.optional(),

page: z.coerce.number().int().min(1).optional().default(1),
/**
* Rules per page
*/
per_page: z.coerce.number().int().min(0).optional().default(20),
})
.nullable();

export interface ReviewRuleUpgradeResponseBody {
/** Aggregated info about all rules available for upgrade */
/**
* @deprecated Use the prebuilt rule status API instead. The field is kept
* here for backward compatibility but can be removed after one Serverless
* release.
*/
stats: RuleUpgradeStatsForReview;

/** Info about individual rules: one object per each rule available for upgrade */
rules: RuleUpgradeInfoForReview[];

/** The requested page number */
page: number;

/** The requested number of items per page */
per_page: number;

/** The total number of rules available for upgrade that match the filter criteria */
total: number;
}

export interface RuleUpgradeStatsForReview {
/** Number of installed prebuilt rules available for upgrade (stock + customized) */
/**
* @deprecated Always 0
*/
num_rules_to_upgrade_total: number;

/** Number of installed prebuilt rules with upgrade conflicts (SOLVABLE or NON_SOLVABLE) */
/**
* @deprecated Always 0
*/
num_rules_with_conflicts: number;

/** Number of installed prebuilt rules with NON_SOLVABLE upgrade conflicts */
/**
* @deprecated Always 0
*/
num_rules_with_non_solvable_conflicts: number;

/** A union of all tags of all rules available for upgrade */
/**
* @deprecated Always an empty array
*/
tags: RuleTagArray;
}

export interface RuleUpgradeInfoForReview {
id: RuleObjectId;
rule_id: RuleSignatureId;
version: RuleVersion;
current_rule: RuleResponse;
target_rule: RuleResponse;
diff: PartialRuleDiff;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ export const STARTED_TRANSFORM_STATES = new Set([
]);

/**
* How many rules to update at a time is set to 50 from errors coming from
* How many rules to update at a time is set to 20 from errors coming from
* the slow environments such as cloud when the rule updates are > 100 we were
* seeing timeout issues.
*
Expand All @@ -403,14 +403,14 @@ export const STARTED_TRANSFORM_STATES = new Set([
* Lastly, we saw weird issues where Chrome on upstream 408 timeouts will re-call the REST route
* which in turn could create additional connections we want to avoid.
*
* See file import_rules_route.ts for another area where 50 was chosen, therefore I chose
* 50 here to mimic it as well. If you see this re-opened or what similar to it, consider
* reducing the 50 above to a lower number.
* See file import_rules_route.ts for another area where 20 was chosen, therefore I chose
* 20 here to mimic it as well. If you see this re-opened or what similar to it, consider
* reducing the 20 above to a lower number.
*
* See the original ticket here:
* https://github.com/elastic/kibana/issues/94418
*/
export const MAX_RULES_TO_UPDATE_IN_PARALLEL = 50;
export const MAX_RULES_TO_UPDATE_IN_PARALLEL = 20;

export const LIMITED_CONCURRENCY_ROUTE_TAG_PREFIX = `${APP_ID}:limitedConcurrency`;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ export const TAGS_FIELD = 'alert.attributes.tags';
export const PARAMS_TYPE_FIELD = 'alert.attributes.params.type';
export const PARAMS_IMMUTABLE_FIELD = 'alert.attributes.params.immutable';
export const LAST_RUN_OUTCOME_FIELD = 'alert.attributes.lastRun.outcome';
export const IS_CUSTOMIZED_FIELD = 'alert.attributes.params.ruleSource.isCustomized';
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@

import type { Type } from '@kbn/securitysolution-io-ts-alerting-types';
import type { RuleExecutionStatus } from '../../api/detection_engine';
import { RuleExecutionStatusEnum } from '../../api/detection_engine';
import { RuleCustomizationStatus, RuleExecutionStatusEnum } from '../../api/detection_engine';
import { prepareKQLStringParam } from '../../utils/kql';
import {
ENABLED_FIELD,
IS_CUSTOMIZED_FIELD,
LAST_RUN_OUTCOME_FIELD,
PARAMS_IMMUTABLE_FIELD,
PARAMS_TYPE_FIELD,
Expand All @@ -23,6 +24,8 @@ export const KQL_FILTER_IMMUTABLE_RULES = `${PARAMS_IMMUTABLE_FIELD}: true`;
export const KQL_FILTER_MUTABLE_RULES = `${PARAMS_IMMUTABLE_FIELD}: false`;
export const KQL_FILTER_ENABLED_RULES = `${ENABLED_FIELD}: true`;
export const KQL_FILTER_DISABLED_RULES = `${ENABLED_FIELD}: false`;
export const KQL_FILTER_CUSTOMIZED_RULES = `${IS_CUSTOMIZED_FIELD}: true`;
export const KQL_FILTER_NOT_CUSTOMIZED_RULES = `${IS_CUSTOMIZED_FIELD}: false`;

interface RulesFilterOptions {
filter: string;
Expand All @@ -32,6 +35,7 @@ interface RulesFilterOptions {
tags: string[];
excludeRuleTypes: Type[];
ruleExecutionStatus: RuleExecutionStatus;
customizationStatus: RuleCustomizationStatus;
ruleIds: string[];
}

Expand All @@ -50,6 +54,7 @@ export function convertRulesFilterToKQL({
tags,
excludeRuleTypes = [],
ruleExecutionStatus,
customizationStatus,
}: Partial<RulesFilterOptions>): string {
const kql: string[] = [];

Expand Down Expand Up @@ -85,6 +90,12 @@ export function convertRulesFilterToKQL({
kql.push(`${LAST_RUN_OUTCOME_FIELD}: "failed"`);
}

if (customizationStatus === RuleCustomizationStatus.CUSTOMIZED) {
kql.push(KQL_FILTER_CUSTOMIZED_RULES);
} else if (customizationStatus === RuleCustomizationStatus.NOT_CUSTOMIZED) {
kql.push(KQL_FILTER_NOT_CUSTOMIZED_RULES);
}

return kql.join(' AND ');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ import type { ActionType, AsApiContract } from '@kbn/actions-plugin/common';
import type { ActionResult } from '@kbn/actions-plugin/server';
import { convertRulesFilterToKQL } from '../../../../common/detection_engine/rule_management/rule_filtering';
import type {
UpgradeSpecificRulesRequest,
PickVersionValues,
PerformRuleUpgradeResponseBody,
InstallSpecificRulesRequest,
PerformRuleInstallationResponseBody,
GetPrebuiltRulesStatusResponseBody,
ReviewRuleUpgradeResponseBody,
ReviewRuleInstallationResponseBody,
ReviewRuleUpgradeRequestBody,
PerformRuleUpgradeRequestBody,
} from '../../../../common/api/detection_engine/prebuilt_rules';
import type {
BulkDuplicateRules,
Expand Down Expand Up @@ -637,13 +637,16 @@ export const getPrebuiltRulesStatus = async ({
*/
export const reviewRuleUpgrade = async ({
signal,
request,
}: {
signal: AbortSignal | undefined;
request: ReviewRuleUpgradeRequestBody;
}): Promise<ReviewRuleUpgradeResponseBody> =>
KibanaServices.get().http.fetch(REVIEW_RULE_UPGRADE_URL, {
method: 'POST',
version: '1',
signal,
body: JSON.stringify(request),
});

/**
Expand Down Expand Up @@ -685,23 +688,13 @@ export const performInstallSpecificRules = async (
}),
});

export interface PerformUpgradeRequest {
rules: UpgradeSpecificRulesRequest['rules'];
pickVersion: PickVersionValues;
}

export const performUpgradeSpecificRules = async ({
rules,
pickVersion,
}: PerformUpgradeRequest): Promise<PerformRuleUpgradeResponseBody> =>
export const performUpgradeRules = async (
body: PerformRuleUpgradeRequestBody
): Promise<PerformRuleUpgradeResponseBody> =>
KibanaServices.get().http.fetch(PERFORM_RULE_UPGRADE_URL, {
method: 'POST',
version: '1',
body: JSON.stringify({
mode: 'SPECIFIC_RULES',
rules,
pick_version: pickVersion,
}),
body: JSON.stringify(body),
});

export const bootstrapPrebuiltRules = async (): Promise<BootstrapPrebuiltRulesResponse> =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,24 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { useCallback } from 'react';
import type { UseQueryOptions } from '@tanstack/react-query';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { PrebuiltRulesStatusStats } from '../../../../../../common/api/detection_engine/prebuilt_rules';
import { useCallback } from 'react';
import type { GetPrebuiltRulesStatusResponseBody } from '../../../../../../common/api/detection_engine/prebuilt_rules';
import { GET_PREBUILT_RULES_STATUS_URL } from '../../../../../../common/api/detection_engine/prebuilt_rules';
import { getPrebuiltRulesStatus } from '../../api';
import { DEFAULT_QUERY_OPTIONS } from '../constants';
import { GET_PREBUILT_RULES_STATUS_URL } from '../../../../../../common/api/detection_engine/prebuilt_rules';

export const PREBUILT_RULES_STATUS_QUERY_KEY = ['GET', GET_PREBUILT_RULES_STATUS_URL];

export const useFetchPrebuiltRulesStatusQuery = (
options?: UseQueryOptions<PrebuiltRulesStatusStats>
options?: UseQueryOptions<GetPrebuiltRulesStatusResponseBody>
) => {
return useQuery<PrebuiltRulesStatusStats>(
return useQuery<GetPrebuiltRulesStatusResponseBody>(
PREBUILT_RULES_STATUS_QUERY_KEY,
async ({ signal }) => {
const response = await getPrebuiltRulesStatus({ signal });
return response.stats;
return response;
},
{
...DEFAULT_QUERY_OPTIONS,
Expand Down
Loading

0 comments on commit dd55c99

Please sign in to comment.