forked from elastic/kibana
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fetch rule actions in chunks (elastic#121110)
- Loading branch information
Showing
5 changed files
with
325 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
...rity_solution/server/lib/detection_engine/routes/rules/utils/get_current_rule_statuses.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
/* | ||
* 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 { chunk } from 'lodash'; | ||
import { Logger } from 'src/core/server'; | ||
import { initPromisePool } from '../../../../../utils/promise_pool'; | ||
import { GetCurrentStatusBulkResult, IRuleExecutionLogClient } from '../../../rule_execution_log'; | ||
|
||
const RULES_PER_CHUNK = 1000; | ||
|
||
interface GetCurrentRuleStatusesArgs { | ||
ruleIds: string[]; | ||
execLogClient: IRuleExecutionLogClient; | ||
spaceId: string; | ||
logger: Logger; | ||
} | ||
|
||
/** | ||
* Get the most recent execution status for each of the given rule IDs. | ||
* This method splits work into chunks so not to owerwhelm Elasticsearch | ||
* when fetching statuses for a big number of rules. | ||
* | ||
* @param ruleIds Rule IDs to fetch statuses for | ||
* @param execLogClient RuleExecutionLogClient | ||
* @param spaceId Current Space ID | ||
* @param logger Logger | ||
* @returns A dict with rule IDs as keys and rule statuses as values | ||
* | ||
* @throws AggregateError if any of the rule status requests fail | ||
*/ | ||
export async function getCurrentRuleStatuses({ | ||
ruleIds, | ||
execLogClient, | ||
spaceId, | ||
logger, | ||
}: GetCurrentRuleStatusesArgs): Promise<GetCurrentStatusBulkResult> { | ||
const { results, errors } = await initPromisePool({ | ||
concurrency: 1, | ||
items: chunk(ruleIds, RULES_PER_CHUNK), | ||
executor: (ruleIdsChunk) => | ||
execLogClient | ||
.getCurrentStatusBulk({ | ||
ruleIds: ruleIdsChunk, | ||
spaceId, | ||
}) | ||
.catch((error) => { | ||
logger.error( | ||
`Error fetching rule status: ${error instanceof Error ? error.message : String(error)}` | ||
); | ||
throw error; | ||
}), | ||
}); | ||
|
||
if (errors.length) { | ||
throw new AggregateError(errors, 'Error fetching rule statuses'); | ||
} | ||
|
||
// Merge all rule statuses into a single dict | ||
return Object.assign({}, ...results); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
174 changes: 174 additions & 0 deletions
174
x-pack/plugins/security_solution/server/utils/promise_pool.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,174 @@ | ||
/* | ||
* 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 { initPromisePool } from './promise_pool'; | ||
|
||
const nextTick = () => new Promise((resolve) => setImmediate(resolve)); | ||
|
||
const initPoolWithTasks = ({ concurrency = 1, items = [1, 2, 3] }) => { | ||
const asyncTasks: Record< | ||
number, | ||
{ | ||
status: 'pending' | 'resolved' | 'rejected'; | ||
resolve: () => void; | ||
reject: () => void; | ||
} | ||
> = {}; | ||
|
||
const promisePool = initPromisePool({ | ||
concurrency, | ||
items, | ||
executor: async (x) => | ||
new Promise((resolve, reject) => { | ||
asyncTasks[x] = { | ||
status: 'pending', | ||
resolve: () => { | ||
asyncTasks[x].status = 'resolved'; | ||
resolve(x); | ||
}, | ||
reject: () => { | ||
asyncTasks[x].status = 'rejected'; | ||
reject(new Error(`Error processing ${x}`)); | ||
}, | ||
}; | ||
}), | ||
}); | ||
|
||
return [promisePool, asyncTasks] as const; | ||
}; | ||
|
||
describe('initPromisePool', () => { | ||
it('should execute async tasks', async () => { | ||
const { results, errors } = await initPromisePool({ | ||
concurrency: 1, | ||
items: [1, 2, 3], | ||
executor: async (x) => x, | ||
}); | ||
|
||
expect(results).toEqual([1, 2, 3]); | ||
expect(errors).toEqual([]); | ||
}); | ||
|
||
it('should capture any errors that occur during tasks execution', async () => { | ||
const { results, errors } = await initPromisePool({ | ||
concurrency: 1, | ||
items: [1, 2, 3], | ||
executor: async (x) => { | ||
throw new Error(`Error processing ${x}`); | ||
}, | ||
}); | ||
|
||
expect(results).toEqual([]); | ||
expect(errors).toEqual([ | ||
new Error(`Error processing 1`), | ||
new Error(`Error processing 2`), | ||
new Error(`Error processing 3`), | ||
]); | ||
}); | ||
|
||
it('should respect concurrency', async () => { | ||
const [promisePool, asyncTasks] = initPoolWithTasks({ | ||
concurrency: 1, | ||
items: [1, 2, 3], | ||
}); | ||
|
||
// Check that we have only one task pending initially as concurrency = 1 | ||
expect(asyncTasks).toEqual({ | ||
1: expect.objectContaining({ status: 'pending' }), | ||
}); | ||
|
||
asyncTasks[1].resolve(); | ||
await nextTick(); | ||
|
||
// Check that after resolving the first task, the second is pending | ||
expect(asyncTasks).toEqual({ | ||
1: expect.objectContaining({ status: 'resolved' }), | ||
2: expect.objectContaining({ status: 'pending' }), | ||
}); | ||
|
||
asyncTasks[2].reject(); | ||
await nextTick(); | ||
|
||
// Check that after rejecting the second task, the third is pending | ||
expect(asyncTasks).toEqual({ | ||
1: expect.objectContaining({ status: 'resolved' }), | ||
2: expect.objectContaining({ status: 'rejected' }), | ||
3: expect.objectContaining({ status: 'pending' }), | ||
}); | ||
|
||
asyncTasks[3].resolve(); | ||
await nextTick(); | ||
|
||
// Check that all taks have been settled | ||
expect(asyncTasks).toEqual({ | ||
1: expect.objectContaining({ status: 'resolved' }), | ||
2: expect.objectContaining({ status: 'rejected' }), | ||
3: expect.objectContaining({ status: 'resolved' }), | ||
}); | ||
|
||
const { results, errors } = await promisePool; | ||
|
||
// Check final reesuts | ||
expect(results).toEqual([1, 3]); | ||
expect(errors).toEqual([new Error(`Error processing 2`)]); | ||
}); | ||
|
||
it('should be possible to configure concurrency', async () => { | ||
const [promisePool, asyncTasks] = initPoolWithTasks({ | ||
concurrency: 2, | ||
items: [1, 2, 3, 4, 5], | ||
}); | ||
|
||
// Check that we have only two tasks pending initially as concurrency = 2 | ||
expect(asyncTasks).toEqual({ | ||
1: expect.objectContaining({ status: 'pending' }), | ||
2: expect.objectContaining({ status: 'pending' }), | ||
}); | ||
|
||
asyncTasks[1].resolve(); | ||
await nextTick(); | ||
|
||
// Check that after resolving the first task, the second and the third is pending | ||
expect(asyncTasks).toEqual({ | ||
1: expect.objectContaining({ status: 'resolved' }), | ||
2: expect.objectContaining({ status: 'pending' }), | ||
3: expect.objectContaining({ status: 'pending' }), | ||
}); | ||
|
||
asyncTasks[2].reject(); | ||
asyncTasks[3].reject(); | ||
await nextTick(); | ||
|
||
// Check that after rejecting the second and the third tasks, the rest are pending | ||
expect(asyncTasks).toEqual({ | ||
1: expect.objectContaining({ status: 'resolved' }), | ||
2: expect.objectContaining({ status: 'rejected' }), | ||
3: expect.objectContaining({ status: 'rejected' }), | ||
4: expect.objectContaining({ status: 'pending' }), | ||
5: expect.objectContaining({ status: 'pending' }), | ||
}); | ||
|
||
asyncTasks[4].resolve(); | ||
asyncTasks[5].resolve(); | ||
await nextTick(); | ||
|
||
// Check that all taks have been settled | ||
expect(asyncTasks).toEqual({ | ||
1: expect.objectContaining({ status: 'resolved' }), | ||
2: expect.objectContaining({ status: 'rejected' }), | ||
3: expect.objectContaining({ status: 'rejected' }), | ||
4: expect.objectContaining({ status: 'resolved' }), | ||
5: expect.objectContaining({ status: 'resolved' }), | ||
}); | ||
|
||
const { results, errors } = await promisePool; | ||
|
||
// Check final reesuts | ||
expect(results).toEqual([1, 4, 5]); | ||
expect(errors).toEqual([new Error(`Error processing 2`), new Error(`Error processing 3`)]); | ||
}); | ||
}); |
58 changes: 58 additions & 0 deletions
58
x-pack/plugins/security_solution/server/utils/promise_pool.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
/* | ||
* 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. | ||
*/ | ||
|
||
interface PromisePoolArgs<Item, Result> { | ||
concurrency?: number; | ||
items: Item[]; | ||
executor: (item: Item) => Promise<Result>; | ||
} | ||
|
||
/** | ||
* Runs promises in batches. It ensures that the number of running async tasks | ||
* doesn't exceed the concurrency parameter passed to the function. | ||
* | ||
* @param concurrency - number of tasks run in parallel | ||
* @param items - array of items to be passes to async executor | ||
* @param executor - an async function to be called with each provided item | ||
* | ||
* @returns Struct holding results or errors of async tasks | ||
*/ | ||
export const initPromisePool = async <Item, Result>({ | ||
concurrency = 1, | ||
items, | ||
executor, | ||
}: PromisePoolArgs<Item, Result>) => { | ||
const tasks: Array<Promise<void>> = []; | ||
const results: Result[] = []; | ||
const errors: unknown[] = []; | ||
|
||
for (const item of items) { | ||
// Check if the pool is full | ||
if (tasks.length >= concurrency) { | ||
// Wait for any first task to finish | ||
await Promise.race(tasks); | ||
} | ||
|
||
const task: Promise<void> = executor(item) | ||
.then((result) => { | ||
results.push(result); | ||
}) | ||
.catch(async (error) => { | ||
errors.push(error); | ||
}) | ||
.finally(() => { | ||
tasks.splice(tasks.indexOf(task), 1); | ||
}); | ||
|
||
tasks.push(task); | ||
} | ||
|
||
// Wait for all remaining tasks to finish | ||
await Promise.all(tasks); | ||
|
||
return { results, errors }; | ||
}; |