Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ResponseOps] Rename some alert -> rule terminology in the code #178988

Merged
merged 11 commits into from
Mar 20, 2024
2 changes: 1 addition & 1 deletion x-pack/plugins/alerting/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,6 @@ export const INTERNAL_ALERTING_API_MAINTENANCE_WINDOW_PATH =
export const INTERNAL_ALERTING_API_GET_ACTIVE_MAINTENANCE_WINDOWS_PATH =
`${INTERNAL_ALERTING_API_MAINTENANCE_WINDOW_PATH}/_active` as const;

export const ALERTS_FEATURE_ID = 'alerts';
export const ALERTING_FEATURE_ID = 'alerts';
export const MONITORING_HISTORY_LIMIT = 200;
export const ENABLE_MAINTENANCE_WINDOWS = true;
2 changes: 1 addition & 1 deletion x-pack/plugins/alerting/public/hooks/use_get_rule_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { useQuery } from '@tanstack/react-query';
import { i18n } from '@kbn/i18n';
import { useKibana } from '../utils/kibana_react';
import { loadRuleTypes } from '../services/alert_api';
import { loadRuleTypes } from '../services/rule_api';

export const useGetRuleTypes = () => {
const {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ import {
} from './create_maintenance_windows_form';

jest.mock('../../../utils/kibana_react');
jest.mock('../../../services/alert_api', () => ({
jest.mock('../../../services/rule_api', () => ({
loadRuleTypes: jest.fn(),
}));

const { loadRuleTypes } = jest.requireMock('../../../services/alert_api');
const { loadRuleTypes } = jest.requireMock('../../../services/rule_api');
const { useKibana, useUiSetting } = jest.requireMock('../../../utils/kibana_react');

const formProps: CreateMaintenanceWindowFormProps = {
Expand Down
4 changes: 2 additions & 2 deletions x-pack/plugins/alerting/public/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
managementPluginMock,
} from '@kbn/management-plugin/public/mocks';

jest.mock('./services/alert_api', () => ({
jest.mock('./services/rule_api', () => ({
loadRule: jest.fn(),
loadRuleType: jest.fn(),
}));
Expand All @@ -24,7 +24,7 @@ const mockSection = createManagementSectionMock();
describe('Alerting Public Plugin', () => {
describe('start()', () => {
it(`should fallback to the viewInAppRelativeUrl part of the rule object if navigation isn't registered`, async () => {
const { loadRule, loadRuleType } = jest.requireMock('./services/alert_api');
const { loadRule, loadRuleType } = jest.requireMock('./services/rule_api');
loadRule.mockResolvedValue({
alertTypeId: 'foo',
consumer: 'abc',
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/alerting/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type { DataPublicPluginStart } from '@kbn/data-plugin/public';
import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public';

import { AlertNavigationRegistry, AlertNavigationHandler } from './alert_navigation_registry';
import { loadRule, loadRuleType } from './services/alert_api';
import { loadRule, loadRuleType } from './services/rule_api';
import { ENABLE_MAINTENANCE_WINDOWS, Rule, MAINTENANCE_WINDOWS_APP_ID } from '../common';

export interface PluginSetupContract {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { Rule, RuleType } from '../../common';
import { httpServiceMock } from '@kbn/core/public/mocks';
import { loadRule, loadRuleType, loadRuleTypes } from './alert_api';
import { loadRule, loadRuleType, loadRuleTypes } from './rule_api';

const http = httpServiceMock.createStartContract();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ describe('create()', () => {
return rulesClient.create(options);
}

test('ensures user is authorised to create this type of alert under the consumer', async () => {
test('ensures user is authorised to create this type of rule under the consumer', async () => {
const data = getMockData({
alertTypeId: 'myType',
consumer: 'myApp',
Expand All @@ -242,18 +242,18 @@ describe('create()', () => {
});
});

test('throws when user is not authorised to create this type of alert', async () => {
test('throws when user is not authorised to create this type of rule', async () => {
const data = getMockData({
alertTypeId: 'myType',
consumer: 'myApp',
});

authorization.ensureAuthorized.mockRejectedValue(
new Error(`Unauthorized to create a "myType" alert for "myApp"`)
new Error(`Unauthorized to create a "myType" rule for "myApp"`)
);

await expect(tryToExecuteOperation({ data })).rejects.toMatchInlineSnapshot(
`[Error: Unauthorized to create a "myType" alert for "myApp"]`
`[Error: Unauthorized to create a "myType" rule for "myApp"]`
);

expect(authorization.ensureAuthorized).toHaveBeenCalledWith({
Expand Down Expand Up @@ -325,7 +325,7 @@ describe('create()', () => {
});
});

test('creates an alert', async () => {
test('creates an rule', async () => {
const data = getMockData();
const createdAttributes = {
...data,
Expand Down Expand Up @@ -556,7 +556,7 @@ describe('create()', () => {
expect(actionsClient.isActionTypeEnabled).toHaveBeenCalledWith('test', { notifyUsage: true });
});

test('creates an alert with a custom id', async () => {
test('creates an rule with a custom id', async () => {
const data = getMockData();
const createdAttributes = {
...data,
Expand Down Expand Up @@ -736,7 +736,7 @@ describe('create()', () => {
`);
});

test('creates an alert with multiple actions', async () => {
test('creates an rule with multiple actions', async () => {
const data = getMockData({
actions: [
{
Expand Down Expand Up @@ -1443,7 +1443,7 @@ describe('create()', () => {
expect(actionsClient.isSystemAction).toHaveBeenCalledTimes(3);
});

test('creates a disabled alert', async () => {
test('creates a disabled rule', async () => {
const data = getMockData({ enabled: false });
unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
id: '1',
Expand Down Expand Up @@ -1893,14 +1893,14 @@ describe('create()', () => {
`);
});

test('should trim alert name when creating API key', async () => {
const data = getMockData({ name: ' my alert name ' });
test('should trim rule name when creating API key', async () => {
const data = getMockData({ name: ' my rule name ' });
unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
id: '1',
type: RULE_SAVED_OBJECT_TYPE,
attributes: {
enabled: false,
name: ' my alert name ',
name: ' my rule name ',
alertTypeId: '123',
schedule: { interval: 10000 },
params: {
Expand Down Expand Up @@ -1931,10 +1931,10 @@ describe('create()', () => {
});

await rulesClient.create({ data });
expect(rulesClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: 123/my alert name');
expect(rulesClientParams.createAPIKey).toHaveBeenCalledWith('Alerting: 123/my rule name');
});

test('should create alert with given notifyWhen value if notifyWhen is not null', async () => {
test('should create rule with given notifyWhen value if notifyWhen is not null', async () => {
const data = getMockData({ notifyWhen: 'onActionGroupChange', throttle: '10m' });
const createdAttributes = {
...data,
Expand Down Expand Up @@ -2075,7 +2075,7 @@ describe('create()', () => {
`);
});

test('should create alert with notifyWhen = onThrottleInterval if notifyWhen is null and throttle is set', async () => {
test('should create rule with notifyWhen = onThrottleInterval if notifyWhen is null and throttle is set', async () => {
const data = getMockData({ throttle: '10m' });
const createdAttributes = {
...data,
Expand Down Expand Up @@ -2216,7 +2216,7 @@ describe('create()', () => {
`);
});

test('should create alert with notifyWhen = onActiveAlert if notifyWhen is null and throttle is null', async () => {
test('should create rule with notifyWhen = onActiveAlert if notifyWhen is null and throttle is null', async () => {
const data = getMockData();
const createdAttributes = {
...data,
Expand Down Expand Up @@ -2357,7 +2357,7 @@ describe('create()', () => {
`);
});

test('should create alerts with mapped_params', async () => {
test('should create rules with mapped_params', async () => {
const data = getMockData({
params: {
bar: true,
Expand Down Expand Up @@ -2742,11 +2742,11 @@ describe('create()', () => {
`"Task manager error"`
);
expect(rulesClientParams.logger.error).toHaveBeenCalledWith(
'Failed to cleanup alert "1" after scheduling task failed. Error: Saved object delete error'
'Failed to cleanup rule "1" after scheduling task failed. Error: Saved object delete error'
);
});

test('throws an error if alert type not registered', async () => {
test('throws an error if rule type not registered', async () => {
const data = getMockData();
ruleTypeRegistry.get.mockImplementation(() => {
throw new Error('Invalid type');
Expand Down Expand Up @@ -2865,7 +2865,7 @@ describe('create()', () => {
);
});

test(`doesn't create API key for disabled alerts`, async () => {
test(`doesn't create API key for disabled rules`, async () => {
const data = getMockData({ enabled: false });
unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
id: '1',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,10 @@ export async function createRule<Params extends RuleParams = never>(

context.ruleTypeRegistry.ensureRuleTypeEnabled(data.alertTypeId);

// Throws an error if alert type isn't registered
// Throws an error if rule type isn't registered
const ruleType = context.ruleTypeRegistry.get(data.alertTypeId);

const validatedAlertTypeParams = validateRuleTypeParams(data.params, ruleType.validate.params);
const validatedRuleTypeParams = validateRuleTypeParams(data.params, ruleType.validate.params);
const username = await context.getUserName();

let createdAPIKey = null;
Expand Down Expand Up @@ -161,7 +161,7 @@ export async function createRule<Params extends RuleParams = never>(
params: updatedParams,
actions,
} = await withSpan({ name: 'extractReferences', type: 'rules' }, () =>
extractReferences(context, ruleType, data.actions, validatedAlertTypeParams)
extractReferences(context, ruleType, data.actions, validatedRuleTypeParams)
);

const createTime = Date.now();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export async function muteInstance(
context: RulesClientContext,
params: MuteAlertParams
): Promise<void> {
const ruleId = params.alertId;
try {
muteAlertParamsSchema.validate(params);
} catch (error) {
Expand All @@ -29,18 +30,18 @@ export async function muteInstance(

return await retryIfConflicts(
context.logger,
`rulesClient.muteInstance('${params.alertId}')`,
`rulesClient.muteInstance('${ruleId}')`,
async () => await muteInstanceWithOCC(context, params)
);
}

async function muteInstanceWithOCC(
context: RulesClientContext,
{ alertId, alertInstanceId }: MuteAlertParams
{ alertId: ruleId, alertInstanceId }: MuteAlertParams
) {
const { attributes, version } = await context.unsecuredSavedObjectsClient.get<Rule>(
RULE_SAVED_OBJECT_TYPE,
alertId
ruleId
);

try {
Expand All @@ -58,7 +59,7 @@ async function muteInstanceWithOCC(
context.auditLogger?.log(
ruleAuditEvent({
action: RuleAuditAction.MUTE_ALERT,
savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: alertId },
savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: ruleId },
error,
})
);
Expand All @@ -69,7 +70,7 @@ async function muteInstanceWithOCC(
ruleAuditEvent({
action: RuleAuditAction.MUTE_ALERT,
outcome: 'unknown',
savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: alertId },
savedObject: { type: RULE_SAVED_OBJECT_TYPE, id: ruleId },
})
);

Expand All @@ -81,7 +82,7 @@ async function muteInstanceWithOCC(
await updateRuleSo({
savedObjectsClient: context.unsecuredSavedObjectsClient,
savedObjectsUpdateOptions: { version },
id: alertId,
id: ruleId,
updateRuleAttributes: updateMeta(context, {
mutedInstanceIds,
updatedBy: await context.getUserName(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { SecurityPluginSetup } from '@kbn/security-plugin/server';
import { PluginStartContract as FeaturesPluginStart } from '@kbn/features-plugin/server';
import { Space } from '@kbn/spaces-plugin/server';
import { RegistryRuleType } from '../rule_type_registry';
import { ALERTS_FEATURE_ID, RuleTypeRegistry } from '../types';
import { ALERTING_FEATURE_ID, RuleTypeRegistry } from '../types';
import {
asFiltersByRuleTypeAndConsumer,
asFiltersBySpaceId,
Expand Down Expand Up @@ -130,7 +130,7 @@ export class AlertingAuthorization {

this.allPossibleConsumers = this.featuresIds.then((featuresIds) => {
return featuresIds.size
? asAuthorizedConsumers([ALERTS_FEATURE_ID, ...featuresIds], {
? asAuthorizedConsumers([ALERTING_FEATURE_ID, ...featuresIds], {
read: true,
all: true,
})
Expand Down Expand Up @@ -338,7 +338,7 @@ export class AlertingAuthorization {
>();
const allPossibleConsumers = await this.allPossibleConsumers;
const addLegacyConsumerPrivileges = (legacyConsumer: string) =>
legacyConsumer === ALERTS_FEATURE_ID || isEmpty(featuresIds);
legacyConsumer === ALERTING_FEATURE_ID || isEmpty(featuresIds);
for (const feature of fIds) {
const featureDef = this.features
.getKibanaFeatures()
Expand Down Expand Up @@ -504,6 +504,6 @@ export const getValidConsumer = ({
legacyConsumer: string;
producer: string;
}): string =>
legacyConsumer === ALERTS_FEATURE_ID || validLegacyConsumers.includes(legacyConsumer)
legacyConsumer === ALERTING_FEATURE_ID || validLegacyConsumers.includes(legacyConsumer)
? producer
: legacyConsumer;
4 changes: 2 additions & 2 deletions x-pack/plugins/alerting/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ import { RulesClientFactory } from './rules_client_factory';
import { RulesSettingsClientFactory } from './rules_settings_client_factory';
import { MaintenanceWindowClientFactory } from './maintenance_window_client_factory';
import { ILicenseState, LicenseState } from './lib/license_state';
import { AlertingRequestHandlerContext, ALERTS_FEATURE_ID, RuleAlertData } from './types';
import { AlertingRequestHandlerContext, ALERTING_FEATURE_ID, RuleAlertData } from './types';
import { defineRoutes } from './routes';
import {
AlertInstanceContext,
Expand Down Expand Up @@ -320,7 +320,7 @@ export class AlertingPlugin {
}

// Usage counter for telemetry
this.usageCounter = plugins.usageCollection?.createUsageCounter(ALERTS_FEATURE_ID);
this.usageCounter = plugins.usageCollection?.createUsageCounter(ALERTING_FEATURE_ID);

const getSearchSourceMigrations = plugins.data.search.searchSource.getAllMigrations.bind(
plugins.data.search.searchSource
Expand Down
Loading