Skip to content

Commit

Permalink
[RAM] Rule is running (#147896)
Browse files Browse the repository at this point in the history
## Summary

#147759


### Checklist

- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
  • Loading branch information
XavierM and kibanamachine authored Jan 10, 2023
1 parent 9786a8f commit adbe6b7
Show file tree
Hide file tree
Showing 26 changed files with 245 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ describe('checking migration metadata changes on all registered SO types', () =>
Object {
"action": "7858e6d5a9f231bf23f6f2e57328eb0095b26735",
"action_task_params": "bbd38cbfd74bf6713586fe078e3fa92db2234299",
"alert": "c29c5e28a6f1d075e528a9273a1a07b080625565",
"alert": "f2e81863be0b50966b876b88b906c962e30b8c9c",
"api_key_pending_invalidation": "9b4bc1235337da9a87ef05a1d1f4858b2a3b77c6",
"apm-indices": "ceb0870f3a74e2ffc3a1cd3a3c73af76baca0999",
"apm-server-schema": "2bfd2998d3873872e1366458ce553def85418f91",
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/alerting/common/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ export interface Rule<Params extends RuleTypeParams = never> {
isSnoozedUntil?: Date | null;
lastRun?: RuleLastRun | null;
nextRun?: Date | null;
running?: boolean | null;
}

export type SanitizedRule<Params extends RuleTypeParams = never> = Omit<Rule<Params>, 'apiKey'>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ export async function clone<Params extends RuleTypeParams = never>(
executionStatus: getRuleExecutionStatusPending(lastRunTimestamp.toISOString()),
monitoring: getDefaultMonitoring(lastRunTimestamp.toISOString()),
scheduledTaskId: null,
running: false,
};

context.auditLogger?.log(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ export async function create<Params extends RuleTypeParams = never>(
throttle,
executionStatus: getRuleExecutionStatusPending(lastRunTimestamp.toISOString()),
monitoring: getDefaultMonitoring(lastRunTimestamp.toISOString()),
running: false,
};

const mappedParams = getMappedParams(updatedParams);
Expand Down
29 changes: 29 additions & 0 deletions x-pack/plugins/alerting/server/rules_client/tests/create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ function getMockData(overwrites: Record<string, unknown> = {}): CreateOptions<{
},
},
],
running: false,
...overwrites,
};
}
Expand Down Expand Up @@ -377,6 +378,7 @@ describe('create()', () => {
"params": Object {
"bar": true,
},
"running": false,
"schedule": Object {
"interval": "1m",
},
Expand Down Expand Up @@ -446,6 +448,7 @@ describe('create()', () => {
"params": Object {
"bar": true,
},
"running": false,
"schedule": Object {
"interval": "1m",
},
Expand Down Expand Up @@ -663,6 +666,7 @@ describe('create()', () => {
"params": Object {
"bar": true,
},
"running": false,
"schedule": Object {
"interval": "1m",
},
Expand Down Expand Up @@ -968,6 +972,7 @@ describe('create()', () => {
},
},
],
running: false,
},
references: [
{
Expand Down Expand Up @@ -1027,6 +1032,7 @@ describe('create()', () => {
"params": Object {
"bar": true,
},
"running": false,
"schedule": Object {
"interval": "1m",
},
Expand Down Expand Up @@ -1085,6 +1091,7 @@ describe('create()', () => {
name: 'abc',
notifyWhen: 'onActiveAlert',
params: { bar: true },
running: false,
schedule: { interval: '1m' },
tags: ['foo'],
throttle: null,
Expand Down Expand Up @@ -1230,6 +1237,7 @@ describe('create()', () => {
},
},
],
running: false,
},
references: [
{
Expand Down Expand Up @@ -1284,6 +1292,7 @@ describe('create()', () => {
name: 'abc',
notifyWhen: 'onActiveAlert',
params: { bar: true, parameterThatIsSavedObjectRef: 'soRef_0' },
running: false,
schedule: { interval: '1m' },
tags: ['foo'],
throttle: null,
Expand Down Expand Up @@ -1326,6 +1335,7 @@ describe('create()', () => {
"bar": true,
"parameterThatIsSavedObjectId": "9",
},
"running": false,
"schedule": Object {
"interval": "1m",
},
Expand Down Expand Up @@ -1398,6 +1408,7 @@ describe('create()', () => {
},
},
],
running: false,
},
references: [
{
Expand Down Expand Up @@ -1452,6 +1463,7 @@ describe('create()', () => {
name: 'abc',
notifyWhen: 'onActiveAlert',
params: { bar: true, parameterThatIsSavedObjectRef: 'action_0' },
running: false,
schedule: { interval: '1m' },
tags: ['foo'],
throttle: null,
Expand Down Expand Up @@ -1494,6 +1506,7 @@ describe('create()', () => {
"bar": true,
"parameterThatIsSavedObjectId": "8",
},
"running": false,
"schedule": Object {
"interval": "1m",
},
Expand Down Expand Up @@ -1569,6 +1582,7 @@ describe('create()', () => {
},
},
],
running: false,
};
unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
id: '1',
Expand Down Expand Up @@ -1623,6 +1637,7 @@ describe('create()', () => {
warning: null,
},
monitoring: getDefaultMonitoring('2019-02-12T21:01:22.479Z'),
running: false,
},
{
id: 'mock-saved-object-id',
Expand Down Expand Up @@ -1660,6 +1675,7 @@ describe('create()', () => {
"params": Object {
"bar": true,
},
"running": false,
"schedule": Object {
"interval": "1m",
},
Expand Down Expand Up @@ -1701,6 +1717,7 @@ describe('create()', () => {
},
},
],
running: false,
};
unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
id: '1',
Expand Down Expand Up @@ -1755,6 +1772,7 @@ describe('create()', () => {
warning: null,
},
monitoring: getDefaultMonitoring('2019-02-12T21:01:22.479Z'),
running: false,
},
{
id: 'mock-saved-object-id',
Expand Down Expand Up @@ -1792,6 +1810,7 @@ describe('create()', () => {
"params": Object {
"bar": true,
},
"running": false,
"schedule": Object {
"interval": "1m",
},
Expand Down Expand Up @@ -1833,6 +1852,7 @@ describe('create()', () => {
},
},
],
running: false,
};
unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
id: '1',
Expand Down Expand Up @@ -1887,6 +1907,7 @@ describe('create()', () => {
warning: null,
},
monitoring: getDefaultMonitoring('2019-02-12T21:01:22.479Z'),
running: false,
},
{
id: 'mock-saved-object-id',
Expand Down Expand Up @@ -1924,6 +1945,7 @@ describe('create()', () => {
"params": Object {
"bar": true,
},
"running": false,
"schedule": Object {
"interval": "1m",
},
Expand Down Expand Up @@ -1973,6 +1995,7 @@ describe('create()', () => {
},
},
],
running: false,
};
unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
id: '123',
Expand Down Expand Up @@ -2058,6 +2081,7 @@ describe('create()', () => {
meta: {
versionApiKeyLastmodified: 'v8.0.0',
},
running: false,
},
{
references: [
Expand Down Expand Up @@ -2098,6 +2122,7 @@ describe('create()', () => {
"risk_score": 42,
"severity": "low",
},
"running": false,
"schedule": Object {
"interval": "10s",
},
Expand Down Expand Up @@ -2407,6 +2432,7 @@ describe('create()', () => {
warning: null,
},
monitoring: getDefaultMonitoring('2019-02-12T21:01:22.479Z'),
running: false,
},
{
id: 'mock-saved-object-id',
Expand Down Expand Up @@ -2442,6 +2468,7 @@ describe('create()', () => {
},
},
],
running: false,
},
references: [
{
Expand Down Expand Up @@ -2509,6 +2536,7 @@ describe('create()', () => {
warning: null,
},
monitoring: getDefaultMonitoring('2019-02-12T21:01:22.479Z'),
running: false,
},
{
id: 'mock-saved-object-id',
Expand Down Expand Up @@ -2612,6 +2640,7 @@ describe('create()', () => {
},
},
],
running: false,
};
unsecuredSavedObjectsClient.create.mockResolvedValueOnce({
id: '1',
Expand Down
4 changes: 3 additions & 1 deletion x-pack/plugins/alerting/server/saved_objects/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export const AlertAttributesExcludedFromAAD = [
'isSnoozedUntil',
'lastRun',
'nextRun',
'running',
];

// useful for Pick<RawAlert, AlertAttributesExcludedFromAADType> which is a
Expand All @@ -56,7 +57,8 @@ export type AlertAttributesExcludedFromAADType =
| 'snoozeSchedule'
| 'isSnoozedUntil'
| 'lastRun'
| 'nextRun';
| 'nextRun'
| 'running';

export function setupSavedObjects(
savedObjects: SavedObjectsServiceSetup,
Expand Down
3 changes: 3 additions & 0 deletions x-pack/plugins/alerting/server/saved_objects/mappings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,5 +339,8 @@ export const alertMappings: SavedObjectsTypeMappingDefinition = {
},
},
},
running: {
type: 'boolean',
},
},
};
1 change: 1 addition & 0 deletions x-pack/plugins/alerting/server/task_runner/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ export const generateSavedObjectParams = ({
},
},
nextRun,
running: false,
},
{ refresh: false, namespace: undefined },
];
Expand Down
78 changes: 78 additions & 0 deletions x-pack/plugins/alerting/server/task_runner/running_handler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* 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 { ISavedObjectsRepository, Logger } from '@kbn/core/server';

import { partiallyUpdateAlert } from '../saved_objects/partially_update_alert';
import { RunningHandler } from './running_handler';

jest.mock('../saved_objects/partially_update_alert', () => ({
partiallyUpdateAlert: jest.fn(),
}));

describe('isRunning handler', () => {
const soClient = jest.fn() as unknown as ISavedObjectsRepository;
const logger = {
error: jest.fn(),
} as unknown as Logger;
const ruleTypeId = 'myType';
beforeEach(() => {
(partiallyUpdateAlert as jest.Mock).mockClear();
(logger.error as jest.Mock).mockClear();
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});

test('Should resolve if nothing got started', async () => {
(partiallyUpdateAlert as jest.Mock).mockImplementation(() => Promise.resolve('resolve'));
const runHandler = new RunningHandler(soClient, logger, ruleTypeId);
const resp = await runHandler.waitFor();
expect(partiallyUpdateAlert).toHaveBeenCalledTimes(0);
expect(logger.error).toHaveBeenCalledTimes(0);
expect(resp).toBe(undefined);
});

test('Should return the promise from partiallyUpdateAlert when the update isRunning has been a success', async () => {
(partiallyUpdateAlert as jest.Mock).mockImplementation(() => Promise.resolve('resolve'));
const runHandler = new RunningHandler(soClient, logger, ruleTypeId);
runHandler.start('9876543210');
jest.runAllTimers();
const resp = await runHandler.waitFor();

expect(partiallyUpdateAlert).toHaveBeenCalledTimes(1);
expect((partiallyUpdateAlert as jest.Mock).mock.calls[0]).toMatchInlineSnapshot(`
Array [
[MockFunction],
"9876543210",
Object {
"running": true,
},
Object {
"ignore404": true,
"namespace": undefined,
"refresh": false,
},
]
`);
expect(logger.error).toHaveBeenCalledTimes(0);
expect(resp).toBe('resolve');
});

test('Should reject when the update isRunning has been a failure', async () => {
(partiallyUpdateAlert as jest.Mock).mockImplementation(() =>
Promise.reject(new Error('error'))
);
const runHandler = new RunningHandler(soClient, logger, ruleTypeId);
runHandler.start('9876543210');
jest.runAllTimers();

await expect(runHandler.waitFor()).rejects.toThrow();
expect(partiallyUpdateAlert).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledTimes(1);
});
});
Loading

0 comments on commit adbe6b7

Please sign in to comment.