From 8d7fbb730662b4301bc983930f703da60153f059 Mon Sep 17 00:00:00 2001 From: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> Date: Wed, 4 Sep 2024 18:49:42 +1000 Subject: [PATCH 01/48] skip failing test suite (#192023) --- .../test_suites/task_manager/task_partitions.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/task_manager_claimer_mget/test_suites/task_manager/task_partitions.ts b/x-pack/test/task_manager_claimer_mget/test_suites/task_manager/task_partitions.ts index 5a4f956655ab3..bc8cde3877673 100644 --- a/x-pack/test/task_manager_claimer_mget/test_suites/task_manager/task_partitions.ts +++ b/x-pack/test/task_manager_claimer_mget/test_suites/task_manager/task_partitions.ts @@ -115,7 +115,8 @@ export default function ({ getService }: FtrProviderContext) { .then((result) => (result as unknown as SearchResults).hits.hits); } - describe('task partitions', () => { + // Failing: See https://github.com/elastic/kibana/issues/192023 + describe.skip('task partitions', () => { beforeEach(async () => { const exists = await es.indices.exists({ index: testHistoryIndex }); if (exists) { From 7aae05da09be053679bf74205ffb906be4f0409f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Loix?= Date: Wed, 4 Sep 2024 10:03:14 +0100 Subject: [PATCH 02/48] [Stateful sidenav] Add ML group menu in oblt & search (#190682) --- .../ui/components/navigation_section_ui.tsx | 2 +- .../observability/public/navigation_tree.ts | 129 ++++++++++++++++++ .../tests/observability_sidenav.ts | 2 +- 3 files changed, 131 insertions(+), 2 deletions(-) diff --git a/packages/shared-ux/chrome/navigation/src/ui/components/navigation_section_ui.tsx b/packages/shared-ux/chrome/navigation/src/ui/components/navigation_section_ui.tsx index 6a53239590d92..0d1814828369f 100644 --- a/packages/shared-ux/chrome/navigation/src/ui/components/navigation_section_ui.tsx +++ b/packages/shared-ux/chrome/navigation/src/ui/components/navigation_section_ui.tsx @@ -342,7 +342,7 @@ function nodeToEuiCollapsibleNavProps( if (renderAs === 'panelOpener') { // Render as a panel opener (button to open a panel as a second navigation) return { - items: [...renderPanelOpener(navNode, deps)], + items: [...renderPanelOpener(navNode, { spaceBefore, ...deps })], isVisible: true, }; } diff --git a/x-pack/plugins/observability_solution/observability/public/navigation_tree.ts b/x-pack/plugins/observability_solution/observability/public/navigation_tree.ts index 65256a1584461..9a064af35d3e8 100644 --- a/x-pack/plugins/observability_solution/observability/public/navigation_tree.ts +++ b/x-pack/plugins/observability_solution/observability/public/navigation_tree.ts @@ -338,6 +338,135 @@ const navTree: NavigationTreeDefinition = { { link: 'fleet', }, + { + id: 'machine_learning-landing', + link: 'securitySolutionUI:machine_learning-landing', + renderAs: 'panelOpener', + spaceBefore: null, + children: [ + { + children: [ + { + link: 'ml:overview', + }, + { + link: 'ml:notifications', + }, + { + link: 'ml:memoryUsage', + }, + ], + }, + { + id: 'category-anomaly_detection', + title: i18n.translate('xpack.observability.obltNav.ml.anomaly_detection', { + defaultMessage: 'Anomaly detection', + }), + breadcrumbStatus: 'hidden', + children: [ + { + link: 'ml:anomalyDetection', + title: i18n.translate('xpack.observability.obltNav.ml.anomaly_detection.jobs', { + defaultMessage: 'Jobs', + }), + }, + { + link: 'ml:anomalyExplorer', + }, + { + link: 'ml:singleMetricViewer', + }, + { + link: 'ml:settings', + }, + ], + }, + { + id: 'category-data_frame analytics', + title: i18n.translate('xpack.observability.obltNav.ml.data_frame_analytics', { + defaultMessage: 'Data frame analytics', + }), + breadcrumbStatus: 'hidden', + children: [ + { + link: 'ml:dataFrameAnalytics', + title: i18n.translate( + 'xpack.observability.obltNav.ml.data_frame_analytics.jobs', + { + defaultMessage: 'Jobs', + } + ), + }, + { + link: 'ml:resultExplorer', + }, + { + link: 'ml:analyticsMap', + }, + ], + }, + { + id: 'category-model_management', + title: i18n.translate('xpack.observability.obltNav.ml.model_management', { + defaultMessage: 'Model management', + }), + breadcrumbStatus: 'hidden', + children: [ + { + link: 'ml:nodesOverview', + }, + ], + }, + { + id: 'category-data_visualizer', + title: i18n.translate('xpack.observability.obltNav.ml.data_visualizer', { + defaultMessage: 'Data visualizer', + }), + breadcrumbStatus: 'hidden', + children: [ + { + link: 'ml:fileUpload', + title: i18n.translate( + 'xpack.observability.obltNav.ml.data_visualizer.file_data_visualizer', + { + defaultMessage: 'File data visualizer', + } + ), + }, + { + link: 'ml:indexDataVisualizer', + title: i18n.translate( + 'xpack.observability.obltNav.ml.data_visualizer.file_data_visualizer', + { + defaultMessage: 'Data view data visualizer', + } + ), + }, + { + link: 'ml:dataDrift', + }, + ], + }, + { + id: 'category-aiops_labs', + title: i18n.translate('xpack.observability.obltNav.ml.aiops_labs', { + defaultMessage: 'Aiops labs', + }), + breadcrumbStatus: 'hidden', + children: [ + { + link: 'ml:logRateAnalysis', + }, + { + link: 'ml:logPatternAnalysis', + }, + { + link: 'ml:changePointDetections', + }, + ], + }, + ], + }, { id: 'cloudLinkUserAndRoles', cloudLink: 'userAndRoles', diff --git a/x-pack/test/functional_solution_sidenav/tests/observability_sidenav.ts b/x-pack/test/functional_solution_sidenav/tests/observability_sidenav.ts index 9e4db0c33da52..c21844d851dce 100644 --- a/x-pack/test/functional_solution_sidenav/tests/observability_sidenav.ts +++ b/x-pack/test/functional_solution_sidenav/tests/observability_sidenav.ts @@ -52,7 +52,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await solutionNavigation.sidenav.openSection('observability_project_nav.aiMl'); // open AI & ML subsection await solutionNavigation.sidenav.clickLink({ deepLinkId: 'ml:anomalyDetection' }); await solutionNavigation.sidenav.expectLinkActive({ deepLinkId: 'ml:anomalyDetection' }); - await solutionNavigation.breadcrumbs.expectBreadcrumbExists({ text: 'AI & ML' }); + await solutionNavigation.breadcrumbs.expectBreadcrumbExists({ text: 'Anomaly Detection' }); await solutionNavigation.breadcrumbs.expectBreadcrumbExists({ deepLinkId: 'ml:anomalyDetection', }); From 760958fed9273d05c4f74c7ded9812d757987c24 Mon Sep 17 00:00:00 2001 From: Julian Gernun <17549662+jcger@users.noreply.github.com> Date: Wed, 4 Sep 2024 11:13:00 +0200 Subject: [PATCH 03/48] [Response Ops][Cases] Flaky Cases List Row Actions Update (#192058) Fixes https://github.com/elastic/kibana/issues/191242 Toasts are stacking up until covering the row action to be clicked next. This PR dismiss every toast created after each test. In the status update test this might happen as well and therefore I did add the toast dismissal to the whole row actions test suite. Screenshot 4 --- .../functional/test_suites/observability/cases/list_view.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/x-pack/test_serverless/functional/test_suites/observability/cases/list_view.ts b/x-pack/test_serverless/functional/test_suites/observability/cases/list_view.ts index 0605df54825e2..64d28534e8a90 100644 --- a/x-pack/test_serverless/functional/test_suites/observability/cases/list_view.ts +++ b/x-pack/test_serverless/functional/test_suites/observability/cases/list_view.ts @@ -211,6 +211,10 @@ export default ({ getPageObject, getService }: FtrProviderContext) => { }); describe('row actions', () => { + afterEach(async () => { + await toasts.dismissAll(); + }); + describe('Status', () => { createNCasesBeforeDeleteAllAfter(1, getPageObject, getService); @@ -258,7 +262,6 @@ export default ({ getPageObject, getService }: FtrProviderContext) => { createNCasesBeforeDeleteAllAfter(1, getPageObject, getService); it('deletes a case correctly', async () => { - await toasts.dismissAll(); await cases.casesTable.deleteCase(0); await cases.casesTable.waitForTableToFinishLoading(); await cases.casesTable.validateCasesTableHasNthRows(0); From c5242d7e5bc3a9b4123dfb83e49a568abd3e440d Mon Sep 17 00:00:00 2001 From: natasha-moore-elastic <137783811+natasha-moore-elastic@users.noreply.github.com> Date: Wed, 4 Sep 2024 10:29:27 +0100 Subject: [PATCH 04/48] Improves Endpoint management API docs content (#191932) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Resolves https://github.com/elastic/security-docs-internal/issues/37 by improving the Endpoint management API docs content. Adds missing and improves existing operation summaries and operation descriptions to adhere to our [OAS standards](https://elasticco.atlassian.net/wiki/spaces/DOC/pages/450494532/API+reference+docs). **Note**: Couldn’t add descriptions for the following operations, since they’re not documented in [ESS API docs](https://www.elastic.co/guide/en/security/8.15/management-api-overview.html): - POST /api/endpoint/protection_updates_note/{package_policy_id} - GET /api/endpoint/protection_updates_note/{package_policy_id} - GET /api/endpoint/policy/summaries - GET /api/endpoint/policy_response - POST /api/endpoint/suggestions/{suggestion_type} - GET /api/endpoint/metadata - GET /api/endpoint/metadata/{id} - GET /api/endpoint/metadata/transforms --------- Co-authored-by: Ash <1849116+ashokaditya@users.noreply.github.com> Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com> --- .../deprecated_action_log.schema.yaml | 4 +- .../actions/details/details.schema.yaml | 4 +- .../file_download/file_download.schema.yaml | 6 +- .../actions/file_info/file_info.schema.yaml | 6 +- .../endpoint/actions/list/list.schema.yaml | 4 +- .../execute/execute.schema.yaml | 4 +- .../get_file/get_file.schema.yaml | 4 +- .../isolate/deprecated_isolate.schema.yaml | 6 +- .../isolate/isolate.schema.yaml | 4 +- .../kill_process/kill_process.schema.yaml | 4 +- .../running_procs/running_procs.schema.yaml | 4 +- .../response_actions/scan/scan.schema.yaml | 4 +- .../suspend_process.schema.yaml | 4 +- .../deprecated_unisolate.schema.yaml | 6 +- .../unisolate/unisolate.schema.yaml | 4 +- .../upload/upload.schema.yaml | 4 +- .../endpoint/actions/state/state.schema.yaml | 3 +- .../actions/status/status.schema.yaml | 4 +- .../metadata/get_metadata.schema.yaml | 6 +- ...eprecated_agent_policy_summary.schema.yaml | 2 +- .../policy/policy_response.schema.yaml | 2 +- .../protection_updates_note.schema.yaml | 4 +- ...agement_api_2023_10_31.bundled.schema.yaml | 107 +++++++++++------- ...agement_api_2023_10_31.bundled.schema.yaml | 89 ++++++++------- .../services/security_solution_api.gen.ts | 50 ++++---- 25 files changed, 192 insertions(+), 147 deletions(-) diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/action_log/deprecated_action_log.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/action_log/deprecated_action_log.schema.yaml index d46a1cbe7d9ba..783fc4794f8bc 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/action_log/deprecated_action_log.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/action_log/deprecated_action_log.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action_log/{agent_id}: get: - summary: Get action requests log schema + summary: Get an action request log operationId: EndpointGetActionLog - description: Get action requests log + description: Get an action request log for the specified agent ID. deprecated: true x-codegen-enabled: false x-labels: [ess, serverless] diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/details/details.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/details/details.schema.yaml index ec3a184e6e9a9..7cf2f808e06f8 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/details/details.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/details/details.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action/{action_id}: get: - summary: Get Action details schema + summary: Get action details operationId: EndpointGetActionsDetails - description: Get action details + description: Get the details of a response action using the action ID. x-codegen-enabled: true x-labels: [ess, serverless] parameters: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/file_download/file_download.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/file_download/file_download.schema.yaml index 8842d1b6acc61..a17baf34b782d 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/file_download/file_download.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/file_download/file_download.schema.yaml @@ -3,11 +3,11 @@ info: title: File Download Schema version: '2023-10-31' paths: - /api/endpoint/action/{action_id}/file/{file_id}/download`: + /api/endpoint/action/{action_id}/file/{file_id}/download: get: - summary: File Download schema + summary: Download a file operationId: EndpointFileDownload - description: Download a file from an endpoint + description: Download a file from an endpoint. x-codegen-enabled: true x-labels: [ess, serverless] parameters: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/file_info/file_info.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/file_info/file_info.schema.yaml index 6199dc56ed1b0..5552ff2054772 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/file_info/file_info.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/file_info/file_info.schema.yaml @@ -3,11 +3,11 @@ info: title: File Info Schema version: '2023-10-31' paths: - /api/endpoint/action/{action_id}/file/{file_id}`: + /api/endpoint/action/{action_id}/file/{file_id}: get: - summary: File Info schema + summary: Get file information operationId: EndpointFileInfo - description: Get file info + description: Get information for the specified file using the file ID. x-codegen-enabled: true x-labels: [ess, serverless] parameters: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/list/list.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/list/list.schema.yaml index b91ba03c60b8d..8e7dcfd5412f4 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/list/list.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/list/list.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action: get: - summary: Get Actions List schema + summary: Get response actions operationId: EndpointGetActionsList - description: Get a list of action requests and their responses + description: Get a list of all response actions. x-codegen-enabled: true x-labels: [ess, serverless] parameters: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/execute/execute.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/execute/execute.schema.yaml index beafae76a4ba6..f2496687b8fb0 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/execute/execute.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/execute/execute.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action/execute: post: - summary: Execute Action + summary: Run a command operationId: EndpointExecuteAction - description: Execute a given command on an endpoint + description: Run a shell command on an endpoint. x-codegen-enabled: true x-labels: [ess, serverless] requestBody: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/get_file/get_file.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/get_file/get_file.schema.yaml index a5211580d7e42..cc36b843110b8 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/get_file/get_file.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/get_file/get_file.schema.yaml @@ -6,9 +6,9 @@ info: paths: /api/endpoint/action/get_file: post: - summary: Get File Action + summary: Get a file operationId: EndpointGetFileAction - description: Get a file from an endpoint + description: Get a file from an endpoint. x-codegen-enabled: true x-labels: [ess, serverless] requestBody: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/isolate/deprecated_isolate.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/isolate/deprecated_isolate.schema.yaml index 89d97c948c5d9..6b6b6c317265e 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/isolate/deprecated_isolate.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/isolate/deprecated_isolate.schema.yaml @@ -5,7 +5,11 @@ info: paths: /api/endpoint/isolate: post: - summary: Permanently redirects to a new location + summary: Isolate an endpoint + description: | + Isolate an endpoint from the network. + > info + > This URL will return a 308 permanent redirect to `POST :/api/endpoint/action/isolate`. operationId: EndpointIsolateRedirect deprecated: true x-codegen-enabled: true diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/isolate/isolate.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/isolate/isolate.schema.yaml index f721c69efa570..5bfd57a4e406d 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/isolate/isolate.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/isolate/isolate.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action/isolate: post: - summary: Isolate Action + summary: Isolate an endpoint operationId: EndpointIsolateAction - description: Isolate an endpoint + description: Isolate an endpoint from the network. The endpoint remains isolated until it's released. x-codegen-enabled: true x-labels: [ess, serverless] requestBody: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/kill_process/kill_process.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/kill_process/kill_process.schema.yaml index 0014026664fe2..65b2e0a4be1b0 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/kill_process/kill_process.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/kill_process/kill_process.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action/kill_process: post: - summary: Kill process Action + summary: Terminate a process operationId: EndpointKillProcessAction - description: Kill a running process on an endpoint + description: Terminate a running process on an endpoint. x-codegen-enabled: true x-labels: [ess, serverless] requestBody: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/running_procs/running_procs.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/running_procs/running_procs.schema.yaml index 0d5ced3b205f4..d49af9a84bc8e 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/running_procs/running_procs.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/running_procs/running_procs.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action/running_procs: post: - summary: Get Running Processes Action + summary: Get running processes operationId: EndpointGetProcessesAction - description: Get list of running processes on an endpoint + description: Get a list of all processes running on an endpoint. x-codegen-enabled: true x-labels: [ess, serverless] requestBody: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/scan/scan.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/scan/scan.schema.yaml index beea986e4546c..7ebf23a51ad7a 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/scan/scan.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/scan/scan.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action/scan: post: - summary: Scan Action + summary: Scan a file or directory operationId: EndpointScanAction - description: Scan a file or directory + description: Scan a specific file or directory on an endpoint for malware. x-codegen-enabled: true x-labels: [ess, serverless] requestBody: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/suspend_process/suspend_process.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/suspend_process/suspend_process.schema.yaml index f5f5b1e46ed2d..1ca77ee262442 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/suspend_process/suspend_process.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/suspend_process/suspend_process.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action/suspend_process: post: - summary: Suspend process Action + summary: Suspend a process operationId: EndpointSuspendProcessAction - description: Suspend a running process on an endpoint + description: Suspend a running process on an endpoint. x-codegen-enabled: true x-labels: [ess, serverless] requestBody: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/unisolate/deprecated_unisolate.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/unisolate/deprecated_unisolate.schema.yaml index 1d347f90fed44..f8504193cc060 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/unisolate/deprecated_unisolate.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/unisolate/deprecated_unisolate.schema.yaml @@ -5,7 +5,11 @@ info: paths: /api/endpoint/unisolate: post: - summary: Permanently redirects to a new location + summary: Release an isolated endpoint + description: | + Release an isolated endpoint, allowing it to rejoin a network. + > info + > This URL will return a 308 permanent redirect to `POST :/api/endpoint/action/unisolate`. operationId: EndpointUnisolateRedirect deprecated: true x-codegen-enabled: true diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/unisolate/unisolate.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/unisolate/unisolate.schema.yaml index 6c12a21f3241a..344f1c89eb096 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/unisolate/unisolate.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/unisolate/unisolate.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action/unisolate: post: - summary: Unisolate Action + summary: Release an isolated endpoint operationId: EndpointUnisolateAction - description: Release an endpoint + description: Release an isolated endpoint, allowing it to rejoin a network. x-codegen-enabled: true x-labels: [ess, serverless] requestBody: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/upload/upload.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/upload/upload.schema.yaml index ff62065ae5403..512fc6c4d4613 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/upload/upload.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/response_actions/upload/upload.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action/upload: post: - summary: Upload Action + summary: Upload a file operationId: EndpointUploadAction - description: Upload a file to an endpoint + description: Upload a file to an endpoint. x-codegen-enabled: true x-labels: [ess, serverless] requestBody: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/state/state.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/state/state.schema.yaml index f97bd90104cfb..467cc3e7e93d8 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/state/state.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/state/state.schema.yaml @@ -5,7 +5,8 @@ info: paths: /api/endpoint/action/state: get: - summary: Get Action State schema + summary: Get actions state + description: Get a response actions state, which reports whether encryption is enabled. operationId: EndpointGetActionsState x-codegen-enabled: true x-labels: [ess, serverless] diff --git a/x-pack/plugins/security_solution/common/api/endpoint/actions/status/status.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/actions/status/status.schema.yaml index 235cd87be0219..5d75a8a17faee 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/actions/status/status.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/actions/status/status.schema.yaml @@ -5,9 +5,9 @@ info: paths: /api/endpoint/action_status: get: - summary: Get Actions status schema + summary: Get response actions status operationId: EndpointGetActionsStatus - description: Get action status + description: Get the status of response actions for the specified agent IDs. x-codegen-enabled: true x-labels: [ess, serverless] parameters: diff --git a/x-pack/plugins/security_solution/common/api/endpoint/metadata/get_metadata.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/metadata/get_metadata.schema.yaml index 5ecea044053d2..680eb1b3be7ed 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/metadata/get_metadata.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/metadata/get_metadata.schema.yaml @@ -5,7 +5,7 @@ info: paths: /api/endpoint/metadata: get: - summary: Get Metadata List schema + summary: Get a metadata list operationId: GetEndpointMetadataList x-codegen-enabled: true x-labels: [ess, serverless] @@ -25,7 +25,7 @@ paths: /api/endpoint/metadata/transforms: get: - summary: Get Metadata Transform schema + summary: Get metadata transforms operationId: GetEndpointMetadataTransform x-codegen-enabled: false x-labels: [ess, serverless] @@ -39,7 +39,7 @@ paths: /api/endpoint/metadata/{id}: get: - summary: Get Metadata schema + summary: Get metadata operationId: GetEndpointMetadata x-codegen-enabled: false x-labels: [ess, serverless] diff --git a/x-pack/plugins/security_solution/common/api/endpoint/policy/deprecated_agent_policy_summary.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/policy/deprecated_agent_policy_summary.schema.yaml index 803010a4e8268..4850a0010d27b 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/policy/deprecated_agent_policy_summary.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/policy/deprecated_agent_policy_summary.schema.yaml @@ -5,7 +5,7 @@ info: paths: /api/endpoint/policy/summaries: get: - summary: Get Agent Policy Summary schema + summary: Get an agent policy summary operationId: GetAgentPolicySummary deprecated: true x-codegen-enabled: true diff --git a/x-pack/plugins/security_solution/common/api/endpoint/policy/policy_response.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/policy/policy_response.schema.yaml index 7acc39013da85..b103fdd37aba2 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/policy/policy_response.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/policy/policy_response.schema.yaml @@ -5,7 +5,7 @@ info: paths: /api/endpoint/policy_response: get: - summary: Get Policy Response schema + summary: Get a policy response operationId: GetPolicyResponse x-codegen-enabled: true x-labels: [ess, serverless] diff --git a/x-pack/plugins/security_solution/common/api/endpoint/protection_updates_note/protection_updates_note.schema.yaml b/x-pack/plugins/security_solution/common/api/endpoint/protection_updates_note/protection_updates_note.schema.yaml index 44c02e417b185..e08e643bcb0b0 100644 --- a/x-pack/plugins/security_solution/common/api/endpoint/protection_updates_note/protection_updates_note.schema.yaml +++ b/x-pack/plugins/security_solution/common/api/endpoint/protection_updates_note/protection_updates_note.schema.yaml @@ -5,7 +5,7 @@ info: paths: /api/endpoint/protection_updates_note/{package_policy_id}: get: - summary: Get Protection Updates Note schema + summary: Get a protection updates note operationId: GetProtectionUpdatesNote x-codegen-enabled: true x-labels: [ess, serverless] @@ -23,7 +23,7 @@ paths: schema: $ref: '../model/schema/common.schema.yaml#/components/schemas/ProtectionUpdatesNoteResponse' post: - summary: Create Update Protection Updates Note schema + summary: Create or update a protection updates note operationId: CreateUpdateProtectionUpdatesNote x-codegen-enabled: true x-labels: [ess, serverless] diff --git a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml index 2f64b045cf7ff..384aa3147e87b 100644 --- a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml @@ -13,7 +13,7 @@ servers: paths: /api/endpoint/action: get: - description: Get a list of action requests and their responses + description: Get a list of all response actions. operationId: EndpointGetActionsList parameters: - in: query @@ -28,13 +28,13 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Actions List schema + summary: Get response actions tags: - Security Solution Endpoint Management API '/api/endpoint/action_log/{agent_id}': get: deprecated: true - description: Get action requests log + description: Get an action request log for the specified agent ID. operationId: EndpointGetActionLog parameters: - in: path @@ -54,12 +54,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get action requests log schema + summary: Get an action request log tags: - Security Solution Endpoint Management API /api/endpoint/action_status: get: - description: Get action status + description: Get the status of response actions for the specified agent IDs. operationId: EndpointGetActionsStatus parameters: - in: query @@ -77,12 +77,12 @@ paths: schema: $ref: '#/components/schemas/ActionStatusSuccessResponse' description: OK - summary: Get Actions status schema + summary: Get response actions status tags: - Security Solution Endpoint Management API '/api/endpoint/action/{action_id}': get: - description: Get action details + description: Get the details of a response action using the action ID. operationId: EndpointGetActionsDetails parameters: - in: path @@ -97,13 +97,13 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Action details schema + summary: Get action details tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}/file/{file_id}/download`': + '/api/endpoint/action/{action_id}/file/{file_id}': get: - description: Download a file from an endpoint - operationId: EndpointFileDownload + description: Get information for the specified file using the file ID. + operationId: EndpointFileInfo parameters: - in: path name: action_id @@ -122,13 +122,13 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: File Download schema + summary: Get file information tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}/file/{file_id}`': + '/api/endpoint/action/{action_id}/file/{file_id}/download': get: - description: Get file info - operationId: EndpointFileInfo + description: Download a file from an endpoint. + operationId: EndpointFileDownload parameters: - in: path name: action_id @@ -147,12 +147,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: File Info schema + summary: Download a file tags: - Security Solution Endpoint Management API /api/endpoint/action/execute: post: - description: Execute a given command on an endpoint + description: Run a shell command on an endpoint. operationId: EndpointExecuteAction requestBody: content: @@ -167,12 +167,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Execute Action + summary: Run a command tags: - Security Solution Endpoint Management API /api/endpoint/action/get_file: post: - description: Get a file from an endpoint + description: Get a file from an endpoint. operationId: EndpointGetFileAction requestBody: content: @@ -187,12 +187,14 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get File Action + summary: Get a file tags: - Security Solution Endpoint Management API /api/endpoint/action/isolate: post: - description: Isolate an endpoint + description: >- + Isolate an endpoint from the network. The endpoint remains isolated + until it's released. operationId: EndpointIsolateAction requestBody: content: @@ -207,12 +209,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Isolate Action + summary: Isolate an endpoint tags: - Security Solution Endpoint Management API /api/endpoint/action/kill_process: post: - description: Kill a running process on an endpoint + description: Terminate a running process on an endpoint. operationId: EndpointKillProcessAction requestBody: content: @@ -227,12 +229,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Kill process Action + summary: Terminate a process tags: - Security Solution Endpoint Management API /api/endpoint/action/running_procs: post: - description: Get list of running processes on an endpoint + description: Get a list of all processes running on an endpoint. operationId: EndpointGetProcessesAction requestBody: content: @@ -247,12 +249,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Running Processes Action + summary: Get running processes tags: - Security Solution Endpoint Management API /api/endpoint/action/scan: post: - description: Scan a file or directory + description: Scan a specific file or directory on an endpoint for malware. operationId: EndpointScanAction requestBody: content: @@ -267,11 +269,14 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Scan Action + summary: Scan a file or directory tags: - Security Solution Endpoint Management API /api/endpoint/action/state: get: + description: >- + Get a response actions state, which reports whether encryption is + enabled. operationId: EndpointGetActionsState responses: '200': @@ -280,12 +285,12 @@ paths: schema: $ref: '#/components/schemas/ActionStateSuccessResponse' description: OK - summary: Get Action State schema + summary: Get actions state tags: - Security Solution Endpoint Management API /api/endpoint/action/suspend_process: post: - description: Suspend a running process on an endpoint + description: Suspend a running process on an endpoint. operationId: EndpointSuspendProcessAction requestBody: content: @@ -300,12 +305,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Suspend process Action + summary: Suspend a process tags: - Security Solution Endpoint Management API /api/endpoint/action/unisolate: post: - description: Release an endpoint + description: 'Release an isolated endpoint, allowing it to rejoin a network.' operationId: EndpointUnisolateAction requestBody: content: @@ -320,12 +325,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Unisolate Action + summary: Release an isolated endpoint tags: - Security Solution Endpoint Management API /api/endpoint/action/upload: post: - description: Upload a file to an endpoint + description: Upload a file to an endpoint. operationId: EndpointUploadAction requestBody: content: @@ -340,12 +345,19 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Upload Action + summary: Upload a file tags: - Security Solution Endpoint Management API /api/endpoint/isolate: post: deprecated: true + description: > + Isolate an endpoint from the network. + + > info + + > This URL will return a 308 permanent redirect to `POST :/api/endpoint/action/isolate`. operationId: EndpointIsolateRedirect requestBody: content: @@ -383,7 +395,7 @@ paths: schema: example: /api/endpoint/action/isolate type: string - summary: Permanently redirects to a new location + summary: Isolate an endpoint tags: - Security Solution Endpoint Management API /api/endpoint/metadata: @@ -402,7 +414,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Metadata List schema + summary: Get a metadata list tags: - Security Solution Endpoint Management API '/api/endpoint/metadata/{id}': @@ -421,7 +433,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Metadata schema + summary: Get metadata tags: - Security Solution Endpoint Management API /api/endpoint/metadata/transforms: @@ -434,7 +446,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Metadata Transform schema + summary: Get metadata transforms tags: - Security Solution Endpoint Management API /api/endpoint/policy_response: @@ -456,7 +468,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Policy Response schema + summary: Get a policy response tags: - Security Solution Endpoint Management API /api/endpoint/policy/summaries: @@ -482,7 +494,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Agent Policy Summary schema + summary: Get an agent policy summary tags: - Security Solution Endpoint Management API '/api/endpoint/protection_updates_note/{package_policy_id}': @@ -501,7 +513,7 @@ paths: schema: $ref: '#/components/schemas/ProtectionUpdatesNoteResponse' description: OK - summary: Get Protection Updates Note schema + summary: Get a protection updates note tags: - Security Solution Endpoint Management API post: @@ -528,7 +540,7 @@ paths: schema: $ref: '#/components/schemas/ProtectionUpdatesNoteResponse' description: OK - summary: Create Update Protection Updates Note schema + summary: Create or update a protection updates note tags: - Security Solution Endpoint Management API '/api/endpoint/suggestions/{suggestion_type}': @@ -570,6 +582,13 @@ paths: /api/endpoint/unisolate: post: deprecated: true + description: > + Release an isolated endpoint, allowing it to rejoin a network. + + > info + + > This URL will return a 308 permanent redirect to `POST :/api/endpoint/action/unisolate`. operationId: EndpointUnisolateRedirect requestBody: content: @@ -607,7 +626,7 @@ paths: schema: example: /api/endpoint/action/unisolate type: string - summary: Permanently redirects to a new location + summary: Release an isolated endpoint tags: - Security Solution Endpoint Management API components: diff --git a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml index cb1c177e78bf8..87ee066125354 100644 --- a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml @@ -13,7 +13,7 @@ servers: paths: /api/endpoint/action: get: - description: Get a list of action requests and their responses + description: Get a list of all response actions. operationId: EndpointGetActionsList parameters: - in: query @@ -28,13 +28,13 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Actions List schema + summary: Get response actions tags: - Security Solution Endpoint Management API '/api/endpoint/action_log/{agent_id}': get: deprecated: true - description: Get action requests log + description: Get an action request log for the specified agent ID. operationId: EndpointGetActionLog parameters: - in: path @@ -54,12 +54,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get action requests log schema + summary: Get an action request log tags: - Security Solution Endpoint Management API /api/endpoint/action_status: get: - description: Get action status + description: Get the status of response actions for the specified agent IDs. operationId: EndpointGetActionsStatus parameters: - in: query @@ -77,12 +77,12 @@ paths: schema: $ref: '#/components/schemas/ActionStatusSuccessResponse' description: OK - summary: Get Actions status schema + summary: Get response actions status tags: - Security Solution Endpoint Management API '/api/endpoint/action/{action_id}': get: - description: Get action details + description: Get the details of a response action using the action ID. operationId: EndpointGetActionsDetails parameters: - in: path @@ -97,13 +97,13 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Action details schema + summary: Get action details tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}/file/{file_id}/download`': + '/api/endpoint/action/{action_id}/file/{file_id}': get: - description: Download a file from an endpoint - operationId: EndpointFileDownload + description: Get information for the specified file using the file ID. + operationId: EndpointFileInfo parameters: - in: path name: action_id @@ -122,13 +122,13 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: File Download schema + summary: Get file information tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}/file/{file_id}`': + '/api/endpoint/action/{action_id}/file/{file_id}/download': get: - description: Get file info - operationId: EndpointFileInfo + description: Download a file from an endpoint. + operationId: EndpointFileDownload parameters: - in: path name: action_id @@ -147,12 +147,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: File Info schema + summary: Download a file tags: - Security Solution Endpoint Management API /api/endpoint/action/execute: post: - description: Execute a given command on an endpoint + description: Run a shell command on an endpoint. operationId: EndpointExecuteAction requestBody: content: @@ -167,12 +167,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Execute Action + summary: Run a command tags: - Security Solution Endpoint Management API /api/endpoint/action/get_file: post: - description: Get a file from an endpoint + description: Get a file from an endpoint. operationId: EndpointGetFileAction requestBody: content: @@ -187,12 +187,14 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get File Action + summary: Get a file tags: - Security Solution Endpoint Management API /api/endpoint/action/isolate: post: - description: Isolate an endpoint + description: >- + Isolate an endpoint from the network. The endpoint remains isolated + until it's released. operationId: EndpointIsolateAction requestBody: content: @@ -207,12 +209,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Isolate Action + summary: Isolate an endpoint tags: - Security Solution Endpoint Management API /api/endpoint/action/kill_process: post: - description: Kill a running process on an endpoint + description: Terminate a running process on an endpoint. operationId: EndpointKillProcessAction requestBody: content: @@ -227,12 +229,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Kill process Action + summary: Terminate a process tags: - Security Solution Endpoint Management API /api/endpoint/action/running_procs: post: - description: Get list of running processes on an endpoint + description: Get a list of all processes running on an endpoint. operationId: EndpointGetProcessesAction requestBody: content: @@ -247,12 +249,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Running Processes Action + summary: Get running processes tags: - Security Solution Endpoint Management API /api/endpoint/action/scan: post: - description: Scan a file or directory + description: Scan a specific file or directory on an endpoint for malware. operationId: EndpointScanAction requestBody: content: @@ -267,11 +269,14 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Scan Action + summary: Scan a file or directory tags: - Security Solution Endpoint Management API /api/endpoint/action/state: get: + description: >- + Get a response actions state, which reports whether encryption is + enabled. operationId: EndpointGetActionsState responses: '200': @@ -280,12 +285,12 @@ paths: schema: $ref: '#/components/schemas/ActionStateSuccessResponse' description: OK - summary: Get Action State schema + summary: Get actions state tags: - Security Solution Endpoint Management API /api/endpoint/action/suspend_process: post: - description: Suspend a running process on an endpoint + description: Suspend a running process on an endpoint. operationId: EndpointSuspendProcessAction requestBody: content: @@ -300,12 +305,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Suspend process Action + summary: Suspend a process tags: - Security Solution Endpoint Management API /api/endpoint/action/unisolate: post: - description: Release an endpoint + description: 'Release an isolated endpoint, allowing it to rejoin a network.' operationId: EndpointUnisolateAction requestBody: content: @@ -320,12 +325,12 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Unisolate Action + summary: Release an isolated endpoint tags: - Security Solution Endpoint Management API /api/endpoint/action/upload: post: - description: Upload a file to an endpoint + description: Upload a file to an endpoint. operationId: EndpointUploadAction requestBody: content: @@ -340,7 +345,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Upload Action + summary: Upload a file tags: - Security Solution Endpoint Management API /api/endpoint/metadata: @@ -359,7 +364,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Metadata List schema + summary: Get a metadata list tags: - Security Solution Endpoint Management API '/api/endpoint/metadata/{id}': @@ -378,7 +383,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Metadata schema + summary: Get metadata tags: - Security Solution Endpoint Management API /api/endpoint/metadata/transforms: @@ -391,7 +396,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Metadata Transform schema + summary: Get metadata transforms tags: - Security Solution Endpoint Management API /api/endpoint/policy_response: @@ -413,7 +418,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Policy Response schema + summary: Get a policy response tags: - Security Solution Endpoint Management API /api/endpoint/policy/summaries: @@ -439,7 +444,7 @@ paths: schema: $ref: '#/components/schemas/SuccessResponse' description: OK - summary: Get Agent Policy Summary schema + summary: Get an agent policy summary tags: - Security Solution Endpoint Management API '/api/endpoint/protection_updates_note/{package_policy_id}': @@ -458,7 +463,7 @@ paths: schema: $ref: '#/components/schemas/ProtectionUpdatesNoteResponse' description: OK - summary: Get Protection Updates Note schema + summary: Get a protection updates note tags: - Security Solution Endpoint Management API post: @@ -485,7 +490,7 @@ paths: schema: $ref: '#/components/schemas/ProtectionUpdatesNoteResponse' description: OK - summary: Create Update Protection Updates Note schema + summary: Create or update a protection updates note tags: - Security Solution Endpoint Management API '/api/endpoint/suggestions/{suggestion_type}': diff --git a/x-pack/test/api_integration/services/security_solution_api.gen.ts b/x-pack/test/api_integration/services/security_solution_api.gen.ts index b1df28bdf908c..0ba9936f4eb66 100644 --- a/x-pack/test/api_integration/services/security_solution_api.gen.ts +++ b/x-pack/test/api_integration/services/security_solution_api.gen.ts @@ -366,7 +366,7 @@ Migrations are initiated per index. While the process is neither destructive nor .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana'); }, /** - * Execute a given command on an endpoint + * Run a shell command on an endpoint. */ endpointExecuteAction(props: EndpointExecuteActionProps) { return supertest @@ -377,32 +377,29 @@ Migrations are initiated per index. While the process is neither destructive nor .send(props.body as object); }, /** - * Download a file from an endpoint + * Download a file from an endpoint. */ endpointFileDownload(props: EndpointFileDownloadProps) { return supertest .get( - replaceParams( - '/api/endpoint/action/{action_id}/file/{file_id}/download`', - props.params - ) + replaceParams('/api/endpoint/action/{action_id}/file/{file_id}/download', props.params) ) .set('kbn-xsrf', 'true') .set(ELASTIC_HTTP_VERSION_HEADER, '2023-10-31') .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana'); }, /** - * Get file info + * Get information for the specified file using the file ID. */ endpointFileInfo(props: EndpointFileInfoProps) { return supertest - .get(replaceParams('/api/endpoint/action/{action_id}/file/{file_id}`', props.params)) + .get(replaceParams('/api/endpoint/action/{action_id}/file/{file_id}', props.params)) .set('kbn-xsrf', 'true') .set(ELASTIC_HTTP_VERSION_HEADER, '2023-10-31') .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana'); }, /** - * Get action details + * Get the details of a response action using the action ID. */ endpointGetActionsDetails(props: EndpointGetActionsDetailsProps) { return supertest @@ -412,7 +409,7 @@ Migrations are initiated per index. While the process is neither destructive nor .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana'); }, /** - * Get a list of action requests and their responses + * Get a list of all response actions. */ endpointGetActionsList(props: EndpointGetActionsListProps) { return supertest @@ -422,6 +419,9 @@ Migrations are initiated per index. While the process is neither destructive nor .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana') .query(props.query); }, + /** + * Get a response actions state, which reports whether encryption is enabled. + */ endpointGetActionsState() { return supertest .get('/api/endpoint/action/state') @@ -430,7 +430,7 @@ Migrations are initiated per index. While the process is neither destructive nor .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana'); }, /** - * Get action status + * Get the status of response actions for the specified agent IDs. */ endpointGetActionsStatus(props: EndpointGetActionsStatusProps) { return supertest @@ -441,7 +441,7 @@ Migrations are initiated per index. While the process is neither destructive nor .query(props.query); }, /** - * Get a file from an endpoint + * Get a file from an endpoint. */ endpointGetFileAction(props: EndpointGetFileActionProps) { return supertest @@ -452,7 +452,7 @@ Migrations are initiated per index. While the process is neither destructive nor .send(props.body as object); }, /** - * Get list of running processes on an endpoint + * Get a list of all processes running on an endpoint. */ endpointGetProcessesAction(props: EndpointGetProcessesActionProps) { return supertest @@ -463,7 +463,7 @@ Migrations are initiated per index. While the process is neither destructive nor .send(props.body as object); }, /** - * Isolate an endpoint + * Isolate an endpoint from the network. The endpoint remains isolated until it's released. */ endpointIsolateAction(props: EndpointIsolateActionProps) { return supertest @@ -473,6 +473,12 @@ Migrations are initiated per index. While the process is neither destructive nor .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana') .send(props.body as object); }, + /** + * Isolate an endpoint from the network. +> info +> This URL will return a 308 permanent redirect to `POST :/api/endpoint/action/isolate`. + + */ endpointIsolateRedirect(props: EndpointIsolateRedirectProps) { return supertest .post('/api/endpoint/isolate') @@ -482,7 +488,7 @@ Migrations are initiated per index. While the process is neither destructive nor .send(props.body as object); }, /** - * Kill a running process on an endpoint + * Terminate a running process on an endpoint. */ endpointKillProcessAction(props: EndpointKillProcessActionProps) { return supertest @@ -493,7 +499,7 @@ Migrations are initiated per index. While the process is neither destructive nor .send(props.body as object); }, /** - * Scan a file or directory + * Scan a specific file or directory on an endpoint for malware. */ endpointScanAction(props: EndpointScanActionProps) { return supertest @@ -504,7 +510,7 @@ Migrations are initiated per index. While the process is neither destructive nor .send(props.body as object); }, /** - * Suspend a running process on an endpoint + * Suspend a running process on an endpoint. */ endpointSuspendProcessAction(props: EndpointSuspendProcessActionProps) { return supertest @@ -515,7 +521,7 @@ Migrations are initiated per index. While the process is neither destructive nor .send(props.body as object); }, /** - * Release an endpoint + * Release an isolated endpoint, allowing it to rejoin a network. */ endpointUnisolateAction(props: EndpointUnisolateActionProps) { return supertest @@ -525,6 +531,12 @@ Migrations are initiated per index. While the process is neither destructive nor .set(X_ELASTIC_INTERNAL_ORIGIN_REQUEST, 'kibana') .send(props.body as object); }, + /** + * Release an isolated endpoint, allowing it to rejoin a network. +> info +> This URL will return a 308 permanent redirect to `POST :/api/endpoint/action/unisolate`. + + */ endpointUnisolateRedirect(props: EndpointUnisolateRedirectProps) { return supertest .post('/api/endpoint/unisolate') @@ -534,7 +546,7 @@ Migrations are initiated per index. While the process is neither destructive nor .send(props.body as object); }, /** - * Upload a file to an endpoint + * Upload a file to an endpoint. */ endpointUploadAction(props: EndpointUploadActionProps) { return supertest From 4a59b49917f25f9933965cff90ac064c6127bfb2 Mon Sep 17 00:00:00 2001 From: Katerina Date: Wed, 4 Sep 2024 13:07:42 +0300 Subject: [PATCH 05/48] [APM][Refactor] Rename create_assets_es_client to create_entities_es_client (#192061) ## Summary Refactoring: Rename assets to entities --- .../create_entities_es_client.ts} | 0 .../routes/custom_dashboards/get_entities_with_dashboards.ts | 2 +- .../apm/server/routes/custom_dashboards/route.ts | 2 +- .../apm/server/routes/entities/get_entities.ts | 2 +- .../routes/entities/get_service_entities_history_metrics.ts | 2 +- .../routes/entities/get_service_entities_history_timeseries.ts | 2 +- .../apm/server/routes/entities/get_service_entity_summary.ts | 2 +- .../apm/server/routes/entities/get_service_latest_entity.ts | 2 +- .../apm/server/routes/entities/services/get_service_entities.ts | 2 +- .../apm/server/routes/entities/services/routes.ts | 2 +- .../routes/historical_data/has_historical_entities_data.ts | 2 +- .../apm/server/routes/historical_data/route.ts | 2 +- .../observability_solution/apm/server/routes/services/route.ts | 2 +- 13 files changed, 12 insertions(+), 12 deletions(-) rename x-pack/plugins/observability_solution/apm/server/lib/helpers/create_es_client/{create_assets_es_client/create_assets_es_clients.ts => create_entities_es_client/create_entities_es_client.ts} (100%) diff --git a/x-pack/plugins/observability_solution/apm/server/lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients.ts b/x-pack/plugins/observability_solution/apm/server/lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client.ts similarity index 100% rename from x-pack/plugins/observability_solution/apm/server/lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients.ts rename to x-pack/plugins/observability_solution/apm/server/lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client.ts diff --git a/x-pack/plugins/observability_solution/apm/server/routes/custom_dashboards/get_entities_with_dashboards.ts b/x-pack/plugins/observability_solution/apm/server/routes/custom_dashboards/get_entities_with_dashboards.ts index 0d5b443ae6d45..df1f785216367 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/custom_dashboards/get_entities_with_dashboards.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/custom_dashboards/get_entities_with_dashboards.ts @@ -9,7 +9,7 @@ import { kqlQuery, termQuery } from '@kbn/observability-plugin/server'; import { estypes } from '@elastic/elasticsearch'; import { SERVICE_NAME } from '../../../common/es_fields/apm'; import { SavedApmCustomDashboard } from '../../../common/custom_dashboards'; -import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; function getSearchRequest(filters: estypes.QueryDslQueryContainer[]) { return { diff --git a/x-pack/plugins/observability_solution/apm/server/routes/custom_dashboards/route.ts b/x-pack/plugins/observability_solution/apm/server/routes/custom_dashboards/route.ts index 4fcc1508715d1..750bacb4ba455 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/custom_dashboards/route.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/custom_dashboards/route.ts @@ -14,7 +14,7 @@ import { getCustomDashboards } from './get_custom_dashboards'; import { getServicesWithDashboards } from './get_services_with_dashboards'; import { getApmEventClient } from '../../lib/helpers/get_apm_event_client'; import { rangeRt } from '../default_api_types'; -import { createEntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { createEntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; import { getEntitiesWithDashboards } from './get_entities_with_dashboards'; const serviceDashboardSaveRoute = createApmServerRoute({ diff --git a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_entities.ts b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_entities.ts index a69a906454ff7..e3a40b698eb13 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_entities.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_entities.ts @@ -14,7 +14,7 @@ import { } from '../../../common/es_fields/apm'; import { FIRST_SEEN, LAST_SEEN, ENTITY, ENTITY_TYPE } from '../../../common/es_fields/entities'; import { environmentQuery } from '../../../common/utils/environment_query'; -import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; import { getServiceEntitiesHistoryMetrics } from './get_service_entities_history_metrics'; import { EntitiesRaw, EntityType, ServiceEntities } from './types'; import { isFiniteNumber } from '../../../common/utils/is_finite_number'; diff --git a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entities_history_metrics.ts b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entities_history_metrics.ts index 606c1748aa0a0..5355cfd8b563c 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entities_history_metrics.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entities_history_metrics.ts @@ -16,7 +16,7 @@ import { ENTITY_METRICS_THROUGHPUT, LAST_SEEN, } from '../../../common/es_fields/entities'; -import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; interface Params { entitiesESClient: EntitiesESClient; diff --git a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entities_history_timeseries.ts b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entities_history_timeseries.ts index 6e969b6022bf2..73811a544701b 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entities_history_timeseries.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entities_history_timeseries.ts @@ -17,7 +17,7 @@ import { LAST_SEEN, } from '../../../common/es_fields/entities'; import { SERVICE_NAME } from '../../../common/es_fields/apm'; -import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; import { environmentQuery } from '../../../common/utils/environment_query'; interface Params { diff --git a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entity_summary.ts b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entity_summary.ts index 37e3ddef9ecc0..84886272ba54a 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entity_summary.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_entity_summary.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; import { withApmSpan } from '../../utils/with_apm_span'; import { getServiceLatestEntity } from './get_service_latest_entity'; import { ServiceEntities } from './types'; diff --git a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_latest_entity.ts b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_latest_entity.ts index f4a4e4d1a81a4..71cead9a17301 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_latest_entity.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/entities/get_service_latest_entity.ts @@ -14,7 +14,7 @@ import { import { ENTITY, ENTITY_TYPE } from '../../../common/es_fields/entities'; import { environmentQuery } from '../../../common/utils/environment_query'; import { isFiniteNumber } from '../../../common/utils/is_finite_number'; -import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; import { entitiesRangeQuery } from './get_entities'; import { EntitiesRaw, EntityType, ServiceEntities } from './types'; diff --git a/x-pack/plugins/observability_solution/apm/server/routes/entities/services/get_service_entities.ts b/x-pack/plugins/observability_solution/apm/server/routes/entities/services/get_service_entities.ts index 0f90afb214cbf..084fbbe438952 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/entities/services/get_service_entities.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/entities/services/get_service_entities.ts @@ -7,7 +7,7 @@ import { errors } from '@elastic/elasticsearch'; import { Logger } from '@kbn/core/server'; import { WrappedElasticsearchClientError } from '@kbn/observability-plugin/server'; -import { EntitiesESClient } from '../../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { EntitiesESClient } from '../../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; import { withApmSpan } from '../../../utils/with_apm_span'; import { getEntities } from '../get_entities'; import { calculateAvgMetrics } from '../utils/calculate_avg_metrics'; diff --git a/x-pack/plugins/observability_solution/apm/server/routes/entities/services/routes.ts b/x-pack/plugins/observability_solution/apm/server/routes/entities/services/routes.ts index 027bd5bd09c98..fad2e495e8c6e 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/entities/services/routes.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/entities/services/routes.ts @@ -9,7 +9,7 @@ import { jsonRt } from '@kbn/io-ts-utils'; import * as t from 'io-ts'; import { EntityServiceListItem } from '../../../../common/entities/types'; import { environmentQuery } from '../../../../common/utils/environment_query'; -import { createEntitiesESClient } from '../../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { createEntitiesESClient } from '../../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; import { createApmServerRoute } from '../../apm_routes/create_apm_server_route'; import { environmentRt, kueryRt, rangeRt } from '../../default_api_types'; import { getServiceEntities } from './get_service_entities'; diff --git a/x-pack/plugins/observability_solution/apm/server/routes/historical_data/has_historical_entities_data.ts b/x-pack/plugins/observability_solution/apm/server/routes/historical_data/has_historical_entities_data.ts index 13c6ebcf7bfd9..f245c27a99036 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/historical_data/has_historical_entities_data.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/historical_data/has_historical_entities_data.ts @@ -7,7 +7,7 @@ import { WrappedElasticsearchClientError } from '@kbn/observability-plugin/server'; import { Logger } from '@kbn/core/server'; import { errors } from '@elastic/elasticsearch'; -import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { EntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; export async function hasEntitiesData(entitiesESClient: EntitiesESClient, logger: Logger) { const params = { diff --git a/x-pack/plugins/observability_solution/apm/server/routes/historical_data/route.ts b/x-pack/plugins/observability_solution/apm/server/routes/historical_data/route.ts index 484590a00a36e..94b7d40b84c2d 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/historical_data/route.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/historical_data/route.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { createEntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { createEntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; import { getApmEventClient } from '../../lib/helpers/get_apm_event_client'; import { createApmServerRoute } from '../apm_routes/create_apm_server_route'; import { hasHistoricalAgentData } from './has_historical_agent_data'; diff --git a/x-pack/plugins/observability_solution/apm/server/routes/services/route.ts b/x-pack/plugins/observability_solution/apm/server/routes/services/route.ts index f80c58c19ed93..1d4cbd0cef1c3 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/services/route.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/services/route.ts @@ -80,7 +80,7 @@ import { import { getThroughput, ServiceThroughputResponse } from './get_throughput'; import { getServiceEntitySummary } from '../entities/get_service_entity_summary'; import { ENVIRONMENT_ALL } from '../../../common/environment_filter_values'; -import { createEntitiesESClient } from '../../lib/helpers/create_es_client/create_assets_es_client/create_assets_es_clients'; +import { createEntitiesESClient } from '../../lib/helpers/create_es_client/create_entities_es_client/create_entities_es_client'; const servicesRoute = createApmServerRoute({ endpoint: 'GET /internal/apm/services', From 00230cfe0c23ccbdbbe217f549f64a45f24429a6 Mon Sep 17 00:00:00 2001 From: Alex Szabo Date: Wed, 4 Sep 2024 12:12:27 +0200 Subject: [PATCH 06/48] [CI] use kibana_install_dir from built artifacts (#191909) ## Summary I noticed recently, that the step "Copying ES Snapshot cache" got cancelled due to a lost agent. On closer inspection, it leads to the changed file (`.buildkite/scripts/steps/functional/osquery_cypress.sh`) where with a note, there's a kibana rebuild. Unless there's something special in that rebuild, we should be using the artifacts built in the build step. So let's follow the TODO notes, and use the downloaded artifacts - this should save ~6m per step where the osquery tests were warmed up. ## Before From [on-merge#49584](https://buildkite.com/elastic/kibana-on-merge/builds/49584), running the pre-PR version: - You can see, after the copying of es snapshot cache, the command to build kibana's plugins is ran, taking 6+ minutes Screenshot 2024-09-02 at 16 25 43 ## After This is on the [PR build](https://buildkite.com/elastic/kibana-pull-request/builds/231455#0191b2cc-f8be-410d-860d-59ab9f984477): - You can see, the es snapshot cache update is only 6 sec, after that, we can get going with the testing Screenshot 2024-09-02 at 16 28 10 ## Results On a primitive comparison between the PR build (https://buildkite.com/elastic/kibana-pull-request/builds/231505) and an on-merge run (https://buildkite.com/elastic/kibana-on-merge/builds/49598) we've **saved on average 9 minutes per runs** of `Osquery Cypress Tests`. We can only say more adequate savings once we compare on-merge with on-merge, but it can be estimated this would be **16 x 9 minutes = 144 minutes** (16 = 8 osquery cypress + 8 osquery serverless cypress) per on-merges. --- .buildkite/scripts/steps/functional/osquery_cypress.sh | 6 +----- .buildkite/scripts/steps/functional/osquery_cypress_burn.sh | 5 ++--- .../scripts/steps/functional/security_serverless_osquery.sh | 6 +----- 3 files changed, 4 insertions(+), 13 deletions(-) diff --git a/.buildkite/scripts/steps/functional/osquery_cypress.sh b/.buildkite/scripts/steps/functional/osquery_cypress.sh index 9ba7cabc4d1cb..0ae47edd8c8e7 100755 --- a/.buildkite/scripts/steps/functional/osquery_cypress.sh +++ b/.buildkite/scripts/steps/functional/osquery_cypress.sh @@ -4,11 +4,7 @@ set -euo pipefail source .buildkite/scripts/steps/functional/common.sh -# TODO: remove the line below to use build artifacts for tests. -# in addition to remove the line, we will have to expose the kibana install dir into the downloaded build location -# by exporting a var like: -# export KIBANA_INSTALL_DIR=${KIBANA_BUILD_LOCATION} -node scripts/build_kibana_platform_plugins.js +export KIBANA_INSTALL_DIR=${KIBANA_BUILD_LOCATION} export JOB=kibana-osquery-cypress diff --git a/.buildkite/scripts/steps/functional/osquery_cypress_burn.sh b/.buildkite/scripts/steps/functional/osquery_cypress_burn.sh index 8068dccac64f3..bebd391d95254 100755 --- a/.buildkite/scripts/steps/functional/osquery_cypress_burn.sh +++ b/.buildkite/scripts/steps/functional/osquery_cypress_burn.sh @@ -2,10 +2,9 @@ set -euo pipefail -source .buildkite/scripts/common/util.sh +source .buildkite/scripts/steps/functional/common.sh -.buildkite/scripts/bootstrap.sh -node scripts/build_kibana_platform_plugins.js +export KIBANA_INSTALL_DIR=${KIBANA_BUILD_LOCATION} export JOB=kibana-osquery-cypress diff --git a/.buildkite/scripts/steps/functional/security_serverless_osquery.sh b/.buildkite/scripts/steps/functional/security_serverless_osquery.sh index 27ed0c79871ee..9844222e7f869 100755 --- a/.buildkite/scripts/steps/functional/security_serverless_osquery.sh +++ b/.buildkite/scripts/steps/functional/security_serverless_osquery.sh @@ -4,11 +4,7 @@ set -euo pipefail source .buildkite/scripts/steps/functional/common.sh -# TODO: remove the line below to use build artifacts for tests. -# in addition to remove the line, we will have to expose the kibana install dir into the downloaded build location -# by exporting a var like: -# export KIBANA_INSTALL_DIR=${KIBANA_BUILD_LOCATION} -node scripts/build_kibana_platform_plugins.js +export KIBANA_INSTALL_DIR=${KIBANA_BUILD_LOCATION} export JOB=kibana-osquery-cypress-serverless From d21d3987e83b35e530acf233da4793374d9fb75c Mon Sep 17 00:00:00 2001 From: Sander Philipse <94373878+sphilipse@users.noreply.github.com> Date: Wed, 4 Sep 2024 13:45:27 +0200 Subject: [PATCH 07/48] Add publicBaseUrl to Elasticsearch config (#191837) ## Summary This adds a publicBaseUrl to the Elasticsearch plugin config so users can set a publicly accessible URL for Elasticsearch. --------- Co-authored-by: Rudolf Meijering --- docs/setup/settings.asciidoc | 9 ++++++--- .../src/elasticsearch_config.ts | 1 + .../core-elasticsearch-server/src/contracts.ts | 6 ++++++ x-pack/plugins/cloud/server/plugin.ts | 2 +- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/setup/settings.asciidoc b/docs/setup/settings.asciidoc index 6df6c8f3c95ee..98968780f3368 100644 --- a/docs/setup/settings.asciidoc +++ b/docs/setup/settings.asciidoc @@ -14,7 +14,7 @@ KBN_PATH_CONF=/home/kibana/config ./bin/kibana -- The default host and port settings configure {kib} to run on `localhost:5601`. To change this behavior and allow remote users to connect, you'll need to update your `kibana.yml` file. You can also enable SSL and set a -variety of other options. +variety of other options. Environment variables can be injected into configuration using `${MY_ENV_VAR}` syntax. By default, configuration validation will fail if an environment variable used in the config file is not present when Kibana starts. This behavior can be changed by using a default value @@ -93,7 +93,7 @@ The maximum number of sockets that can be used for communications with {es}. *Default: `Infinity`* [[elasticsearch-maxResponseSize]] `elasticsearch.maxResponseSize`:: -Either `false` or a `byteSize` value. When set, responses from {es} with a size higher than the defined limit will be rejected. +Either `false` or a `byteSize` value. When set, responses from {es} with a size higher than the defined limit will be rejected. This is intended to be used as a circuit-breaker mechanism to avoid memory errors in case of unexpectedly high responses coming from {es}. *Default: `false`* @@ -117,6 +117,9 @@ listed here must be on the same cluster. *Default: `[ "http://localhost:9200" ]` To enable SSL/TLS for outbound connections to {es}, use the `https` protocol in this setting. +[[elasticsearch-publicBaseUrl]] `elasticsearch.publicBaseUrl:`:: +The URL through which Elasticsearch is publicly accessible, if any. This will be shown to users in Kibana when they need connection details for your Elasticsearch cluster. + [[elasticsearch-pingTimeout]] `elasticsearch.pingTimeout`:: Time in milliseconds to wait for {es} to respond to pings. *Default: the value of the <> setting* @@ -470,7 +473,7 @@ identifies this {kib} instance. *Default: `"your-hostname"`* setting specifies the port to use. *Default: `5601`* `server.protocol`:: -experimental[] The http protocol to use, either `http1` or `http2`. Set to `http2` to enable `HTTP/2` support for the {kib} server. +experimental[] The http protocol to use, either `http1` or `http2`. Set to `http2` to enable `HTTP/2` support for the {kib} server. *Default: `http1`* + NOTE: By default, enabling `http2` requires a valid `h2c` configuration, meaning that TLS must be enabled via <> diff --git a/packages/core/elasticsearch/core-elasticsearch-server-internal/src/elasticsearch_config.ts b/packages/core/elasticsearch/core-elasticsearch-server-internal/src/elasticsearch_config.ts index 010bc3ac1c796..4807cfe8e598c 100644 --- a/packages/core/elasticsearch/core-elasticsearch-server-internal/src/elasticsearch_config.ts +++ b/packages/core/elasticsearch/core-elasticsearch-server-internal/src/elasticsearch_config.ts @@ -190,6 +190,7 @@ export const configSchema = schema.object({ { defaultValue: [] } ), dnsCacheTtl: schema.duration({ defaultValue: 0, min: 0 }), + publicBaseUrl: schema.maybe(hostURISchema), }); const deprecations: ConfigDeprecationProvider = () => [ diff --git a/packages/core/elasticsearch/core-elasticsearch-server/src/contracts.ts b/packages/core/elasticsearch/core-elasticsearch-server/src/contracts.ts index fced65ce95c79..e1584e9e63cf3 100644 --- a/packages/core/elasticsearch/core-elasticsearch-server/src/contracts.ts +++ b/packages/core/elasticsearch/core-elasticsearch-server/src/contracts.ts @@ -90,6 +90,12 @@ export interface ElasticsearchServiceSetup { */ readonly config$: Observable; }; + + /** + * The public base URL (if any) that should be used by end users to access the Elasticsearch cluster. + */ + + readonly publicBaseUrl?: string; } /** diff --git a/x-pack/plugins/cloud/server/plugin.ts b/x-pack/plugins/cloud/server/plugin.ts index 362a69b4ac0a6..4d77cae8d870f 100644 --- a/x-pack/plugins/cloud/server/plugin.ts +++ b/x-pack/plugins/cloud/server/plugin.ts @@ -202,7 +202,7 @@ export class CloudPlugin implements Plugin { organizationId, instanceSizeMb: readInstanceSizeMb(), deploymentId, - elasticsearchUrl: decodedId?.elasticsearchUrl, + elasticsearchUrl: core.elasticsearch.publicBaseUrl || decodedId?.elasticsearchUrl, kibanaUrl: decodedId?.kibanaUrl, cloudHost: decodedId?.host, cloudDefaultPort: decodedId?.defaultPort, From e9eb03ace8110201f986895b8d16900f4d99c6d1 Mon Sep 17 00:00:00 2001 From: Katerina Date: Wed, 4 Sep 2024 14:48:00 +0300 Subject: [PATCH 08/48] [APM][ECO] Update logs error % to logs error rate in service inventory (#191959) ## Summary closes https://github.com/elastic/kibana/issues/191253 - Update the metrics filter for the log error rate in service builtin definition - Update column from Log error rate % to log Error rate - Update the formula and the tooltip ### Before https://github.com/user-attachments/assets/87e22dc8-1a67-49ac-ad21-cecf0a1fbb14 ### After https://github.com/user-attachments/assets/3d5eafdb-a829-46f0-a5f0-36b62969ceaf --- .../entities/charts/log_error_rate_chart.tsx | 2 +- .../table/get_service_columns.tsx | 6 ++-- .../charts/helper/get_metrics_formulas.tsx | 2 +- .../server/lib/entities/built_in/services.ts | 11 ++------ .../translations/translations/fr-FR.json | 28 +++++++++---------- .../translations/translations/ja-JP.json | 28 +++++++++---------- .../translations/translations/zh-CN.json | 28 +++++++++---------- 7 files changed, 50 insertions(+), 55 deletions(-) diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/entities/charts/log_error_rate_chart.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/entities/charts/log_error_rate_chart.tsx index 68b41a6542a1a..419605236c8a8 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/entities/charts/log_error_rate_chart.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/entities/charts/log_error_rate_chart.tsx @@ -94,7 +94,7 @@ export function LogErrorRateChart({ height }: { height: number }) { formula={getMetricsFormula(ChartMetricType.LOG_ERROR_RATE)} description={ ); diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/helper/get_metrics_formulas.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/helper/get_metrics_formulas.tsx index 5e969d250e1dd..e5b694832c301 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/helper/get_metrics_formulas.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/helper/get_metrics_formulas.tsx @@ -12,7 +12,7 @@ export enum ChartMetricType { const metricsFormulasMap: Record = { [ChartMetricType.LOG_RATE]: `count(kql='log.level: *') / [PERIOD_IN_MINUTES]`, - [ChartMetricType.LOG_ERROR_RATE]: `count(kql='log.level: "error" OR log.level: "ERROR"') / count(kql='log.level: *')`, + [ChartMetricType.LOG_ERROR_RATE]: `count(kql='log.level: "error" OR log.level: "ERROR" OR error.log.level: "error"') / [PERIOD_IN_MINUTES]`, }; export function getMetricsFormula(chartMetricType: ChartMetricType) { diff --git a/x-pack/plugins/observability_solution/entity_manager/server/lib/entities/built_in/services.ts b/x-pack/plugins/observability_solution/entity_manager/server/lib/entities/built_in/services.ts index 4c97d5cec72ed..78f6b9f4e6041 100644 --- a/x-pack/plugins/observability_solution/entity_manager/server/lib/entities/built_in/services.ts +++ b/x-pack/plugins/observability_solution/entity_manager/server/lib/entities/built_in/services.ts @@ -20,7 +20,7 @@ const serviceTransactionFilter = (additionalFilters: string[] = []) => { export const builtInServicesFromLogsEntityDefinition: EntityDefinition = entityDefinitionSchema.parse({ - version: '1.0.0', + version: '1.0.1', id: `${BUILT_IN_ID_PREFIX}services_from_ecs_data`, name: 'Services from ECS data', description: @@ -104,17 +104,12 @@ export const builtInServicesFromLogsEntityDefinition: EntityDefinition = }, { name: 'logErrorRate', - equation: 'A / B', + equation: 'A', metrics: [ { name: 'A', aggregation: 'doc_count', - filter: 'log.level: "error" OR error.log.level: "error"', - }, - { - name: 'B', - aggregation: 'doc_count', - filter: 'log.level: * OR error.log.level: *', + filter: 'log.level: "error" OR log.level: "ERROR" OR error.log.level: "error"', }, ], }, diff --git a/x-pack/plugins/translations/translations/fr-FR.json b/x-pack/plugins/translations/translations/fr-FR.json index c7110d0042477..760d745ebe0c8 100644 --- a/x-pack/plugins/translations/translations/fr-FR.json +++ b/x-pack/plugins/translations/translations/fr-FR.json @@ -9473,7 +9473,16 @@ "visualizationUiComponents.filterQueryInput.clickToEdit": "Cliquer pour modifier", "visualizationUiComponents.filterQueryInput.emptyFilterQuery": "(vide)", "visualizationUiComponents.filterQueryInput.label": "Filtrer par", + "visualizationUiComponents.iconSelect.alertIconLabel": "Alerte", + "visualizationUiComponents.iconSelect.asteriskIconLabel": "Astérisque", + "visualizationUiComponents.iconSelect.bellIconLabel": "Cloche", + "visualizationUiComponents.iconSelect.boltIconLabel": "Éclair", + "visualizationUiComponents.iconSelect.bugIconLabel": "Bug", + "visualizationUiComponents.iconSelect.commentIconLabel": "Commentaire", + "visualizationUiComponents.iconSelect.flagIconLabel": "Drapeau", "visualizationUiComponents.iconSelect.label": "Décoration de l’icône", + "visualizationUiComponents.iconSelect.noIconLabel": "Aucun", + "visualizationUiComponents.iconSelect.tagIconLabel": "Balise", "visualizationUiComponents.lineMarker.textVisibility": "Décoration du texte", "visualizationUiComponents.nameInput.columnLabel": "Nom", "visualizationUiComponents.queryInput.queryPlaceholderKql": "{example}", @@ -11089,8 +11098,8 @@ "xpack.apm.serviceIcons.service": "Service", "xpack.apm.serviceIcons.serviceDetails.cloud.architecture": "Architecture", "xpack.apm.serviceIcons.serviceDetails.cloud.availabilityZoneLabel": "{zones, plural, =0 {Zone de disponibilité} one {Zone de disponibilité} other {Zones de disponibilité}} ", - "xpack.apm.serviceIcons.serviceDetails.cloud.functionNameLabel": "{functionNames, plural, =0 {Nom de fonction} one {Nom de fonction} other {Noms de fonction}} ", "xpack.apm.serviceIcons.serviceDetails.cloud.faasTriggerTypeLabel": "{triggerTypes, plural, =0 {Type de déclencheur} one {Type de déclencheur} other {Types de déclencheurs}} ", + "xpack.apm.serviceIcons.serviceDetails.cloud.functionNameLabel": "{functionNames, plural, =0 {Nom de fonction} one {Nom de fonction} other {Noms de fonction}} ", "xpack.apm.serviceIcons.serviceDetails.cloud.machineTypesLabel": "{machineTypes, plural, =0{Type de machine} one {Type de machine} other {Types de machines}} ", "xpack.apm.serviceIcons.serviceDetails.cloud.projectIdLabel": "ID de projet", "xpack.apm.serviceIcons.serviceDetails.cloud.providerLabel": "Fournisseur cloud", @@ -26028,15 +26037,6 @@ "xpack.lens.xyChart.horizontalAxisLabel": "Axe horizontal", "xpack.lens.xyChart.horizontalLeftAxisLabel": "Axe supérieur horizontal", "xpack.lens.xyChart.horizontalRightAxisLabel": "Axe inférieur horizontal", - "visualizationUiComponents.iconSelect.alertIconLabel": "Alerte", - "visualizationUiComponents.iconSelect.asteriskIconLabel": "Astérisque", - "visualizationUiComponents.iconSelect.bellIconLabel": "Cloche", - "visualizationUiComponents.iconSelect.boltIconLabel": "Éclair", - "visualizationUiComponents.iconSelect.bugIconLabel": "Bug", - "visualizationUiComponents.iconSelect.commentIconLabel": "Commentaire", - "visualizationUiComponents.iconSelect.flagIconLabel": "Drapeau", - "visualizationUiComponents.iconSelect.noIconLabel": "Aucun", - "visualizationUiComponents.iconSelect.tagIconLabel": "Balise", "xpack.lens.xyChart.layerAnnotation": "Annotation", "xpack.lens.xyChart.layerAnnotationsIgnoreTitle": "Calques ignorant les filtres globaux", "xpack.lens.xyChart.layerAnnotationsLabel": "Annotations", @@ -26951,8 +26951,8 @@ "xpack.maps.source.esSearch.descendingLabel": "décroissant", "xpack.maps.source.esSearch.extentFilterLabel": "Filtre dynamique pour les données de la zone de carte visible", "xpack.maps.source.esSearch.fieldNotFoundMsg": "Impossible de trouver \"{fieldName}\" dans le modèle d'indexation \"{indexPatternName}\".", - "xpack.maps.source.esSearch.geoFieldLabel": "Champ géospatial", "xpack.maps.source.esSearch.geofieldLabel": "Champ géospatial", + "xpack.maps.source.esSearch.geoFieldLabel": "Champ géospatial", "xpack.maps.source.esSearch.geoFieldTypeLabel": "Type de champ géospatial", "xpack.maps.source.esSearch.indexOverOneLengthEditError": "Votre vue de données pointe vers plusieurs index. Un seul index est autorisé par vue de données.", "xpack.maps.source.esSearch.indexZeroLengthEditError": "Votre vue de données ne pointe vers aucun index.", @@ -36409,8 +36409,8 @@ "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.maxAlertsFieldLessThanWarning": "Kibana ne permet qu'un maximum de {maxNumber} {maxNumber, plural, =1 {alerte} other {alertes}} par exécution de règle.", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.nameFieldRequiredError": "Nom obligatoire.", "xpack.securitySolution.detectionEngine.createRule.stepAboutrule.noteHelpText": "Ajouter un guide d'investigation sur les règles...", - "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupHelpText": "Fournissez des instructions sur les conditions préalables à la règle, telles que les intégrations requises, les étapes de configuration et tout ce qui est nécessaire au bon fonctionnement de la règle.", "xpack.securitySolution.detectionEngine.createRule.stepAboutrule.setupHelpText": "Ajouter le guide de configuration de règle...", + "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupHelpText": "Fournissez des instructions sur les conditions préalables à la règle, telles que les intégrations requises, les étapes de configuration et tout ce qui est nécessaire au bon fonctionnement de la règle.", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupLabel": "Guide de configuration", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.tagFieldEmptyError": "Une balise ne doit pas être vide", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.threatIndicatorPathFieldEmptyError": "Le remplacement du préfixe d'indicateur ne peut pas être vide.", @@ -42010,8 +42010,8 @@ "xpack.slo.sloEmbeddable.config.sloSelector.placeholder": "Sélectionner un SLO", "xpack.slo.sloEmbeddable.displayName": "Aperçu du SLO", "xpack.slo.sloEmbeddable.overview.sloNotFoundText": "Le SLO a été supprimé. Vous pouvez supprimer sans risque le widget du tableau de bord.", - "xpack.slo.sLOGridItem.targetFlexItemLabel": "Cible {target}", "xpack.slo.sloGridItem.targetFlexItemLabel": "Cible {target}", + "xpack.slo.sLOGridItem.targetFlexItemLabel": "Cible {target}", "xpack.slo.sloGroupConfiguration.customFiltersLabel": "Personnaliser le filtre", "xpack.slo.sloGroupConfiguration.customFiltersOptional": "Facultatif", "xpack.slo.sloGroupConfiguration.customFilterText": "Personnaliser le filtre", @@ -43457,8 +43457,8 @@ "xpack.stackConnectors.components.casesWebhookxpack.stackConnectors.components.casesWebhook.connectorTypeTitle": "Webhook - Données de gestion des cas", "xpack.stackConnectors.components.d3security.bodyCodeEditorAriaLabel": "Éditeur de code", "xpack.stackConnectors.components.d3security.bodyFieldLabel": "Corps", - "xpack.stackConnectors.components.d3Security.connectorTypeTitle": "D3 Security", "xpack.stackConnectors.components.d3security.connectorTypeTitle": "Données D3", + "xpack.stackConnectors.components.d3Security.connectorTypeTitle": "D3 Security", "xpack.stackConnectors.components.d3security.eventTypeFieldLabel": "Type d'événement", "xpack.stackConnectors.components.d3security.invalidActionText": "Nom d'action non valide.", "xpack.stackConnectors.components.d3security.requiredActionText": "L'action est requise.", diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index df3185aff999b..366d85478acda 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -9468,7 +9468,16 @@ "visualizationUiComponents.filterQueryInput.clickToEdit": "クリックして編集", "visualizationUiComponents.filterQueryInput.emptyFilterQuery": "(空)", "visualizationUiComponents.filterQueryInput.label": "フィルタリング条件", + "visualizationUiComponents.iconSelect.alertIconLabel": "アラート", + "visualizationUiComponents.iconSelect.asteriskIconLabel": "アスタリスク", + "visualizationUiComponents.iconSelect.bellIconLabel": "ベル", + "visualizationUiComponents.iconSelect.boltIconLabel": "ボルト", + "visualizationUiComponents.iconSelect.bugIconLabel": "バグ", + "visualizationUiComponents.iconSelect.commentIconLabel": "コメント", + "visualizationUiComponents.iconSelect.flagIconLabel": "旗", "visualizationUiComponents.iconSelect.label": "アイコン装飾", + "visualizationUiComponents.iconSelect.noIconLabel": "なし", + "visualizationUiComponents.iconSelect.tagIconLabel": "タグ", "visualizationUiComponents.lineMarker.textVisibility": "テキスト装飾", "visualizationUiComponents.nameInput.columnLabel": "名前", "visualizationUiComponents.queryInput.queryPlaceholderKql": "{example}", @@ -11079,8 +11088,8 @@ "xpack.apm.serviceIcons.service": "サービス", "xpack.apm.serviceIcons.serviceDetails.cloud.architecture": "アーキテクチャー", "xpack.apm.serviceIcons.serviceDetails.cloud.availabilityZoneLabel": "{zones, plural, other {可用性ゾーン}} ", - "xpack.apm.serviceIcons.serviceDetails.cloud.functionNameLabel": "{functionNames, plural, other {関数名}} ", "xpack.apm.serviceIcons.serviceDetails.cloud.faasTriggerTypeLabel": "{triggerTypes, plural, other {トリガータイプ}} ", + "xpack.apm.serviceIcons.serviceDetails.cloud.functionNameLabel": "{functionNames, plural, other {関数名}} ", "xpack.apm.serviceIcons.serviceDetails.cloud.machineTypesLabel": "{machineTypes, plural, other {コンピュータータイプ} }\n ", "xpack.apm.serviceIcons.serviceDetails.cloud.projectIdLabel": "プロジェクト ID", "xpack.apm.serviceIcons.serviceDetails.cloud.providerLabel": "クラウドプロバイダー", @@ -26017,15 +26026,6 @@ "xpack.lens.xyChart.horizontalAxisLabel": "横軸", "xpack.lens.xyChart.horizontalLeftAxisLabel": "横上軸", "xpack.lens.xyChart.horizontalRightAxisLabel": "横下軸", - "visualizationUiComponents.iconSelect.alertIconLabel": "アラート", - "visualizationUiComponents.iconSelect.asteriskIconLabel": "アスタリスク", - "visualizationUiComponents.iconSelect.bellIconLabel": "ベル", - "visualizationUiComponents.iconSelect.boltIconLabel": "ボルト", - "visualizationUiComponents.iconSelect.bugIconLabel": "バグ", - "visualizationUiComponents.iconSelect.commentIconLabel": "コメント", - "visualizationUiComponents.iconSelect.flagIconLabel": "旗", - "visualizationUiComponents.iconSelect.noIconLabel": "なし", - "visualizationUiComponents.iconSelect.tagIconLabel": "タグ", "xpack.lens.xyChart.layerAnnotation": "注釈", "xpack.lens.xyChart.layerAnnotationsIgnoreTitle": "グローバルフィルターを無視するレイヤー", "xpack.lens.xyChart.layerAnnotationsLabel": "注釈", @@ -26940,8 +26940,8 @@ "xpack.maps.source.esSearch.descendingLabel": "降順", "xpack.maps.source.esSearch.extentFilterLabel": "マップの表示範囲でデータを動的にフィルタリング", "xpack.maps.source.esSearch.fieldNotFoundMsg": "インデックスパターン''{indexPatternName}''に''{fieldName}''が見つかりません。", - "xpack.maps.source.esSearch.geoFieldLabel": "地理空間フィールド", "xpack.maps.source.esSearch.geofieldLabel": "地理空間フィールド", + "xpack.maps.source.esSearch.geoFieldLabel": "地理空間フィールド", "xpack.maps.source.esSearch.geoFieldTypeLabel": "地理空間フィールドタイプ", "xpack.maps.source.esSearch.indexOverOneLengthEditError": "データビューは複数のインデックスを参照しています。データビューごとに1つのインデックスのみが許可されています。", "xpack.maps.source.esSearch.indexZeroLengthEditError": "データビューはどのインデックスも参照していません。", @@ -36393,8 +36393,8 @@ "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.maxAlertsFieldLessThanWarning": "Kibanaで許可される最大数は、1回の実行につき、{maxNumber} {maxNumber, plural, other {アラート}}です。", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.nameFieldRequiredError": "名前が必要です。", "xpack.securitySolution.detectionEngine.createRule.stepAboutrule.noteHelpText": "ルール調査ガイドを追加...", - "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupHelpText": "必要な統合、構成ステップ、ルールが正常に動作するために必要な他のすべての項目といった、ルール前提条件に関する指示を入力します。", "xpack.securitySolution.detectionEngine.createRule.stepAboutrule.setupHelpText": "ルールセットアップガイドを追加...", + "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupHelpText": "必要な統合、構成ステップ、ルールが正常に動作するために必要な他のすべての項目といった、ルール前提条件に関する指示を入力します。", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupLabel": "セットアップガイド", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.tagFieldEmptyError": "タグを空にすることはできません", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.threatIndicatorPathFieldEmptyError": "インジケータープレフィックスの無効化を空にすることはできません", @@ -41994,8 +41994,8 @@ "xpack.slo.sloEmbeddable.config.sloSelector.placeholder": "SLOを選択", "xpack.slo.sloEmbeddable.displayName": "SLO概要", "xpack.slo.sloEmbeddable.overview.sloNotFoundText": "SLOが削除されました。ウィジェットをダッシュボードから安全に削除できます。", - "xpack.slo.sLOGridItem.targetFlexItemLabel": "目標{target}", "xpack.slo.sloGridItem.targetFlexItemLabel": "目標{target}", + "xpack.slo.sLOGridItem.targetFlexItemLabel": "目標{target}", "xpack.slo.sloGroupConfiguration.customFiltersLabel": "カスタムフィルター", "xpack.slo.sloGroupConfiguration.customFiltersOptional": "オプション", "xpack.slo.sloGroupConfiguration.customFilterText": "カスタムフィルター", @@ -43437,8 +43437,8 @@ "xpack.stackConnectors.components.casesWebhookxpack.stackConnectors.components.casesWebhook.connectorTypeTitle": "Webフック - ケース管理データ", "xpack.stackConnectors.components.d3security.bodyCodeEditorAriaLabel": "コードエディター", "xpack.stackConnectors.components.d3security.bodyFieldLabel": "本文", - "xpack.stackConnectors.components.d3Security.connectorTypeTitle": "D3セキュリティ", "xpack.stackConnectors.components.d3security.connectorTypeTitle": "D3データ", + "xpack.stackConnectors.components.d3Security.connectorTypeTitle": "D3セキュリティ", "xpack.stackConnectors.components.d3security.eventTypeFieldLabel": "イベントタイプ", "xpack.stackConnectors.components.d3security.invalidActionText": "無効なアクション名です。", "xpack.stackConnectors.components.d3security.requiredActionText": "アクションが必要です。", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 3a241ffc431c1..455314827fd7e 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -9482,7 +9482,16 @@ "visualizationUiComponents.filterQueryInput.clickToEdit": "单击以编辑", "visualizationUiComponents.filterQueryInput.emptyFilterQuery": "(空)", "visualizationUiComponents.filterQueryInput.label": "筛选依据", + "visualizationUiComponents.iconSelect.alertIconLabel": "告警", + "visualizationUiComponents.iconSelect.asteriskIconLabel": "星号", + "visualizationUiComponents.iconSelect.bellIconLabel": "钟铃", + "visualizationUiComponents.iconSelect.boltIconLabel": "闪电", + "visualizationUiComponents.iconSelect.bugIconLabel": "昆虫", + "visualizationUiComponents.iconSelect.commentIconLabel": "注释", + "visualizationUiComponents.iconSelect.flagIconLabel": "旗帜", "visualizationUiComponents.iconSelect.label": "图标装饰", + "visualizationUiComponents.iconSelect.noIconLabel": "无", + "visualizationUiComponents.iconSelect.tagIconLabel": "标签", "visualizationUiComponents.lineMarker.textVisibility": "文本装饰", "visualizationUiComponents.nameInput.columnLabel": "名称", "visualizationUiComponents.queryInput.queryPlaceholderKql": "{example}", @@ -11098,8 +11107,8 @@ "xpack.apm.serviceIcons.service": "服务", "xpack.apm.serviceIcons.serviceDetails.cloud.architecture": "架构", "xpack.apm.serviceIcons.serviceDetails.cloud.availabilityZoneLabel": "{zones, plural, other {可用性区域}} ", - "xpack.apm.serviceIcons.serviceDetails.cloud.functionNameLabel": "{functionNames, plural, other {功能名称}} ", "xpack.apm.serviceIcons.serviceDetails.cloud.faasTriggerTypeLabel": "{triggerTypes, plural, other {触发类型}} ", + "xpack.apm.serviceIcons.serviceDetails.cloud.functionNameLabel": "{functionNames, plural, other {功能名称}} ", "xpack.apm.serviceIcons.serviceDetails.cloud.machineTypesLabel": "{machineTypes, plural, other {机器类型}} ", "xpack.apm.serviceIcons.serviceDetails.cloud.projectIdLabel": "项目 ID", "xpack.apm.serviceIcons.serviceDetails.cloud.providerLabel": "云服务提供商", @@ -26049,15 +26058,6 @@ "xpack.lens.xyChart.horizontalAxisLabel": "水平轴", "xpack.lens.xyChart.horizontalLeftAxisLabel": "水平顶轴", "xpack.lens.xyChart.horizontalRightAxisLabel": "水平底轴", - "visualizationUiComponents.iconSelect.alertIconLabel": "告警", - "visualizationUiComponents.iconSelect.asteriskIconLabel": "星号", - "visualizationUiComponents.iconSelect.bellIconLabel": "钟铃", - "visualizationUiComponents.iconSelect.boltIconLabel": "闪电", - "visualizationUiComponents.iconSelect.bugIconLabel": "昆虫", - "visualizationUiComponents.iconSelect.commentIconLabel": "注释", - "visualizationUiComponents.iconSelect.flagIconLabel": "旗帜", - "visualizationUiComponents.iconSelect.noIconLabel": "无", - "visualizationUiComponents.iconSelect.tagIconLabel": "标签", "xpack.lens.xyChart.layerAnnotation": "标注", "xpack.lens.xyChart.layerAnnotationsIgnoreTitle": "忽略全局筛选的图层", "xpack.lens.xyChart.layerAnnotationsLabel": "标注", @@ -26972,8 +26972,8 @@ "xpack.maps.source.esSearch.descendingLabel": "降序", "xpack.maps.source.esSearch.extentFilterLabel": "在可见地图区域中动态筛留数据", "xpack.maps.source.esSearch.fieldNotFoundMsg": "在索引模式“{indexPatternName}”中找不到“{fieldName}”。", - "xpack.maps.source.esSearch.geoFieldLabel": "地理空间字段", "xpack.maps.source.esSearch.geofieldLabel": "地理空间字段", + "xpack.maps.source.esSearch.geoFieldLabel": "地理空间字段", "xpack.maps.source.esSearch.geoFieldTypeLabel": "地理空间字段类型", "xpack.maps.source.esSearch.indexOverOneLengthEditError": "您的数据视图指向多个索引。每个数据视图只允许一个索引。", "xpack.maps.source.esSearch.indexZeroLengthEditError": "您的数据视图未指向任何索引。", @@ -36435,8 +36435,8 @@ "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.maxAlertsFieldLessThanWarning": "每次规则运行时,Kibana 最多只允许 {maxNumber} 个{maxNumber, plural, other {告警}}。", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.nameFieldRequiredError": "名称必填。", "xpack.securitySolution.detectionEngine.createRule.stepAboutrule.noteHelpText": "添加规则调查指南......", - "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupHelpText": "提供有关规则先决条件的说明,如所需集成、配置步骤,以及规则正常运行所需的任何其他内容。", "xpack.securitySolution.detectionEngine.createRule.stepAboutrule.setupHelpText": "添加规则设置指南......", + "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupHelpText": "提供有关规则先决条件的说明,如所需集成、配置步骤,以及规则正常运行所需的任何其他内容。", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.setupLabel": "设置指南", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.tagFieldEmptyError": "标签不得为空", "xpack.securitySolution.detectionEngine.createRule.stepAboutRule.threatIndicatorPathFieldEmptyError": "指标前缀覆盖不得为空", @@ -42038,8 +42038,8 @@ "xpack.slo.sloEmbeddable.config.sloSelector.placeholder": "选择 SLO", "xpack.slo.sloEmbeddable.displayName": "SLO 概览", "xpack.slo.sloEmbeddable.overview.sloNotFoundText": "SLO 已删除。您可以放心从仪表板中删除小组件。", - "xpack.slo.sLOGridItem.targetFlexItemLabel": "目标 {target}", "xpack.slo.sloGridItem.targetFlexItemLabel": "目标 {target}", + "xpack.slo.sLOGridItem.targetFlexItemLabel": "目标 {target}", "xpack.slo.sloGroupConfiguration.customFiltersLabel": "定制筛选", "xpack.slo.sloGroupConfiguration.customFiltersOptional": "可选", "xpack.slo.sloGroupConfiguration.customFilterText": "定制筛选", @@ -43485,8 +43485,8 @@ "xpack.stackConnectors.components.casesWebhookxpack.stackConnectors.components.casesWebhook.connectorTypeTitle": "Webhook - 案例管理数据", "xpack.stackConnectors.components.d3security.bodyCodeEditorAriaLabel": "代码编辑器", "xpack.stackConnectors.components.d3security.bodyFieldLabel": "正文", - "xpack.stackConnectors.components.d3Security.connectorTypeTitle": "D3 Security", "xpack.stackConnectors.components.d3security.connectorTypeTitle": "D3 数据", + "xpack.stackConnectors.components.d3Security.connectorTypeTitle": "D3 Security", "xpack.stackConnectors.components.d3security.eventTypeFieldLabel": "事件类型", "xpack.stackConnectors.components.d3security.invalidActionText": "操作名称无效。", "xpack.stackConnectors.components.d3security.requiredActionText": "“操作”必填。", From 8c67fecd3297b3cf9d460bad59baeb9e30995d3c Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Wed, 4 Sep 2024 13:14:52 +0100 Subject: [PATCH 09/48] [ML] Renaming ML API service (#191742) Addresses the comment from the description of this [PR](https://github.com/elastic/kibana/pull/189729): `We have a bit of a mix of naming: ml, mlApiServices, useMlApiContext() for the same thing` Renames: `useMlApiContext` -> `useMlApi` `ml` -> `mlApi` `mlApiServices` -> `mlApi` `MlApiServices ` -> `MlApi` E.g. we can now use `const mlApi = useMlApi();` Rather than: `const ml = useMlApiContext();` or `const mlServices = useMlApiContext();` or ``` const { services: { mlServices: { mlApiServices }, }, } = useMlKibana(); ``` --- .../ml/public/alerting/job_selector.tsx | 4 +-- .../capabilities/check_capabilities.ts | 10 +++---- .../capabilities/get_capabilities.ts | 6 ++-- .../annotation_flyout/index.test.tsx | 2 +- .../annotations/annotation_flyout/index.tsx | 8 ++--- .../annotations_table/annotations_table.js | 6 ++-- .../anomalies_table/anomalies_table.js | 4 +-- .../components/anomalies_table/links_menu.tsx | 8 ++--- .../custom_urls/custom_url_editor/list.tsx | 6 ++-- .../custom_urls/custom_url_editor/utils.ts | 24 +++++++-------- .../components/custom_urls/custom_urls.tsx | 4 +-- .../data_recognizer/data_recognizer.js | 5 ++-- .../delete_space_aware_item_check_modal.tsx | 4 +-- .../export_jobs_flyout_content.tsx | 6 ++-- .../export_jobs_flyout/jobs_export_service.ts | 12 ++++---- .../import_jobs_flyout/import_jobs_flyout.tsx | 2 +- .../import_jobs_flyout/validate.ts | 4 +-- .../job_selector/job_selector_flyout.tsx | 4 +-- .../job_spaces_sync_flyout.tsx | 4 +-- .../new_job_awaiting_node_shared.tsx | 10 +++---- .../ml_entity_selector.test.tsx | 16 +++++----- .../ml_entity_selector/ml_entity_selector.tsx | 4 +-- .../add_inference_pipeline_flyout.tsx | 4 +-- .../components/reindex_with_pipeline.tsx | 10 +++---- .../ml_inference/components/test_pipeline.tsx | 10 +++---- .../ml_inference/hooks/use_fetch_pipelines.ts | 4 +-- .../ml_inference/retry_create_data_view.ts | 10 +++---- .../ml_saved_objects_spaces_list.tsx | 4 +-- .../edit_model_snapshot_flyout.tsx | 8 ++--- .../model_snapshots/model_snapshots_table.tsx | 16 +++++----- .../revert_model_snapshot_flyout.tsx | 8 ++--- .../node_available_warning/hooks.ts | 14 ++++----- .../rule_editor/rule_editor_flyout.js | 16 +++++----- .../rule_editor/rule_editor_flyout.test.js | 2 +- .../select_rule_action/rule_action_panel.js | 4 +-- .../rule_action_panel.test.js | 2 +- .../components/rule_editor/utils.js | 23 +++++--------- .../saved_objects_warning.tsx | 4 +-- .../scatterplot_matrix.test.tsx | 2 +- .../scatterplot_matrix/scatterplot_matrix.tsx | 4 +-- .../validate_job/validate_job_view.js | 2 +- .../validate_job/validate_job_view.test.js | 2 +- .../contexts/kibana/__mocks__/index.ts | 2 +- .../kibana/__mocks__/kibana_context.ts | 2 +- .../kibana/__mocks__/use_ml_api_context.ts | 6 ++-- .../application/contexts/kibana/index.ts | 2 +- .../contexts/kibana/use_ml_api_context.ts | 4 +-- .../ml/ml_notifications_context.test.tsx | 30 +++++++++---------- .../contexts/ml/ml_notifications_context.tsx | 6 ++-- .../data_frame_analytics/common/analytics.ts | 14 ++++----- .../common/get_index_data.ts | 8 ++--- .../common/get_index_fields.ts | 6 ++-- .../common/use_results_view_config.ts | 8 ++--- .../advanced_step/advanced_step_form.tsx | 6 ++-- .../configuration_step_form.tsx | 8 ++--- .../create_analytics_advanced_editor.tsx | 6 ++-- .../create_step_footer/create_step_footer.tsx | 6 ++-- .../details_step/details_step_form.tsx | 8 ++--- .../components/shared/fetch_explain_data.ts | 6 ++-- .../validation_step_wrapper.tsx | 4 +-- .../hooks/use_has_index_permission.ts | 2 +- .../hooks/use_index_data.ts | 10 +++---- .../pages/analytics_creation/page.tsx | 9 ++++-- .../use_confusion_matrix.ts | 8 ++--- .../use_roc_curve.ts | 6 ++-- .../expandable_section_analytics.tsx | 8 ++--- .../use_exploration_results.ts | 10 +++---- .../outlier_exploration/use_outlier_data.ts | 10 +++---- .../regression_exploration/evaluate_panel.tsx | 12 ++++---- .../pages/analytics_exploration/page.tsx | 4 +-- .../action_delete/delete_action_name.test.tsx | 2 +- .../action_edit/edit_action_flyout.tsx | 8 ++--- .../expanded_row_messages_pane.tsx | 6 ++-- .../use_create_analytics_form.ts | 8 ++--- .../analytics_service/delete_analytics.ts | 14 ++++----- .../analytics_service/get_analytics.ts | 8 ++--- .../analytics_service/start_analytics.ts | 6 ++-- .../analytics_service/stop_analytics.ts | 6 ++-- .../analytics_id_selector.tsx | 4 +-- .../pages/job_map/page.tsx | 4 +-- .../job_map/use_fetch_analytics_map_data.ts | 6 ++-- .../file_based/file_datavisualizer.tsx | 8 ++--- .../index_based/data_loader/data_loader.ts | 6 ++-- .../index_based/index_data_visualizer.tsx | 8 ++--- .../explorer/actions/load_explorer_data.ts | 23 ++++++-------- .../explorer/anomaly_explorer_context.tsx | 6 ++-- .../application/explorer/explorer_utils.ts | 14 ++++----- .../datafeed_chart_flyout.tsx | 14 ++++----- .../edit_query_delay.tsx | 4 +-- .../edit_job_flyout/edit_job_flyout.js | 10 +++---- .../components/edit_job_flyout/edit_utils.js | 10 +++---- .../edit_job_flyout/tabs/detectors.js | 2 +- .../edit_job_flyout/tabs/job_details.js | 4 +-- .../components/job_actions/management.js | 4 +-- .../job_details/datafeed_preview_tab.tsx | 4 +-- .../forecasts_table/forecasts_table.js | 4 +-- .../job_details/job_messages_pane.tsx | 8 ++--- .../job_filter_bar/job_filter_bar.tsx | 4 +-- .../components/jobs_list/jobs_list.js | 6 ++-- .../jobs_list_view/jobs_list_view.js | 12 ++++---- .../multi_job_actions/actions_menu.js | 4 +-- .../group_selector/group_selector.js | 6 ++-- .../start_datafeed_modal.js | 2 +- .../jobs/jobs_list/components/utils.d.ts | 11 +++---- .../jobs/jobs_list/components/utils.js | 22 +++++--------- .../common/chart_loader/chart_loader.ts | 19 +++++------- .../new_job/common/chart_loader/searches.ts | 6 ++-- .../job_creator/advanced_job_creator.ts | 6 ++-- .../job_creator/categorization_job_creator.ts | 6 ++-- .../common/job_creator/geo_job_creator.ts | 6 ++-- .../new_job/common/job_creator/job_creator.ts | 12 ++++---- .../common/job_creator/job_creator_factory.ts | 6 ++-- .../job_creator/multi_metric_job_creator.ts | 6 ++-- .../job_creator/population_job_creator.ts | 6 ++-- .../common/job_creator/rare_job_creator.ts | 6 ++-- .../job_creator/single_metric_job_creator.ts | 6 ++-- .../util/model_memory_estimator.test.ts | 6 ++-- .../util/model_memory_estimator.ts | 14 ++++----- .../new_job/common/job_runner/job_runner.ts | 10 +++---- .../common/job_validator/validators.ts | 6 ++-- .../new_job/common/map_loader/map_loader.ts | 6 ++-- .../categorization_examples_loader.ts | 2 +- .../common/results_loader/results_loader.ts | 4 +-- .../new_job/common/results_loader/searches.ts | 6 ++-- .../quick_create_job_base.ts | 14 ++++----- .../new_job/job_from_lens/quick_create_job.ts | 6 ++-- .../new_job/job_from_lens/route_resolver.ts | 16 +++------- .../new_job/job_from_map/quick_create_job.ts | 6 ++-- .../new_job/job_from_map/route_resolver.ts | 9 +++--- .../quick_create_job.ts | 6 ++-- .../route_resolver.ts | 8 ++--- .../datafeed_preview.tsx | 4 +-- .../components/data_view/change_data_view.tsx | 8 ++--- .../calendars/calendars_selection.tsx | 6 ++-- .../estimate_bucket_span.ts | 6 ++-- .../category_stopped_partitions.tsx | 6 ++-- .../categorization_view/top_categories.tsx | 6 ++-- .../jobs/new_job/pages/new_job/page.tsx | 14 ++++----- .../jobs/new_job/recognize/page.tsx | 2 +- .../ml_nodes_check/check_ml_nodes.ts | 6 ++-- .../create_pipeline_for_model_flyout.tsx | 4 +-- .../model_management/model_actions.tsx | 6 ++-- .../test_models/selected_model.tsx | 4 +-- .../components/notifications_list.test.tsx | 4 +-- .../components/notifications_list.tsx | 6 ++-- .../anomaly_detection_panel.tsx | 6 ++-- .../overview/components/content.tsx | 4 +-- .../public/application/routing/resolvers.ts | 4 +-- .../analytics_job_creation.tsx | 6 ++-- .../routing/routes/explorer/explorer.tsx | 4 +-- .../routing/routes/explorer/state_manager.tsx | 4 +-- .../routing/routes/new_job/from_lens.tsx | 4 +-- .../routing/routes/new_job/from_map.tsx | 4 +-- .../routes/new_job/from_pattern_analysis.tsx | 4 +-- .../routing/routes/new_job/recognize.tsx | 10 +++---- .../routing/routes/new_job/wizard.tsx | 9 +++--- .../timeseriesexplorer.test.tsx | 2 +- .../timeseriesexplorer/timeseriesexplorer.tsx | 4 +-- .../application/routing/use_resolver.tsx | 8 ++--- .../services/anomaly_detector_service.ts | 10 +++---- .../anomaly_explorer_charts_service.test.ts | 4 +-- .../anomaly_explorer_charts_service.ts | 8 ++--- .../application/services/calendar_service.ts | 13 ++++---- .../services/field_format_service.ts | 12 ++++---- .../services/field_format_service_factory.ts | 6 ++-- .../application/services/forecast_service.ts | 18 +++++------ .../services/get_shared_ml_services.ts | 8 ++--- .../application/services/job_service.d.ts | 4 +-- .../application/services/job_service.js | 10 +++---- .../services/ml_api_service/index.ts | 4 +-- .../services/ml_server_info.test.ts | 4 +-- .../application/services/ml_server_info.ts | 6 ++-- .../load_new_job_capabilities.ts | 8 ++--- .../new_job_capabilities_service.test.ts | 4 +-- .../new_job_capabilities_service.ts | 16 +++++----- .../new_job_capabilities_service_analytics.ts | 16 +++++----- .../services/results_service/index.ts | 14 ++++----- .../results_service/result_service_rx.ts | 16 +++++----- .../results_service/results_service.d.ts | 4 +-- .../results_service/results_service.js | 22 +++++++------- .../settings/anomaly_detection_settings.tsx | 8 ++--- .../settings/calendars/edit/new_calendar.js | 10 +++---- .../calendars/edit/new_calendar.test.js | 2 +- .../settings/calendars/edit/utils.js | 20 ++++++------- .../settings/calendars/list/calendars_list.js | 8 ++--- .../calendars/list/calendars_list.test.js | 4 +-- .../calendars/list/delete_calendars.js | 9 ++---- .../delete_filter_list_modal.js | 2 +- .../delete_filter_lists.js | 4 +-- .../filter_lists/edit/edit_filter_list.js | 6 ++-- .../edit/edit_filter_list.test.js | 2 +- .../settings/filter_lists/edit/utils.js | 16 +++++----- .../filter_lists/list/filter_lists.js | 4 +-- .../filter_lists/list/filter_lists.test.js | 4 +-- .../application/settings/settings.test.tsx | 2 +- .../forecasting_modal/forecasting_modal.js | 10 +++---- .../components/forecasting_modal/modal.js | 6 ++-- .../series_controls/series_controls.tsx | 2 +- .../timeseries_chart/timeseries_chart.js | 2 +- .../timeseries_chart/timeseries_chart.test.js | 2 +- .../timeseries_chart_with_tooltip.tsx | 4 +-- .../timeseriesexplorer/timeseriesexplorer.js | 18 +++++------ .../timeseriesexplorer_embeddable_chart.js | 6 ++-- .../time_series_search_service.ts | 17 +++++------ .../public/application/util/get_services.ts | 12 ++++---- .../util/time_series_explorer_service.ts | 18 +++++------ .../anomaly_charts_initializer.test.tsx | 4 +-- .../anomaly_charts_initializer.tsx | 4 +-- ...et_anomaly_charts_services_dependencies.ts | 12 ++++---- .../anomaly_swimlane_embeddable_factory.tsx | 4 +-- .../anomaly_swimlane_initializer.tsx | 4 +-- .../job_creation/aiops/flyout/create_job.tsx | 12 ++++---- .../job_creation/common/job_details.tsx | 4 +-- .../layer/compatible_layer.tsx | 6 ++-- .../layer/compatible_layer.tsx | 6 ++-- .../single_metric_viewer/get_services.ts | 20 ++++++------- ...ingle_metric_viewer_embeddable_factory.tsx | 4 +-- .../single_metric_viewer_initializer.tsx | 14 ++++----- .../single_metric_viewer_setup_flyout.tsx | 8 ++--- x-pack/plugins/ml/public/embeddables/types.ts | 6 ++-- .../ml/public/maps/anomaly_job_selector.tsx | 4 +-- .../maps/anomaly_layer_wizard_factory.tsx | 4 +-- .../plugins/ml/public/maps/anomaly_source.tsx | 4 +-- .../ml/public/maps/anomaly_source_factory.ts | 8 ++--- .../maps/create_anomaly_source_editor.tsx | 4 +-- x-pack/plugins/ml/public/maps/util.ts | 4 +-- x-pack/plugins/ml/public/plugin.ts | 6 ++-- .../single_metric_viewer.tsx | 10 +++---- .../create_single_metric_viewer.tsx | 8 ++--- 229 files changed, 827 insertions(+), 878 deletions(-) diff --git a/x-pack/plugins/ml/public/alerting/job_selector.tsx b/x-pack/plugins/ml/public/alerting/job_selector.tsx index 80ef8a5fed0c3..68bc75e2de2b5 100644 --- a/x-pack/plugins/ml/public/alerting/job_selector.tsx +++ b/x-pack/plugins/ml/public/alerting/job_selector.tsx @@ -14,7 +14,7 @@ import { EuiButton, EuiComboBox, EuiEmptyPrompt, EuiFormRow } from '@elastic/eui import useMountedState from 'react-use/lib/useMountedState'; import { useMlKibana } from '../application/contexts/kibana'; import type { JobId } from '../../common/types/anomaly_detection_jobs'; -import type { MlApiServices } from '../application/services/ml_api_service'; +import type { MlApi } from '../application/services/ml_api_service'; import { ALL_JOBS_SELECTION } from '../../common/constants/alerts'; import { LoadingIndicator } from '../application/components/loading_indicator'; @@ -26,7 +26,7 @@ interface JobSelection { export interface JobSelectorControlProps { jobsAndGroupIds?: string[]; onChange: (jobSelection: JobSelection) => void; - adJobsApiService: MlApiServices['jobs']; + adJobsApiService: MlApi['jobs']; /** * Validation is handled by alerting framework */ diff --git a/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts b/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts index ee7868adb41fa..ed930b857473d 100644 --- a/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts +++ b/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts @@ -27,7 +27,7 @@ import { type MlCapabilitiesKey, } from '../../../common/types/capabilities'; import { getCapabilities } from './get_capabilities'; -import type { MlApiServices } from '../services/ml_api_service'; +import type { MlApi } from '../services/ml_api_service'; import type { MlGlobalServices } from '../app'; let _capabilities: MlCapabilities = getDefaultCapabilities(); @@ -54,7 +54,7 @@ export class MlCapabilitiesService { private _subscription: Subscription | undefined; - constructor(private readonly mlApiServices: MlApiServices) { + constructor(private readonly mlApi: MlApi) { this.init(); } @@ -67,7 +67,7 @@ export class MlCapabilitiesService { tap(() => { this._isLoading$.next(true); }), - switchMap(() => from(this.mlApiServices.checkMlCapabilities())), + switchMap(() => from(this.mlApi.checkMlCapabilities())), retry({ delay: CAPABILITIES_REFRESH_INTERVAL }) ) .subscribe((results) => { @@ -197,11 +197,11 @@ export function checkGetManagementMlJobsResolver({ mlCapabilities }: MlGlobalSer } export function checkCreateJobsCapabilitiesResolver( - mlApiServices: MlApiServices, + mlApi: MlApi, redirectToJobsManagementPage: () => Promise ): Promise { return new Promise((resolve, reject) => { - getCapabilities(mlApiServices) + getCapabilities(mlApi) .then(async ({ capabilities, isPlatinumOrTrialLicense }) => { _capabilities = capabilities; // if the license is basic (isPlatinumOrTrialLicense === false) then do not redirect, diff --git a/x-pack/plugins/ml/public/application/capabilities/get_capabilities.ts b/x-pack/plugins/ml/public/application/capabilities/get_capabilities.ts index 2f7ad039b2700..079256997e1c5 100644 --- a/x-pack/plugins/ml/public/application/capabilities/get_capabilities.ts +++ b/x-pack/plugins/ml/public/application/capabilities/get_capabilities.ts @@ -5,10 +5,10 @@ * 2.0. */ -import type { MlApiServices } from '../services/ml_api_service'; +import type { MlApi } from '../services/ml_api_service'; import type { MlCapabilitiesResponse } from '../../../common/types/capabilities'; -export function getCapabilities(ml: MlApiServices): Promise { - return ml.checkMlCapabilities(); +export function getCapabilities(mlApi: MlApi): Promise { + return mlApi.checkMlCapabilities(); } diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.test.tsx b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.test.tsx index 81cafabbae827..7d8434dcc4680 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.test.tsx +++ b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.test.tsx @@ -21,7 +21,7 @@ import { MlAnnotationUpdatesContext } from '../../../contexts/ml/ml_annotation_u const kibanaReactContextMock = createKibanaReactContext({ mlServices: { - mlApiServices: { + mlApi: { annotations: { indexAnnotation: jest.fn().mockResolvedValue({}), deleteAnnotation: jest.fn().mockResolvedValue({}), diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx index 3bea429042299..eb54db4f327dc 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx +++ b/x-pack/plugins/ml/public/application/components/annotations/annotation_flyout/index.tsx @@ -136,10 +136,10 @@ export class AnnotationFlyoutUI extends Component { this.deletionInProgress = true; - const ml = this.context.services.mlServices.mlApiServices; + const mlApi = this.context.services.mlServices.mlApi; const toastNotifications = this.context.services.notifications.toasts; try { - await ml.annotations.deleteAnnotation(annotationState._id); + await mlApi.annotations.deleteAnnotation(annotationState._id); toastNotifications.addSuccess( i18n.translate( 'xpack.ml.timeSeriesExplorer.timeSeriesChart.deletedAnnotationNotificationMessage', @@ -241,9 +241,9 @@ export class AnnotationFlyoutUI extends Component { annotation.event = annotation.event ?? ANNOTATION_EVENT_USER; annotationUpdatesService.setValue(null); - const ml = this.context.services.mlServices.mlApiServices; + const mlApi = this.context.services.mlServices.mlApi; const toastNotifications = this.context.services.notifications.toasts; - ml.annotations + mlApi.annotations .indexAnnotation(annotation) .then(() => { annotationsRefreshed(); diff --git a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js index cea2554876c4d..b5842e479ba11 100644 --- a/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js +++ b/x-pack/plugins/ml/public/application/components/annotations/annotations_table/annotations_table.js @@ -103,7 +103,7 @@ class AnnotationsTableUI extends Component { }; this.mlJobService = mlJobServiceFactory( toastNotificationServiceProvider(props.kibana.services.notifications.toasts), - props.kibana.services.mlServices.mlApiServices + props.kibana.services.mlServices.mlApi ); } @@ -115,11 +115,11 @@ class AnnotationsTableUI extends Component { isLoading: true, }); - const ml = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; if (dataCounts.processed_record_count > 0) { // Load annotations for the selected job. - ml.annotations + mlApi.annotations .getAnnotations$({ jobIds: [job.job_id], earliestMs: null, diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js index 80ee0f7a64820..4429a3022122e 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/anomalies_table.js @@ -68,7 +68,7 @@ export class AnomaliesTableInternal extends Component { } toggleRow = async (item, tab = ANOMALIES_TABLE_TABS.DETAILS) => { - const ml = this.context.services.mlServices.mlApiServices; + const mlApi = this.context.services.mlServices.mlApi; const itemIdToExpandedRowMap = { ...this.state.itemIdToExpandedRowMap }; if (itemIdToExpandedRowMap[item.rowId]) { delete itemIdToExpandedRowMap[item.rowId]; @@ -81,7 +81,7 @@ export class AnomaliesTableInternal extends Component { if (examples !== undefined) { try { - definition = await ml.results.getCategoryDefinition( + definition = await mlApi.results.getCategoryDefinition( item.jobId, item.source.mlcategory[0] ); diff --git a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.tsx b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.tsx index 70364abc50389..ccf9083c90791 100644 --- a/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.tsx +++ b/x-pack/plugins/ml/public/application/components/anomalies_table/links_menu.tsx @@ -58,7 +58,7 @@ import { getUrlForRecord, openCustomUrlWindow } from '../../util/custom_url_util import type { SourceIndicesWithGeoFields } from '../../explorer/explorer_utils'; import { escapeDoubleQuotes, getDateFormatTz } from '../../explorer/explorer_utils'; import { usePermissionCheck } from '../../capabilities/check_capabilities'; -import { useMlApiContext, useMlKibana } from '../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../contexts/kibana'; import { useMlIndexUtils } from '../../util/index_service'; import { getQueryStringForInfluencers } from './get_query_string_for_influencers'; @@ -110,7 +110,7 @@ export const LinksMenuUI = (props: LinksMenuProps) => { }, } = kibana; const { getDataViewById, getDataViewIdFromName } = useMlIndexUtils(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const mlJobService = useMlJobService(); const job = useMemo(() => { @@ -510,7 +510,7 @@ export const LinksMenuUI = (props: LinksMenuProps) => { // - use first value (will only ever be more than one if influenced by category other than by/partition/over). const categoryId = record.mlcategory[0]; - ml.results + mlApi.results .getCategoryDefinition(jobId, categoryId) .then((resp) => { // Prefix each of the terms with '+' so that the Elasticsearch Query String query @@ -647,7 +647,7 @@ export const LinksMenuUI = (props: LinksMenuProps) => { // Get the definition of the category and use the terms or regex to view the // matching events in the Kibana Discover tab depending on whether the // categorization field is of mapping type text (preferred) or keyword. - ml.results + mlApi.results .getCategoryDefinition(record.job_id, categoryId) .then(async (resp) => { // We should not redirect to Discover if data view doesn't exist diff --git a/x-pack/plugins/ml/public/application/components/custom_urls/custom_url_editor/list.tsx b/x-pack/plugins/ml/public/application/components/custom_urls/custom_url_editor/list.tsx index 16dba857ed6cc..bb913b8ecec34 100644 --- a/x-pack/plugins/ml/public/application/components/custom_urls/custom_url_editor/list.tsx +++ b/x-pack/plugins/ml/public/application/components/custom_urls/custom_url_editor/list.tsx @@ -29,7 +29,7 @@ import { } from '@kbn/ml-data-frame-analytics-utils'; import { parseUrlState } from '@kbn/ml-url-state'; -import { useMlApiContext, useMlKibana } from '../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../contexts/kibana'; import { useToastNotificationService } from '../../../services/toast_notification_service'; import { isValidLabel, openCustomUrlWindow } from '../../../util/custom_url_utils'; import { getTestUrl } from './utils'; @@ -73,7 +73,7 @@ export const CustomUrlList: FC = ({ data: { dataViews }, }, } = useMlKibana(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { displayErrorToast } = useToastNotificationService(); const [expandedUrlIndex, setExpandedUrlIndex] = useState(null); @@ -162,7 +162,7 @@ export const CustomUrlList: FC = ({ if (index < customUrls.length) { try { const testUrl = await getTestUrl( - ml, + mlApi, job, customUrl, timefieldName, diff --git a/x-pack/plugins/ml/public/application/components/custom_urls/custom_url_editor/utils.ts b/x-pack/plugins/ml/public/application/components/custom_urls/custom_url_editor/utils.ts index cd0a52e170453..0fc2a7b514b2d 100644 --- a/x-pack/plugins/ml/public/application/components/custom_urls/custom_url_editor/utils.ts +++ b/x-pack/plugins/ml/public/application/components/custom_urls/custom_url_editor/utils.ts @@ -47,7 +47,7 @@ import { escapeForElasticsearchQuery } from '../../../util/string_utils'; import type { CombinedJob, Job } from '../../../../../common/types/anomaly_detection_jobs'; import { isAnomalyDetectionJob } from '../../../../../common/types/anomaly_detection_jobs'; import type { TimeRangeType } from './constants'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; export interface TimeRange { type: TimeRangeType; @@ -427,7 +427,7 @@ function buildAppStateQueryParam(queryFieldNames: string[]) { // may contain dollar delimited partition / influencer entity tokens and // drilldown time range settings. async function getAnomalyDetectionJobTestUrl( - ml: MlApiServices, + mlApi: MlApi, job: Job, customUrl: MlUrlConfig ): Promise { @@ -455,7 +455,7 @@ async function getAnomalyDetectionJobTestUrl( let resp; try { - resp = await ml.results.anomalySearch( + resp = await mlApi.results.anomalySearch( { body, }, @@ -479,8 +479,8 @@ async function getAnomalyDetectionJobTestUrl( try { // attempt load the non-combined job and datafeed so they can be used in the datafeed preview const [{ jobs }, { datafeeds }] = await Promise.all([ - ml.getJobs({ jobId: job.job_id }), - ml.getDatafeeds({ datafeedId: job.datafeed_config?.datafeed_id ?? '' }), + mlApi.getJobs({ jobId: job.job_id }), + mlApi.getDatafeeds({ datafeedId: job.datafeed_config?.datafeed_id ?? '' }), ]); datafeedConfig = datafeeds[0]; jobConfig = jobs[0]; @@ -500,7 +500,7 @@ async function getAnomalyDetectionJobTestUrl( delete jobConfig.datafeed_config; } - const preview = (await ml.jobs.datafeedPreview( + const preview = (await mlApi.jobs.datafeedPreview( undefined, jobConfig, datafeedConfig @@ -520,7 +520,7 @@ async function getAnomalyDetectionJobTestUrl( } async function getDataFrameAnalyticsTestUrl( - ml: MlApiServices, + mlApi: MlApi, job: DataFrameAnalyticsConfig, customUrl: MlKibanaUrlConfig, timeFieldName: string | null, @@ -543,13 +543,13 @@ async function getDataFrameAnalyticsTestUrl( }, }; - resp = await ml.esSearch(body); + resp = await mlApi.esSearch(body); if (resp && resp.hits.total.value > 0) { record = resp.hits.hits[0]._source; } else { // No results for this job yet so use source index for example doc. - resp = await ml.esSearch({ + resp = await mlApi.esSearch({ index: Array.isArray(job.source.index) ? job.source.index.join(',') : job.source.index, body: { size: 1, @@ -594,7 +594,7 @@ async function getDataFrameAnalyticsTestUrl( } export function getTestUrl( - ml: MlApiServices, + mlApi: MlApi, job: Job | DataFrameAnalyticsConfig, customUrl: MlUrlConfig, timeFieldName: string | null, @@ -603,7 +603,7 @@ export function getTestUrl( ) { if (isDataFrameAnalyticsConfigs(job) || isPartialDFAJob) { return getDataFrameAnalyticsTestUrl( - ml, + mlApi, job as DataFrameAnalyticsConfig, customUrl, timeFieldName, @@ -612,5 +612,5 @@ export function getTestUrl( ); } - return getAnomalyDetectionJobTestUrl(ml, job, customUrl); + return getAnomalyDetectionJobTestUrl(mlApi, job, customUrl); } diff --git a/x-pack/plugins/ml/public/application/components/custom_urls/custom_urls.tsx b/x-pack/plugins/ml/public/application/components/custom_urls/custom_urls.tsx index 8c92a4c4515a5..7bec64f3bf6b3 100644 --- a/x-pack/plugins/ml/public/application/components/custom_urls/custom_urls.tsx +++ b/x-pack/plugins/ml/public/application/components/custom_urls/custom_urls.tsx @@ -178,7 +178,7 @@ export class CustomUrls extends Component { http: { basePath }, data: { dataViews }, dashboard, - mlServices: { mlApiServices: ml }, + mlServices: { mlApi }, } = this.context.services; const dataViewId = this.state?.editorSettings?.kibanaSettings?.discoverIndexPatternId; const job = this.props.job; @@ -194,7 +194,7 @@ export class CustomUrls extends Component { buildCustomUrlFromSettings(dashboard, this.state.editorSettings as CustomUrlSettings).then( (customUrl) => { getTestUrl( - ml, + mlApi, job, customUrl, timefieldName, diff --git a/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js b/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js index 409002011926d..7f4501a087784 100644 --- a/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js +++ b/x-pack/plugins/ml/public/application/components/data_recognizer/data_recognizer.js @@ -29,9 +29,10 @@ export class DataRecognizer extends Component { } componentDidMount() { - const ml = this.context.services.mlServices.mlApiServices; + const mlApi = this.context.services.mlServices.mlApi; // once the mount is complete, call the recognize endpoint to see if the index format is known to us, - ml.recognizeIndex({ indexPatternTitle: this.indexPattern.title }) + mlApi + .recognizeIndex({ indexPatternTitle: this.indexPattern.title }) .then((resp) => { // Sort results by title prior to display resp.sort((res1, res2) => res1.title.localeCompare(res2.title)); diff --git a/x-pack/plugins/ml/public/application/components/delete_space_aware_item_check_modal/delete_space_aware_item_check_modal.tsx b/x-pack/plugins/ml/public/application/components/delete_space_aware_item_check_modal/delete_space_aware_item_check_modal.tsx index 70290bee78c98..053c6e0ad8039 100644 --- a/x-pack/plugins/ml/public/application/components/delete_space_aware_item_check_modal/delete_space_aware_item_check_modal.tsx +++ b/x-pack/plugins/ml/public/application/components/delete_space_aware_item_check_modal/delete_space_aware_item_check_modal.tsx @@ -27,7 +27,7 @@ import type { CanDeleteMLSpaceAwareItemsResponse, MlSavedObjectType, } from '../../../../common/types/saved_objects'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { useToastNotificationService } from '../../services/toast_notification_service'; import { ManagedJobsWarningCallout } from '../../jobs/jobs_list/components/confirm_modals/managed_jobs_warning_callout'; @@ -252,7 +252,7 @@ export const DeleteSpaceAwareItemCheckModal: FC = ({ const { savedObjects: { canDeleteMLSpaceAwareItems, removeItemFromCurrentSpace }, - } = useMlApiContext(); + } = useMlApi(); const { displayErrorToast, displaySuccessToast } = useToastNotificationService(); // delay showing the modal to avoid flickering diff --git a/x-pack/plugins/ml/public/application/components/import_export_jobs/export_jobs_flyout/export_jobs_flyout_content.tsx b/x-pack/plugins/ml/public/application/components/import_export_jobs/export_jobs_flyout/export_jobs_flyout_content.tsx index 987280d2617db..2bda1c4ea24f0 100644 --- a/x-pack/plugins/ml/public/application/components/import_export_jobs/export_jobs_flyout/export_jobs_flyout_content.tsx +++ b/x-pack/plugins/ml/public/application/components/import_export_jobs/export_jobs_flyout/export_jobs_flyout_content.tsx @@ -96,16 +96,16 @@ export const ExportJobsFlyoutContent = ({ const { services: { notifications: { toasts }, - mlServices: { mlUsageCollection, mlApiServices }, + mlServices: { mlUsageCollection, mlApi }, }, } = useMlKibana(); const { getJobs, dataFrameAnalytics: { getDataFrameAnalytics }, - } = mlApiServices; + } = mlApi; - const jobsExportService = useMemo(() => new JobsExportService(mlApiServices), [mlApiServices]); + const jobsExportService = useMemo(() => new JobsExportService(mlApi), [mlApi]); const [adJobIds, setAdJobIds] = useState([]); const [dfaJobIds, setDfaJobIds] = useState([]); const [selectedJobIds, setSelectedJobIds] = useState([]); diff --git a/x-pack/plugins/ml/public/application/components/import_export_jobs/export_jobs_flyout/jobs_export_service.ts b/x-pack/plugins/ml/public/application/components/import_export_jobs/export_jobs_flyout/jobs_export_service.ts index 52e9bb2e101c2..bdc77872c7261 100644 --- a/x-pack/plugins/ml/public/application/components/import_export_jobs/export_jobs_flyout/jobs_export_service.ts +++ b/x-pack/plugins/ml/public/application/components/import_export_jobs/export_jobs_flyout/jobs_export_service.ts @@ -8,7 +8,7 @@ // @ts-expect-error import { saveAs } from '@elastic/filesaver'; import type { DataFrameAnalyticsConfig } from '@kbn/ml-data-frame-analytics-utils'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; import type { JobType } from '../../../../../common/types/saved_objects'; import type { Job, Datafeed } from '../../../../../common/types/anomaly_detection_jobs'; import { GLOBAL_CALENDAR } from '../../../../../common/constants/calendars'; @@ -27,18 +27,16 @@ type ExportableConfigs = | DataFrameAnalyticsConfig[]; export class JobsExportService { - constructor(private _mlApiServices: MlApiServices) {} + constructor(private _mlApi: MlApi) {} public async exportAnomalyDetectionJobs(jobIds: string[]) { - const configs = await Promise.all( - jobIds.map((id) => this._mlApiServices.jobs.jobForCloning(id, true)) - ); + const configs = await Promise.all(jobIds.map((id) => this._mlApi.jobs.jobForCloning(id, true))); this._export(configs, 'anomaly-detector'); } public async exportDataframeAnalyticsJobs(jobIds: string[]) { const { data_frame_analytics: configs } = - await this._mlApiServices.dataFrameAnalytics.getDataFrameAnalytics(jobIds.join(','), true); + await this._mlApi.dataFrameAnalytics.getDataFrameAnalytics(jobIds.join(','), true); this._export(configs, 'data-frame-analytics'); } @@ -58,7 +56,7 @@ export class JobsExportService { } public async getJobDependencies(jobs: Job[]): Promise { - const calendars = await this._mlApiServices.calendars(); + const calendars = await this._mlApi.calendars(); // create a map of all jobs in groups const groups = jobs.reduce((acc, cur) => { diff --git a/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/import_jobs_flyout.tsx b/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/import_jobs_flyout.tsx index d0870466aa89a..de13bed60152d 100644 --- a/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/import_jobs_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/import_jobs_flyout.tsx @@ -57,7 +57,7 @@ export const ImportJobsFlyout: FC = ({ isDisabled, onImportComplete }) => notifications: { toasts }, mlServices: { mlUsageCollection, - mlApiServices: { + mlApi: { jobs: { bulkCreateJobs }, dataFrameAnalytics: { createDataFrameAnalytics }, filters: { filters: getFilters }, diff --git a/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/validate.ts b/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/validate.ts index 611a3c464b440..235c3d7b5ffe0 100644 --- a/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/validate.ts +++ b/x-pack/plugins/ml/public/application/components/import_export_jobs/import_jobs_flyout/validate.ts @@ -12,7 +12,7 @@ import { isValidIndexName } from '../../../../../common/util/es_utils'; import { isJobIdValid } from '../../../../../common/util/job_utils'; import { JOB_ID_MAX_LENGTH } from '../../../../../common/constants/validation'; import type { JobIdObject } from './jobs_import_service'; -import { useMlApiContext } from '../../../contexts/kibana'; +import { useMlApi } from '../../../contexts/kibana'; export const useValidateIds = ( jobType: JobType | null, @@ -25,7 +25,7 @@ export const useValidateIds = ( jobs: { jobsExist: adJobsExist }, dataFrameAnalytics: { jobsExist: dfaJobsExist }, checkIndicesExists, - } = useMlApiContext(); + } = useMlApi(); const validateIds = useCallback(async () => { const jobIdExistsChecks: string[] = []; diff --git a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx index b4da44047fd86..02fb52c120303 100644 --- a/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/job_selector/job_selector_flyout.tsx @@ -74,7 +74,7 @@ export const JobSelectorFlyoutContent: FC = ({ const { services: { notifications, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); @@ -163,7 +163,7 @@ export const JobSelectorFlyoutContent: FC = ({ async function fetchJobs() { try { - const resp = await mlApiServices.jobs.jobsWithTimerange(dateFormatTz); + const resp = await mlApi.jobs.jobsWithTimerange(dateFormatTz); const normalizedJobs = normalizeTimes(resp.jobs, dateFormatTz, DEFAULT_GANTT_BAR_WIDTH); const { groups: groupsWithTimerange, groupsMap } = getGroupsFromJobs(normalizedJobs); setJobs(normalizedJobs); diff --git a/x-pack/plugins/ml/public/application/components/job_spaces_sync/job_spaces_sync_flyout.tsx b/x-pack/plugins/ml/public/application/components/job_spaces_sync/job_spaces_sync_flyout.tsx index a36a2abd025cc..fe4b23fbdf3a1 100644 --- a/x-pack/plugins/ml/public/application/components/job_spaces_sync/job_spaces_sync_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/job_spaces_sync/job_spaces_sync_flyout.tsx @@ -24,7 +24,7 @@ import { EuiSpacer, } from '@elastic/eui'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import type { SyncSavedObjectResponse, SyncResult } from '../../../../common/types/saved_objects'; import { SyncList } from './sync_list'; import { useToastNotificationService } from '../../services/toast_notification_service'; @@ -40,7 +40,7 @@ export const JobSpacesSyncFlyout: FC = ({ onClose }) => { const [syncResp, setSyncResp] = useState(null); const { savedObjects: { syncSavedObjects }, - } = useMlApiContext(); + } = useMlApi(); async function loadSyncList(simulate: boolean = true) { setLoading(true); diff --git a/x-pack/plugins/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx b/x-pack/plugins/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx index 44860fc5a8834..f70bf526ae113 100644 --- a/x-pack/plugins/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx +++ b/x-pack/plugins/ml/public/application/components/jobs_awaiting_node_warning/new_job_awaiting_node_shared/new_job_awaiting_node_shared.tsx @@ -13,7 +13,7 @@ import { EuiCallOut, EuiSpacer, EuiLink } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { useKibana } from '@kbn/kibana-react-plugin/public'; import { JOB_STATE } from '../../../../../common/constants/states'; -import { mlApiServicesProvider } from '../../../services/ml_api_service'; +import { mlApiProvider } from '../../../services/ml_api_service'; import { HttpService } from '../../../services/http_service'; import type { CloudInfo } from '../../../services/ml_server_info'; import { extractDeploymentId } from '../../../services/ml_server_info'; @@ -28,7 +28,7 @@ function isJobAwaitingNodeAssignment(job: estypes.MlJobStats) { const MLJobsAwaitingNodeWarning: FC = ({ jobIds }) => { const { http } = useKibana().services; - const ml = useMemo(() => mlApiServicesProvider(new HttpService(http!)), [http]); + const mlApi = useMemo(() => mlApiProvider(new HttpService(http!)), [http]); const [unassignedJobCount, setUnassignedJobCount] = useState(0); const [cloudInfo, setCloudInfo] = useState(null); @@ -40,13 +40,13 @@ const MLJobsAwaitingNodeWarning: FC = ({ jobIds }) => { return; } - const { lazyNodeCount } = await ml.mlNodeCount(); + const { lazyNodeCount } = await mlApi.mlNodeCount(); if (lazyNodeCount === 0) { setUnassignedJobCount(0); return; } - const { jobs } = await ml.getJobStats({ jobId: jobIds.join(',') }); + const { jobs } = await mlApi.getJobStats({ jobId: jobIds.join(',') }); const unassignedJobs = jobs.filter(isJobAwaitingNodeAssignment); setUnassignedJobCount(unassignedJobs.length); } catch (error) { @@ -63,7 +63,7 @@ const MLJobsAwaitingNodeWarning: FC = ({ jobIds }) => { } try { - const resp = await ml.mlInfo(); + const resp = await mlApi.mlInfo(); const cloudId = resp.cloudId ?? null; const isCloudTrial = resp.isCloudTrial === true; setCloudInfo({ diff --git a/x-pack/plugins/ml/public/application/components/ml_entity_selector/ml_entity_selector.test.tsx b/x-pack/plugins/ml/public/application/components/ml_entity_selector/ml_entity_selector.test.tsx index 1ab9bf280b291..04591a6a9037e 100644 --- a/x-pack/plugins/ml/public/application/components/ml_entity_selector/ml_entity_selector.test.tsx +++ b/x-pack/plugins/ml/public/application/components/ml_entity_selector/ml_entity_selector.test.tsx @@ -8,8 +8,8 @@ import React from 'react'; import { render, waitFor, screen } from '@testing-library/react'; import { MlEntitySelector } from './ml_entity_selector'; -import { useMlApiContext } from '../../contexts/kibana'; -import type { MlApiServices } from '../../services/ml_api_service'; +import { useMlApi } from '../../contexts/kibana'; +import type { MlApi } from '../../services/ml_api_service'; import { useToastNotificationService } from '../../services/toast_notification_service'; jest.mock('../../contexts/kibana'); @@ -32,7 +32,7 @@ describe('MlEntitySelector', () => { return Promise.resolve([{ model_id: 'model_01' }]); }); - (useMlApiContext as jest.MockedFunction).mockImplementation(() => { + (useMlApi as jest.MockedFunction).mockImplementation(() => { return { jobs: { getAllJobAndGroupIds, @@ -43,7 +43,7 @@ describe('MlEntitySelector', () => { trainedModels: { getTrainedModels, }, - } as unknown as jest.Mocked; + } as unknown as jest.Mocked; }); beforeEach(() => {}); @@ -132,7 +132,7 @@ describe('MlEntitySelector', () => { }); test('provide current selection update on change with duplicates handling', async () => { - (useMlApiContext as jest.MockedFunction).mockImplementationOnce(() => { + (useMlApi as jest.MockedFunction).mockImplementationOnce(() => { return { jobs: { getAllJobAndGroupIds, @@ -149,7 +149,7 @@ describe('MlEntitySelector', () => { trainedModels: { getTrainedModels, }, - } as unknown as jest.Mocked; + } as unknown as jest.Mocked; }); const onChangeSpy = jest.fn(); @@ -182,14 +182,14 @@ describe('MlEntitySelector', () => { const displayErrorToast = jest.fn(); const sampleError = new Error('try a bit later'); - (useMlApiContext as jest.MockedFunction).mockImplementationOnce(() => { + (useMlApi as jest.MockedFunction).mockImplementationOnce(() => { return { jobs: { getAllJobAndGroupIds: jest.fn(() => { throw sampleError; }), }, - } as unknown as jest.Mocked; + } as unknown as jest.Mocked; }); ( useToastNotificationService as jest.MockedFunction diff --git a/x-pack/plugins/ml/public/application/components/ml_entity_selector/ml_entity_selector.tsx b/x-pack/plugins/ml/public/application/components/ml_entity_selector/ml_entity_selector.tsx index 61a5c540be649..ebafb61cebd71 100644 --- a/x-pack/plugins/ml/public/application/components/ml_entity_selector/ml_entity_selector.tsx +++ b/x-pack/plugins/ml/public/application/components/ml_entity_selector/ml_entity_selector.tsx @@ -16,7 +16,7 @@ import { import { i18n } from '@kbn/i18n'; import { countBy } from 'lodash'; import useMount from 'react-use/lib/useMount'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { useToastNotificationService } from '../../services/toast_notification_service'; import { useEnabledFeatures } from '../../contexts/ml'; @@ -63,7 +63,7 @@ export const MlEntitySelector: FC = ({ handleDuplicates = false, }) => { const { isADEnabled, isDFAEnabled, isNLPEnabled } = useEnabledFeatures(); - const { jobs: jobsApi, trainedModels, dataFrameAnalytics } = useMlApiContext(); + const { jobs: jobsApi, trainedModels, dataFrameAnalytics } = useMlApi(); const { displayErrorToast } = useToastNotificationService(); const visColorsBehindText = euiPaletteColorBlindBehindText(); diff --git a/x-pack/plugins/ml/public/application/components/ml_inference/add_inference_pipeline_flyout.tsx b/x-pack/plugins/ml/public/application/components/ml_inference/add_inference_pipeline_flyout.tsx index 9cb6e50b8f876..1d58dce866449 100644 --- a/x-pack/plugins/ml/public/application/components/ml_inference/add_inference_pipeline_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/ml_inference/add_inference_pipeline_flyout.tsx @@ -31,7 +31,7 @@ import { ProcessorConfiguration } from './components/processor_configuration'; import { OnFailureConfiguration } from '../shared'; import { TestPipeline } from './components/test_pipeline'; import { ReviewAndCreatePipeline } from '../shared'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { getPipelineConfig } from './get_pipeline_config'; import { validateInferencePipelineConfigurationStep } from './validation'; import { type MlInferenceState, type InferenceModelTypes, TEST_PIPELINE_MODE } from './types'; @@ -54,7 +54,7 @@ export const AddInferencePipelineFlyout: FC = ( const { trainedModels: { createInferencePipeline }, - } = useMlApiContext(); + } = useMlApi(); const modelType = getModelType(model); diff --git a/x-pack/plugins/ml/public/application/components/ml_inference/components/reindex_with_pipeline.tsx b/x-pack/plugins/ml/public/application/components/ml_inference/components/reindex_with_pipeline.tsx index 17128208e7aec..b8cbdb78b20b4 100644 --- a/x-pack/plugins/ml/public/application/components/ml_inference/components/reindex_with_pipeline.tsx +++ b/x-pack/plugins/ml/public/application/components/ml_inference/components/reindex_with_pipeline.tsx @@ -29,7 +29,7 @@ import { extractErrorMessage } from '@kbn/ml-error-utils'; import { i18n } from '@kbn/i18n'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { debounce } from 'lodash'; -import { useMlApiContext, useMlKibana } from '../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../contexts/kibana'; import { isValidIndexName } from '../../../../../common/util/es_utils'; import { createKibanaDataView, checkIndexExists } from '../retry_create_data_view'; import { useToastNotificationService } from '../../../services/toast_notification_service'; @@ -85,8 +85,8 @@ export const ReindexWithPipeline: FC = ({ pipelineName, sourceIndex }) => docLinks: { links }, }, } = useMlKibana(); - const ml = useMlApiContext(); - const { getIndices, reindexWithPipeline, hasPrivileges } = ml; + const mlApi = useMlApi(); + const { getIndices, reindexWithPipeline, hasPrivileges } = mlApi; const { displayErrorToast } = useToastNotificationService(); @@ -123,7 +123,7 @@ export const ReindexWithPipeline: FC = ({ pipelineName, sourceIndex }) => ); const debouncedIndexCheck = debounce(async () => { - const checkResp = await checkIndexExists(destinationIndex, ml); + const checkResp = await checkIndexExists(destinationIndex, mlApi); if (checkResp.errorMessage !== undefined) { displayErrorToast( checkResp.errorMessage, @@ -239,7 +239,7 @@ export const ReindexWithPipeline: FC = ({ pipelineName, sourceIndex }) => const dataViewCreationResult = await createKibanaDataView( destinationIndex, data.dataViews, - ml + mlApi ); if ( dataViewCreationResult?.success === true && diff --git a/x-pack/plugins/ml/public/application/components/ml_inference/components/test_pipeline.tsx b/x-pack/plugins/ml/public/application/components/ml_inference/components/test_pipeline.tsx index 48ae32d615d93..10b02310b39d8 100644 --- a/x-pack/plugins/ml/public/application/components/ml_inference/components/test_pipeline.tsx +++ b/x-pack/plugins/ml/public/application/components/ml_inference/components/test_pipeline.tsx @@ -36,7 +36,7 @@ import { extractErrorProperties } from '@kbn/ml-error-utils'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; import { CodeEditor } from '@kbn/code-editor'; -import { useMlApiContext, useMlKibana } from '../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../contexts/kibana'; import { getPipelineConfig } from '../get_pipeline_config'; import { isValidJson } from '../../../../../common/util/validation_utils'; import type { MlInferenceState } from '../types'; @@ -67,7 +67,7 @@ export const TestPipeline: FC = memo(({ state, sourceIndex, mode }) => { const [lastFetchedSampleDocsString, setLastFetchedSampleDocsString] = useState(''); const [isValid, setIsValid] = useState(true); const [showCallOut, setShowCallOut] = useState(true); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { notifications: { toasts }, services: { @@ -88,7 +88,7 @@ export const TestPipeline: FC = memo(({ state, sourceIndex, mode }) => { const simulatePipeline = async () => { try { - const result = await ml.trainedModels.trainedModelPipelineSimulate( + const result = await mlApi.trainedModels.trainedModelPipelineSimulate( pipelineConfig, JSON.parse(sampleDocsString) as IngestSimulateDocument[] ); @@ -127,7 +127,7 @@ export const TestPipeline: FC = memo(({ state, sourceIndex, mode }) => { let records: IngestSimulateDocument[] = []; let resp; try { - resp = await ml.esSearch(body); + resp = await mlApi.esSearch(body); if (resp && resp.hits.total.value > 0) { records = resp.hits.hits; @@ -177,7 +177,7 @@ export const TestPipeline: FC = memo(({ state, sourceIndex, mode }) => { useEffect( function checkSourceIndexExists() { async function ensureSourceIndexExists() { - const resp = await checkIndexExists(sourceIndex!, ml); + const resp = await checkIndexExists(sourceIndex!, mlApi); const indexExists = resp.resp && resp.resp[sourceIndex!] && resp.resp[sourceIndex!].exists; if (indexExists === false) { setSourceIndexMissingError(sourceIndexMissingMessage); diff --git a/x-pack/plugins/ml/public/application/components/ml_inference/hooks/use_fetch_pipelines.ts b/x-pack/plugins/ml/public/application/components/ml_inference/hooks/use_fetch_pipelines.ts index 837aef2f92093..e622caf206b2e 100644 --- a/x-pack/plugins/ml/public/application/components/ml_inference/hooks/use_fetch_pipelines.ts +++ b/x-pack/plugins/ml/public/application/components/ml_inference/hooks/use_fetch_pipelines.ts @@ -7,7 +7,7 @@ import { useEffect, useState } from 'react'; import { i18n } from '@kbn/i18n'; -import { useMlApiContext, useMlKibana } from '../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../contexts/kibana'; export const useFetchPipelines = () => { const [pipelineNames, setPipelineNames] = useState([]); @@ -17,7 +17,7 @@ export const useFetchPipelines = () => { const { trainedModels: { getAllIngestPipelines }, - } = useMlApiContext(); + } = useMlApi(); useEffect(() => { async function fetchPipelines() { diff --git a/x-pack/plugins/ml/public/application/components/ml_inference/retry_create_data_view.ts b/x-pack/plugins/ml/public/application/components/ml_inference/retry_create_data_view.ts index fd270ae70dfd7..a09d0c2568e85 100644 --- a/x-pack/plugins/ml/public/application/components/ml_inference/retry_create_data_view.ts +++ b/x-pack/plugins/ml/public/application/components/ml_inference/retry_create_data_view.ts @@ -9,7 +9,7 @@ import { i18n } from '@kbn/i18n'; import { extractErrorMessage } from '@kbn/ml-error-utils'; import type { DataViewsContract } from '@kbn/data-views-plugin/public'; import { DuplicateDataViewError } from '@kbn/data-plugin/public'; -import type { MlApiServices } from '../../services/ml_api_service'; +import type { MlApi } from '../../services/ml_api_service'; import type { FormMessage } from '../../data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state'; interface CreateKibanaDataViewResponse { @@ -25,11 +25,11 @@ function delay(ms = 1000) { }); } -export async function checkIndexExists(destIndex: string, ml: MlApiServices) { +export async function checkIndexExists(destIndex: string, mlApi: MlApi) { let resp; let errorMessage; try { - resp = await ml.checkIndicesExists({ indices: [destIndex] }); + resp = await mlApi.checkIndicesExists({ indices: [destIndex] }); } catch (e) { errorMessage = extractErrorMessage(e); } @@ -38,7 +38,7 @@ export async function checkIndexExists(destIndex: string, ml: MlApiServices) { export async function retryIndexExistsCheck( destIndex: string, - ml: MlApiServices + ml: MlApi ): Promise<{ success: boolean; indexExists: boolean; @@ -70,7 +70,7 @@ export async function retryIndexExistsCheck( export const createKibanaDataView = async ( destinationIndex: string, dataViewsService: DataViewsContract, - ml: MlApiServices, + ml: MlApi, timeFieldName?: string, callback?: (response: FormMessage) => void ) => { diff --git a/x-pack/plugins/ml/public/application/components/ml_saved_objects_spaces_list/ml_saved_objects_spaces_list.tsx b/x-pack/plugins/ml/public/application/components/ml_saved_objects_spaces_list/ml_saved_objects_spaces_list.tsx index 378ae1a00fef6..9da8804d64512 100644 --- a/x-pack/plugins/ml/public/application/components/ml_saved_objects_spaces_list/ml_saved_objects_spaces_list.tsx +++ b/x-pack/plugins/ml/public/application/components/ml_saved_objects_spaces_list/ml_saved_objects_spaces_list.tsx @@ -13,7 +13,7 @@ import { i18n } from '@kbn/i18n'; import type { SpacesPluginStart, ShareToSpaceFlyoutProps } from '@kbn/spaces-plugin/public'; import type { SavedObjectResult, MlSavedObjectType } from '../../../../common/types/saved_objects'; import { ML_JOB_SAVED_OBJECT_TYPE } from '../../../../common/types/saved_objects'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { useToastNotificationService } from '../../services/toast_notification_service'; interface Props { @@ -42,7 +42,7 @@ export const MLSavedObjectsSpacesList: FC = ({ }) => { const { savedObjects: { updateJobsSpaces, updateModelsSpaces }, - } = useMlApiContext(); + } = useMlApi(); const { displayErrorToast } = useToastNotificationService(); const [showFlyout, setShowFlyout] = useState(false); diff --git a/x-pack/plugins/ml/public/application/components/model_snapshots/edit_model_snapshot_flyout/edit_model_snapshot_flyout.tsx b/x-pack/plugins/ml/public/application/components/model_snapshots/edit_model_snapshot_flyout/edit_model_snapshot_flyout.tsx index 1be4c7f479ea2..68afdde3470b1 100644 --- a/x-pack/plugins/ml/public/application/components/model_snapshots/edit_model_snapshot_flyout/edit_model_snapshot_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/model_snapshots/edit_model_snapshot_flyout/edit_model_snapshot_flyout.tsx @@ -30,7 +30,7 @@ import type { ModelSnapshot, CombinedJobWithStats, } from '../../../../../common/types/anomaly_detection_jobs'; -import { useMlApiContext, useNotifications } from '../../../contexts/kibana'; +import { useMlApi, useNotifications } from '../../../contexts/kibana'; interface Props { snapshot: ModelSnapshot; @@ -39,7 +39,7 @@ interface Props { } export const EditModelSnapshotFlyout: FC = ({ snapshot, job, closeFlyout }) => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { toasts } = useNotifications(); const [description, setDescription] = useState(snapshot.description); const [retain, setRetain] = useState(snapshot.retain); @@ -55,7 +55,7 @@ export const EditModelSnapshotFlyout: FC = ({ snapshot, job, closeFlyout const updateSnapshot = useCallback(async () => { try { - await ml.updateModelSnapshot(snapshot.job_id, snapshot.snapshot_id, { + await mlApi.updateModelSnapshot(snapshot.job_id, snapshot.snapshot_id, { description, retain, }); @@ -72,7 +72,7 @@ export const EditModelSnapshotFlyout: FC = ({ snapshot, job, closeFlyout const deleteSnapshot = useCallback(async () => { try { - await ml.deleteModelSnapshot(snapshot.job_id, snapshot.snapshot_id); + await mlApi.deleteModelSnapshot(snapshot.job_id, snapshot.snapshot_id); hideDeleteModal(); closeWithReload(); } catch (error) { diff --git a/x-pack/plugins/ml/public/application/components/model_snapshots/model_snapshots_table.tsx b/x-pack/plugins/ml/public/application/components/model_snapshots/model_snapshots_table.tsx index 2c74bb9f67969..81a3e4a8de285 100644 --- a/x-pack/plugins/ml/public/application/components/model_snapshots/model_snapshots_table.tsx +++ b/x-pack/plugins/ml/public/application/components/model_snapshots/model_snapshots_table.tsx @@ -12,7 +12,7 @@ import { i18n } from '@kbn/i18n'; import type { EuiBasicTableColumn } from '@elastic/eui'; import { EuiFlexGroup, EuiFlexItem, EuiInMemoryTable, EuiLoadingSpinner } from '@elastic/eui'; import { timeFormatter } from '@kbn/ml-date-utils'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { usePermissionCheck } from '../../capabilities/check_capabilities'; import { EditModelSnapshotFlyout } from './edit_model_snapshot_flyout'; import { RevertModelSnapshotFlyout } from './revert_model_snapshot_flyout'; @@ -36,7 +36,7 @@ export enum COMBINED_JOB_STATE { } export const ModelSnapshotTable: FC = ({ job, refreshJobList }) => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const [canCreateJob, canStartStopDatafeed] = usePermissionCheck([ 'canCreateJob', @@ -66,14 +66,14 @@ export const ModelSnapshotTable: FC = ({ job, refreshJobList }) => { // ensure the table is still visible before attempted to refresh it. return; } - const { model_snapshots: ms } = await ml.getModelSnapshots(job.job_id); + const { model_snapshots: ms } = await mlApi.getModelSnapshots(job.job_id); setSnapshots(ms); setSnapshotsLoaded(true); } const checkJobIsClosed = useCallback( async (snapshot: ModelSnapshot) => { - const jobs = await ml.jobs.jobs([job.job_id]); + const jobs = await mlApi.jobs.jobs([job.job_id]); const state = getCombinedJobState(jobs); if (state === COMBINED_JOB_STATE.UNKNOWN) { // this will only happen if the job has been deleted by another user @@ -93,7 +93,7 @@ export const ModelSnapshotTable: FC = ({ job, refreshJobList }) => { setCloseJobModalVisible(snapshot); } }, - // skip mlApiServices from deps + // skip mlApi from deps // eslint-disable-next-line react-hooks/exhaustive-deps [job] ); @@ -104,16 +104,16 @@ export const ModelSnapshotTable: FC = ({ job, refreshJobList }) => { } const forceCloseJob = useCallback(async () => { - await ml.jobs.forceStopAndCloseJob(job.job_id); + await mlApi.jobs.forceStopAndCloseJob(job.job_id); if (closeJobModalVisible !== null) { - const jobs = await ml.jobs.jobs([job.job_id]); + const jobs = await mlApi.jobs.jobs([job.job_id]); const state = getCombinedJobState(jobs); if (state === COMBINED_JOB_STATE.CLOSED) { setRevertSnapshot(closeJobModalVisible); } } hideCloseJobModalVisible(); - // skip mlApiServices from deps + // skip mlApi from deps // eslint-disable-next-line react-hooks/exhaustive-deps }, [job, closeJobModalVisible]); diff --git a/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/revert_model_snapshot_flyout.tsx b/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/revert_model_snapshot_flyout.tsx index c25bcee687e04..639c101e7be6f 100644 --- a/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/revert_model_snapshot_flyout.tsx +++ b/x-pack/plugins/ml/public/application/components/model_snapshots/revert_model_snapshot_flyout/revert_model_snapshot_flyout.tsx @@ -36,7 +36,7 @@ import type { ModelSnapshot, CombinedJobWithStats, } from '../../../../../common/types/anomaly_detection_jobs'; -import { useMlApiContext, useNotifications } from '../../../contexts/kibana'; +import { useMlApi, useNotifications } from '../../../contexts/kibana'; import { chartLoaderProvider } from './chart_loader'; import { mlResultsServiceProvider } from '../../../services/results_service'; import type { LineChartPoint } from '../../../jobs/new_job/common/chart_loader'; @@ -63,10 +63,10 @@ export const RevertModelSnapshotFlyout: FC = ({ closeFlyout, refresh, }) => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { toasts } = useNotifications(); const { loadAnomalyDataForJob, loadEventRateForJob } = useMemo( - () => chartLoaderProvider(mlResultsServiceProvider(ml)), + () => chartLoaderProvider(mlResultsServiceProvider(mlApi)), // eslint-disable-next-line react-hooks/exhaustive-deps [] ); @@ -139,7 +139,7 @@ export const RevertModelSnapshotFlyout: FC = ({ })) : undefined; - ml.jobs + mlApi.jobs .revertModelSnapshot(job.job_id, currentSnapshot.snapshot_id, replay, end, events) .then(() => { toasts.addSuccess( diff --git a/x-pack/plugins/ml/public/application/components/node_available_warning/hooks.ts b/x-pack/plugins/ml/public/application/components/node_available_warning/hooks.ts index 01b291e4b4f61..a08edd5d576d3 100644 --- a/x-pack/plugins/ml/public/application/components/node_available_warning/hooks.ts +++ b/x-pack/plugins/ml/public/application/components/node_available_warning/hooks.ts @@ -8,7 +8,7 @@ import { useEffect, useMemo, useState, useCallback } from 'react'; import { useKibana } from '@kbn/kibana-react-plugin/public'; import { HttpService } from '../../services/http_service'; -import { mlApiServicesProvider } from '../../services/ml_api_service'; +import { mlApiProvider } from '../../services/ml_api_service'; import { type CloudInfo, extractDeploymentId } from '../../services/ml_server_info'; export function useMlNodeAvailableCheck() { @@ -25,7 +25,7 @@ export function useMlNodeAvailableCheck() { export function useMlNodeCheck() { const { http } = useKibana().services; - const ml = useMemo(() => mlApiServicesProvider(new HttpService(http!)), [http]); + const mlApi = useMemo(() => mlApiProvider(new HttpService(http!)), [http]); const [mlNodeCount, setMlNodeCount] = useState(null); const [lazyMlNodeCount, setLazyMlNodeCount] = useState(null); const [userHasPermissionToViewMlNodeCount, setUserHasPermissionToViewMlNodeCount] = useState< @@ -35,7 +35,7 @@ export function useMlNodeCheck() { const checkNodes = useCallback(async () => { try { - const { count, lazyNodeCount } = await ml.mlNodeCount(); + const { count, lazyNodeCount } = await mlApi.mlNodeCount(); setMlNodeCount(count); setLazyMlNodeCount(lazyNodeCount); setUserHasPermissionToViewMlNodeCount(true); @@ -47,7 +47,7 @@ export function useMlNodeCheck() { setMlNodesAvailable(true); } } - }, [ml]); + }, [mlApi]); useEffect( function checkNodesInit() { @@ -74,12 +74,12 @@ const defaultCloudInfo: CloudInfo = { export function useCloudCheck() { const { http } = useKibana().services; - const ml = useMemo(() => mlApiServicesProvider(new HttpService(http!)), [http]); + const mlApi = useMemo(() => mlApiProvider(new HttpService(http!)), [http]); const [cloudInfo, setCloudInfo] = useState(defaultCloudInfo); const loadInfo = useCallback(async () => { try { - const resp = await ml.mlInfo(); + const resp = await mlApi.mlInfo(); setCloudInfo({ cloudId: resp.cloudId ?? null, isCloud: resp.cloudId !== undefined, @@ -91,7 +91,7 @@ export function useCloudCheck() { setCloudInfo(defaultCloudInfo); } } - }, [ml]); + }, [mlApi]); useEffect( function loadInfoInit() { diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js index 36c7d6cc00a88..59f1fd3d39818 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.js @@ -83,7 +83,7 @@ class RuleEditorFlyoutUI extends Component { this.mlJobService = mlJobServiceFactory( toastNotificationServiceProvider(props.kibana.services.notifications.toasts), - props.kibana.services.mlServices.mlApiServices + props.kibana.services.mlServices.mlApi ); } @@ -154,7 +154,7 @@ class RuleEditorFlyoutUI extends Component { if (this.partitioningFieldNames.length > 0 && this.canGetFilters) { // Load the current list of filters. These are used for configuring rule scope. - this.props.kibana.services.mlServices.mlApiServices.filters + this.props.kibana.services.mlServices.mlApi.filters .filters() .then((filters) => { const filterListIds = filters.map((filter) => filter.filter_id); @@ -344,13 +344,13 @@ class RuleEditorFlyoutUI extends Component { updateRuleAtIndex = (ruleIndex, editedRule) => { const mlJobService = this.mlJobService; const { toasts } = this.props.kibana.services.notifications; - const { mlApiServices } = this.props.kibana.services.mlServices; + const { mlApi } = this.props.kibana.services.mlServices; const { job, anomaly } = this.state; const jobId = job.job_id; const detectorIndex = anomaly.detectorIndex; - saveJobRule(mlJobService, job, detectorIndex, ruleIndex, editedRule, mlApiServices) + saveJobRule(mlJobService, job, detectorIndex, ruleIndex, editedRule, mlApi) .then((resp) => { if (resp.success) { toasts.add({ @@ -400,12 +400,12 @@ class RuleEditorFlyoutUI extends Component { deleteRuleAtIndex = (index) => { const mlJobService = this.mlJobService; const { toasts } = this.props.kibana.services.notifications; - const { mlApiServices } = this.props.kibana.services.mlServices; + const { mlApi } = this.props.kibana.services.mlServices; const { job, anomaly } = this.state; const jobId = job.job_id; const detectorIndex = anomaly.detectorIndex; - deleteJobRule(mlJobService, job, detectorIndex, index, mlApiServices) + deleteJobRule(mlJobService, job, detectorIndex, index, mlApi) .then((resp) => { if (resp.success) { toasts.addSuccess( @@ -453,8 +453,8 @@ class RuleEditorFlyoutUI extends Component { addItemToFilterList = (item, filterId, closeFlyoutOnAdd) => { const { toasts } = this.props.kibana.services.notifications; - const { mlApiServices } = this.props.kibana.services.mlServices; - addItemToFilter(item, filterId, mlApiServices) + const { mlApi } = this.props.kibana.services.mlServices; + addItemToFilter(item, filterId, mlApi) .then(() => { if (closeFlyoutOnAdd === true) { toasts.add({ diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js index 8dce7f8f45f78..a711774b0a21d 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/rule_editor_flyout.test.js @@ -92,7 +92,7 @@ function prepareTest() { }, }, }, - mlServices: { mlApiServices: {} }, + mlServices: { mlApi: {} }, notifications: { toasts: { addDanger: () => {}, diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js index aeca2d6425fd7..1da606864a1e6 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.js @@ -43,7 +43,7 @@ export class RuleActionPanel extends Component { } componentDidMount() { - const ml = this.context.services.mlServices.mlApiServices; + const mlApi = this.context.services.mlServices.mlApi; // If the rule has a scope section with a single partitioning field key, // load the filter list to check whether to add a link to add the // anomaly partitioning field value to the filter list. @@ -59,7 +59,7 @@ export class RuleActionPanel extends Component { partitionFieldValue[0].length > 0 ) { const filterId = scope[partitionFieldName].filter_id; - ml.filters + mlApi.filters .filters({ filterId }) .then((filter) => { const filterItems = filter.items; diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.test.js b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.test.js index 79414b02a5e48..0ca4e3d692d09 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.test.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/select_rule_action/rule_action_panel.test.js @@ -31,7 +31,7 @@ const mockTestFilter = { const kibanaReactContextMock = createKibanaReactContext({ mlServices: { - mlApiServices: { + mlApi: { filters: { filters: () => { return Promise.resolve(mockTestFilter); diff --git a/x-pack/plugins/ml/public/application/components/rule_editor/utils.js b/x-pack/plugins/ml/public/application/components/rule_editor/utils.js index a2c8c6d11f8e5..7f0a28a77a98b 100644 --- a/x-pack/plugins/ml/public/application/components/rule_editor/utils.js +++ b/x-pack/plugins/ml/public/application/components/rule_editor/utils.js @@ -68,14 +68,7 @@ export function isValidRule(rule) { return isValid; } -export function saveJobRule( - mlJobService, - job, - detectorIndex, - ruleIndex, - editedRule, - mlApiServices -) { +export function saveJobRule(mlJobService, job, detectorIndex, ruleIndex, editedRule, mlApi) { const detector = job.analysis_config.detectors[detectorIndex]; // Filter out any scope expression where the UI=specific 'enabled' @@ -108,16 +101,16 @@ export function saveJobRule( } } - return updateJobRules(mlJobService, job, detectorIndex, rules, mlApiServices); + return updateJobRules(mlJobService, job, detectorIndex, rules, mlApi); } -export function deleteJobRule(mlJobService, job, detectorIndex, ruleIndex, mlApiServices) { +export function deleteJobRule(mlJobService, job, detectorIndex, ruleIndex, mlApi) { const detector = job.analysis_config.detectors[detectorIndex]; let customRules = []; if (detector.custom_rules !== undefined && ruleIndex < detector.custom_rules.length) { customRules = cloneDeep(detector.custom_rules); customRules.splice(ruleIndex, 1); - return updateJobRules(mlJobService, job, detectorIndex, customRules, mlApiServices); + return updateJobRules(mlJobService, job, detectorIndex, customRules, mlApi); } else { return Promise.reject( new Error( @@ -133,7 +126,7 @@ export function deleteJobRule(mlJobService, job, detectorIndex, ruleIndex, mlApi } } -export function updateJobRules(mlJobService, job, detectorIndex, rules, mlApiServices) { +export function updateJobRules(mlJobService, job, detectorIndex, rules, mlApi) { // Pass just the detector with the edited rule to the updateJob endpoint. const jobId = job.job_id; const jobData = { @@ -152,7 +145,7 @@ export function updateJobRules(mlJobService, job, detectorIndex, rules, mlApiSer jobData.custom_settings = customSettings; } return new Promise((resolve, reject) => { - mlApiServices + mlApi .updateJob({ jobId: jobId, job: jobData }) .then(() => { mlJobService @@ -172,9 +165,9 @@ export function updateJobRules(mlJobService, job, detectorIndex, rules, mlApiSer // Updates an ML filter used in the scope part of a rule, // adding an item to the filter with the specified ID. -export function addItemToFilter(item, filterId, mlApiServices) { +export function addItemToFilter(item, filterId, mlApi) { return new Promise((resolve, reject) => { - mlApiServices.filters + mlApi.filters .updateFilter(filterId, undefined, [item], undefined) .then((updatedFilter) => { resolve(updatedFilter); diff --git a/x-pack/plugins/ml/public/application/components/saved_objects_warning/saved_objects_warning.tsx b/x-pack/plugins/ml/public/application/components/saved_objects_warning/saved_objects_warning.tsx index 05d0888d1df58..e20bb825f7d79 100644 --- a/x-pack/plugins/ml/public/application/components/saved_objects_warning/saved_objects_warning.tsx +++ b/x-pack/plugins/ml/public/application/components/saved_objects_warning/saved_objects_warning.tsx @@ -10,7 +10,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { EuiCallOut, EuiLink, EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import type { MlSavedObjectType } from '../../../../common/types/saved_objects'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { JobSpacesSyncFlyout } from '../job_spaces_sync'; import { usePermissionCheck } from '../../capabilities/check_capabilities'; @@ -27,7 +27,7 @@ export const SavedObjectsWarning: FC = ({ }) => { const { savedObjects: { syncCheck }, - } = useMlApiContext(); + } = useMlApi(); const mounted = useRef(false); const [showWarning, setShowWarning] = useState(false); diff --git a/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.test.tsx b/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.test.tsx index 247623d1dcacb..3fd25534134ae 100644 --- a/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.test.tsx +++ b/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.test.tsx @@ -25,7 +25,7 @@ const mockEsSearch = jest.fn((body) => ({ const mockEuiTheme = euiThemeLight; jest.mock('../../contexts/kibana', () => ({ - useMlApiContext: () => ({ + useMlApi: () => ({ esSearch: mockEsSearch, }), useMlKibana: () => ({ diff --git a/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx b/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx index cbde25596b60b..dab7dc4117083 100644 --- a/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx +++ b/x-pack/plugins/ml/public/application/components/scatterplot_matrix/scatterplot_matrix.tsx @@ -36,7 +36,7 @@ import { } from '@kbn/ml-runtime-field-utils'; import { getProcessedFields } from '@kbn/ml-data-grid'; -import { useCurrentThemeVars, useMlApiContext, useMlKibana } from '../../contexts/kibana'; +import { useCurrentThemeVars, useMlApi, useMlKibana } from '../../contexts/kibana'; // Separate imports for lazy loadable VegaChart and related code import { VegaChart } from '../vega_chart'; @@ -117,7 +117,7 @@ export const ScatterplotMatrix: FC = ({ dataView, query, }) => { - const { esSearch } = useMlApiContext(); + const { esSearch } = useMlApi(); const kibana = useMlKibana(); const { services: { application, data }, diff --git a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js index acc17d6b8c0da..a959208fe0c31 100644 --- a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js +++ b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.js @@ -130,7 +130,7 @@ export class ValidateJobUI extends Component { if (typeof duration === 'object' && duration.start !== null && duration.end !== null) { let shouldShowLoadingIndicator = true; - this.props.kibana.services.mlServices.mlApiServices + this.props.kibana.services.mlServices.mlApi .validateJob({ duration, fields, job }) .then((validationMessages) => { const messages = parseMessages(validationMessages, docLinks); diff --git a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.test.js b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.test.js index 5bc57a1a1fd73..265245bcd883f 100644 --- a/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.test.js +++ b/x-pack/plugins/ml/public/application/components/validate_job/validate_job_view.test.js @@ -35,7 +35,7 @@ const mockKibanaContext = { services: { docLinks: { links: { ml: { anomalyDetectionJobTips: 'https://anomalyDetectionJobTips' } } }, notifications: { toasts: { addDanger: jest.fn(), addError: jest.fn() } }, - mlServices: { mlApiServices: { validateJob: mockValidateJob } }, + mlServices: { mlApi: { validateJob: mockValidateJob } }, }, }; diff --git a/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/index.ts b/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/index.ts index 991fd607f024e..bd360725fd3c5 100644 --- a/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/index.ts +++ b/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/index.ts @@ -7,5 +7,5 @@ export { useMlKibana } from './kibana_context'; export { useTimefilter } from './use_timefilter'; -export { useMlApiContext } from './use_ml_api_context'; +export { useMlApi } from './use_ml_api_context'; export { useMlLicenseInfo } from './use_ml_license'; diff --git a/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/kibana_context.ts b/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/kibana_context.ts index 671df792a9375..c31a7e57c73d5 100644 --- a/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/kibana_context.ts +++ b/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/kibana_context.ts @@ -61,7 +61,7 @@ export const kibanaContextMock = { charts: chartsServiceMock, fieldFormats: fieldFormatsServiceMock.createStartContract(), mlServices: { - mlApiServices: mlApiServicesMock, + mlApi: mlApiServicesMock, mlCapabilities: { refreshCapabilities: jest.fn(), }, diff --git a/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/use_ml_api_context.ts b/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/use_ml_api_context.ts index b50802dd74b93..e257ad2613701 100644 --- a/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/use_ml_api_context.ts +++ b/x-pack/plugins/ml/public/application/contexts/kibana/__mocks__/use_ml_api_context.ts @@ -5,9 +5,9 @@ * 2.0. */ -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; -export const useMlApiContext: () => jest.Mocked = jest.fn(() => { +export const useMlApi: () => jest.Mocked = jest.fn(() => { return { jobs: { getAllJobAndGroupIds: jest.fn(), @@ -18,5 +18,5 @@ export const useMlApiContext: () => jest.Mocked = jest.fn(() => { dataFrameAnalytics: { getDataFrameAnalytics: jest.fn(), }, - } as unknown as jest.Mocked; + } as unknown as jest.Mocked; }); diff --git a/x-pack/plugins/ml/public/application/contexts/kibana/index.ts b/x-pack/plugins/ml/public/application/contexts/kibana/index.ts index e8696e9b49068..47836e6495c06 100644 --- a/x-pack/plugins/ml/public/application/contexts/kibana/index.ts +++ b/x-pack/plugins/ml/public/application/contexts/kibana/index.ts @@ -12,7 +12,7 @@ export { useNavigateToPath } from './use_navigate_to_path'; export { useUiSettings } from './use_ui_settings_context'; export { useNotifications } from './use_notifications_context'; export { useMlLocator, useMlLink } from './use_create_url'; -export { useMlApiContext } from './use_ml_api_context'; +export { useMlApi } from './use_ml_api_context'; export { useFieldFormatter } from './use_field_formatter'; export { useCurrentThemeVars } from './use_current_theme'; export { useMlLicenseInfo } from './use_ml_license'; diff --git a/x-pack/plugins/ml/public/application/contexts/kibana/use_ml_api_context.ts b/x-pack/plugins/ml/public/application/contexts/kibana/use_ml_api_context.ts index f06610df1e4ce..c403bc5036876 100644 --- a/x-pack/plugins/ml/public/application/contexts/kibana/use_ml_api_context.ts +++ b/x-pack/plugins/ml/public/application/contexts/kibana/use_ml_api_context.ts @@ -7,6 +7,6 @@ import { useMlKibana } from './kibana_context'; -export const useMlApiContext = () => { - return useMlKibana().services.mlServices.mlApiServices; +export const useMlApi = () => { + return useMlKibana().services.mlServices.mlApi; }; diff --git a/x-pack/plugins/ml/public/application/contexts/ml/ml_notifications_context.test.tsx b/x-pack/plugins/ml/public/application/contexts/ml/ml_notifications_context.test.tsx index ad6c05d07d4e1..a2623266712dc 100644 --- a/x-pack/plugins/ml/public/application/contexts/ml/ml_notifications_context.test.tsx +++ b/x-pack/plugins/ml/public/application/contexts/ml/ml_notifications_context.test.tsx @@ -18,7 +18,7 @@ const mockCountMessages = jest.fn(() => { const mockKibana = { services: { mlServices: { - mlApiServices: { + mlApi: { notifications: { countMessages$: mockCountMessages, }, @@ -67,7 +67,7 @@ describe('useMlNotifications', () => { }); test('retries polling on error with 1m delay', () => { - mockKibana.services.mlServices.mlApiServices.notifications.countMessages$.mockReturnValueOnce( + mockKibana.services.mlServices.mlApi.notifications.countMessages$.mockReturnValueOnce( throwError(() => new Error('Cluster is down')) ); @@ -79,24 +79,24 @@ describe('useMlNotifications', () => { jest.advanceTimersByTime(0); }); - expect( - mockKibana.services.mlServices.mlApiServices.notifications.countMessages$ - ).toHaveBeenCalledTimes(1); - expect( - mockKibana.services.mlServices.mlApiServices.notifications.countMessages$ - ).toHaveBeenCalledWith({ lastCheckedAt: 1663340537063 }); + expect(mockKibana.services.mlServices.mlApi.notifications.countMessages$).toHaveBeenCalledTimes( + 1 + ); + expect(mockKibana.services.mlServices.mlApi.notifications.countMessages$).toHaveBeenCalledWith({ + lastCheckedAt: 1663340537063, + }); act(() => { // ticks 4 minutes jest.advanceTimersByTime(60000 * 4); }); - expect( - mockKibana.services.mlServices.mlApiServices.notifications.countMessages$ - ).toHaveBeenCalledTimes(4); - expect( - mockKibana.services.mlServices.mlApiServices.notifications.countMessages$ - ).toHaveBeenCalledWith({ lastCheckedAt: 1663340537063 }); + expect(mockKibana.services.mlServices.mlApi.notifications.countMessages$).toHaveBeenCalledTimes( + 4 + ); + expect(mockKibana.services.mlServices.mlApi.notifications.countMessages$).toHaveBeenCalledWith({ + lastCheckedAt: 1663340537063, + }); }); test('returns the default values', () => { @@ -244,7 +244,7 @@ describe('useMlNotifications', () => { }); expect( - mockKibana.services.mlServices.mlApiServices.notifications.countMessages$ + mockKibana.services.mlServices.mlApi.notifications.countMessages$ ).not.toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/ml/public/application/contexts/ml/ml_notifications_context.tsx b/x-pack/plugins/ml/public/application/contexts/ml/ml_notifications_context.tsx index dc37535517659..d0ffdf528fc7c 100644 --- a/x-pack/plugins/ml/public/application/contexts/ml/ml_notifications_context.tsx +++ b/x-pack/plugins/ml/public/application/contexts/ml/ml_notifications_context.tsx @@ -42,7 +42,7 @@ export const MlNotificationsContext = React.createContext<{ export const MlNotificationsContextProvider: FC> = ({ children }) => { const { services: { - mlServices: { mlApiServices }, + mlServices: { mlApi }, application: { capabilities }, }, } = useMlKibana(); @@ -75,7 +75,7 @@ export const MlNotificationsContextProvider: FC> = ({ setLatestRequestedAt(lastCheckedAtQuery); }), switchMap((lastCheckedAtQuery) => - mlApiServices.notifications.countMessages$({ + mlApi.notifications.countMessages$({ lastCheckedAt: lastCheckedAtQuery, }) ), @@ -89,7 +89,7 @@ export const MlNotificationsContextProvider: FC> = ({ subscription.unsubscribe(); }; }, - [canGetNotifications, lastCheckedAt$, mlApiServices.notifications] + [canGetNotifications, lastCheckedAt$, mlApi.notifications] ); return ( diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts index a636974e68b94..3264c7cc11f7a 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts @@ -20,7 +20,7 @@ import { } from '@kbn/ml-data-frame-analytics-utils'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { Dictionary } from '../../../../common/types/common'; -import type { MlApiServices } from '../../services/ml_api_service'; +import type { MlApi } from '../../services/ml_api_service'; export type IndexPattern = string; @@ -289,7 +289,7 @@ export enum REGRESSION_STATS { } interface LoadEvalDataConfig { - mlApiServices: MlApiServices; + mlApi: MlApi; isTraining?: boolean; index: string; dependentVariable: string; @@ -304,7 +304,7 @@ interface LoadEvalDataConfig { } export const loadEvalData = async ({ - mlApiServices, + mlApi, isTraining, index, dependentVariable, @@ -362,7 +362,7 @@ export const loadEvalData = async ({ }; try { - const evalResult = await mlApiServices.dataFrameAnalytics.evaluateDataFrameAnalytics(config); + const evalResult = await mlApi.dataFrameAnalytics.evaluateDataFrameAnalytics(config); results.success = true; results.eval = evalResult; return results; @@ -373,7 +373,7 @@ export const loadEvalData = async ({ }; interface LoadDocsCountConfig { - mlApiServices: MlApiServices; + mlApi: MlApi; ignoreDefaultQuery?: boolean; isTraining?: boolean; searchQuery: estypes.QueryDslQueryContainer; @@ -387,7 +387,7 @@ interface LoadDocsCountResponse { } export const loadDocsCount = async ({ - mlApiServices, + mlApi, ignoreDefaultQuery = true, isTraining, searchQuery, @@ -402,7 +402,7 @@ export const loadDocsCount = async ({ query, }; - const resp: TrackTotalHitsSearchResponse = await mlApiServices.esSearch({ + const resp: TrackTotalHitsSearchResponse = await mlApi.esSearch({ index: destIndex, size: 0, body, diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts index bd289f3a1cdd7..6e2cb20025e72 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_data.ts @@ -12,17 +12,17 @@ import type { EsSorting, UseDataGridReturnType } from '@kbn/ml-data-grid'; import { getProcessedFields, INDEX_STATUS } from '@kbn/ml-data-grid'; import { mlJobCapsServiceAnalyticsFactory } from '../../services/new_job_capabilities/new_job_capabilities_service_analytics'; -import type { MlApiServices } from '../../services/ml_api_service'; +import type { MlApi } from '../../services/ml_api_service'; export const getIndexData = async ( - mlApiServices: MlApiServices, + mlApi: MlApi, jobConfig: DataFrameAnalyticsConfig | undefined, dataGrid: UseDataGridReturnType, searchQuery: estypes.QueryDslQueryContainer, options: { didCancel: boolean } ) => { if (jobConfig !== undefined) { - const newJobCapsServiceAnalytics = mlJobCapsServiceAnalyticsFactory(mlApiServices); + const newJobCapsServiceAnalytics = mlJobCapsServiceAnalyticsFactory(mlApi); const { pagination, @@ -50,7 +50,7 @@ export const getIndexData = async ( const { pageIndex, pageSize } = pagination; // TODO: remove results_field from `fields` when possible - const resp: estypes.SearchResponse = await mlApiServices.esSearch({ + const resp: estypes.SearchResponse = await mlApi.esSearch({ index: jobConfig.dest.index, body: { fields: ['*'], diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts index 0cc1bb0b587c0..f4bcec71fdcdf 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/get_index_fields.ts @@ -9,20 +9,20 @@ import type { ES_FIELD_TYPES } from '@kbn/field-types'; import type { DataFrameAnalyticsConfig } from '@kbn/ml-data-frame-analytics-utils'; import { mlJobCapsServiceAnalyticsFactory } from '../../services/new_job_capabilities/new_job_capabilities_service_analytics'; -import type { MlApiServices } from '../../services/ml_api_service'; +import type { MlApi } from '../../services/ml_api_service'; export interface FieldTypes { [key: string]: ES_FIELD_TYPES; } export const getIndexFields = ( - mlApiServices: MlApiServices, + mlApi: MlApi, jobConfig: DataFrameAnalyticsConfig | undefined, needsDestIndexFields: boolean ) => { if (jobConfig !== undefined) { const { selectedFields: defaultSelected, docFields } = mlJobCapsServiceAnalyticsFactory( - mlApiServices + mlApi ).getDefaultFields(jobConfig, needsDestIndexFields); const types: FieldTypes = {}; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts index fba862558b766..3ff08a2845c88 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/use_results_view_config.ts @@ -19,7 +19,7 @@ import { type TotalFeatureImportance, } from '@kbn/ml-data-frame-analytics-utils'; -import { useMlApiContext, useMlKibana } from '../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../contexts/kibana'; import { useNewJobCapsServiceAnalytics } from '../../services/new_job_capabilities/new_job_capabilities_service_analytics'; import { useMlIndexUtils } from '../../util/index_service'; @@ -35,7 +35,7 @@ export const useResultsViewConfig = (jobId: string) => { }, } = useMlKibana(); const toastNotificationService = useToastNotificationService(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { getDataViewIdFromName } = useMlIndexUtils(); const trainedModelsApiService = useTrainedModelsApiService(); const newJobCapsServiceAnalytics = useNewJobCapsServiceAnalytics(); @@ -62,9 +62,9 @@ export const useResultsViewConfig = (jobId: string) => { setIsLoadingJobConfig(false); try { - const analyticsConfigs = await ml.dataFrameAnalytics.getDataFrameAnalytics(jobId); + const analyticsConfigs = await mlApi.dataFrameAnalytics.getDataFrameAnalytics(jobId); - const analyticsStats = await ml.dataFrameAnalytics.getDataFrameAnalyticsStats(jobId); + const analyticsStats = await mlApi.dataFrameAnalytics.getDataFrameAnalyticsStats(jobId); const stats = isGetDataFrameAnalyticsStatsResponseOk(analyticsStats) ? analyticsStats.data_frame_analytics[0] : undefined; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_form.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_form.tsx index 9b8dec570a5e9..e87201cbb7b11 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_form.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_form.tsx @@ -32,7 +32,7 @@ import { import { HyperParameters } from './hyper_parameters'; import type { CreateAnalyticsStepProps } from '../../../analytics_management/hooks/use_create_analytics_form'; import { getModelMemoryLimitErrors } from '../../../analytics_management/hooks/use_create_analytics_form/reducer'; -import { useMlKibana, useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlKibana, useMlApi } from '../../../../../contexts/kibana'; import { DEFAULT_MODEL_MEMORY_LIMIT } from '../../../analytics_management/hooks/use_create_analytics_form/state'; import { ANALYTICS_STEPS } from '../../page'; import { fetchExplainData } from '../shared'; @@ -134,7 +134,7 @@ export const AdvancedStepForm: FC = ({ const { services: { docLinks }, } = useMlKibana(); - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const classAucRocDocLink = docLinks.links.ml.classificationAucRoc; const { setEstimatedModelMemoryLimit, setFormState } = actions; @@ -207,7 +207,7 @@ export const AdvancedStepForm: FC = ({ setFetchingAdvancedParamErrors(true); (async function () { const { success, errorMessage, errorReason, expectedMemory } = await fetchExplainData( - mlApiServices, + mlApi, form ); const paramErrors: AdvancedParamErrors = {}; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx index 4f737c1137663..c0920b39d47fc 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/configuration_step/configuration_step_form.tsx @@ -29,7 +29,7 @@ import { } from '@kbn/ml-data-frame-analytics-utils'; import { DataGrid } from '@kbn/ml-data-grid'; import { SEARCH_QUERY_LANGUAGE } from '@kbn/ml-query-utils'; -import { useMlApiContext, useMlKibana } from '../../../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../../../contexts/kibana'; import { EuiComboBoxWithFieldStats, FieldStatsFlyoutProvider, @@ -116,7 +116,7 @@ export const ConfigurationStepForm: FC = ({ }) => { const { services } = useMlKibana(); const toastNotifications = services.notifications.toasts; - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const newJobCapsServiceAnalytics = useNewJobCapsServiceAnalytics(); const { selectedDataView, selectedSavedSearch } = useDataSource(); const { savedSearchQuery, savedSearchQueryStr } = useSavedSearch(); @@ -288,7 +288,7 @@ export const ConfigurationStepForm: FC = ({ fieldSelection, errorMessage, noDocsContainMappedFields: noDocsWithFields, - } = await fetchExplainData(mlApiServices, formToUse); + } = await fetchExplainData(mlApi, formToUse); if (success) { if (shouldUpdateEstimatedMml) { @@ -444,7 +444,7 @@ export const ConfigurationStepForm: FC = ({ fieldSelection, errorMessage, noDocsContainMappedFields: noDocsWithFields, - } = await fetchExplainData(mlApiServices, formCopy); + } = await fetchExplainData(mlApi, formCopy); if (success) { // update the field selection table const hasRequiredFields = fieldSelection.some( diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx index a2a6e965c3e70..2f329be788398 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_analytics_advanced_editor/create_analytics_advanced_editor.tsx @@ -14,7 +14,7 @@ import { i18n } from '@kbn/i18n'; import { extractErrorMessage } from '@kbn/ml-error-utils'; import { dynamic } from '@kbn/shared-ux-utility'; -import { useMlApiContext, useNotifications } from '../../../../../contexts/kibana'; +import { useMlApi, useNotifications } from '../../../../../contexts/kibana'; import type { CreateAnalyticsFormProps } from '../../../analytics_management/hooks/use_create_analytics_form'; import { CreateStep } from '../create_step'; import { ANALYTICS_STEPS } from '../../page'; @@ -24,7 +24,7 @@ const EditorComponent = dynamic(async () => ({ })); export const CreateAnalyticsAdvancedEditor: FC = (props) => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { actions, state } = props; const { setAdvancedEditorRawString, setFormState } = actions; @@ -43,7 +43,7 @@ export const CreateAnalyticsAdvancedEditor: FC = (prop () => debounce(async () => { try { - const results = await ml.dataFrameAnalytics.jobsExist([jobId], true); + const results = await mlApi.dataFrameAnalytics.jobsExist([jobId], true); setFormState({ jobIdExists: results[jobId].exists }); } catch (e) { toasts.addDanger( diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_step_footer/create_step_footer.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_step_footer/create_step_footer.tsx index b7dac69e1226e..715733c163314 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_step_footer/create_step_footer.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/create_step_footer/create_step_footer.tsx @@ -16,7 +16,7 @@ import { } from '@kbn/ml-data-frame-analytics-utils'; import { getDataFrameAnalyticsProgressPhase } from '../../../analytics_management/components/analytics_list/common'; import { isGetDataFrameAnalyticsStatsResponseOk } from '../../../analytics_management/services/analytics_service/get_analytics'; -import { useMlApiContext, useMlKibana } from '../../../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../../../contexts/kibana'; import { BackToListPanel } from '../back_to_list_panel'; import { ViewResultsPanel } from '../view_results_panel'; import { ProgressStats } from './progress_stats'; @@ -48,7 +48,7 @@ export const CreateStepFooter: FC = ({ jobId, jobType, showProgress }) => const { services: { notifications }, } = useMlKibana(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); useEffect(() => { setInitialized(true); @@ -59,7 +59,7 @@ export const CreateStepFooter: FC = ({ jobId, jobType, showProgress }) => const interval = setInterval(async () => { try { - const analyticsStats = await ml.dataFrameAnalytics.getDataFrameAnalyticsStats(jobId); + const analyticsStats = await mlApi.dataFrameAnalytics.getDataFrameAnalyticsStats(jobId); const jobStats = isGetDataFrameAnalyticsStatsResponseOk(analyticsStats) ? analyticsStats.data_frame_analytics[0] : undefined; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/details_step/details_step_form.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/details_step/details_step_form.tsx index d80c23732dcbd..f43ce7bd2fb9b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/details_step/details_step_form.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/details_step/details_step_form.tsx @@ -14,7 +14,7 @@ import { extractErrorMessage } from '@kbn/ml-error-utils'; import { CreateDataViewForm } from '@kbn/ml-data-view-utils/components/create_data_view_form_row'; import { DestinationIndexForm } from '@kbn/ml-creation-wizard-utils/components/destination_index_form'; -import { useMlApiContext, useMlKibana } from '../../../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../../../contexts/kibana'; import type { CreateAnalyticsStepProps } from '../../../analytics_management/hooks/use_create_analytics_form'; import { JOB_ID_MAX_LENGTH } from '../../../../../../../common/constants/validation'; import { ContinueButton } from '../continue_button'; @@ -42,7 +42,7 @@ export const DetailsStepForm: FC = ({ const { services: { docLinks, notifications }, } = useMlKibana(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const canCreateDataView = useCanCreateDataView(); const { dataViewAvailableTimeFields, onTimeFieldChanged } = useDataViewTimeFields({ @@ -90,7 +90,7 @@ export const DetailsStepForm: FC = ({ const debouncedIndexCheck = debounce(async () => { try { - const resp = await ml.checkIndicesExists({ indices: [destinationIndex] }); + const resp = await mlApi.checkIndicesExists({ indices: [destinationIndex] }); setFormState({ destinationIndexNameExists: resp[destinationIndex].exists }); } catch (e) { notifications.toasts.addDanger( @@ -106,7 +106,7 @@ export const DetailsStepForm: FC = ({ () => debounce(async () => { try { - const results = await ml.dataFrameAnalytics.jobsExist([jobId], true); + const results = await mlApi.dataFrameAnalytics.jobsExist([jobId], true); setFormState({ jobIdExists: results[jobId].exists }); } catch (e) { notifications.toasts.addDanger( diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/shared/fetch_explain_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/shared/fetch_explain_data.ts index 680415e189354..44150ae0e047a 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/shared/fetch_explain_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/shared/fetch_explain_data.ts @@ -13,9 +13,9 @@ import type { } from '@kbn/ml-data-frame-analytics-utils'; import type { State } from '../../../analytics_management/hooks/use_create_analytics_form/state'; import { getJobConfigFromFormState } from '../../../analytics_management/hooks/use_create_analytics_form/state'; -import type { MlApiServices } from '../../../../../services/ml_api_service'; +import type { MlApi } from '../../../../../services/ml_api_service'; -export const fetchExplainData = async (mlApiServices: MlApiServices, formState: State['form']) => { +export const fetchExplainData = async (mlApi: MlApi, formState: State['form']) => { const jobConfig = getJobConfigFromFormState(formState); let errorMessage = ''; let errorReason = ''; @@ -29,7 +29,7 @@ export const fetchExplainData = async (mlApiServices: MlApiServices, formState: delete jobConfig.model_memory_limit; delete jobConfig.analyzed_fields; const resp: DfAnalyticsExplainResponse = - await mlApiServices.dataFrameAnalytics.explainDataFrameAnalytics(jobConfig); + await mlApi.dataFrameAnalytics.explainDataFrameAnalytics(jobConfig); expectedMemory = resp.memory_estimation?.expected_memory_without_disk; fieldSelection = resp.field_selection || []; } catch (error) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/validation_step/validation_step_wrapper.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/validation_step/validation_step_wrapper.tsx index d0adffc24ec01..3c8cba36458a2 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/validation_step/validation_step_wrapper.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/validation_step/validation_step_wrapper.tsx @@ -18,7 +18,7 @@ import type { CreateAnalyticsStepProps } from '../../../analytics_management/hoo import { ValidationStep } from './validation_step'; import { ValidationStepDetails } from './validation_step_details'; import { ANALYTICS_STEPS } from '../../page'; -import { useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../contexts/kibana'; import { getJobConfigFromFormState } from '../../../analytics_management/hooks/use_create_analytics_form/state'; import type { CalloutMessage, @@ -53,7 +53,7 @@ export const ValidationStepWrapper: FC = ({ const showDetails = step !== ANALYTICS_STEPS.VALIDATION && stepActivated === true; const { dataFrameAnalytics: { validateDataFrameAnalytics }, - } = useMlApiContext(); + } = useMlApi(); const dataTestSubj = `mlAnalyticsCreateJobWizardValidationStepWrapper${ showValidationStep ? ' active' : '' diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_has_index_permission.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_has_index_permission.ts index 2fc8fb6b85f14..a618d172cbb4c 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_has_index_permission.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_has_index_permission.ts @@ -17,7 +17,7 @@ export const useHasRequiredIndicesPermissions = ( const { services: { mlServices: { - mlApiServices: { hasPrivileges }, + mlApi: { hasPrivileges }, }, }, } = useMlKibana(); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts index 80abafecd83ed..a0b995fabffc8 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts @@ -34,7 +34,7 @@ import { INDEX_STATUS, } from '@kbn/ml-data-grid'; -import { useMlApiContext } from '../../../../contexts/kibana'; +import { useMlApi } from '../../../../contexts/kibana'; import { DataLoader } from '../../../../datavisualizer/index_based/data_loader'; type IndexSearchResponse = estypes.SearchResponse; @@ -81,7 +81,7 @@ export const useIndexData = ( toastNotifications: CoreSetup['notifications']['toasts'], runtimeMappings?: RuntimeMappings ): UseIndexDataReturnType => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); // Fetch 500 random documents to determine populated fields. // This is a workaround to avoid passing potentially thousands of unpopulated fields // (for example, as part of filebeat/metricbeat/ECS based indices) @@ -110,7 +110,7 @@ export const useIndexData = ( }; try { - const resp: IndexSearchResponse = await ml.esSearch(esSearchRequest); + const resp: IndexSearchResponse = await mlApi.esSearch(esSearchRequest); const docs = resp.hits.hits.map((d) => getProcessedFields(d.fields ?? {})); // Get all field names for each returned doc and flatten it @@ -216,7 +216,7 @@ export const useIndexData = ( }; try { - const resp: IndexSearchResponse = await ml.esSearch(esSearchRequest); + const resp: IndexSearchResponse = await mlApi.esSearch(esSearchRequest); if ( resp.aggregations && @@ -258,7 +258,7 @@ export const useIndexData = ( ]); const dataLoader = useMemo( - () => new DataLoader(dataView, ml), + () => new DataLoader(dataView, mlApi), // eslint-disable-next-line react-hooks/exhaustive-deps [dataView] ); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/page.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/page.tsx index 4890ac59ffbe6..aa276e55ba024 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/page.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/page.tsx @@ -21,7 +21,7 @@ import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; import type { DataFrameAnalyticsId } from '@kbn/ml-data-frame-analytics-utils'; import { useDataSource } from '../../../contexts/ml/data_source_context'; -import { useMlApiContext } from '../../../contexts/kibana'; +import { useMlApi } from '../../../contexts/kibana'; import { useCreateAnalyticsForm } from '../analytics_management/hooks/use_create_analytics_form'; import { CreateAnalyticsAdvancedEditor } from './components/create_analytics_advanced_editor'; import { @@ -46,7 +46,7 @@ interface Props { } export const Page: FC = ({ jobId }) => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const [currentStep, setCurrentStep] = useState(ANALYTICS_STEPS.CONFIGURATION); const [activatedSteps, setActivatedSteps] = useState([ true, @@ -71,7 +71,10 @@ export const Page: FC = ({ jobId }) => { if (selectedDataView) { (async function () { if (jobId !== undefined) { - const analyticsConfigs = await ml.dataFrameAnalytics.getDataFrameAnalytics(jobId, true); + const analyticsConfigs = await mlApi.dataFrameAnalytics.getDataFrameAnalytics( + jobId, + true + ); if ( Array.isArray(analyticsConfigs.data_frame_analytics) && analyticsConfigs.data_frame_analytics.length > 0 diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/use_confusion_matrix.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/use_confusion_matrix.ts index 74ca62a874081..132ce9bd12aae 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/use_confusion_matrix.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/use_confusion_matrix.ts @@ -17,7 +17,7 @@ import { } from '@kbn/ml-data-frame-analytics-utils'; import { useNewJobCapsServiceAnalytics } from '../../../../../services/new_job_capabilities/new_job_capabilities_service_analytics'; -import { useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../contexts/kibana'; import type { ResultsSearchQuery, ClassificationMetricItem } from '../../../../common/analytics'; import { isClassificationEvaluateResponse } from '../../../../common/analytics'; @@ -60,7 +60,7 @@ export const useConfusionMatrix = ( jobConfig: DataFrameAnalyticsConfig, searchQuery: ResultsSearchQuery ) => { - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const newJobCapsServiceAnalytics = useNewJobCapsServiceAnalytics(); const [confusionMatrixData, setConfusionMatrixData] = useState([]); const [overallAccuracy, setOverallAccuracy] = useState(null); @@ -89,7 +89,7 @@ export const useConfusionMatrix = ( } const evalData = await loadEvalData({ - mlApiServices, + mlApi, isTraining, index: jobConfig.dest.index, dependentVariable, @@ -101,7 +101,7 @@ export const useConfusionMatrix = ( }); const docsCountResp = await loadDocsCount({ - mlApiServices, + mlApi, isTraining, searchQuery, resultsField, diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/use_roc_curve.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/use_roc_curve.ts index 88dd6f20cd75d..de85a818b6c16 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/use_roc_curve.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/classification_exploration/use_roc_curve.ts @@ -16,7 +16,7 @@ import { } from '@kbn/ml-data-frame-analytics-utils'; import { useNewJobCapsServiceAnalytics } from '../../../../../services/new_job_capabilities/new_job_capabilities_service_analytics'; -import { useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../contexts/kibana'; import type { ResultsSearchQuery } from '../../../../common/analytics'; import { isClassificationEvaluateResponse } from '../../../../common/analytics'; @@ -40,7 +40,7 @@ export const useRocCurve = ( searchQuery: ResultsSearchQuery, columns: string[] ) => { - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const newJobCapsServiceAnalytics = useNewJobCapsServiceAnalytics(); const classificationClasses = columns.filter( (d) => d !== ACTUAL_CLASS_ID && d !== OTHER_CLASS_ID @@ -77,7 +77,7 @@ export const useRocCurve = ( for (let i = 0; i < classificationClasses.length; i++) { const rocCurveClassName = classificationClasses[i]; const evalData = await loadEvalData({ - mlApiServices, + mlApi, isTraining: isTrainingFilter(searchQuery, resultsField), index: jobConfig.dest.index, dependentVariable, diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/expandable_section_analytics.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/expandable_section_analytics.tsx index 10e302fad2249..2b90712726666 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/expandable_section_analytics.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/expandable_section/expandable_section_analytics.tsx @@ -21,7 +21,7 @@ import { isGetDataFrameAnalyticsStatsResponseOk } from '../../../analytics_manag import type { DataFrameAnalyticsListRow } from '../../../analytics_management/components/analytics_list/common'; import { DATA_FRAME_MODE } from '../../../analytics_management/components/analytics_list/common'; import { ExpandedRow } from '../../../analytics_management/components/analytics_list/expanded_row'; -import { useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../contexts/kibana'; import type { ExpandableSectionProps } from './expandable_section'; import { ExpandableSection, HEADER_ITEMS_LOADING } from './expandable_section'; @@ -75,13 +75,13 @@ interface ExpandableSectionAnalyticsProps { } export const ExpandableSectionAnalytics: FC = ({ jobId }) => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const [expandedRowItem, setExpandedRowItem] = useState(); const fetchStats = async () => { - const analyticsConfigs = await ml.dataFrameAnalytics.getDataFrameAnalytics(jobId); - const analyticsStats = await ml.dataFrameAnalytics.getDataFrameAnalyticsStats(jobId); + const analyticsConfigs = await mlApi.dataFrameAnalytics.getDataFrameAnalytics(jobId); + const analyticsStats = await mlApi.dataFrameAnalytics.getDataFrameAnalyticsStats(jobId); const config = analyticsConfigs.data_frame_analytics[0]; const stats = isGetDataFrameAnalyticsStatsResponseOk(analyticsStats) diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts index 34ad61d02cd3b..8d2d70dd898a4 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts @@ -34,7 +34,7 @@ import { } from '@kbn/ml-data-grid'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import { useMlApiContext, useMlKibana } from '../../../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../../../contexts/kibana'; import { DataLoader } from '../../../../../datavisualizer/index_based/data_loader'; import { getIndexData, getIndexFields } from '../../../../common'; @@ -51,7 +51,7 @@ export const useExplorationResults = ( notifications: { toasts }, }, } = useMlKibana(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const [baseline, setBaseLine] = useState(); const trainedModelsApiService = useTrainedModelsApiService(); @@ -63,7 +63,7 @@ export const useExplorationResults = ( if (jobConfig !== undefined) { const resultsField = jobConfig.dest.results_field!; - const { fieldTypes } = getIndexFields(ml, jobConfig, needsDestIndexFields); + const { fieldTypes } = getIndexFields(mlApi, jobConfig, needsDestIndexFields); columns.push( ...getDataGridSchemasFromFieldTypes(fieldTypes, resultsField).sort((a: any, b: any) => sortExplorationResultsFields(a.id, b.id, jobConfig) @@ -84,7 +84,7 @@ export const useExplorationResults = ( // passed on to `getIndexData`. useEffect(() => { const options = { didCancel: false }; - getIndexData(ml, jobConfig, dataGrid, searchQuery, options); + getIndexData(mlApi, jobConfig, dataGrid, searchQuery, options); return () => { options.didCancel = true; }; @@ -93,7 +93,7 @@ export const useExplorationResults = ( }, [jobConfig && jobConfig.id, dataGrid.pagination, searchQuery, dataGrid.sortingColumns]); const dataLoader = useMemo( - () => (dataView !== undefined ? new DataLoader(dataView, ml) : undefined), + () => (dataView !== undefined ? new DataLoader(dataView, mlApi) : undefined), // eslint-disable-next-line react-hooks/exhaustive-deps [dataView] ); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts index 5b9ce4646b9e7..8c362cd1b06b4 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts @@ -33,7 +33,7 @@ import { COLOR_RANGE, COLOR_RANGE_SCALE, } from '../../../../../components/color_range_legend'; -import { useMlApiContext, useMlKibana } from '../../../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../../../contexts/kibana'; import { getIndexData, getIndexFields } from '../../../../common'; @@ -50,7 +50,7 @@ export const useOutlierData = ( notifications: { toasts }, }, } = useMlKibana(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const needsDestIndexFields = dataView !== undefined && dataView.title === jobConfig?.source.index[0]; @@ -59,7 +59,7 @@ export const useOutlierData = ( if (jobConfig !== undefined && dataView !== undefined) { const resultsField = jobConfig.dest.results_field; - const { fieldTypes } = getIndexFields(ml, jobConfig, needsDestIndexFields); + const { fieldTypes } = getIndexFields(mlApi, jobConfig, needsDestIndexFields); newColumns.push( ...getDataGridSchemasFromFieldTypes(fieldTypes, resultsField!).sort((a: any, b: any) => sortExplorationResultsFields(a.id, b.id, jobConfig) @@ -92,7 +92,7 @@ export const useOutlierData = ( // passed on to `getIndexData`. useEffect(() => { const options = { didCancel: false }; - getIndexData(ml, jobConfig, dataGrid, searchQuery, options); + getIndexData(mlApi, jobConfig, dataGrid, searchQuery, options); return () => { options.didCancel = true; }; @@ -101,7 +101,7 @@ export const useOutlierData = ( }, [jobConfig && jobConfig.id, dataGrid.pagination, searchQuery, dataGrid.sortingColumns]); const dataLoader = useMemo( - () => (dataView !== undefined ? new DataLoader(dataView, ml) : undefined), + () => (dataView !== undefined ? new DataLoader(dataView, mlApi) : undefined), // skip ml API services from deps check // eslint-disable-next-line react-hooks/exhaustive-deps [dataView] diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/evaluate_panel.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/evaluate_panel.tsx index 398e0ecb61505..935a1eecb8538 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/evaluate_panel.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/regression_exploration/evaluate_panel.tsx @@ -28,7 +28,7 @@ import { } from '@kbn/ml-data-frame-analytics-utils'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; -import { useMlApiContext, useMlKibana } from '../../../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../../../contexts/kibana'; import type { Eval } from '../../../../common'; import { getValuesFromResponse, loadEvalData, loadDocsCount } from '../../../../common'; @@ -65,7 +65,7 @@ export const EvaluatePanel: FC = ({ jobConfig, jobStatus, searchQuery }) const { services: { docLinks }, } = useMlKibana(); - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const docLink = docLinks.links.ml.regressionEvaluation; const [trainingEval, setTrainingEval] = useState(defaultEval); const [generalizationEval, setGeneralizationEval] = useState(defaultEval); @@ -85,7 +85,7 @@ export const EvaluatePanel: FC = ({ jobConfig, jobStatus, searchQuery }) setIsLoadingGeneralization(true); const genErrorEval = await loadEvalData({ - mlApiServices, + mlApi, isTraining: false, index, dependentVariable, @@ -124,7 +124,7 @@ export const EvaluatePanel: FC = ({ jobConfig, jobStatus, searchQuery }) setIsLoadingTraining(true); const trainingErrorEval = await loadEvalData({ - mlApiServices, + mlApi, isTraining: true, index, dependentVariable, @@ -162,7 +162,7 @@ export const EvaluatePanel: FC = ({ jobConfig, jobStatus, searchQuery }) const loadData = async () => { loadGeneralizationData(false); const genDocsCountResp = await loadDocsCount({ - mlApiServices, + mlApi, ignoreDefaultQuery: false, isTraining: false, searchQuery, @@ -177,7 +177,7 @@ export const EvaluatePanel: FC = ({ jobConfig, jobStatus, searchQuery }) loadTrainingData(false); const trainDocsCountResp = await loadDocsCount({ - mlApiServices, + mlApi, ignoreDefaultQuery: false, isTraining: true, searchQuery, diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/page.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/page.tsx index d9994a47e6a88..fd7cf90dbb7df 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/page.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/page.tsx @@ -20,7 +20,7 @@ import { RegressionExploration } from './components/regression_exploration'; import { ClassificationExploration } from './components/classification_exploration'; import { HelpMenu } from '../../../components/help_menu'; -import { useMlKibana, useMlApiContext } from '../../../contexts/kibana'; +import { useMlKibana, useMlApi } from '../../../contexts/kibana'; import { MlPageHeader } from '../../../components/page_header'; import type { AnalyticsSelectorIds } from '../components/analytics_selector'; import { AnalyticsIdSelector, AnalyticsIdSelectorControls } from '../components/analytics_selector'; @@ -39,7 +39,7 @@ export const Page: FC<{ } = useMlKibana(); const { dataFrameAnalytics: { getDataFrameAnalytics }, - } = useMlApiContext(); + } = useMlApi(); const helpLink = docLinks.links.ml.dataFrameAnalytics; const jobIdToUse = jobId ?? analyticsId?.job_id; const [analysisTypeToUse, setAnalysisTypeToUse] = useState< diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/delete_action_name.test.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/delete_action_name.test.tsx index 2ae6a2ae1b265..08abae19d3401 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/delete_action_name.test.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/delete_action_name.test.tsx @@ -22,7 +22,7 @@ jest.mock('../../../../../capabilities/check_capabilities', () => ({ })); jest.mock('../../../../../contexts/kibana', () => ({ - useMlApiContext: jest.fn(), + useMlApi: jest.fn(), useMlKibana: () => ({ services: { ...mockCoreServices.createStart(), data: { data_view: { find: jest.fn() } } }, }), diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_edit/edit_action_flyout.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_edit/edit_action_flyout.tsx index cc66cf0c34dbf..77aa8b669011c 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_edit/edit_action_flyout.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_edit/edit_action_flyout.tsx @@ -36,7 +36,7 @@ import { type UpdateDataFrameAnalyticsConfig, } from '@kbn/ml-data-frame-analytics-utils'; -import { useMlKibana, useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlKibana, useMlApi } from '../../../../../contexts/kibana'; import { useToastNotificationService } from '../../../../../services/toast_notification_service'; import type { MemoryInputValidatorResult } from '../../../../../../../common/util/validators'; import { memoryInputValidator } from '../../../../../../../common/util/validators'; @@ -69,10 +69,10 @@ export const EditActionFlyout: FC> = ({ closeFlyout, item } } = useMlKibana(); const { refresh } = useRefreshAnalyticsList(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { dataFrameAnalytics: { getDataFrameAnalytics }, - } = ml; + } = mlApi; const toastNotificationService = useToastNotificationService(); @@ -122,7 +122,7 @@ export const EditActionFlyout: FC> = ({ closeFlyout, item } const updateDataFrameAnalytics = async (updateConfig: UpdateDataFrameAnalyticsConfig) => { try { - await ml.dataFrameAnalytics.updateDataFrameAnalytics(jobId, updateConfig); + await mlApi.dataFrameAnalytics.updateDataFrameAnalytics(jobId, updateConfig); notifications.toasts.addSuccess( i18n.translate('xpack.ml.dataframe.analyticsList.editFlyoutSuccessMessage', { defaultMessage: 'Analytics job {jobId} has been updated.', diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_messages_pane.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_messages_pane.tsx index cdfd3f00ff3dc..ed16443cff7b1 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_messages_pane.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/analytics_list/expanded_row_messages_pane.tsx @@ -10,7 +10,7 @@ import './expanded_row_messages_pane.scss'; import type { FC } from 'react'; import React, { useState, useEffect, useCallback } from 'react'; import { i18n } from '@kbn/i18n'; -import { useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../contexts/kibana'; import { useRefreshAnalyticsList } from '../../../../common'; import { JobMessages } from '../../../../../components/job_messages'; import type { JobMessage } from '../../../../../../../common/types/audit_message'; @@ -22,7 +22,7 @@ interface Props { } export const ExpandedRowMessagesPane: FC = ({ analyticsId, dataTestSubj }) => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const [messages, setMessages] = useState([]); const [isLoading, setIsLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(''); @@ -31,7 +31,7 @@ export const ExpandedRowMessagesPane: FC = ({ analyticsId, dataTestSubj } const getMessages = useCallback(async () => { try { setIsLoading(true); - const messagesResp = await ml.dataFrameAnalytics.getAnalyticsAuditMessages(analyticsId); + const messagesResp = await mlApi.dataFrameAnalytics.getAnalyticsAuditMessages(analyticsId); setIsLoading(false); setMessages(messagesResp); } catch (error) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts index f458c11551698..07fa5e133d701 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/use_create_analytics_form.ts @@ -13,7 +13,7 @@ import { extractErrorMessage } from '@kbn/ml-error-utils'; import { extractErrorProperties } from '@kbn/ml-error-utils'; import type { DataFrameAnalyticsConfig } from '@kbn/ml-data-frame-analytics-utils'; -import { useMlApiContext, useMlKibana } from '../../../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../../../contexts/kibana'; import type { DeepReadonly } from '../../../../../../../common/types/common'; import { useRefreshAnalyticsList } from '../../../../common'; @@ -49,7 +49,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { data: { dataViews }, }, } = useMlKibana(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const [state, dispatch] = useReducer(reducer, getInitialState()); const { refresh } = useRefreshAnalyticsList(); @@ -95,7 +95,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { ); try { - const creationResp = await ml.dataFrameAnalytics.createDataFrameAnalytics( + const creationResp = await mlApi.dataFrameAnalytics.createDataFrameAnalytics( jobId, analyticsJobConfig, createDataView, @@ -168,7 +168,7 @@ export const useCreateAnalyticsForm = (): CreateAnalyticsFormProps => { const startAnalyticsJob = async () => { try { - const response = await ml.dataFrameAnalytics.startDataFrameAnalytics(jobId); + const response = await mlApi.dataFrameAnalytics.startDataFrameAnalytics(jobId); if (response.acknowledged !== true) { throw new Error(response); } diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts index 281ebeccabac9..074f3257580c2 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts @@ -8,18 +8,18 @@ import { i18n } from '@kbn/i18n'; import { extractErrorMessage } from '@kbn/ml-error-utils'; -import { useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../contexts/kibana'; import { useToastNotificationService } from '../../../../../services/toast_notification_service'; import { refreshAnalyticsList$, REFRESH_ANALYTICS_LIST_STATE } from '../../../../common'; import type { DataFrameAnalyticsListRow } from '../../components/analytics_list/common'; export const useDeleteAnalytics = () => { const toastNotificationService = useToastNotificationService(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); return async (analyticsConfig: DataFrameAnalyticsListRow['config']) => { try { - await ml.dataFrameAnalytics.deleteDataFrameAnalytics(analyticsConfig.id); + await mlApi.dataFrameAnalytics.deleteDataFrameAnalytics(analyticsConfig.id); toastNotificationService.displaySuccessToast( i18n.translate('xpack.ml.dataframe.analyticsList.deleteAnalyticsSuccessMessage', { defaultMessage: 'Request to delete data frame analytics job {analyticsId} acknowledged.', @@ -41,7 +41,7 @@ export const useDeleteAnalytics = () => { export const useDeleteAnalyticsAndDestIndex = () => { const toastNotificationService = useToastNotificationService(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); return async ( analyticsConfig: DataFrameAnalyticsListRow['config'], @@ -50,7 +50,7 @@ export const useDeleteAnalyticsAndDestIndex = () => { ) => { const destinationIndex = analyticsConfig.dest.index; try { - const status = await ml.dataFrameAnalytics.deleteDataFrameAnalyticsAndDestIndex( + const status = await mlApi.dataFrameAnalytics.deleteDataFrameAnalyticsAndDestIndex( analyticsConfig.id, deleteDestIndex, deleteDestDataView @@ -134,11 +134,11 @@ export const useDeleteAnalyticsAndDestIndex = () => { export const useCanDeleteIndex = () => { const toastNotificationService = useToastNotificationService(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); return async (indexName: string) => { try { - const privilege = await ml.hasPrivileges({ + const privilege = await mlApi.hasPrivileges({ index: [ { names: [indexName], // uses wildcard diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts index 9a7cccc77aa3f..b143271c61cc8 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/get_analytics.ts @@ -11,7 +11,7 @@ import { type DataFrameAnalysisConfigType, DATA_FRAME_TASK_STATE, } from '@kbn/ml-data-frame-analytics-utils'; -import { useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../contexts/kibana'; import type { GetDataFrameAnalyticsStatsResponseError, GetDataFrameAnalyticsStatsResponseOk, @@ -116,7 +116,7 @@ export const useGetAnalytics = ( setJobsAwaitingNodeCount: React.Dispatch>, blockRefresh: boolean ): GetAnalytics => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); let concurrentLoads = 0; @@ -130,8 +130,8 @@ export const useGetAnalytics = ( } try { - const analyticsConfigs = await ml.dataFrameAnalytics.getDataFrameAnalytics(); - const analyticsStats = await ml.dataFrameAnalytics.getDataFrameAnalyticsStats(); + const analyticsConfigs = await mlApi.dataFrameAnalytics.getDataFrameAnalytics(); + const analyticsStats = await mlApi.dataFrameAnalytics.getDataFrameAnalyticsStats(); const analyticsStatsResult = isGetDataFrameAnalyticsStatsResponseOk(analyticsStats) ? getAnalyticsJobsStats(analyticsStats) diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/start_analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/start_analytics.ts index a5b0dfd32ffa5..b938872c76163 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/start_analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/start_analytics.ts @@ -7,7 +7,7 @@ import { i18n } from '@kbn/i18n'; -import { useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../contexts/kibana'; import { useToastNotificationService } from '../../../../../services/toast_notification_service'; import { refreshAnalyticsList$, REFRESH_ANALYTICS_LIST_STATE } from '../../../../common'; @@ -16,11 +16,11 @@ import type { DataFrameAnalyticsListRow } from '../../components/analytics_list/ export const useStartAnalytics = () => { const toastNotificationService = useToastNotificationService(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); return async (d: DataFrameAnalyticsListRow) => { try { - await ml.dataFrameAnalytics.startDataFrameAnalytics(d.config.id); + await mlApi.dataFrameAnalytics.startDataFrameAnalytics(d.config.id); toastNotificationService.displaySuccessToast( i18n.translate('xpack.ml.dataframe.analyticsList.startAnalyticsSuccessMessage', { defaultMessage: 'Request to start data frame analytics {analyticsId} acknowledged.', diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/stop_analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/stop_analytics.ts index af0b746a17332..af471ab21df21 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/stop_analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/stop_analytics.ts @@ -7,7 +7,7 @@ import { i18n } from '@kbn/i18n'; -import { useMlApiContext } from '../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../contexts/kibana'; import { useToastNotificationService } from '../../../../../services/toast_notification_service'; import { refreshAnalyticsList$, REFRESH_ANALYTICS_LIST_STATE } from '../../../../common'; @@ -17,11 +17,11 @@ import { isDataFrameAnalyticsFailed } from '../../components/analytics_list/comm export const useStopAnalytics = () => { const toastNotificationService = useToastNotificationService(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); return async (d: DataFrameAnalyticsListRow) => { try { - await ml.dataFrameAnalytics.stopDataFrameAnalytics( + await mlApi.dataFrameAnalytics.stopDataFrameAnalytics( d.config.id, isDataFrameAnalyticsFailed(d.stats.state) ); diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/components/analytics_selector/analytics_id_selector.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/components/analytics_selector/analytics_id_selector.tsx index 7878e58193b89..bf786436919a9 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/components/analytics_selector/analytics_id_selector.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/components/analytics_selector/analytics_id_selector.tsx @@ -29,7 +29,7 @@ import { useTrainedModelsApiService } from '../../../../services/ml_api_service/ import type { GetDataFrameAnalyticsResponse } from '../../../../services/ml_api_service/data_frame_analytics'; import { useToastNotificationService } from '../../../../services/toast_notification_service'; import { ModelsTableToConfigMapping } from '../../../../model_management/config_mapping'; -import { useMlApiContext } from '../../../../contexts/kibana'; +import { useMlApi } from '../../../../contexts/kibana'; import type { TrainedModelConfigResponse } from '../../../../../../common/types/trained_models'; export interface AnalyticsSelectorIds { @@ -127,7 +127,7 @@ export function AnalyticsIdSelector({ const trainedModelsApiService = useTrainedModelsApiService(); const { dataFrameAnalytics: { getDataFrameAnalytics }, - } = useMlApiContext(); + } = useMlApi(); function renderTabs() { return ; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/page.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/page.tsx index 6cb7532b7bb9a..7afb189cf91f3 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/page.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/page.tsx @@ -16,7 +16,7 @@ import { SavedObjectsWarning } from '../../../components/saved_objects_warning'; import { UpgradeWarning } from '../../../components/upgrade'; import { JobMap } from '.'; import { HelpMenu } from '../../../components/help_menu'; -import { useMlKibana, useMlApiContext } from '../../../contexts/kibana'; +import { useMlKibana, useMlApi } from '../../../contexts/kibana'; import { useRefreshAnalyticsList } from '../../common'; import { MlPageHeader } from '../../../components/page_header'; import type { AnalyticsSelectorIds } from '../components/analytics_selector'; @@ -52,7 +52,7 @@ export const Page: FC = () => { } = useMlKibana(); const { dataFrameAnalytics: { getDataFrameAnalytics }, - } = useMlApiContext(); + } = useMlApi(); const helpLink = docLinks.links.ml.dataFrameAnalytics; const checkJobsExist = async () => { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/use_fetch_analytics_map_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/use_fetch_analytics_map_data.ts index d56cd4b7c638d..53c144e62ffd0 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/use_fetch_analytics_map_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/job_map/use_fetch_analytics_map_data.ts @@ -14,7 +14,7 @@ import { JOB_MAP_NODE_TYPES, type AnalyticsMapReturnType, } from '@kbn/ml-data-frame-analytics-utils'; -import { useMlApiContext } from '../../../contexts/kibana'; +import { useMlApi } from '../../../contexts/kibana'; interface GetDataObjectParameter { analyticsId?: string; id?: string; @@ -23,7 +23,7 @@ interface GetDataObjectParameter { } export const useFetchAnalyticsMapData = () => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const [isLoading, setIsLoading] = useState(false); const [elements, setElements] = useState([]); const [error, setError] = useState(); @@ -39,7 +39,7 @@ export const useFetchAnalyticsMapData = () => { } // Pass in treatAsRoot flag - endpoint will take job or index to grab jobs created from it const analyticsMap: AnalyticsMapReturnType = - await ml.dataFrameAnalytics.getDataFrameAnalyticsMap(idToUse, treatAsRoot, type); + await mlApi.dataFrameAnalytics.getDataFrameAnalyticsMap(idToUse, treatAsRoot, type); const { elements: nodeElements, details, error: fetchError } = analyticsMap; diff --git a/x-pack/plugins/ml/public/application/datavisualizer/file_based/file_datavisualizer.tsx b/x-pack/plugins/ml/public/application/datavisualizer/file_based/file_datavisualizer.tsx index bc4d204fda223..a4ff83970c9c0 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/file_based/file_datavisualizer.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/file_based/file_datavisualizer.tsx @@ -17,7 +17,7 @@ import type { import { useTimefilter } from '@kbn/ml-date-picker'; import type { ResultLinks } from '@kbn/data-visualizer-plugin/common/app'; import { HelpMenu } from '../../components/help_menu'; -import { useMlApiContext, useMlKibana, useMlLocator } from '../../contexts/kibana'; +import { useMlApi, useMlKibana, useMlLocator } from '../../contexts/kibana'; import { ML_PAGES } from '../../../../common/constants/locator'; import { isFullLicense } from '../../license'; @@ -36,9 +36,9 @@ export const FileDataVisualizerPage: FC = () => { }, }, } = useMlKibana(); - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const mlLocator = useMlLocator()!; - getMlNodeCount(mlApiServices); + getMlNodeCount(mlApi); const [FileDataVisualizer, setFileDataVisualizer] = useState(null); const [resultLinks, setResultLinks] = useState(null); @@ -105,7 +105,7 @@ export const FileDataVisualizerPage: FC = () => { useEffect(() => { // ML uses this function if (dataVisualizer !== undefined) { - getMlNodeCount(mlApiServices); + getMlNodeCount(mlApi); const { getFileDataVisualizerComponent } = dataVisualizer; getFileDataVisualizerComponent().then((resp) => { const items = resp(); diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts b/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts index 3ca5acb5a41bc..fcf4e1cb484c4 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts @@ -12,7 +12,7 @@ import { type RuntimeMappings } from '@kbn/ml-runtime-field-utils'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import type { IndexPatternTitle } from '../../../../../common/types/kibana'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; import type { FieldHistogramRequestConfig } from '../common/request'; @@ -24,7 +24,7 @@ export class DataLoader { private _indexPatternTitle: IndexPatternTitle = ''; private _maxExamples: number = MAX_EXAMPLES_DEFAULT; - constructor(private _indexPattern: DataView, private _mlApiServices: MlApiServices) { + constructor(private _indexPattern: DataView, private _mlApi: MlApi) { this._runtimeMappings = this._indexPattern.getComputedFields().runtimeFields as RuntimeMappings; this._indexPatternTitle = _indexPattern.title; } @@ -35,7 +35,7 @@ export class DataLoader { samplerShardSize = DEFAULT_SAMPLER_SHARD_SIZE, editorRuntimeMappings?: RuntimeMappings ): Promise { - const stats = await this._mlApiServices.getVisualizerFieldHistograms({ + const stats = await this._mlApi.getVisualizerFieldHistograms({ indexPattern: this._indexPatternTitle, query, fields, diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/index_data_visualizer.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/index_data_visualizer.tsx index ac980bf21c32c..e85da14ddb808 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/index_data_visualizer.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/index_data_visualizer.tsx @@ -18,7 +18,7 @@ import type { import { useTimefilter } from '@kbn/ml-date-picker'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import useMountedState from 'react-use/lib/useMountedState'; -import { useMlApiContext, useMlKibana, useMlLocator } from '../../contexts/kibana'; +import { useMlApi, useMlKibana, useMlLocator } from '../../contexts/kibana'; import { HelpMenu } from '../../components/help_menu'; import { ML_PAGES } from '../../../../common/constants/locator'; import { isFullLicense } from '../../license'; @@ -36,15 +36,15 @@ export const IndexDataVisualizerPage: FC<{ esql: boolean }> = ({ esql = false }) dataViews: { get: getDataView }, }, mlServices: { - mlApiServices: { recognizeIndex }, + mlApi: { recognizeIndex }, }, }, } = useMlKibana(); - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const { showNodeInfo } = useEnabledFeatures(); const mlLocator = useMlLocator()!; const mlFeaturesDisabled = !isFullLicense(); - getMlNodeCount(mlApiServices); + getMlNodeCount(mlApi); const [IndexDataVisualizer, setIndexDataVisualizer] = useState( null diff --git a/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts b/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts index 80f32a3df82fc..41a3da0586e02 100644 --- a/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts +++ b/x-pack/plugins/ml/public/application/explorer/actions/load_explorer_data.ts @@ -32,12 +32,12 @@ import { loadOverallAnnotations, } from '../explorer_utils'; import type { ExplorerState } from '../reducers'; -import { useMlApiContext, useUiSettings } from '../../contexts/kibana'; +import { useMlApi, useUiSettings } from '../../contexts/kibana'; import type { MlResultsService } from '../../services/results_service'; import { mlResultsServiceProvider } from '../../services/results_service'; import type { AnomalyExplorerChartsService } from '../../services/anomaly_explorer_charts_service'; import { useAnomalyExplorerContext } from '../anomaly_explorer_context'; -import type { MlApiServices } from '../../services/ml_api_service'; +import type { MlApi } from '../../services/ml_api_service'; import { useMlJobService, type MlJobService } from '../../services/job_service'; // Memoize the data fetching methods. @@ -97,7 +97,7 @@ export const isLoadExplorerDataConfig = (arg: any): arg is LoadExplorerDataConfi */ const loadExplorerDataProvider = ( uiSettings: IUiSettingsClient, - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, mlResultsService: MlResultsService, anomalyExplorerChartsService: AnomalyExplorerChartsService, @@ -131,15 +131,10 @@ const loadExplorerDataProvider = ( // First get the data where we have all necessary args at hand using forkJoin: // annotationsData, anomalyChartRecords, influencers, overallState, tableData return forkJoin({ - overallAnnotations: memoizedLoadOverallAnnotations( - lastRefresh, - mlApiServices, - selectedJobs, - bounds - ), + overallAnnotations: memoizedLoadOverallAnnotations(lastRefresh, mlApi, selectedJobs, bounds), annotationsData: memoizedLoadAnnotationsTableData( lastRefresh, - mlApiServices, + mlApi, selectedCells, selectedJobs, bounds @@ -167,7 +162,7 @@ const loadExplorerDataProvider = ( : Promise.resolve({}), tableData: memoizedLoadAnomaliesTableData( lastRefresh, - mlApiServices, + mlApi, mlJobService, selectedCells, selectedJobs, @@ -218,16 +213,16 @@ const loadExplorerDataProvider = ( export const useExplorerData = (): [Partial | undefined, (d: any) => void] => { const uiSettings = useUiSettings(); const timefilter = useTimefilter(); - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const mlJobService = useMlJobService(); const { anomalyExplorerChartsService } = useAnomalyExplorerContext(); const loadExplorerData = useMemo(() => { - const mlResultsService = mlResultsServiceProvider(mlApiServices); + const mlResultsService = mlResultsServiceProvider(mlApi); return loadExplorerDataProvider( uiSettings, - mlApiServices, + mlApi, mlJobService, mlResultsService, anomalyExplorerChartsService, diff --git a/x-pack/plugins/ml/public/application/explorer/anomaly_explorer_context.tsx b/x-pack/plugins/ml/public/application/explorer/anomaly_explorer_context.tsx index 35b552a95cac8..2c1fb6dc8c182 100644 --- a/x-pack/plugins/ml/public/application/explorer/anomaly_explorer_context.tsx +++ b/x-pack/plugins/ml/public/application/explorer/anomaly_explorer_context.tsx @@ -61,7 +61,7 @@ export const AnomalyExplorerContextProvider: FC> = ({ const { services: { - mlServices: { mlApiServices, mlFieldFormatService }, + mlServices: { mlApi, mlFieldFormatService }, uiSettings, data, }, @@ -71,7 +71,7 @@ export const AnomalyExplorerContextProvider: FC> = ({ const [, , tableSeverityState] = useTableSeverity(); // eslint-disable-next-line react-hooks/exhaustive-deps - const mlResultsService = useMemo(() => mlResultsServiceProvider(mlApiServices), []); + const mlResultsService = useMemo(() => mlResultsServiceProvider(mlApi), []); const [anomalyExplorerContextValue, setAnomalyExplorerContextValue] = useState< AnomalyExplorerContextValue | undefined @@ -104,7 +104,7 @@ export const AnomalyExplorerContextProvider: FC> = ({ const anomalyExplorerChartsService = new AnomalyExplorerChartsService( timefilter, - mlApiServices, + mlApi, mlResultsService ); diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_utils.ts b/x-pack/plugins/ml/public/application/explorer/explorer_utils.ts index fbfad277ff45f..753e81e8204e0 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_utils.ts +++ b/x-pack/plugins/ml/public/application/explorer/explorer_utils.ts @@ -52,7 +52,7 @@ import { import type { CombinedJob } from '../../../common/types/anomaly_detection_jobs'; import type { MlResultsService } from '../services/results_service'; import type { Annotations, AnnotationsTable } from '../../../common/types/annotations'; -import type { MlApiServices } from '../services/ml_api_service'; +import type { MlApi } from '../services/ml_api_service'; export interface ExplorerJob { id: string; @@ -352,7 +352,7 @@ export function getSelectionJobIds( } export function loadOverallAnnotations( - mlApiServices: MlApiServices, + mlApi: MlApi, selectedJobs: ExplorerJob[], bounds: TimeRangeBounds ): Promise { @@ -361,7 +361,7 @@ export function loadOverallAnnotations( return new Promise((resolve) => { lastValueFrom( - mlApiServices.annotations.getAnnotations$({ + mlApi.annotations.getAnnotations$({ jobIds, earliestMs: timeRange.earliestMs, latestMs: timeRange.latestMs, @@ -407,7 +407,7 @@ export function loadOverallAnnotations( } export function loadAnnotationsTableData( - mlApiServices: MlApiServices, + mlApi: MlApi, selectedCells: AppStateSelectedCells | undefined | null, selectedJobs: ExplorerJob[], bounds: Required @@ -417,7 +417,7 @@ export function loadAnnotationsTableData( return new Promise((resolve) => { lastValueFrom( - mlApiServices.annotations.getAnnotations$({ + mlApi.annotations.getAnnotations$({ jobIds, earliestMs: timeRange.earliestMs, latestMs: timeRange.latestMs, @@ -466,7 +466,7 @@ export function loadAnnotationsTableData( } export async function loadAnomaliesTableData( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, selectedCells: AppStateSelectedCells | undefined | null, selectedJobs: ExplorerJob[], @@ -482,7 +482,7 @@ export async function loadAnomaliesTableData( const timeRange = getSelectionTimeRange(selectedCells, bounds); return new Promise((resolve, reject) => { - mlApiServices.results + mlApi.results .getAnomaliesTableData( jobIds, [], diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/datafeed_chart_flyout.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/datafeed_chart_flyout.tsx index 510149ada47e6..055b297af893f 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/datafeed_chart_flyout.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/datafeed_chart_flyout.tsx @@ -60,7 +60,7 @@ import type { import type { JobMessage } from '../../../../../../common/types/audit_message'; import type { LineAnnotationDatumWithModelSnapshot } from '../../../../../../common/types/results'; import { useToastNotificationService } from '../../../../services/toast_notification_service'; -import { useCurrentThemeVars, useMlApiContext } from '../../../../contexts/kibana'; +import { useCurrentThemeVars, useMlApi } from '../../../../contexts/kibana'; import { RevertModelSnapshotFlyout } from '../../../../components/model_snapshots/revert_model_snapshot_flyout'; import { JobMessagesPane } from '../job_details/job_messages_pane'; import { EditQueryDelay } from './edit_query_delay'; @@ -110,7 +110,7 @@ export const DatafeedChartFlyout: FC = ({ onClose, onModelSnapshotAnnotationClick, }) => { - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const [data, setData] = useState<{ datafeedConfig: CombinedJobWithStats['datafeed_config'] | undefined; bucketSpan: string | undefined; @@ -144,7 +144,7 @@ export const DatafeedChartFlyout: FC = ({ const { getModelSnapshots, results: { getDatafeedResultChartData }, - } = useMlApiContext(); + } = useMlApi(); const { displayErrorToast } = useToastNotificationService(); const { euiTheme } = useCurrentThemeVars(); const handleChange = (date: moment.Moment) => setEndDate(date); @@ -213,7 +213,7 @@ export const DatafeedChartFlyout: FC = ({ const getJobAndSnapshotData = useCallback(async () => { try { - const job: CombinedJobWithStats = await loadFullJob(mlApiServices, jobId); + const job: CombinedJobWithStats = await loadFullJob(mlApi, jobId); const modelSnapshotResultsLine: LineAnnotationDatumWithModelSnapshot[] = []; const modelSnapshotsResp = await getModelSnapshots(jobId); const modelSnapshots = modelSnapshotsResp.model_snapshots ?? []; @@ -660,7 +660,7 @@ export const JobListDatafeedChartFlyout: FC = ( unsetShowFunction, refreshJobs, }) => { - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const [isVisible, setIsVisible] = useState(false); const [job, setJob] = useState(); const [jobWithStats, setJobWithStats] = useState(); @@ -677,10 +677,10 @@ export const JobListDatafeedChartFlyout: FC = ( const showRevertModelSnapshot = useCallback(async () => { // Need to load the full job with stats, as the model snapshot // flyout needs the timestamp of the last result. - const fullJob: CombinedJobWithStats = await loadFullJob(mlApiServices, job!.id); + const fullJob: CombinedJobWithStats = await loadFullJob(mlApi, job!.id); setJobWithStats(fullJob); setIsRevertModelSnapshotFlyoutVisible(true); - // exclude mlApiServices from deps + // exclude mlApi from deps // eslint-disable-next-line react-hooks/exhaustive-deps }, [job]); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/edit_query_delay.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/edit_query_delay.tsx index 6d753cd2d3a7f..9b829222ae46a 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/edit_query_delay.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/datafeed_chart_flyout/edit_query_delay.tsx @@ -18,7 +18,7 @@ import { EuiToolTip, } from '@elastic/eui'; -import { useMlApiContext } from '../../../../contexts/kibana'; +import { useMlApi } from '../../../../contexts/kibana'; import { useToastNotificationService } from '../../../../services/toast_notification_service'; import type { Datafeed } from '../../../../../../common/types/anomaly_detection_jobs'; @@ -38,7 +38,7 @@ export const EditQueryDelay: FC<{ const [currentQueryDelay, setCurrentQueryDelay] = useState(queryDelay); const [newQueryDelay, setNewQueryDelay] = useState(); const [isEditing, setIsEditing] = useState(false); - const { updateDatafeed } = useMlApiContext(); + const { updateDatafeed } = useMlApi(); const { displaySuccessToast, displayErrorToast } = useToastNotificationService(); const updateQueryDelay = useCallback(async () => { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js index 03d8745b20ee1..4659121fd8306 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js @@ -120,7 +120,7 @@ export class EditJobFlyoutUI extends Component { showFlyout = (jobLite) => { const hasDatafeed = jobLite.hasDatafeed; - loadFullJob(this.props.kibana.services.mlServices.mlApiServices, jobLite.id) + loadFullJob(this.props.kibana.services.mlServices.mlApi, jobLite.id) .then((job) => { this.extractJob(job, hasDatafeed); this.setState({ @@ -203,12 +203,12 @@ export class EditJobFlyoutUI extends Component { ).message; } - const ml = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; if (jobDetails.jobGroups !== undefined) { jobGroupsValidationError = validateGroupNames(jobDetails.jobGroups).message; if (jobGroupsValidationError === '') { - ml.jobs.jobsExist(jobDetails.jobGroups, true).then((resp) => { + mlApi.jobs.jobsExist(jobDetails.jobGroups, true).then((resp) => { const groups = Object.values(resp); const valid = groups.some((g) => g.exists === true && g.isGroup === false) === false; if (valid === false) { @@ -273,11 +273,11 @@ export class EditJobFlyoutUI extends Component { customUrls: this.state.jobCustomUrls, }; - const mlApiServices = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; const { toasts } = this.props.kibana.services.notifications; const toastNotificationService = toastNotificationServiceProvider(toasts); - saveJob(mlApiServices, this.state.job, newJobData) + saveJob(mlApi, this.state.job, newJobData) .then(() => { toasts.addSuccess( i18n.translate('xpack.ml.jobsList.editJobFlyout.changesSavedNotificationMessage', { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js index b3c36304ed381..80680c3da2c44 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_utils.js @@ -9,7 +9,7 @@ import { difference } from 'lodash'; import { getNewJobLimits } from '../../../../services/ml_server_info'; import { processCreatedBy } from '../../../../../../common/util/job_utils'; -export function saveJob(mlApiServices, job, newJobData, finish) { +export function saveJob(mlApi, job, newJobData, finish) { return new Promise((resolve, reject) => { const jobData = { ...extractDescription(job, newJobData), @@ -29,7 +29,7 @@ export function saveJob(mlApiServices, job, newJobData, finish) { } const saveDatafeedWrapper = () => { - saveDatafeed(mlApiServices, datafeedData, job, finish) + saveDatafeed(mlApi, datafeedData, job, finish) .then(() => { resolve(); }) @@ -40,7 +40,7 @@ export function saveJob(mlApiServices, job, newJobData, finish) { // if anything has changed, post the changes if (Object.keys(jobData).length) { - mlApiServices + mlApi .updateJob({ jobId: job.job_id, job: jobData }) .then(() => { saveDatafeedWrapper(); @@ -54,11 +54,11 @@ export function saveJob(mlApiServices, job, newJobData, finish) { }); } -function saveDatafeed(mlApiServices, datafeedConfig, job) { +function saveDatafeed(mlApi, datafeedConfig, job) { return new Promise((resolve, reject) => { if (Object.keys(datafeedConfig).length) { const datafeedId = job.datafeed_config.datafeed_id; - mlApiServices + mlApi .updateDatafeed({ datafeedId, datafeedConfig }) .then(() => { resolve(); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js index 01fe676a4133b..daf9e7996b5c8 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/detectors.js @@ -25,7 +25,7 @@ export class Detectors extends Component { const mlJobService = mlJobServiceFactory( toastNotificationServiceProvider(constructorContext.services.notifications.toasts), - constructorContext.services.mlServices.mlApiServices + constructorContext.services.mlServices.mlApi ); this.detectors = mlJobService.getJobGroups().map((g) => ({ label: g.id })); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js index 5cb7b9edd607e..322221045b652 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/tabs/job_details.js @@ -42,9 +42,9 @@ export class JobDetailsUI extends Component { } componentDidMount() { - const ml = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; // load groups to populate the select options - ml.jobs + mlApi.jobs .groups() .then((resp) => { const groups = resp.map((g) => ({ label: g.id, color: tabColor(g.id) })); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js index 1734182ff3ebc..eac225f2db990 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_actions/management.js @@ -24,7 +24,7 @@ import { isManagedJob } from '../../../jobs_utils'; export function actionsMenuContent( toastNotifications, application, - mlApiServices, + mlApi, mlJobService, showEditJobFlyout, showDatafeedChartFlyout, @@ -153,7 +153,7 @@ export function actionsMenuContent( return isJobBlocked(item) === false && canCreateJob; }, onClick: (item) => { - cloneJob(toastNotifications, application, mlApiServices, mlJobService, item.id); + cloneJob(toastNotifications, application, mlApi, mlJobService, item.id); closeMenu(true); }, 'data-test-subj': 'mlActionButtonCloneJob', diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.tsx index b9813ece905f4..38ac41983f489 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/datafeed_preview_tab.tsx @@ -11,7 +11,7 @@ import { EuiCallOut, EuiLoadingSpinner } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { useEnabledFeatures } from '../../../../contexts/ml'; import { ML_DATA_PREVIEW_COUNT } from '../../../../../../common/util/job_utils'; -import { useMlApiContext } from '../../../../contexts/kibana'; +import { useMlApi } from '../../../../contexts/kibana'; import { usePermissionCheck } from '../../../../capabilities/check_capabilities'; import { MLJobEditor } from '../ml_job_editor'; import type { CombinedJob } from '../../../../../../common/types/anomaly_detection_jobs'; @@ -23,7 +23,7 @@ interface Props { export const DatafeedPreviewPane: FC = ({ job }) => { const { jobs: { datafeedPreview }, - } = useMlApiContext(); + } = useMlApi(); const { showNodeInfo } = useEnabledFeatures(); const canPreviewDatafeed = usePermissionCheck('canPreviewDatafeed'); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js index 0db362a094c1e..976ea8bc9968b 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js @@ -45,9 +45,7 @@ export class ForecastsTable extends Component { isLoading: props.job.data_counts.processed_record_count !== 0, forecasts: [], }; - this.mlForecastService = forecastServiceFactory( - constructorContext.services.mlServices.mlApiServices - ); + this.mlForecastService = forecastServiceFactory(constructorContext.services.mlServices.mlApi); } /** diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_messages_pane.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_messages_pane.tsx index eb0ce2d6be817..c4ba5c3c7d5d8 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_messages_pane.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/job_messages_pane.tsx @@ -14,7 +14,7 @@ import { extractErrorMessage } from '@kbn/ml-error-utils'; import { JobMessages } from '../../../../components/job_messages'; import type { JobMessage } from '../../../../../../common/types/audit_message'; import { useToastNotificationService } from '../../../../services/toast_notification_service'; -import { useMlApiContext } from '../../../../contexts/kibana'; +import { useMlApi } from '../../../../contexts/kibana'; import { checkPermission } from '../../../../capabilities/check_capabilities'; import { blurButtonOnClick } from '../../../../util/component_utils'; interface JobMessagesPaneProps { @@ -37,12 +37,12 @@ export const JobMessagesPane: FC = React.memo( const [isClearing, setIsClearing] = useState(false); const toastNotificationService = useToastNotificationService(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const fetchMessages = async () => { setIsLoading(true); try { - const messagesResp = await ml.jobs.jobAuditMessages({ jobId, start, end }); + const messagesResp = await mlApi.jobs.jobAuditMessages({ jobId, start, end }); setMessages(messagesResp.messages); setNotificationIndices(messagesResp.notificationIndices); @@ -67,7 +67,7 @@ export const JobMessagesPane: FC = React.memo( const clearMessages = useCallback(async () => { setIsClearing(true); try { - await ml.jobs.clearJobAuditMessages(jobId, notificationIndices); + await mlApi.jobs.clearJobAuditMessages(jobId, notificationIndices); setIsClearing(false); if (typeof refreshJobList === 'function') { refreshJobList(); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.tsx b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.tsx index 4e819f093a2e2..c326761a7e3ff 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.tsx +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_filter_bar/job_filter_bar.tsx @@ -24,13 +24,13 @@ export const JobFilterBar: FC = ({ queryText, setFilters }) = const [error, setError] = useState(null); const { services: { - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); const loadGroups = useCallback(async () => { try { - const response = await mlApiServices.jobs.groups(); + const response = await mlApi.jobs.groups(); return response.map((g) => ({ value: g.id, view: ( diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js index e6fd50d96a65d..f6deecc3ba309 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list/jobs_list.js @@ -46,10 +46,10 @@ export class JobsListUI extends Component { itemIdToExpandedRowMap: {}, }; - this.mlApiServices = props.kibana.services.mlServices.mlApiServices; + this.mlApi = props.kibana.services.mlServices.mlApi; this.mlJobService = mlJobServiceFactory( toastNotificationServiceProvider(props.kibana.services.notifications.toasts), - this.mlApiServices + this.mlApi ); } @@ -340,7 +340,7 @@ export class JobsListUI extends Component { actions: actionsMenuContent( this.props.kibana.services.notifications.toasts, this.props.kibana.services.application, - this.mlApiServices, + this.mlApi, this.mlJobService, this.props.showEditJobFlyout, this.props.showDatafeedChartFlyout, diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js index efb9211e99c0e..6693f9bc22ab1 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/jobs_list_view/jobs_list_view.js @@ -83,7 +83,7 @@ export class JobsListViewUI extends Component { this.mlJobService = mlJobServiceFactory( toastNotificationServiceProvider(props.kibana.services.notifications.toasts), - props.kibana.services.mlServices.mlApiServices + props.kibana.services.mlServices.mlApi ); } @@ -147,7 +147,7 @@ export class JobsListViewUI extends Component { } this.setState({ itemIdToExpandedRowMap }, () => { - loadFullJob(this.props.kibana.services.mlServices.mlApiServices, jobId) + loadFullJob(this.props.kibana.services.mlServices.mlApi, jobId) .then((job) => { const fullJobsList = { ...this.state.fullJobsList }; if (this.props.showNodeInfo === false) { @@ -324,11 +324,11 @@ export class JobsListViewUI extends Component { this.setState({ loading: true }); } - const ml = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; const expandedJobsIds = Object.keys(this.state.itemIdToExpandedRowMap); try { let jobsAwaitingNodeCount = 0; - const jobs = await ml.jobs.jobsSummary(expandedJobsIds); + const jobs = await mlApi.jobs.jobsSummary(expandedJobsIds); const fullJobsList = {}; const jobsSummaryList = jobs.map((job) => { if (job.fullJob !== undefined) { @@ -387,8 +387,8 @@ export class JobsListViewUI extends Component { return; } - const ml = this.props.kibana.services.mlServices.mlApiServices; - const { jobs } = await ml.jobs.blockingJobTasks(); + const mlApi = this.props.kibana.services.mlServices.mlApi; + const { jobs } = await mlApi.jobs.blockingJobTasks(); const blockingJobIds = jobs.map((j) => Object.keys(j)[0]).sort(); const taskListHasChanged = blockingJobIds.join() !== this.state.blockingJobIds.join(); diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js index e12b770039b8d..a8bd2789e5433 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/actions_menu.js @@ -47,11 +47,11 @@ class MultiJobActionsMenuUI extends Component { this.canCreateMlAlerts = checkPermission('canCreateMlAlerts'); this.toastNoticiations = constructorContext.services.notifications.toasts; - const mlApiServices = constructorContext.services.mlServices.mlApiServices; + const mlApi = constructorContext.services.mlServices.mlApi; const toastNotificationService = toastNotificationServiceProvider( constructorContext.services.notifications.toasts ); - this.mlJobService = mlJobServiceFactory(toastNotificationService, mlApiServices); + this.mlJobService = mlJobServiceFactory(toastNotificationService, mlApi); } onButtonClick = () => { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js index 9fe8bbf230322..6248915b87d4b 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/multi_job_actions/group_selector/group_selector.js @@ -91,8 +91,8 @@ export class GroupSelectorUI extends Component { if (this.state.isPopoverOpen) { this.closePopover(); } else { - const ml = this.props.kibana.services.mlServices.mlApiServices; - ml.jobs + const mlApi = this.props.kibana.services.mlServices.mlApi; + mlApi.jobs .groups() .then((groups) => { const selectedGroups = createSelectedGroups(this.props.jobs, groups); @@ -158,7 +158,7 @@ export class GroupSelectorUI extends Component { } const tempJobs = newJobs.map((j) => ({ jobId: j.id, groups: j.newGroups })); - const ml = this.props.kibana.services.mlServices.mlApiServices; + const ml = this.props.kibana.services.mlServices.mlApi; ml.jobs .updateGroups(tempJobs) .then((resp) => { diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js index d56fc973a0249..db5f28a5e242b 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js @@ -59,7 +59,7 @@ export class StartDatafeedModal extends Component { this.toastNotifications = constructorContext.services.notifications.toasts; this.mlJobService = mlJobServiceFactory( toastNotificationServiceProvider(this.toastNotifications), - constructorContext.services.mlServices.mlApiServices + constructorContext.services.mlServices.mlApi ); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.d.ts b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.d.ts index a4c20309129f3..bd6f60a050047 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.d.ts +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.d.ts @@ -13,13 +13,10 @@ import type { MlSummaryJob, } from '../../../../../common/types/anomaly_detection_jobs'; import type { MlJobService } from '../../../services/job_service'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; -export function loadFullJob( - mlApiServices: MlApiServices, - jobId: string -): Promise; -export function loadJobForCloning(mlApiServices: MlApiServices, jobId: string): Promise; +export function loadFullJob(mlApi: MlApi, jobId: string): Promise; +export function loadJobForCloning(mlApi: MlApi, jobId: string): Promise; export function isStartable(jobs: CombinedJobWithStats[]): boolean; export function isClosable(jobs: CombinedJobWithStats[]): boolean; export function isResettable(jobs: CombinedJobWithStats[]): boolean; @@ -45,7 +42,7 @@ export function showResults( export function cloneJob( toastNotifications: ToastsStart, application: ApplicationStart, - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, jobId: string ): Promise; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js index 471e56be7a840..36a070b851147 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js @@ -19,9 +19,9 @@ import { ML_PAGES } from '../../../../../common/constants/locator'; import { PLUGIN_ID } from '../../../../../common/constants/app'; import { CREATED_BY_LABEL } from '../../../../../common/constants/new_job'; -export function loadFullJob(mlApiServices, jobId) { +export function loadFullJob(mlApi, jobId) { return new Promise((resolve, reject) => { - mlApiServices.jobs + mlApi.jobs .jobs([jobId]) .then((jobs) => { if (jobs.length) { @@ -36,9 +36,9 @@ export function loadFullJob(mlApiServices, jobId) { }); } -export function loadJobForCloning(mlApiServices, jobId) { +export function loadJobForCloning(mlApi, jobId) { return new Promise((resolve, reject) => { - mlApiServices.jobs + mlApi.jobs .jobForCloning(jobId) .then((resp) => { if (resp) { @@ -214,17 +214,11 @@ function showResults(toastNotifications, resp, action) { } } -export async function cloneJob( - toastNotifications, - application, - mlApiServices, - mlJobService, - jobId -) { +export async function cloneJob(toastNotifications, application, mlApi, mlJobService, jobId) { try { const [{ job: cloneableJob, datafeed }, originalJob] = await Promise.all([ - loadJobForCloning(mlApiServices, jobId), - loadFullJob(mlApiServices, jobId), + loadJobForCloning(mlApi, jobId), + loadFullJob(mlApi, jobId), ]); const createdBy = originalJob?.custom_settings?.created_by; @@ -277,7 +271,7 @@ export async function cloneJob( if (originalJob.calendars) { mlJobService.tempJobCloningObjects.calendars = await mlCalendarService.fetchCalendarsByIds( - mlApiServices, + mlApi, originalJob.calendars ); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts index 68ddfe1b83b44..983fa2f352016 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/chart_loader.ts @@ -14,7 +14,7 @@ import type { IndicesOptions } from '../../../../../../common/types/anomaly_dete import { mlResultsServiceProvider } from '../../../../services/results_service'; import { getCategoryFields as getCategoryFieldsOrig } from './searches'; import { aggFieldPairsCanBeCharted } from '../job_creator/util/general'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; type DetectorIndex = number; export interface LineChartPoint { @@ -28,7 +28,7 @@ const eq = (newArgs: any[], lastArgs: any[]) => isEqual(newArgs, lastArgs); export class ChartLoader { protected _dataView: DataView; - protected _mlApiServices: MlApiServices; + protected _mlApi: MlApi; private _timeFieldName: string = ''; private _query: object = {}; @@ -38,17 +38,14 @@ export class ChartLoader { private _getEventRateData; private _getCategoryFields; - constructor(mlApiServices: MlApiServices, indexPattern: DataView, query: object) { - this._mlApiServices = mlApiServices; + constructor(mlApi: MlApi, indexPattern: DataView, query: object) { + this._mlApi = mlApi; this._dataView = indexPattern; this._query = query; - this._newJobLineChart = memoizeOne(mlApiServices.jobs.newJobLineChart, eq); - this._newJobPopulationsChart = memoizeOne(mlApiServices.jobs.newJobPopulationsChart, eq); - this._getEventRateData = memoizeOne( - mlResultsServiceProvider(mlApiServices).getEventRateData, - eq - ); + this._newJobLineChart = memoizeOne(mlApi.jobs.newJobLineChart, eq); + this._newJobPopulationsChart = memoizeOne(mlApi.jobs.newJobPopulationsChart, eq); + this._getEventRateData = memoizeOne(mlResultsServiceProvider(mlApi).getEventRateData, eq); this._getCategoryFields = memoizeOne(getCategoryFieldsOrig, eq); if (typeof indexPattern.timeFieldName === 'string') { @@ -166,7 +163,7 @@ export class ChartLoader { indicesOptions?: IndicesOptions ): Promise { const { results } = await this._getCategoryFields( - this._mlApiServices, + this._mlApi, this._dataView.getIndexPattern(), field.name, 10, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/searches.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/searches.ts index 3c4ca1c5f54d7..f36dd70d42194 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/searches.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/chart_loader/searches.ts @@ -8,7 +8,7 @@ import { get } from 'lodash'; import type { RuntimeMappings } from '@kbn/ml-runtime-field-utils'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import type { IndicesOptions } from '../../../../../../common/types/anomaly_detection_jobs'; interface CategoryResults { @@ -17,7 +17,7 @@ interface CategoryResults { } export function getCategoryFields( - mlApiServices: MlApiServices, + mlApi: MlApi, indexPatternName: string, fieldName: string, size: number, @@ -26,7 +26,7 @@ export function getCategoryFields( indicesOptions?: IndicesOptions ): Promise { return new Promise((resolve, reject) => { - mlApiServices + mlApi .esSearch({ index: indexPatternName, size: 0, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts index 30a472348d587..04f99a6f7895b 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/advanced_job_creator.ts @@ -11,7 +11,7 @@ import type { Field, Aggregation, SplitField } from '@kbn/ml-anomaly-utils'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; import type { MlJobService } from '../../../../services/job_service'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import { JobCreator } from './job_creator'; import type { Job, @@ -43,14 +43,14 @@ export class AdvancedJobCreator extends JobCreator { private _queryString: string; constructor( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, newJobCapsService: NewJobCapsService, indexPattern: DataView, savedSearch: SavedSearch | null, query: object ) { - super(mlApiServices, mlJobService, newJobCapsService, indexPattern, savedSearch, query); + super(mlApi, mlJobService, newJobCapsService, indexPattern, savedSearch, query); this.createdBy = CREATED_BY_LABEL.ADVANCED; this._queryString = JSON.stringify(this._datafeed_config.query); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/categorization_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/categorization_job_creator.ts index a12266e556e73..cb79defa16302 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/categorization_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/categorization_job_creator.ts @@ -35,7 +35,7 @@ import { DEFAULT_RARE_BUCKET_SPAN, } from '../../../../../../common/constants/new_job'; import type { MlJobService } from '../../../../services/job_service'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import type { NewJobCapsService } from '../../../../services/new_job_capabilities/new_job_capabilities_service'; import { getRichDetectors } from './util/general'; @@ -65,14 +65,14 @@ export class CategorizationJobCreator extends JobCreator { private _ccsVersionFailure: boolean = false; constructor( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, newJobCapsService: NewJobCapsService, indexPattern: DataView, savedSearch: SavedSearch | null, query: object ) { - super(mlApiServices, mlJobService, newJobCapsService, indexPattern, savedSearch, query); + super(mlApi, mlJobService, newJobCapsService, indexPattern, savedSearch, query); this.createdBy = CREATED_BY_LABEL.CATEGORIZATION; this._examplesLoader = new CategorizationExamplesLoader(this, indexPattern, query); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/geo_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/geo_job_creator.ts index 76fda339afa44..986f1480e7bf3 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/geo_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/geo_job_creator.ts @@ -9,7 +9,7 @@ import type { DataView } from '@kbn/data-views-plugin/public'; import type { Field, Aggregation, SplitField, AggFieldPair } from '@kbn/ml-anomaly-utils'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; import type { MlJobService } from '../../../../services/job_service'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import type { NewJobCapsService } from '../../../../services/new_job_capabilities/new_job_capabilities_service'; import { JobCreator } from './job_creator'; import type { @@ -31,14 +31,14 @@ export class GeoJobCreator extends JobCreator { protected _type: JOB_TYPE = JOB_TYPE.GEO; constructor( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, newJobCapsService: NewJobCapsService, indexPattern: DataView, savedSearch: SavedSearch | null, query: object ) { - super(mlApiServices, mlJobService, newJobCapsService, indexPattern, savedSearch, query); + super(mlApi, mlJobService, newJobCapsService, indexPattern, savedSearch, query); this.createdBy = CREATED_BY_LABEL.GEO; this._wizardInitialized$.next(true); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts index 82e5fe1209a13..2346ff863e489 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator.ts @@ -22,7 +22,7 @@ import { import type { RuntimeMappings } from '@kbn/ml-runtime-field-utils'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import type { IndexPatternTitle } from '../../../../../../common/types/kibana'; import { getQueryFromSavedSearchObject } from '../../../../util/index_utils'; import type { @@ -79,19 +79,19 @@ export class JobCreator { protected _wizardInitialized$ = new BehaviorSubject(false); public wizardInitialized$ = this._wizardInitialized$.asObservable(); - public mlApiServices: MlApiServices; + public mlApi: MlApi; public mlJobService: MlJobService; public newJobCapsService: NewJobCapsService; constructor( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, newJobCapsService: NewJobCapsService, indexPattern: DataView, savedSearch: SavedSearch | null, query: object ) { - this.mlApiServices = mlApiServices; + this.mlApi = mlApi; this.mlJobService = mlJobService; this.newJobCapsService = newJobCapsService; this._indexPattern = indexPattern; @@ -492,7 +492,7 @@ export class JobCreator { } for (const calendar of this._calendars) { - await mlCalendarService.assignNewJobId(this.mlApiServices, calendar, this.jobId); + await mlCalendarService.assignNewJobId(this.mlApi, calendar, this.jobId); } } @@ -845,7 +845,7 @@ export class JobCreator { // load the start and end times for the selected index // and apply them to the job creator public async autoSetTimeRange(excludeFrozenData = true) { - const { start, end } = await this.mlApiServices.getTimeFieldRange({ + const { start, end } = await this.mlApi.getTimeFieldRange({ index: this._indexPatternTitle, timeFieldName: this.timeFieldName, query: excludeFrozenData ? addExcludeFrozenToQuery(this.query) : this.query, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator_factory.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator_factory.ts index 9e5f9988b292f..07424b709d5b6 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator_factory.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/job_creator_factory.ts @@ -8,7 +8,7 @@ import type { DataView } from '@kbn/data-views-plugin/public'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; import type { MlJobService } from '../../../../services/job_service'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import type { NewJobCapsService } from '../../../../services/new_job_capabilities/new_job_capabilities_service'; import { SingleMetricJobCreator } from './single_metric_job_creator'; import { MultiMetricJobCreator } from './multi_metric_job_creator'; @@ -23,7 +23,7 @@ import { JOB_TYPE } from '../../../../../../common/constants/new_job'; export const jobCreatorFactory = (jobType: JOB_TYPE) => ( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, newJobCapsService: NewJobCapsService, indexPattern: DataView, @@ -57,5 +57,5 @@ export const jobCreatorFactory = jc = SingleMetricJobCreator; break; } - return new jc(mlApiServices, mlJobService, newJobCapsService, indexPattern, savedSearch, query); + return new jc(mlApi, mlJobService, newJobCapsService, indexPattern, savedSearch, query); }; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts index 69ca14a40c4e4..cb734c84e3d23 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/multi_metric_job_creator.ts @@ -9,7 +9,7 @@ import type { DataView } from '@kbn/data-views-plugin/public'; import type { Field, Aggregation, SplitField, AggFieldPair } from '@kbn/ml-anomaly-utils'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; import type { MlJobService } from '../../../../services/job_service'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import type { NewJobCapsService } from '../../../../services/new_job_capabilities/new_job_capabilities_service'; import { JobCreator } from './job_creator'; import type { @@ -30,14 +30,14 @@ export class MultiMetricJobCreator extends JobCreator { protected _type: JOB_TYPE = JOB_TYPE.MULTI_METRIC; constructor( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, newJobCapsService: NewJobCapsService, indexPattern: DataView, savedSearch: SavedSearch | null, query: object ) { - super(mlApiServices, mlJobService, newJobCapsService, indexPattern, savedSearch, query); + super(mlApi, mlJobService, newJobCapsService, indexPattern, savedSearch, query); this.createdBy = CREATED_BY_LABEL.MULTI_METRIC; this._wizardInitialized$.next(true); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts index 342583636d37f..36e4e8f6f5659 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/population_job_creator.ts @@ -9,7 +9,7 @@ import type { DataView } from '@kbn/data-views-plugin/public'; import type { Field, Aggregation, SplitField, AggFieldPair } from '@kbn/ml-anomaly-utils'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; import type { MlJobService } from '../../../../services/job_service'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import type { NewJobCapsService } from '../../../../services/new_job_capabilities/new_job_capabilities_service'; import { JobCreator } from './job_creator'; import type { @@ -29,14 +29,14 @@ export class PopulationJobCreator extends JobCreator { protected _type: JOB_TYPE = JOB_TYPE.POPULATION; constructor( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, newJobCapsService: NewJobCapsService, indexPattern: DataView, savedSearch: SavedSearch | null, query: object ) { - super(mlApiServices, mlJobService, newJobCapsService, indexPattern, savedSearch, query); + super(mlApi, mlJobService, newJobCapsService, indexPattern, savedSearch, query); this.createdBy = CREATED_BY_LABEL.POPULATION; this._wizardInitialized$.next(true); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/rare_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/rare_job_creator.ts index aaaa7d101c09a..e142a35ba380d 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/rare_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/rare_job_creator.ts @@ -14,7 +14,7 @@ import { } from '@kbn/ml-anomaly-utils'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; import type { MlJobService } from '../../../../services/job_service'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import type { NewJobCapsService } from '../../../../services/new_job_capabilities/new_job_capabilities_service'; import { JobCreator } from './job_creator'; import type { @@ -37,14 +37,14 @@ export class RareJobCreator extends JobCreator { private _freqRareAgg: Aggregation; constructor( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, newJobCapsService: NewJobCapsService, indexPattern: DataView, savedSearch: SavedSearch | null, query: object ) { - super(mlApiServices, mlJobService, newJobCapsService, indexPattern, savedSearch, query); + super(mlApi, mlJobService, newJobCapsService, indexPattern, savedSearch, query); this.createdBy = CREATED_BY_LABEL.RARE; this._wizardInitialized$.next(true); this._rareAgg = {} as Aggregation; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/single_metric_job_creator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/single_metric_job_creator.ts index 2b7a1133c1d1f..10a55e5210d60 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/single_metric_job_creator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/single_metric_job_creator.ts @@ -16,7 +16,7 @@ import { } from '@kbn/ml-anomaly-utils'; import type { SavedSearch } from '@kbn/saved-search-plugin/public'; import type { MlJobService } from '../../../../services/job_service'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import { parseInterval } from '../../../../../../common/util/parse_interval'; import { JobCreator } from './job_creator'; import type { @@ -35,14 +35,14 @@ export class SingleMetricJobCreator extends JobCreator { protected _type: JOB_TYPE = JOB_TYPE.SINGLE_METRIC; constructor( - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService, newJobCapsService: NewJobCapsService, indexPattern: DataView, savedSearch: SavedSearch | null, query: object ) { - super(mlApiServices, mlJobService, newJobCapsService, indexPattern, savedSearch, query); + super(mlApi, mlJobService, newJobCapsService, indexPattern, savedSearch, query); this.createdBy = CREATED_BY_LABEL.SINGLE_METRIC; this._wizardInitialized$.next(true); } diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.test.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.test.ts index f73c54653f93b..77030455fb3bf 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.test.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.test.ts @@ -10,7 +10,7 @@ import { useFakeTimers } from 'sinon'; import type { CalculatePayload } from './model_memory_estimator'; import { modelMemoryEstimatorProvider } from './model_memory_estimator'; import type { JobValidator } from '../../job_validator'; -import type { MlApiServices } from '../../../../../services/ml_api_service'; +import type { MlApi } from '../../../../../services/ml_api_service'; import type { JobCreator } from '../job_creator'; import { BehaviorSubject } from 'rxjs'; @@ -20,7 +20,7 @@ describe('delay', () => { let mockJobCreator: JobCreator; let wizardInitialized$: BehaviorSubject; let mockJobValidator: JobValidator; - let mockMlApiServices: MlApiServices; + let mockMlApiServices: MlApi; beforeEach(() => { clock = useFakeTimers(); @@ -37,7 +37,7 @@ describe('delay', () => { const { of } = require('rxjs'); return of({ modelMemoryLimit: '15MB' }); }), - } as unknown as MlApiServices; + } as unknown as MlApi; modelMemoryEstimator = modelMemoryEstimatorProvider( mockJobCreator, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts index b3550b039a862..4fae97ed3e3a2 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_creator/util/model_memory_estimator.ts @@ -30,16 +30,16 @@ import type { JobValidator } from '../../job_validator/job_validator'; import { VALIDATION_DELAY_MS } from '../../job_validator/job_validator'; import { useMlKibana } from '../../../../../contexts/kibana'; import type { JobCreator } from '../job_creator'; -import type { MlApiServices } from '../../../../../services/ml_api_service'; +import type { MlApi } from '../../../../../services/ml_api_service'; -export type CalculatePayload = Parameters[0]; +export type CalculatePayload = Parameters[0]; type ModelMemoryEstimator = ReturnType; export const modelMemoryEstimatorProvider = ( jobCreator: JobCreator, jobValidator: JobValidator, - mlApiServices: MlApiServices + mlApi: MlApi ) => { const modelMemoryCheck$ = new Subject(); const error$ = new Subject(); @@ -65,7 +65,7 @@ export const modelMemoryEstimatorProvider = ( // don't call the endpoint with invalid payload filter(() => jobValidator.isModelMemoryEstimationPayloadValid), switchMap((payload) => { - return mlApiServices.calculateModelMemoryLimit$(payload).pipe( + return mlApi.calculateModelMemoryLimit$(payload).pipe( pluck('modelMemoryLimit'), catchError((error) => { // eslint-disable-next-line no-console @@ -93,14 +93,14 @@ export const useModelMemoryEstimator = ( const { services: { notifications, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); // Initialize model memory estimator only once const modelMemoryEstimator = useMemo( - () => modelMemoryEstimatorProvider(jobCreator, jobValidator, mlApiServices), - [jobCreator, jobValidator, mlApiServices] + () => modelMemoryEstimatorProvider(jobCreator, jobValidator, mlApi), + [jobCreator, jobValidator, mlApi] ); // Listen for estimation results and errors diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts index bd3d68afdc6d0..335d952929741 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts @@ -6,7 +6,7 @@ */ import { BehaviorSubject } from 'rxjs'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; import type { MlJobService } from '../../../../services/job_service'; import type { JobCreator } from '../job_creator'; import type { DatafeedId, JobId } from '../../../../../../common/types/anomaly_detection_jobs'; @@ -22,7 +22,7 @@ export type ProgressSubscriber = (progress: number) => void; export type JobAssignmentSubscriber = (assigned: boolean) => void; export class JobRunner { - private _mlApiServices: MlApiServices; + private _mlApi: MlApi; private _mlJobService: MlJobService; private _jobId: JobId; private _datafeedId: DatafeedId; @@ -44,7 +44,7 @@ export class JobRunner { private _jobAssignedToNode$: BehaviorSubject; constructor(jobCreator: JobCreator) { - this._mlApiServices = jobCreator.mlApiServices; + this._mlApi = jobCreator.mlApi; this._mlJobService = jobCreator.mlJobService; this._jobId = jobCreator.jobId; this._datafeedId = jobCreator.datafeedId; @@ -193,7 +193,7 @@ export class JobRunner { } private async _isJobAssigned(): Promise { - const { jobs } = await this._mlApiServices.getJobStats({ jobId: this._jobId }); + const { jobs } = await this._mlApi.getJobStats({ jobId: this._jobId }); return jobs.length > 0 && jobs[0].node !== undefined; } @@ -212,7 +212,7 @@ export class JobRunner { isRunning: boolean; isJobClosed: boolean; }> { - return await this._mlApiServices.jobs.getLookBackProgress(this._jobId, this._start, this._end); + return await this._mlApi.jobs.getLookBackProgress(this._jobId, this._start, this._end); } public subscribeToProgress(func: ProgressSubscriber) { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts index 0ec37e612a3fa..0bd0731b6dbe2 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_validator/validators.ts @@ -81,7 +81,7 @@ export function cardinalityValidator( }), switchMap(({ jobCreator }) => { // Perform a cardinality check only with enabled model plot. - return jobCreator.mlApiServices + return jobCreator.mlApi .validateCardinality$({ ...jobCreator.jobConfig, datafeed_config: jobCreator.datafeedConfig, @@ -117,7 +117,7 @@ export function jobIdValidator(jobCreator$: Subject): Observable prevJobCreator.jobId === currJobCreator.jobId ), - switchMap((jobCreator) => jobCreator.mlApiServices.jobs.jobsExist$([jobCreator.jobId], true)), + switchMap((jobCreator) => jobCreator.mlApi.jobs.jobsExist$([jobCreator.jobId], true)), map((jobExistsResults) => { const jobs = Object.values(jobExistsResults); const valid = jobs?.[0].exists === false; @@ -139,7 +139,7 @@ export function groupIdsValidator(jobCreator$: Subject): Observable< JSON.stringify(prevJobCreator.groups) === JSON.stringify(currJobCreator.groups) ), switchMap((jobCreator) => { - return jobCreator.mlApiServices.jobs.jobsExist$(jobCreator.groups, true); + return jobCreator.mlApi.jobs.jobsExist$(jobCreator.groups, true); }), map((jobExistsResults) => { const groups = Object.values(jobExistsResults); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/map_loader/map_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/map_loader/map_loader.ts index a75152e93bd88..e6a54aaa66880 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/map_loader/map_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/map_loader/map_loader.ts @@ -13,7 +13,7 @@ import type { CreateLayerDescriptorParams, MapsStartApi } from '@kbn/maps-plugin import type { Query } from '@kbn/es-query'; import type { Field, SplitField } from '@kbn/ml-anomaly-utils'; import { ChartLoader } from '../chart_loader'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; const eq = (newArgs: any[], lastArgs: any[]) => isEqual(newArgs, lastArgs); @@ -21,12 +21,12 @@ export class MapLoader extends ChartLoader { private _getMapData; constructor( - mlApiServices: MlApiServices, + mlApi: MlApi, indexPattern: DataView, query: object, mapsPlugin: MapsStartApi | undefined ) { - super(mlApiServices, indexPattern, query); + super(mlApi, indexPattern, query); this._getMapData = mapsPlugin ? memoizeOne(mapsPlugin.createLayerDescriptors.createESSearchSourceLayerDescriptor, eq) diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts index de24a7cff2995..96512c8540111 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/categorization_examples_loader.ts @@ -39,7 +39,7 @@ export class CategorizationExamplesLoader { }; } - const resp = await this._jobCreator.mlApiServices.jobs.categorizationFieldExamples( + const resp = await this._jobCreator.mlApi.jobs.categorizationFieldExamples( this._indexPatternTitle, this._query, NUMBER_OF_CATEGORY_EXAMPLES, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts index 742d0b476ebac..0492cb49ebedd 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/results_loader.ts @@ -85,7 +85,7 @@ export class ResultsLoader { this._chartInterval = chartInterval; this._results$ = new BehaviorSubject(this._results); this._chartLoader = chartLoader; - this._mlResultsService = mlResultsServiceProvider(jobCreator.mlApiServices); + this._mlResultsService = mlResultsServiceProvider(jobCreator.mlApi); jobCreator.subscribeToProgress(this.progressSubscriber); } @@ -242,7 +242,7 @@ export class ResultsLoader { private async _loadDetectorsAnomalyData(): Promise> { const resp = await getScoresByRecord( - this._jobCreator.mlApiServices, + this._jobCreator.mlApi, this._jobCreator.jobId, this._jobCreator.start, this._jobCreator.end, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/searches.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/searches.ts index 738bb880bd700..f9aaa56f59c06 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/searches.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/common/results_loader/searches.ts @@ -8,7 +8,7 @@ import { get } from 'lodash'; import { escapeForElasticsearchQuery } from '../../../../util/string_utils'; -import type { MlApiServices } from '../../../../services/ml_api_service'; +import type { MlApi } from '../../../../services/ml_api_service'; interface SplitFieldWithValue { name: string; @@ -30,7 +30,7 @@ interface ProcessedResults { // detector swimlane search export function getScoresByRecord( - mlApiServices: MlApiServices, + mlApi: MlApi, jobId: string, earliestMs: number, latestMs: number, @@ -54,7 +54,7 @@ export function getScoresByRecord( jobIdFilterStr += `"${String(firstSplitField.value).replace(/\\/g, '\\\\')}"`; } - mlApiServices.results + mlApi.results .anomalySearch( { body: { diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_dashboard/quick_create_job_base.ts b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_dashboard/quick_create_job_base.ts index b685bb181f7c6..98c2a74baf543 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_dashboard/quick_create_job_base.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_dashboard/quick_create_job_base.ts @@ -21,7 +21,7 @@ import type { Filter, Query, DataViewBase } from '@kbn/es-query'; import { FilterStateStore } from '@kbn/es-query'; import type { ErrorType } from '@kbn/ml-error-utils'; import type { DataViewsContract } from '@kbn/data-views-plugin/public'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; import type { MlJobService } from '../../../services/job_service'; import type { Job, Datafeed } from '../../../../../common/types/anomaly_detection_jobs'; import { getFiltersForDSLQuery } from '../../../../../common/util/job_utils'; @@ -57,7 +57,7 @@ export class QuickJobCreatorBase { protected readonly kibanaConfig: IUiSettingsClient, protected readonly timeFilter: TimefilterContract, protected readonly dashboardService: DashboardStart, - protected readonly mlApiServices: MlApiServices, + protected readonly mlApi: MlApi, protected readonly mlJobService: MlJobService ) {} @@ -110,7 +110,7 @@ export class QuickJobCreatorBase { datafeedConfig.indices.length > 0 ) { const { modelMemoryLimit } = await firstValueFrom( - this.mlApiServices.calculateModelMemoryLimit$({ + this.mlApi.calculateModelMemoryLimit$({ datafeedConfig: datafeed, analysisConfig: job.analysis_config, indexPattern: datafeedConfig.indices[0], @@ -133,7 +133,7 @@ export class QuickJobCreatorBase { // put job try { - await this.mlApiServices.addJob({ jobId: job.job_id, job }); + await this.mlApi.addJob({ jobId: job.job_id, job }); } catch (error) { result.jobCreated.error = error; return result; @@ -142,7 +142,7 @@ export class QuickJobCreatorBase { // put datafeed try { - await this.mlApiServices.addDatafeed({ datafeedId, datafeedConfig: datafeed }); + await this.mlApi.addDatafeed({ datafeedId, datafeedConfig: datafeed }); } catch (error) { result.datafeedCreated.error = error; return result; @@ -152,7 +152,7 @@ export class QuickJobCreatorBase { if (startJob) { // open job, ignore error if already open try { - await this.mlApiServices.openJob({ jobId }); + await this.mlApi.openJob({ jobId }); } catch (error) { // job may already be open, so ignore 409 error. if (error.body.statusCode !== 409) { @@ -164,7 +164,7 @@ export class QuickJobCreatorBase { // start datafeed try { - await this.mlApiServices.startDatafeed({ + await this.mlApi.startDatafeed({ datafeedId, start, ...(runInRealTime ? {} : { end }), diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_lens/quick_create_job.ts b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_lens/quick_create_job.ts index 3ce3289a424b8..db1e025406538 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_lens/quick_create_job.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_lens/quick_create_job.ts @@ -19,7 +19,7 @@ import type { DashboardStart } from '@kbn/dashboard-plugin/public'; import type { LensApi } from '@kbn/lens-plugin/public'; import type { JobCreatorType } from '../common/job_creator'; import { createEmptyJob, createEmptyDatafeed } from '../common/job_creator/util/default_configs'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; import type { MlJobService } from '../../../services/job_service'; import { CREATED_BY_LABEL, @@ -42,10 +42,10 @@ export class QuickLensJobCreator extends QuickJobCreatorBase { kibanaConfig: IUiSettingsClient, timeFilter: TimefilterContract, dashboardService: DashboardStart, - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService ) { - super(dataViews, kibanaConfig, timeFilter, dashboardService, mlApiServices, mlJobService); + super(dataViews, kibanaConfig, timeFilter, dashboardService, mlApi, mlJobService); } public async createAndSaveJob( diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_lens/route_resolver.ts b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_lens/route_resolver.ts index dd6fb765e158b..0f5c102859bb8 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_lens/route_resolver.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_lens/route_resolver.ts @@ -14,7 +14,7 @@ import type { TimefilterContract } from '@kbn/data-plugin/public'; import type { DashboardStart } from '@kbn/dashboard-plugin/public'; import type { DataViewsContract } from '@kbn/data-views-plugin/public'; import { QuickLensJobCreator } from './quick_create_job'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; import type { MlJobService } from '../../../services/job_service'; import { getDefaultQuery, getRisonValue } from '../utils/new_job_utils'; @@ -25,7 +25,7 @@ interface Dependencies { kibanaConfig: IUiSettingsClient; timeFilter: TimefilterContract; dashboardService: DashboardStart; - mlApiServices: MlApiServices; + mlApi: MlApi; mlJobService: MlJobService; } export async function resolver( @@ -37,15 +37,7 @@ export async function resolver( filtersRisonString: string, layerIndexRisonString: string ) { - const { - dataViews, - lens, - mlApiServices, - mlJobService, - timeFilter, - kibanaConfig, - dashboardService, - } = deps; + const { dataViews, lens, mlApi, mlJobService, timeFilter, kibanaConfig, dashboardService } = deps; if (lensSavedObjectRisonString === undefined) { throw new Error('Cannot create visualization'); } @@ -67,7 +59,7 @@ export async function resolver( kibanaConfig, timeFilter, dashboardService, - mlApiServices, + mlApi, mlJobService ); await jobCreator.createAndStashADJob(vis, from, to, query, filters, layerIndex); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_map/quick_create_job.ts b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_map/quick_create_job.ts index 0f14eaaf515fe..cc36762162e2a 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_map/quick_create_job.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_map/quick_create_job.ts @@ -12,7 +12,7 @@ import type { Filter, Query } from '@kbn/es-query'; import type { DataView, DataViewsContract } from '@kbn/data-views-plugin/public'; import type { DashboardStart } from '@kbn/dashboard-plugin/public'; import type { MapApi } from '@kbn/maps-plugin/public'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; import type { MlJobService } from '../../../services/job_service'; import { CREATED_BY_LABEL, @@ -43,10 +43,10 @@ export class QuickGeoJobCreator extends QuickJobCreatorBase { kibanaConfig: IUiSettingsClient, timeFilter: TimefilterContract, dashboardService: DashboardStart, - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService ) { - super(dataViews, kibanaConfig, timeFilter, dashboardService, mlApiServices, mlJobService); + super(dataViews, kibanaConfig, timeFilter, dashboardService, mlApi, mlJobService); } public async createAndSaveGeoJob({ diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_map/route_resolver.ts b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_map/route_resolver.ts index 455802fcc3f4a..d3a9b8641ca75 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_map/route_resolver.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_map/route_resolver.ts @@ -9,7 +9,7 @@ import type { IUiSettingsClient } from '@kbn/core-ui-settings-browser'; import type { TimefilterContract } from '@kbn/data-plugin/public'; import type { DashboardStart } from '@kbn/dashboard-plugin/public'; import type { DataViewsContract } from '@kbn/data-views-plugin/public'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; import type { MlJobService } from '../../../services/job_service'; import { QuickGeoJobCreator } from './quick_create_job'; @@ -20,7 +20,7 @@ interface Dependencies { kibanaConfig: IUiSettingsClient; timeFilter: TimefilterContract; dashboardService: DashboardStart; - mlApiServices: MlApiServices; + mlApi: MlApi; mlJobService: MlJobService; } export async function resolver( @@ -34,8 +34,7 @@ export async function resolver( toRisonString: string, layerRisonString?: string ) { - const { dataViews, kibanaConfig, timeFilter, dashboardService, mlApiServices, mlJobService } = - deps; + const { dataViews, kibanaConfig, timeFilter, dashboardService, mlApi, mlJobService } = deps; const defaultLayer = { query: getDefaultQuery(), filters: [] }; const dashboard = getRisonValue(dashboardRisonString, defaultLayer); @@ -58,7 +57,7 @@ export async function resolver( kibanaConfig, timeFilter, dashboardService, - mlApiServices, + mlApi, mlJobService ); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_pattern_analysis/quick_create_job.ts b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_pattern_analysis/quick_create_job.ts index 0b81525f4013d..92dbbced01a3c 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_pattern_analysis/quick_create_job.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_pattern_analysis/quick_create_job.ts @@ -16,7 +16,7 @@ import { MLCATEGORY, ML_JOB_AGGREGATION } from '@kbn/ml-anomaly-utils'; import type { QueryDslQueryContainer } from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { CREATED_BY_LABEL, DEFAULT_BUCKET_SPAN } from '../../../../../common/constants/new_job'; import { type CreateState, QuickJobCreatorBase } from '../job_from_dashboard/quick_create_job_base'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; import type { MlJobService } from '../../../services/job_service'; import { createEmptyDatafeed, createEmptyJob } from '../common/job_creator/util/default_configs'; import type { JobCreatorType } from '../common/job_creator'; @@ -36,10 +36,10 @@ export class QuickCategorizationJobCreator extends QuickJobCreatorBase { timeFilter: TimefilterContract, dashboardService: DashboardStart, private data: DataPublicPluginStart, - mlApiServices: MlApiServices, + mlApi: MlApi, mlJobService: MlJobService ) { - super(dataViews, kibanaConfig, timeFilter, dashboardService, mlApiServices, mlJobService); + super(dataViews, kibanaConfig, timeFilter, dashboardService, mlApi, mlJobService); } public async createAndSaveJob( diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_pattern_analysis/route_resolver.ts b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_pattern_analysis/route_resolver.ts index a2277babcc195..d950c631f6bb6 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/job_from_pattern_analysis/route_resolver.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/job_from_pattern_analysis/route_resolver.ts @@ -14,7 +14,7 @@ import { QuickCategorizationJobCreator, CATEGORIZATION_TYPE, } from './quick_create_job'; -import type { MlApiServices } from '../../../services/ml_api_service'; +import type { MlApi } from '../../../services/ml_api_service'; import type { MlJobService } from '../../../services/job_service'; import { getDefaultDatafeedQuery, getRisonValue } from '../utils/new_job_utils'; @@ -24,7 +24,7 @@ interface Dependencies { timeFilter: TimefilterContract; dashboardService: DashboardStart; data: DataPublicPluginStart; - mlApiServices: MlApiServices; + mlApi: MlApi; mlJobService: MlJobService; } export async function resolver( @@ -38,7 +38,7 @@ export async function resolver( toRisonString: string, queryRisonString: string ) { - const { mlApiServices, mlJobService, timeFilter, kibanaConfig, dashboardService, data } = deps; + const { mlApi, mlJobService, timeFilter, kibanaConfig, dashboardService, data } = deps; const query = getRisonValue(queryRisonString, getDefaultDatafeedQuery()); const from = getRisonValue(fromRisonString, ''); @@ -59,7 +59,7 @@ export async function resolver( timeFilter, dashboardService, data, - mlApiServices, + mlApi, mlJobService ); await jobCreator.createAndStashADJob( diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/datafeed_preview_flyout/datafeed_preview.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/datafeed_preview_flyout/datafeed_preview.tsx index ed9fdc22b9954..dc5bfc6003dd3 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/datafeed_preview_flyout/datafeed_preview.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/common/datafeed_preview_flyout/datafeed_preview.tsx @@ -20,7 +20,7 @@ import { import type { CombinedJob } from '../../../../../../../../common/types/anomaly_detection_jobs'; import { MLJobEditor } from '../../../../../jobs_list/components/ml_job_editor'; -import { useMlApiContext } from '../../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../../contexts/kibana'; export const DatafeedPreview: FC<{ combinedJob: CombinedJob | null; @@ -28,7 +28,7 @@ export const DatafeedPreview: FC<{ }> = ({ combinedJob, heightOffset = 0 }) => { const { jobs: { datafeedPreview }, - } = useMlApiContext(); + } = useMlApi(); // the ace editor requires a fixed height const editorHeight = useMemo( () => `${window.innerHeight - 230 - heightOffset}px`, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/data_view/change_data_view.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/data_view/change_data_view.tsx index cb6a636a8c296..a45022a615be0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/data_view/change_data_view.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/datafeed_step/components/data_view/change_data_view.tsx @@ -37,11 +37,7 @@ import type { } from '../../../../../../../../../common/types/anomaly_detection_jobs'; import type { DatafeedValidationResponse } from '../../../../../../../../../common/types/job_validation'; -import { - useMlKibana, - useMlApiContext, - useNavigateToPath, -} from '../../../../../../../contexts/kibana'; +import { useMlKibana, useMlApi, useNavigateToPath } from '../../../../../../../contexts/kibana'; const fixedPageSize: number = 8; @@ -63,7 +59,7 @@ export const ChangeDataViewModal: FC = ({ onClose }) => { }, } = useMlKibana(); const navigateToPath = useNavigateToPath(); - const { validateDatafeedPreview } = useMlApiContext(); + const { validateDatafeedPreview } = useMlApi(); const { jobCreator: jc } = useContext(JobCreatorContext); const jobCreator = jc as AdvancedJobCreator; diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx index bd3b52f5bb003..06718f175b266 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/job_details_step/components/additional_section/components/calendars/calendars_selection.tsx @@ -24,7 +24,7 @@ import { JobCreatorContext } from '../../../../../job_creator_context'; import { Description } from './description'; import { PLUGIN_ID } from '../../../../../../../../../../../common/constants/app'; import type { Calendar } from '../../../../../../../../../../../common/types/calendars'; -import { useMlApiContext, useMlKibana } from '../../../../../../../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../../../../../../../contexts/kibana'; import { GLOBAL_CALENDAR } from '../../../../../../../../../../../common/constants/calendars'; import { ML_PAGES } from '../../../../../../../../../../../common/constants/locator'; @@ -34,7 +34,7 @@ export const CalendarsSelection: FC = () => { application: { getUrlForApp }, }, } = useMlKibana(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { jobCreator, jobCreatorUpdate } = useContext(JobCreatorContext); const [selectedCalendars, setSelectedCalendars] = useState(jobCreator.calendars); @@ -46,7 +46,7 @@ export const CalendarsSelection: FC = () => { async function loadCalendars() { setIsLoading(true); - const calendars = (await ml.calendars()).filter( + const calendars = (await mlApi.calendars()).filter( (c) => c.job_ids.includes(GLOBAL_CALENDAR) === false ); setOptions(calendars.map((c) => ({ label: c.calendar_id, value: c }))); diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts index de279236d8755..71bdad4aadf14 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/bucket_span_estimator/estimate_bucket_span.ts @@ -8,7 +8,7 @@ import { useContext, useState } from 'react'; import { i18n } from '@kbn/i18n'; import { EVENT_RATE_FIELD_ID } from '@kbn/ml-anomaly-utils'; -import { useMlApiContext } from '../../../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../../../contexts/kibana'; import { JobCreatorContext } from '../../../job_creator_context'; import type { BucketSpanEstimatorData } from '../../../../../../../../../common/types/job_service'; import { @@ -27,7 +27,7 @@ export enum ESTIMATE_STATUS { export function useEstimateBucketSpan() { const toastNotificationService = useToastNotificationService(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { jobCreator, jobCreatorUpdate } = useContext(JobCreatorContext); const dataSourceContext = useDataSource(); @@ -78,7 +78,7 @@ export function useEstimateBucketSpan() { async function estimateBucketSpan() { setStatus(ESTIMATE_STATUS.RUNNING); - const { name, error, message: text } = await ml.estimateBucketSpan(data); + const { name, error, message: text } = await mlApi.estimateBucketSpan(data); setStatus(ESTIMATE_STATUS.NOT_RUNNING); if (error === true) { const title = i18n.translate( diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/category_stopped_partitions.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/category_stopped_partitions.tsx index 912bc1af40e12..bf770601ae0c3 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/category_stopped_partitions.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/category_stopped_partitions.tsx @@ -13,13 +13,13 @@ import { i18n } from '@kbn/i18n'; import { from } from 'rxjs'; import { switchMap, takeWhile, tap } from 'rxjs'; import { extractErrorProperties } from '@kbn/ml-error-utils'; -import { useMlApiContext } from '../../../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../../../contexts/kibana'; import { JobCreatorContext } from '../../../job_creator_context'; import type { CategorizationJobCreator } from '../../../../../common/job_creator'; const NUMBER_OF_PREVIEW = 5; export const CategoryStoppedPartitions: FC = () => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { jobCreator: jc, resultsLoader } = useContext(JobCreatorContext); const jobCreator = jc as CategorizationJobCreator; const [tableRow, setTableRow] = useState>([]); @@ -47,7 +47,7 @@ export const CategoryStoppedPartitions: FC = () => { const loadCategoryStoppedPartitions = useCallback(async () => { try { - const { jobs } = await ml.results.getCategoryStoppedPartitions([jobCreator.jobId]); + const { jobs } = await mlApi.results.getCategoryStoppedPartitions([jobCreator.jobId]); if ( !Array.isArray(jobs) && // if jobs is object of jobId: [partitions] diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx index 1a9db2f5c67fb..f69ba6f1ee9f0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/components/pick_fields_step/components/categorization_view/top_categories.tsx @@ -10,7 +10,7 @@ import React, { useContext, useEffect, useState } from 'react'; import { EuiBasicTable, EuiText } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n-react'; import { extractErrorProperties } from '@kbn/ml-error-utils'; -import { useMlApiContext } from '../../../../../../../contexts/kibana'; +import { useMlApi } from '../../../../../../../contexts/kibana'; import { NUMBER_OF_CATEGORY_EXAMPLES } from '../../../../../../../../../common/constants/new_job'; import { JobCreatorContext } from '../../../job_creator_context'; import type { CategorizationJobCreator } from '../../../../../common/job_creator'; @@ -18,7 +18,7 @@ import type { Results } from '../../../../../common/results_loader'; import { useToastNotificationService } from '../../../../../../../services/toast_notification_service'; export const TopCategories: FC = () => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { displayErrorToast } = useToastNotificationService(); const { jobCreator: jc, resultsLoader } = useContext(JobCreatorContext); @@ -33,7 +33,7 @@ export const TopCategories: FC = () => { async function loadTopCats() { try { - const results = await ml.jobs.topCategories(jobCreator.jobId, NUMBER_OF_CATEGORY_EXAMPLES); + const results = await mlApi.jobs.topCategories(jobCreator.jobId, NUMBER_OF_CATEGORY_EXAMPLES); setTableRow( results.categories.map((c) => ({ count: c.count, diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/page.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/page.tsx index e4cc4dd88a4e2..cd90f4f552eff 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/page.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/pages/new_job/page.tsx @@ -33,7 +33,7 @@ import { MapLoader } from '../../common/map_loader'; import { ResultsLoader } from '../../common/results_loader'; import { JobValidator } from '../../common/job_validator'; import { useDataSource } from '../../../../contexts/ml'; -import { useMlApiContext, useMlKibana } from '../../../../contexts/kibana'; +import { useMlApi, useMlKibana } from '../../../../contexts/kibana'; import type { ExistingJobsAndGroups } from '../../../../services/job_service'; import { useMlJobService } from '../../../../services/job_service'; import { useNewJobCapsService } from '../../../../services/new_job_capabilities/new_job_capabilities_service'; @@ -56,7 +56,7 @@ export const Page: FC = ({ existingJobsAndGroups, jobType }) => { const { services: { maps: mapsPlugin, uiSettings }, } = useMlKibana(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const mlJobService = useMlJobService(); const newJobCapsService = useNewJobCapsService(); @@ -65,7 +65,7 @@ export const Page: FC = ({ existingJobsAndGroups, jobType }) => { const jobCreator = useMemo( () => jobCreatorFactory(jobType)( - ml, + mlApi, mlJobService, newJobCapsService, dataSourceContext.selectedDataView, @@ -208,13 +208,13 @@ export const Page: FC = ({ existingJobsAndGroups, jobType }) => { chartInterval.setInterval('auto'); const chartLoader = useMemo( - () => new ChartLoader(ml, dataSourceContext.selectedDataView, jobCreator.query), - [ml, dataSourceContext.selectedDataView, jobCreator.query] + () => new ChartLoader(mlApi, dataSourceContext.selectedDataView, jobCreator.query), + [mlApi, dataSourceContext.selectedDataView, jobCreator.query] ); const mapLoader = useMemo( - () => new MapLoader(ml, dataSourceContext.selectedDataView, jobCreator.query, mapsPlugin), - [ml, dataSourceContext.selectedDataView, jobCreator.query, mapsPlugin] + () => new MapLoader(mlApi, dataSourceContext.selectedDataView, jobCreator.query, mapsPlugin), + [mlApi, dataSourceContext.selectedDataView, jobCreator.query, mapsPlugin] ); const resultsLoader = useMemo( diff --git a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx index f12a870d8d448..f664db9800de0 100644 --- a/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx +++ b/x-pack/plugins/ml/public/application/jobs/new_job/recognize/page.tsx @@ -73,7 +73,7 @@ export const Page: FC = ({ moduleId, existingGroupIds }) => { services: { notifications, mlServices: { - mlApiServices: { getTimeFieldRange, setupDataRecognizerConfig, getDataRecognizerModule }, + mlApi: { getTimeFieldRange, setupDataRecognizerConfig, getDataRecognizerModule }, }, }, } = useMlKibana(); diff --git a/x-pack/plugins/ml/public/application/ml_nodes_check/check_ml_nodes.ts b/x-pack/plugins/ml/public/application/ml_nodes_check/check_ml_nodes.ts index 78afdd80fcc24..3fd19b2b810ae 100644 --- a/x-pack/plugins/ml/public/application/ml_nodes_check/check_ml_nodes.ts +++ b/x-pack/plugins/ml/public/application/ml_nodes_check/check_ml_nodes.ts @@ -5,16 +5,16 @@ * 2.0. */ -import type { MlApiServices } from '../services/ml_api_service'; +import type { MlApi } from '../services/ml_api_service'; import type { MlNodeCount } from '../../../common/types/ml_server_info'; let mlNodeCount: number = 0; let lazyMlNodeCount: number = 0; let userHasPermissionToViewMlNodeCount: boolean = false; -export async function getMlNodeCount(mlApiServices: MlApiServices): Promise { +export async function getMlNodeCount(mlApi: MlApi): Promise { try { - const nodes = await mlApiServices.mlNodeCount(); + const nodes = await mlApi.mlNodeCount(); mlNodeCount = nodes.count; lazyMlNodeCount = nodes.lazyNodeCount; userHasPermissionToViewMlNodeCount = true; diff --git a/x-pack/plugins/ml/public/application/model_management/create_pipeline_for_model/create_pipeline_for_model_flyout.tsx b/x-pack/plugins/ml/public/application/model_management/create_pipeline_for_model/create_pipeline_for_model_flyout.tsx index 991e085384c3d..21fac6f6a28f8 100644 --- a/x-pack/plugins/ml/public/application/model_management/create_pipeline_for_model/create_pipeline_for_model_flyout.tsx +++ b/x-pack/plugins/ml/public/application/model_management/create_pipeline_for_model/create_pipeline_for_model_flyout.tsx @@ -31,7 +31,7 @@ import { PipelineDetails } from './pipeline_details'; import { TestTrainedModel } from './test_trained_model'; import { OnFailureConfiguration } from '../../components/shared'; import { ReviewAndCreatePipeline } from '../../components/shared'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { getPipelineConfig } from './get_pipeline_config'; import { validateInferencePipelineConfigurationStep } from '../../components/ml_inference/validation'; import { type InferecePipelineCreationState } from './state'; @@ -67,7 +67,7 @@ export const CreatePipelineForModelFlyout: FC const { trainedModels: { createInferencePipeline }, - } = useMlApiContext(); + } = useMlApi(); const createPipeline = async () => { setFormState({ ...formState, creatingPipeline: true }); diff --git a/x-pack/plugins/ml/public/application/model_management/model_actions.tsx b/x-pack/plugins/ml/public/application/model_management/model_actions.tsx index 9bcf348f45189..e9d323a8f6407 100644 --- a/x-pack/plugins/ml/public/application/model_management/model_actions.tsx +++ b/x-pack/plugins/ml/public/application/model_management/model_actions.tsx @@ -56,7 +56,7 @@ export function useModelActions({ application: { navigateToUrl }, overlays, docLinks, - mlServices: { mlApiServices }, + mlServices: { mlApi }, ...startServices }, } = useMlKibana(); @@ -87,7 +87,7 @@ export function useModelActions({ useEffect(() => { let isMounted = true; - mlApiServices + mlApi .hasPrivileges({ cluster: ['manage_ingest_pipelines'], }) @@ -102,7 +102,7 @@ export function useModelActions({ return () => { isMounted = false; }; - }, [mlApiServices]); + }, [mlApi]); const getUserConfirmation = useMemo( () => getUserConfirmationProvider(overlays, startServices), diff --git a/x-pack/plugins/ml/public/application/model_management/test_models/selected_model.tsx b/x-pack/plugins/ml/public/application/model_management/test_models/selected_model.tsx index d75c910e9a40e..598bd206608c6 100644 --- a/x-pack/plugins/ml/public/application/model_management/test_models/selected_model.tsx +++ b/x-pack/plugins/ml/public/application/model_management/test_models/selected_model.tsx @@ -23,7 +23,7 @@ import { import { TextEmbeddingInference } from './models/text_embedding'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { type TestTrainedModelsContextType } from './test_trained_models_context'; import { InferenceInputForm } from './models/inference_input_form'; import type { InferrerType } from './models'; @@ -53,7 +53,7 @@ export const SelectedModel: FC = ({ externalPipelineConfig, setCurrentContext, }) => { - const { trainedModels } = useMlApiContext(); + const { trainedModels } = useMlApi(); const inferrer = useMemo(() => { const taskType = Object.keys(model.inference_config ?? {})[0]; diff --git a/x-pack/plugins/ml/public/application/notifications/components/notifications_list.test.tsx b/x-pack/plugins/ml/public/application/notifications/components/notifications_list.test.tsx index dac36551377be..fb4256636135b 100644 --- a/x-pack/plugins/ml/public/application/notifications/components/notifications_list.test.tsx +++ b/x-pack/plugins/ml/public/application/notifications/components/notifications_list.test.tsx @@ -82,10 +82,10 @@ describe('NotificationsList', () => { await waitFor(() => { expect( - useMlKibana().services.mlServices.mlApiServices.notifications.findMessages + useMlKibana().services.mlServices.mlApi.notifications.findMessages ).toHaveBeenCalledTimes(1); expect( - useMlKibana().services.mlServices.mlApiServices.notifications.findMessages + useMlKibana().services.mlServices.mlApi.notifications.findMessages ).toHaveBeenCalledWith({ earliest: '', latest: '', diff --git a/x-pack/plugins/ml/public/application/notifications/components/notifications_list.tsx b/x-pack/plugins/ml/public/application/notifications/components/notifications_list.tsx index 1ebba13d1f520..399b880c6a331 100644 --- a/x-pack/plugins/ml/public/application/notifications/components/notifications_list.tsx +++ b/x-pack/plugins/ml/public/application/notifications/components/notifications_list.tsx @@ -56,7 +56,7 @@ export const getDefaultNotificationsListState = (): ListingPageUrlState => ({ export const NotificationsList: FC = () => { const { services: { - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); @@ -116,7 +116,7 @@ export const NotificationsList: FC = () => { try { setIsLoading(true); - const response = await mlApiServices.notifications.findMessages({ + const response = await mlApi.notifications.findMessages({ sortField: sorting.sort!.field, sortDirection: sorting.sort!.direction, earliest: timeRange.from, @@ -135,7 +135,7 @@ export const NotificationsList: FC = () => { } setIsLoading(false); - }, [sorting, queryInstance, mlApiServices.notifications, displayErrorToast, timeRange]); + }, [sorting, queryInstance, mlApi.notifications, displayErrorToast, timeRange]); useEffect( function updateLastCheckedAt() { diff --git a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx index c33681f69f76a..5e17304fff1c4 100644 --- a/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx +++ b/x-pack/plugins/ml/public/application/overview/components/anomaly_detection_panel/anomaly_detection_panel.tsx @@ -17,7 +17,7 @@ import { ML_OVERVIEW_PANELS } from '../../../../../common/types/storage'; import { ML_PAGES } from '../../../../../common/constants/locator'; import { OverviewStatsBar } from '../../../components/collapsible_panel/collapsible_panel'; import { CollapsiblePanel } from '../../../components/collapsible_panel'; -import { useMlApiContext, useMlKibana, useMlLink } from '../../../contexts/kibana'; +import { useMlApi, useMlKibana, useMlLink } from '../../../contexts/kibana'; import { AnomalyDetectionTable } from './table'; import { getGroupsFromJobs, getStatsBarData } from './utils'; import type { Dictionary } from '../../../../../common/types/common'; @@ -56,7 +56,7 @@ export const AnomalyDetectionPanel: FC = ({ anomalyTimelineService, setLa const { services: { charts: chartsService }, } = useMlKibana(); - const ml = useMlApiContext(); + const mlApi = useMlApi(); const { displayErrorToast } = useToastNotificationService(); const { showNodeInfo } = useEnabledFeatures(); @@ -85,7 +85,7 @@ export const AnomalyDetectionPanel: FC = ({ anomalyTimelineService, setLa let lazyJobCount = 0; try { - const jobsResult: MlSummaryJobs = await ml.jobs.jobsSummary([]); + const jobsResult: MlSummaryJobs = await mlApi.jobs.jobsSummary([]); const jobsSummaryList = jobsResult.map((job: MlSummaryJob) => { job.latestTimestampSortValue = job.latestTimestampMs || 0; if (job.awaitingNodeAssignment) { diff --git a/x-pack/plugins/ml/public/application/overview/components/content.tsx b/x-pack/plugins/ml/public/application/overview/components/content.tsx index 1d0db5c6b9632..d70d590784e3e 100644 --- a/x-pack/plugins/ml/public/application/overview/components/content.tsx +++ b/x-pack/plugins/ml/public/application/overview/components/content.tsx @@ -29,7 +29,7 @@ export const OverviewContent: FC = ({ const { services: { uiSettings, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); @@ -41,7 +41,7 @@ export const OverviewContent: FC = ({ useEffect(() => { setAnomalyTimelineService( - new AnomalyTimelineService(timefilter, uiSettings, mlResultsServiceProvider(mlApiServices)) + new AnomalyTimelineService(timefilter, uiSettings, mlResultsServiceProvider(mlApi)) ); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); diff --git a/x-pack/plugins/ml/public/application/routing/resolvers.ts b/x-pack/plugins/ml/public/application/routing/resolvers.ts index e94f4e189f63c..7d7ca41ebf9c3 100644 --- a/x-pack/plugins/ml/public/application/routing/resolvers.ts +++ b/x-pack/plugins/ml/public/application/routing/resolvers.ts @@ -7,10 +7,10 @@ import { getMlNodeCount } from '../ml_nodes_check/check_ml_nodes'; import { loadMlServerInfo } from '../services/ml_server_info'; -import type { MlApiServices } from '../services/ml_api_service'; +import type { MlApi } from '../services/ml_api_service'; export interface Resolvers { - [name: string]: (mlApiServices: MlApiServices) => Promise; + [name: string]: (mlApi: MlApi) => Promise; } export type ResolverResults = | { diff --git a/x-pack/plugins/ml/public/application/routing/routes/data_frame_analytics/analytics_job_creation.tsx b/x-pack/plugins/ml/public/application/routing/routes/data_frame_analytics/analytics_job_creation.tsx index ffbcb0b8564ae..d48efb079af34 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/data_frame_analytics/analytics_job_creation.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/data_frame_analytics/analytics_job_creation.tsx @@ -13,7 +13,7 @@ import { dynamic } from '@kbn/shared-ux-utility'; import { DataSourceContextProvider } from '../../../contexts/ml'; import { ML_PAGES } from '../../../../locator'; import type { NavigateToPath } from '../../../contexts/kibana'; -import { useMlApiContext } from '../../../contexts/kibana'; +import { useMlApi } from '../../../contexts/kibana'; import { useMlKibana } from '../../../contexts/kibana'; import type { MlRoute, PageProps } from '../../router'; import { createPath, PageLoader } from '../../router'; @@ -58,7 +58,7 @@ const PageWrapper: FC = ({ location }) => { savedSearch: savedSearchService, }, } = useMlKibana(); - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const { context } = useRouteResolver( 'full', @@ -69,7 +69,7 @@ const PageWrapper: FC = ({ location }) => { loadNewJobCapabilities( index, savedSearchId, - mlApiServices, + mlApi, dataViewsService, savedSearchService, DATA_FRAME_ANALYTICS diff --git a/x-pack/plugins/ml/public/application/routing/routes/explorer/explorer.tsx b/x-pack/plugins/ml/public/application/routing/routes/explorer/explorer.tsx index 04cd415527ace..648cceee7ce3b 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/explorer/explorer.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/explorer/explorer.tsx @@ -56,7 +56,7 @@ export const explorerRouteFactory = ( const PageWrapper: FC = () => { const { services: { - mlServices: { mlApiServices }, + mlServices: { mlApi }, uiSettings, }, } = useMlKibana(); @@ -65,7 +65,7 @@ const PageWrapper: FC = () => { const { context, results } = useRouteResolver('full', ['canGetJobs'], { ...basicResolvers(), jobs: mlJobService.loadJobsWrapper, - jobsWithTimeRange: () => mlApiServices.jobs.jobsWithTimerange(getDateFormatTz(uiSettings)), + jobsWithTimeRange: () => mlApi.jobs.jobsWithTimerange(getDateFormatTz(uiSettings)), }); const annotationUpdatesService = useMemo(() => new AnnotationUpdatesService(), []); diff --git a/x-pack/plugins/ml/public/application/routing/routes/explorer/state_manager.tsx b/x-pack/plugins/ml/public/application/routing/routes/explorer/state_manager.tsx index 1aa59116be935..d61849436c73d 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/explorer/state_manager.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/explorer/state_manager.tsx @@ -41,7 +41,7 @@ export const ExplorerUrlStateManager: FC = ({ const { services: { cases, presentationUtil, uiSettings, mlServices }, } = useMlKibana(); - const { mlApiServices: ml } = mlServices; + const { mlApi } = mlServices; const [globalState] = useUrlState('_g'); const [stoppedPartitions, setStoppedPartitions] = useState(); @@ -77,7 +77,7 @@ export const ExplorerUrlStateManager: FC = ({ const getJobsWithStoppedPartitions = useCallback(async (selectedJobIds: string[]) => { try { - const fetchedStoppedPartitions = await ml.results.getCategoryStoppedPartitions( + const fetchedStoppedPartitions = await mlApi.results.getCategoryStoppedPartitions( selectedJobIds, ML_JOB_ID ); diff --git a/x-pack/plugins/ml/public/application/routing/routes/new_job/from_lens.tsx b/x-pack/plugins/ml/public/application/routing/routes/new_job/from_lens.tsx index 210198b54afbb..bc5e1f23b31bc 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/new_job/from_lens.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/new_job/from_lens.tsx @@ -40,7 +40,7 @@ const PageWrapper: FC = ({ location }) => { }, dashboard: dashboardService, uiSettings: kibanaConfig, - mlServices: { mlApiServices }, + mlServices: { mlApi }, lens, }, } = useMlKibana(); @@ -52,7 +52,7 @@ const PageWrapper: FC = ({ location }) => { { dataViews, lens, - mlApiServices, + mlApi, mlJobService, timeFilter, kibanaConfig, diff --git a/x-pack/plugins/ml/public/application/routing/routes/new_job/from_map.tsx b/x-pack/plugins/ml/public/application/routing/routes/new_job/from_map.tsx index 0ba538ec24348..730dbb4cf1e26 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/new_job/from_map.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/new_job/from_map.tsx @@ -47,7 +47,7 @@ const PageWrapper: FC = ({ location }) => { }, dashboard: dashboardService, uiSettings: kibanaConfig, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); const mlJobService = useMlJobService(); @@ -55,7 +55,7 @@ const PageWrapper: FC = ({ location }) => { const { context } = useRouteResolver('full', ['canCreateJob'], { redirect: () => resolver( - { dataViews, mlApiServices, mlJobService, timeFilter, kibanaConfig, dashboardService }, + { dataViews, mlApi, mlJobService, timeFilter, kibanaConfig, dashboardService }, dashboard, dataViewId, embeddable, diff --git a/x-pack/plugins/ml/public/application/routing/routes/new_job/from_pattern_analysis.tsx b/x-pack/plugins/ml/public/application/routing/routes/new_job/from_pattern_analysis.tsx index e6bc8f046a97b..d1dfcb2e21ed4 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/new_job/from_pattern_analysis.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/new_job/from_pattern_analysis.tsx @@ -41,7 +41,7 @@ const PageWrapper: FC = ({ location }) => { data, dashboard: dashboardService, uiSettings: kibanaConfig, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); const mlJobService = useMlJobService(); @@ -50,7 +50,7 @@ const PageWrapper: FC = ({ location }) => { redirect: () => resolver( { - mlApiServices, + mlApi, mlJobService, timeFilter: data.query.timefilter.timefilter, kibanaConfig, diff --git a/x-pack/plugins/ml/public/application/routing/routes/new_job/recognize.tsx b/x-pack/plugins/ml/public/application/routing/routes/new_job/recognize.tsx index 0a6166c3ff3b0..fb6c2aa15b651 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/new_job/recognize.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/new_job/recognize.tsx @@ -13,7 +13,7 @@ import { dynamic } from '@kbn/shared-ux-utility'; import { basicResolvers } from '../../resolvers'; import { ML_PAGES } from '../../../../locator'; import type { NavigateToPath } from '../../../contexts/kibana'; -import { useMlApiContext, useMlKibana, useNavigateToPath } from '../../../contexts/kibana'; +import { useMlApi, useMlKibana, useNavigateToPath } from '../../../contexts/kibana'; import type { MlRoute, PageProps } from '../../router'; import { createPath, PageLoader } from '../../router'; import { useRouteResolver } from '../../use_resolver'; @@ -55,13 +55,13 @@ export const checkViewOrCreateRouteFactory = (): MlRoute => ({ const PageWrapper: FC = ({ location }) => { const { id } = parse(location.search, { sort: false }); - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const toastNotificationService = useToastNotificationService(); const { context, results } = useRouteResolver('full', ['canGetJobs'], { ...basicResolvers(), existingJobsAndGroups: () => - mlJobServiceFactory(toastNotificationService, mlApiServices).getJobAndGroupIds(), + mlJobServiceFactory(toastNotificationService, mlApi).getJobAndGroupIds(), }); return ( @@ -79,7 +79,7 @@ const CheckViewOrCreateWrapper: FC = ({ location }) => { const { services: { notifications: { toasts }, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); @@ -102,7 +102,7 @@ const CheckViewOrCreateWrapper: FC = ({ location }) => { // If so, load the jobs in the Anomaly Explorer. // Otherwise open the data recognizer wizard for the module. // Always want to call reject() so as not to load original page. - mlApiServices + mlApi .dataRecognizerModuleJobsExist({ moduleId }) .then(async (resp: any) => { if (resp.jobsExist === true) { diff --git a/x-pack/plugins/ml/public/application/routing/routes/new_job/wizard.tsx b/x-pack/plugins/ml/public/application/routing/routes/new_job/wizard.tsx index 66ef374b4879e..d5f43fab97f45 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/new_job/wizard.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/new_job/wizard.tsx @@ -207,7 +207,7 @@ const PageWrapper: FC = ({ location, jobType }) => { services: { data: { dataViews: dataViewsService }, savedSearch: savedSearchService, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); const toastNotificationService = useToastNotificationService(); @@ -215,19 +215,18 @@ const PageWrapper: FC = ({ location, jobType }) => { const { context, results } = useRouteResolver('full', ['canGetJobs', 'canCreateJob'], { ...basicResolvers(), // TODO useRouteResolver should be responsible for the redirect - privileges: () => - checkCreateJobsCapabilitiesResolver(mlApiServices, redirectToJobsManagementPage), + privileges: () => checkCreateJobsCapabilitiesResolver(mlApi, redirectToJobsManagementPage), jobCaps: () => loadNewJobCapabilities( index, savedSearchId, - mlApiServices, + mlApi, dataViewsService, savedSearchService, ANOMALY_DETECTOR ), existingJobsAndGroups: () => - mlJobServiceFactory(toastNotificationService, mlApiServices).getJobAndGroupIds(), + mlJobServiceFactory(toastNotificationService, mlApi).getJobAndGroupIds(), }); return ( diff --git a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer/timeseriesexplorer.test.tsx b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer/timeseriesexplorer.test.tsx index 8119c7305c0fd..5bf60c8b41779 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer/timeseriesexplorer.test.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer/timeseriesexplorer.test.tsx @@ -113,7 +113,7 @@ jest.mock('../../../contexts/kibana/kibana_context', () => { timefilter: getMockedTimefilter(), }, }, - mlServices: { mlApiServices: {} }, + mlServices: { mlApi: {} }, notifications: { toasts: { addDanger: () => {}, diff --git a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer/timeseriesexplorer.tsx b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer/timeseriesexplorer.tsx index b7e7c7a4332c0..14abe1b8029b7 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer/timeseriesexplorer.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/timeseriesexplorer/timeseriesexplorer.tsx @@ -11,7 +11,7 @@ import { i18n } from '@kbn/i18n'; import { dynamic } from '@kbn/shared-ux-utility'; import { ML_PAGES } from '../../../../locator'; import type { NavigateToPath } from '../../../contexts/kibana'; -import { useMlApiContext, useUiSettings } from '../../../contexts/kibana'; +import { useMlApi, useUiSettings } from '../../../contexts/kibana'; import { getDateFormatTz } from '../../../explorer/explorer_utils'; import { useMlJobService } from '../../../services/job_service'; import type { MlRoute, PageProps } from '../../router'; @@ -49,7 +49,7 @@ export const timeSeriesExplorerRouteFactory = ( }); const PageWrapper: FC = ({ deps }) => { - const mlApi = useMlApiContext(); + const mlApi = useMlApi(); const mlJobService = useMlJobService(); const uiSettings = useUiSettings(); const { context, results } = useRouteResolver('full', ['canGetJobs'], { diff --git a/x-pack/plugins/ml/public/application/routing/use_resolver.tsx b/x-pack/plugins/ml/public/application/routing/use_resolver.tsx index d7e7e8762caaf..d65107410012b 100644 --- a/x-pack/plugins/ml/public/application/routing/use_resolver.tsx +++ b/x-pack/plugins/ml/public/application/routing/use_resolver.tsx @@ -10,7 +10,7 @@ import { i18n } from '@kbn/i18n'; import useMount from 'react-use/lib/useMount'; import { AccessDeniedCallout } from '../access_denied'; import { PLUGIN_ID } from '../../../common/constants/app'; -import { useMlApiContext, useMlKibana, useMlLicenseInfo } from '../contexts/kibana'; +import { useMlApi, useMlKibana, useMlLicenseInfo } from '../contexts/kibana'; import { type MlCapabilitiesKey } from '../../../common/types/capabilities'; import { usePermissionCheck } from '../capabilities/check_capabilities'; import type { ResolverResults, Resolvers } from './resolvers'; @@ -54,7 +54,7 @@ export const useRouteResolver = ( }, }, } = useMlKibana(); - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const mlLicenseInfo = useMlLicenseInfo(); useMount(function refreshCapabilitiesOnMount() { @@ -119,11 +119,11 @@ export const useRouteResolver = ( p[c] = {}; return p; }, {} as Exclude); - const res = await Promise.all(funcs.map((r) => r(mlApiServices))); + const res = await Promise.all(funcs.map((r) => r(mlApi))); res.forEach((r, i) => (tempResults[funcNames[i]] = r)); return tempResults; - // skip mlApiServices from deps + // skip mlApi from deps // eslint-disable-next-line react-hooks/exhaustive-deps }, []); diff --git a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts index 040753af178b2..972a0d7bb3963 100644 --- a/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts +++ b/x-pack/plugins/ml/public/application/services/anomaly_detector_service.ts @@ -9,13 +9,13 @@ import type { Observable } from 'rxjs'; import { map } from 'rxjs'; import type { Job, JobId } from '../../../common/types/anomaly_detection_jobs'; import type { HttpService } from './http_service'; -import { type MlApiServices, mlApiServicesProvider } from './ml_api_service'; +import { type MlApi, mlApiProvider } from './ml_api_service'; export class AnomalyDetectorService { - private mlApiServices: MlApiServices; + private mlApi: MlApi; constructor(httpService: HttpService) { - this.mlApiServices = mlApiServicesProvider(httpService); + this.mlApi = mlApiProvider(httpService); } /** @@ -31,8 +31,6 @@ export class AnomalyDetectorService { * @param jobIds */ getJobs$(jobIds: JobId[]): Observable { - return this.mlApiServices - .getJobs$({ jobId: jobIds.join(',') }) - .pipe(map((response) => response.jobs)); + return this.mlApi.getJobs$({ jobId: jobIds.join(',') }).pipe(map((response) => response.jobs)); } } diff --git a/x-pack/plugins/ml/public/application/services/anomaly_explorer_charts_service.test.ts b/x-pack/plugins/ml/public/application/services/anomaly_explorer_charts_service.test.ts index 1efaddabe1a34..9b1f41c6aa04a 100644 --- a/x-pack/plugins/ml/public/application/services/anomaly_explorer_charts_service.test.ts +++ b/x-pack/plugins/ml/public/application/services/anomaly_explorer_charts_service.test.ts @@ -7,7 +7,7 @@ import { AnomalyExplorerChartsService } from './anomaly_explorer_charts_service'; import { of } from 'rxjs'; -import type { MlApiServices } from './ml_api_service'; +import type { MlApi } from './ml_api_service'; import type { MlResultsService } from './results_service'; import { createTimefilterMock } from '../contexts/kibana/__mocks__/use_timefilter'; import moment from 'moment'; @@ -56,7 +56,7 @@ describe('AnomalyExplorerChartsService', () => { anomalyExplorerService = new AnomalyExplorerChartsService( timefilterMock, - mlApiServicesMock as unknown as MlApiServices, + mlApiServicesMock as unknown as MlApi, mlResultsServiceMock as unknown as MlResultsService ) as jest.Mocked; }); diff --git a/x-pack/plugins/ml/public/application/services/anomaly_explorer_charts_service.ts b/x-pack/plugins/ml/public/application/services/anomaly_explorer_charts_service.ts index 1eb752c28ce5d..8be72301a9613 100644 --- a/x-pack/plugins/ml/public/application/services/anomaly_explorer_charts_service.ts +++ b/x-pack/plugins/ml/public/application/services/anomaly_explorer_charts_service.ts @@ -25,7 +25,7 @@ import type { ExplorerChartsData } from '../explorer/explorer_charts/explorer_ch import type { AppStateSelectedCells } from '../explorer/explorer_utils'; import { SWIM_LANE_LABEL_WIDTH } from '../explorer/constants'; -import type { MlApiServices } from './ml_api_service'; +import type { MlApi } from './ml_api_service'; import type { MlResultsService } from './results_service'; const MAX_CHARTS_PER_ROW = 4; @@ -45,7 +45,7 @@ export class AnomalyExplorerChartsService { constructor( private timeFilter: TimefilterContract, - private mlApiServices: MlApiServices, + private mlApi: MlApi, private mlResultsService: MlResultsService ) { this.timeFilter.enableTimeRangeSelector(); @@ -64,7 +64,7 @@ export class AnomalyExplorerChartsService { public async getCombinedJobs(jobIds: string[]): Promise { const combinedResults = await Promise.all( // Getting only necessary job config and datafeed config without the stats - jobIds.map((jobId) => this.mlApiServices.jobs.jobForCloning(jobId)) + jobIds.map((jobId) => this.mlApi.jobs.jobForCloning(jobId)) ); return combinedResults .filter(isDefined) @@ -139,7 +139,7 @@ export class AnomalyExplorerChartsService { const maxSeriesToPlot = maxSeries ?? Math.max(chartsPerRow * 2, DEFAULT_MAX_SERIES_TO_PLOT); - return this.mlApiServices.results + return this.mlApi.results .getAnomalyCharts$( jobIds, influencers ?? [], diff --git a/x-pack/plugins/ml/public/application/services/calendar_service.ts b/x-pack/plugins/ml/public/application/services/calendar_service.ts index d44653e5ee86b..ada2cbce43f6c 100644 --- a/x-pack/plugins/ml/public/application/services/calendar_service.ts +++ b/x-pack/plugins/ml/public/application/services/calendar_service.ts @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import type { Calendar, CalendarId } from '../../../common/types/calendars'; import type { JobId } from '../../../common/types/anomaly_detection_jobs'; -import type { MlApiServices } from './ml_api_service'; +import type { MlApi } from './ml_api_service'; class CalendarService { /** @@ -16,10 +16,10 @@ class CalendarService { * @param calendar * @param jobId */ - async assignNewJobId(mlApiServices: MlApiServices, calendar: Calendar, jobId: JobId) { + async assignNewJobId(mlApi: MlApi, calendar: Calendar, jobId: JobId) { const { calendar_id: calendarId } = calendar; try { - await mlApiServices.updateCalendar({ + await mlApi.updateCalendar({ ...calendar, calendarId, job_ids: [...calendar.job_ids, jobId], @@ -38,12 +38,9 @@ class CalendarService { * Fetches calendars by the list of ids. * @param calendarIds */ - async fetchCalendarsByIds( - mlApiServices: MlApiServices, - calendarIds: CalendarId[] - ): Promise { + async fetchCalendarsByIds(mlApi: MlApi, calendarIds: CalendarId[]): Promise { try { - const calendars = await mlApiServices.calendars({ calendarIds }); + const calendars = await mlApi.calendars({ calendarIds }); return Array.isArray(calendars) ? calendars : [calendars]; } catch (e) { throw new Error( diff --git a/x-pack/plugins/ml/public/application/services/field_format_service.ts b/x-pack/plugins/ml/public/application/services/field_format_service.ts index 509e791cc75a4..8d21c368a7303 100644 --- a/x-pack/plugins/ml/public/application/services/field_format_service.ts +++ b/x-pack/plugins/ml/public/application/services/field_format_service.ts @@ -8,7 +8,7 @@ import { mlFunctionToESAggregation } from '../../../common/util/job_utils'; import type { MlJobService } from './job_service'; import type { MlIndexUtils } from '../util/index_service'; -import type { MlApiServices } from './ml_api_service'; +import type { MlApi } from './ml_api_service'; type FormatsByJobId = Record; type IndexPatternIdsByJob = Record; @@ -20,7 +20,7 @@ export class FieldFormatService { formatsByJob: FormatsByJobId = {}; constructor( - private mlApiServices: MlApiServices, + private mlApi: MlApi, private mlIndexUtils: MlIndexUtils, private mlJobService: MlJobService ) {} @@ -40,8 +40,8 @@ export class FieldFormatService { await Promise.all( jobIds.map(async (jobId) => { let jobObj; - if (this.mlApiServices) { - const { jobs } = await this.mlApiServices.getJobs({ jobId }); + if (this.mlApi) { + const { jobs } = await this.mlApi.getJobs({ jobId }); jobObj = jobs[0]; } else { jobObj = this.mlJobService.getJob(jobId); @@ -85,8 +85,8 @@ export class FieldFormatService { async getFormatsForJob(jobId: string): Promise { let jobObj; - if (this.mlApiServices) { - const { jobs } = await this.mlApiServices.getJobs({ jobId }); + if (this.mlApi) { + const { jobs } = await this.mlApi.getJobs({ jobId }); jobObj = jobs[0]; } else { jobObj = this.mlJobService.getJob(jobId); diff --git a/x-pack/plugins/ml/public/application/services/field_format_service_factory.ts b/x-pack/plugins/ml/public/application/services/field_format_service_factory.ts index fc59dbdf03ce4..1b40579cc74c3 100644 --- a/x-pack/plugins/ml/public/application/services/field_format_service_factory.ts +++ b/x-pack/plugins/ml/public/application/services/field_format_service_factory.ts @@ -7,13 +7,13 @@ import { type MlFieldFormatService, FieldFormatService } from './field_format_service'; import type { MlIndexUtils } from '../util/index_service'; -import type { MlApiServices } from './ml_api_service'; +import type { MlApi } from './ml_api_service'; import type { MlJobService } from './job_service'; export function fieldFormatServiceFactory( - mlApiServices: MlApiServices, + mlApi: MlApi, mlIndexUtils: MlIndexUtils, mlJobService: MlJobService ): MlFieldFormatService { - return new FieldFormatService(mlApiServices, mlIndexUtils, mlJobService); + return new FieldFormatService(mlApi, mlIndexUtils, mlJobService); } diff --git a/x-pack/plugins/ml/public/application/services/forecast_service.ts b/x-pack/plugins/ml/public/application/services/forecast_service.ts index 316577d98dd44..d1778dbf948f6 100644 --- a/x-pack/plugins/ml/public/application/services/forecast_service.ts +++ b/x-pack/plugins/ml/public/application/services/forecast_service.ts @@ -11,7 +11,7 @@ import { useMemo } from 'react'; import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey'; import { get, find, each } from 'lodash'; import { map } from 'rxjs'; -import type { MlApiServices } from './ml_api_service'; +import type { MlApi } from './ml_api_service'; import type { Job } from '../../../common/types/anomaly_detection_jobs'; import { useMlKibana } from '../contexts/kibana'; @@ -21,7 +21,7 @@ export interface AggType { min: string; } -export function forecastServiceFactory(mlApiServices: MlApiServices) { +export function forecastServiceFactory(mlApi: MlApi) { // Gets a basic summary of the most recently run forecasts for the specified // job, with results at or later than the supplied timestamp. // Extra query object can be supplied, or pass null if no additional query. @@ -58,7 +58,7 @@ export function forecastServiceFactory(mlApiServices: MlApiServices) { filterCriteria.push(query); } - mlApiServices.results + mlApi.results .anomalySearch( { // @ts-expect-error SearchRequest type has not been updated to include size @@ -121,7 +121,7 @@ export function forecastServiceFactory(mlApiServices: MlApiServices) { // TODO - add in criteria for detector index and entity fields (by, over, partition) // once forecasting with these parameters is supported. - mlApiServices.results + mlApi.results .anomalySearch( { // @ts-expect-error SearchRequest type has not been updated to include size @@ -261,7 +261,7 @@ export function forecastServiceFactory(mlApiServices: MlApiServices) { min: aggType.min, }; - return mlApiServices.results + return mlApi.results .anomalySearch$( { // @ts-expect-error SearchRequest type has not been updated to include size @@ -323,7 +323,7 @@ export function forecastServiceFactory(mlApiServices: MlApiServices) { // eslint-disable-next-line no-console console.log('ML forecast service run forecast with duration:', duration); return new Promise((resolve, reject) => { - mlApiServices + mlApi .forecast({ jobId, duration, @@ -364,7 +364,7 @@ export function forecastServiceFactory(mlApiServices: MlApiServices) { }, ]; - mlApiServices.results + mlApi.results .anomalySearch( { // @ts-expect-error SearchRequest type has not been updated to include size @@ -405,10 +405,10 @@ export type MlForecastService = ReturnType; export function useForecastService(): MlForecastService { const { services: { - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); - const mlForecastService = useMemo(() => forecastServiceFactory(mlApiServices), [mlApiServices]); + const mlForecastService = useMemo(() => forecastServiceFactory(mlApi), [mlApi]); return mlForecastService; } diff --git a/x-pack/plugins/ml/public/application/services/get_shared_ml_services.ts b/x-pack/plugins/ml/public/application/services/get_shared_ml_services.ts index 44e6a5e5746e8..ac003ea078219 100644 --- a/x-pack/plugins/ml/public/application/services/get_shared_ml_services.ts +++ b/x-pack/plugins/ml/public/application/services/get_shared_ml_services.ts @@ -8,7 +8,7 @@ import { type HttpStart } from '@kbn/core-http-browser'; import { ElasticModels } from './elastic_models_service'; import { HttpService } from './http_service'; -import { mlApiServicesProvider } from './ml_api_service'; +import { mlApiProvider } from './ml_api_service'; export type MlSharedServices = ReturnType; @@ -17,10 +17,10 @@ export type MlSharedServices = ReturnType; */ export function getMlSharedServices(httpStart: HttpStart) { const httpService = new HttpService(httpStart); - const mlApiServices = mlApiServicesProvider(httpService); + const mlApi = mlApiProvider(httpService); return { - elasticModels: new ElasticModels(mlApiServices.trainedModels), - mlApiServices, + elasticModels: new ElasticModels(mlApi.trainedModels), + mlApi, }; } diff --git a/x-pack/plugins/ml/public/application/services/job_service.d.ts b/x-pack/plugins/ml/public/application/services/job_service.d.ts index 685a0cf86cf9a..54a1fb3170918 100644 --- a/x-pack/plugins/ml/public/application/services/job_service.d.ts +++ b/x-pack/plugins/ml/public/application/services/job_service.d.ts @@ -9,7 +9,7 @@ import type { TimeRange } from '@kbn/data-plugin/common/query/timefilter/types'; import type { CombinedJob, Datafeed, Job } from '../../../common/types/anomaly_detection_jobs'; import type { Calendar } from '../../../common/types/calendars'; import type { ToastNotificationService } from './toast_notification_service'; -import type { MlApiServices } from './ml_api_service'; +import type { MlApi } from './ml_api_service'; import type { JobCreatorType } from '../jobs/new_job/common/job_creator'; export interface ExistingJobsAndGroups { @@ -62,7 +62,7 @@ export declare interface MlJobService { export const mlJobServiceFactory: ( toastNotificationService: ToastNotificationService, - mlApiServices: MlApiServices + mlApi: MlApi ) => MlJobService; export const useMlJobService: () => MlJobService; diff --git a/x-pack/plugins/ml/public/application/services/job_service.js b/x-pack/plugins/ml/public/application/services/job_service.js index c37502ab570ac..dc7d96f4e3236 100644 --- a/x-pack/plugins/ml/public/application/services/job_service.js +++ b/x-pack/plugins/ml/public/application/services/job_service.js @@ -13,7 +13,7 @@ import { validateTimeRange, TIME_FORMAT } from '@kbn/ml-date-utils'; import { parseInterval } from '../../../common/util/parse_interval'; import { isWebUrl } from '../util/url_utils'; -import { useMlApiContext } from '../contexts/kibana'; +import { useMlApi } from '../contexts/kibana'; import { useToastNotificationService } from './toast_notification_service'; @@ -596,15 +596,15 @@ function createResultsUrl(jobIds, start, end, resultsPage, mode = 'absolute') { // This is to retain the singleton behavior of the previous direct instantiation and export. let mlJobService; -export const mlJobServiceFactory = (toastNotificationService, mlApiServices) => { +export const mlJobServiceFactory = (toastNotificationService, mlApi) => { if (mlJobService) return mlJobService; - mlJobService = new JobService(toastNotificationService, mlApiServices); + mlJobService = new JobService(toastNotificationService, mlApi); return mlJobService; }; export const useMlJobService = () => { const toastNotificationService = useToastNotificationService(); - const mlApiServices = useMlApiContext(); - return mlJobServiceFactory(toastNotificationService, mlApiServices); + const mlApi = useMlApi(); + return mlJobServiceFactory(toastNotificationService, mlApi); }; diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts index 77c074a97bec4..f185a6452d654 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts @@ -99,7 +99,7 @@ export interface GetModelSnapshotsResponse { model_snapshots: ModelSnapshot[]; } -export function mlApiServicesProvider(httpService: HttpService) { +export function mlApiProvider(httpService: HttpService) { return { getJobs(obj?: { jobId?: string }) { const jobId = obj && obj.jobId ? `/${obj.jobId}` : ''; @@ -785,4 +785,4 @@ export function mlApiServicesProvider(httpService: HttpService) { }; } -export type MlApiServices = ReturnType; +export type MlApi = ReturnType; diff --git a/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts b/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts index bb10e9b466f6e..38f3a196a9baf 100644 --- a/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts +++ b/x-pack/plugins/ml/public/application/services/ml_server_info.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { MlApiServices } from './ml_api_service'; +import type { MlApi } from './ml_api_service'; import { loadMlServerInfo, getCloudDeploymentId, @@ -19,7 +19,7 @@ import mockMlInfoResponse from './__mocks__/ml_info_response.json'; const mlApiServicesMock = { mlInfo: jest.fn(() => Promise.resolve(mockMlInfoResponse)), -} as unknown as MlApiServices; +} as unknown as MlApi; describe('ml_server_info initial state', () => { it('should fail to get server info ', () => { diff --git a/x-pack/plugins/ml/public/application/services/ml_server_info.ts b/x-pack/plugins/ml/public/application/services/ml_server_info.ts index 101cb33264502..e01236534f2c4 100644 --- a/x-pack/plugins/ml/public/application/services/ml_server_info.ts +++ b/x-pack/plugins/ml/public/application/services/ml_server_info.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { MlApiServices } from './ml_api_service'; +import type { MlApi } from './ml_api_service'; import type { MlServerDefaults, MlServerLimits } from '../../../common/types/ml_server_info'; export interface CloudInfo { @@ -28,9 +28,9 @@ const cloudInfo: CloudInfo = { deploymentId: null, }; -export async function loadMlServerInfo(mlApiServices: MlApiServices) { +export async function loadMlServerInfo(mlApi: MlApi) { try { - const resp = await mlApiServices.mlInfo(); + const resp = await mlApi.mlInfo(); defaults = resp.defaults; limits = resp.limits; cloudInfo.cloudId = resp.cloudId ?? null; diff --git a/x-pack/plugins/ml/public/application/services/new_job_capabilities/load_new_job_capabilities.ts b/x-pack/plugins/ml/public/application/services/new_job_capabilities/load_new_job_capabilities.ts index 6c25d43020d52..f1e02597e3795 100644 --- a/x-pack/plugins/ml/public/application/services/new_job_capabilities/load_new_job_capabilities.ts +++ b/x-pack/plugins/ml/public/application/services/new_job_capabilities/load_new_job_capabilities.ts @@ -9,7 +9,7 @@ import type { DataView, DataViewsContract } from '@kbn/data-views-plugin/public' import type { SavedSearchPublicPluginStart } from '@kbn/saved-search-plugin/public'; import { getDataViewAndSavedSearchCallback } from '../../util/index_utils'; import type { JobType } from '../../../../common/types/saved_objects'; -import type { MlApiServices } from '../ml_api_service'; +import type { MlApi } from '../ml_api_service'; import { mlJobCapsServiceAnalyticsFactory } from './new_job_capabilities_service_analytics'; import { mlJobCapsServiceFactory } from './new_job_capabilities_service'; @@ -21,7 +21,7 @@ export const DATA_FRAME_ANALYTICS = 'data-frame-analytics'; export function loadNewJobCapabilities( dataViewId: string, savedSearchId: string, - mlApiServices: MlApiServices, + mlApi: MlApi, dataViewsService: DataViewsContract, savedSearchService: SavedSearchPublicPluginStart, jobType: JobType @@ -30,8 +30,8 @@ export function loadNewJobCapabilities( try { const serviceToUse = jobType === ANOMALY_DETECTOR - ? mlJobCapsServiceFactory(mlApiServices) - : mlJobCapsServiceAnalyticsFactory(mlApiServices); + ? mlJobCapsServiceFactory(mlApi) + : mlJobCapsServiceAnalyticsFactory(mlApi); if (dataViewId !== undefined) { // index pattern is being used diff --git a/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service.test.ts b/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service.test.ts index ed257199db16b..057b558485729 100644 --- a/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service.test.ts +++ b/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service.test.ts @@ -8,7 +8,7 @@ import { mlJobCapsServiceFactory } from './new_job_capabilities_service'; import type { DataView } from '@kbn/data-views-plugin/public'; -import type { MlApiServices } from '../ml_api_service'; +import type { MlApi } from '../ml_api_service'; // there is magic happening here. starting the include name with `mock..` // ensures it can be lazily loaded by the jest.mock function below. @@ -18,7 +18,7 @@ const mlApiServicesMock = { jobs: { newJobCaps: jest.fn(() => Promise.resolve(mockCloudwatchResponse)), }, -} as unknown as MlApiServices; +} as unknown as MlApi; const dataView = { id: 'cloudwatch-*', diff --git a/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service.ts b/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service.ts index 990d411779a6f..59f2e74b9ca36 100644 --- a/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service.ts +++ b/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service.ts @@ -15,9 +15,9 @@ import { EVENT_RATE_FIELD_ID, } from '@kbn/ml-anomaly-utils'; import { DataViewType } from '@kbn/data-views-plugin/public'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { getGeoFields, filterCategoryFields } from '../../../../common/util/fields_utils'; -import type { MlApiServices } from '../ml_api_service'; +import type { MlApi } from '../ml_api_service'; import { processTextAndKeywordFields, NewJobCapabilitiesServiceBase } from './new_job_capabilities'; export class NewJobCapsService extends NewJobCapabilitiesServiceBase { @@ -26,9 +26,9 @@ export class NewJobCapsService extends NewJobCapabilitiesServiceBase { private _geoFields: Field[] = []; private _includeEventRateField: boolean = true; private _removeTextFields: boolean = true; - private _mlApiService: MlApiServices; + private _mlApiService: MlApi; - constructor(mlApiService: MlApiServices) { + constructor(mlApiService: MlApi) { super(); this._mlApiService = mlApiService; } @@ -189,14 +189,14 @@ function addEventRateField(aggs: Aggregation[], fields: Field[]) { // This is to retain the singleton behavior of the previous direct instantiation and export. let newJobCapsService: NewJobCapsService; -export const mlJobCapsServiceFactory = (mlApiServices: MlApiServices) => { +export const mlJobCapsServiceFactory = (mlApi: MlApi) => { if (newJobCapsService) return newJobCapsService; - newJobCapsService = new NewJobCapsService(mlApiServices); + newJobCapsService = new NewJobCapsService(mlApi); return newJobCapsService; }; export const useNewJobCapsService = () => { - const mlApiServices = useMlApiContext(); - return mlJobCapsServiceFactory(mlApiServices); + const mlApi = useMlApi(); + return mlJobCapsServiceFactory(mlApi); }; diff --git a/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service_analytics.ts b/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service_analytics.ts index c2b7a4dc24906..f3ea32f42565d 100644 --- a/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service_analytics.ts +++ b/x-pack/plugins/ml/public/application/services/new_job_capabilities/new_job_capabilities_service_analytics.ts @@ -25,9 +25,9 @@ import { TOP_CLASSES, type DataFrameAnalyticsConfig, } from '@kbn/ml-data-frame-analytics-utils'; -import { useMlApiContext } from '../../contexts/kibana'; +import { useMlApi } from '../../contexts/kibana'; import { processTextAndKeywordFields, NewJobCapabilitiesServiceBase } from './new_job_capabilities'; -import type { MlApiServices } from '../ml_api_service'; +import type { MlApi } from '../ml_api_service'; // Keep top nested field and remove all .* fields export function removeNestedFieldChildren(resp: NewJobCapsResponse, indexPatternTitle: string) { @@ -61,9 +61,9 @@ export function removeNestedFieldChildren(resp: NewJobCapsResponse, indexPattern } export class NewJobCapsServiceAnalytics extends NewJobCapabilitiesServiceBase { - private _mlApiService: MlApiServices; + private _mlApiService: MlApi; - constructor(mlApiService: MlApiServices) { + constructor(mlApiService: MlApi) { super(); this._mlApiService = mlApiService; } @@ -227,14 +227,14 @@ export class NewJobCapsServiceAnalytics extends NewJobCapabilitiesServiceBase { // This is to retain the singleton behavior of the previous direct instantiation and export. let newJobCapsServiceAnalytics: NewJobCapsServiceAnalytics; -export const mlJobCapsServiceAnalyticsFactory = (mlApiServices: MlApiServices) => { +export const mlJobCapsServiceAnalyticsFactory = (mlApi: MlApi) => { if (newJobCapsServiceAnalytics) return newJobCapsServiceAnalytics; - newJobCapsServiceAnalytics = new NewJobCapsServiceAnalytics(mlApiServices); + newJobCapsServiceAnalytics = new NewJobCapsServiceAnalytics(mlApi); return newJobCapsServiceAnalytics; }; export const useNewJobCapsServiceAnalytics = () => { - const mlApiServices = useMlApiContext(); - return mlJobCapsServiceAnalyticsFactory(mlApiServices); + const mlApi = useMlApi(); + return mlJobCapsServiceAnalyticsFactory(mlApi); }; diff --git a/x-pack/plugins/ml/public/application/services/results_service/index.ts b/x-pack/plugins/ml/public/application/services/results_service/index.ts index d8621eff633a4..6ee762511d280 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/index.ts +++ b/x-pack/plugins/ml/public/application/services/results_service/index.ts @@ -7,8 +7,8 @@ import { resultsServiceRxProvider } from './result_service_rx'; import { resultsServiceProvider } from './results_service'; -import type { MlApiServices } from '../ml_api_service'; -import { useMlApiContext } from '../../contexts/kibana'; +import type { MlApi } from '../ml_api_service'; +import { useMlApi } from '../../contexts/kibana'; export type MlResultsService = ReturnType & ReturnType; @@ -25,18 +25,18 @@ export interface CriteriaField { // This is to retain the singleton behavior of the previous direct instantiation and export. let mlResultsService: MlResultsService; -export function mlResultsServiceProvider(mlApiServices: MlApiServices) { +export function mlResultsServiceProvider(mlApi: MlApi) { if (mlResultsService) return mlResultsService; mlResultsService = { - ...resultsServiceProvider(mlApiServices), - ...resultsServiceRxProvider(mlApiServices), + ...resultsServiceProvider(mlApi), + ...resultsServiceRxProvider(mlApi), }; return mlResultsService; } export function useMlResultsService(): MlResultsService { - const mlApiServices = useMlApiContext(); - return mlResultsServiceProvider(mlApiServices); + const mlApi = useMlApi(); + return mlResultsServiceProvider(mlApi); } diff --git a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts index 281139160bee5..0f6e31ea96e95 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts +++ b/x-pack/plugins/ml/public/application/services/results_service/result_service_rx.ts @@ -30,7 +30,7 @@ import { ML_MEDIAN_PERCENTS } from '../../../../common/util/job_utils'; import type { Datafeed, JobId } from '../../../../common/types/anomaly_detection_jobs'; import { findAggField } from '../../../../common/util/validation_utils'; import { getDatafeedAggregations } from '../../../../common/util/datafeed_utils'; -import type { MlApiServices } from '../ml_api_service'; +import type { MlApi } from '../ml_api_service'; import type { CriteriaField } from '.'; export interface ResultResponse { @@ -71,7 +71,7 @@ export interface ScheduledEventsByBucket extends ResultResponse { events: Record; } -export function resultsServiceRxProvider(mlApiServices: MlApiServices) { +export function resultsServiceRxProvider(mlApi: MlApi) { return { getMetricData( index: string, @@ -216,7 +216,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { } } } - return mlApiServices.esSearch$({ index, body }).pipe( + return mlApi.esSearch$({ index, body }).pipe( map((resp: any) => { const obj: MetricData = { success: true, results: {} }; const dataByTime = resp?.aggregations?.byTime?.buckets ?? []; @@ -316,7 +316,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { }, ]; - return mlApiServices.results + return mlApi.results .anomalySearch$( { body: { @@ -469,7 +469,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { }); } - return mlApiServices.results + return mlApi.results .anomalySearch$( { body: { @@ -555,7 +555,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { }); } - return mlApiServices.results + return mlApi.results .anomalySearch$( { body: { @@ -634,7 +634,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { earliestMs: number, latestMs: number ) { - return mlApiServices.results.fetchPartitionFieldsValues( + return mlApi.results.fetchPartitionFieldsValues( jobId, searchTerm, criteriaFields, @@ -734,7 +734,7 @@ export function resultsServiceRxProvider(mlApiServices: MlApiServices) { }); } - return mlApiServices.results + return mlApi.results .anomalySearch$( { body: { diff --git a/x-pack/plugins/ml/public/application/services/results_service/results_service.d.ts b/x-pack/plugins/ml/public/application/services/results_service/results_service.d.ts index aff49acc3b853..a55c56d795d86 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/results_service.d.ts +++ b/x-pack/plugins/ml/public/application/services/results_service/results_service.d.ts @@ -8,9 +8,9 @@ import type { InfluencersFilterQuery, EntityField } from '@kbn/ml-anomaly-utils'; import type { RuntimeMappings } from '@kbn/ml-runtime-field-utils'; import type { IndicesOptions } from '../../../../common/types/anomaly_detection_jobs'; -import type { MlApiServices } from '../ml_api_service'; +import type { MlApi } from '../ml_api_service'; -export function resultsServiceProvider(mlApiServices: MlApiServices): { +export function resultsServiceProvider(mlApi: MlApi): { getScoresByBucket( jobIds: string[], earliestMs: number, diff --git a/x-pack/plugins/ml/public/application/services/results_service/results_service.js b/x-pack/plugins/ml/public/application/services/results_service/results_service.js index f7074a3498b75..5b6df89e52249 100644 --- a/x-pack/plugins/ml/public/application/services/results_service/results_service.js +++ b/x-pack/plugins/ml/public/application/services/results_service/results_service.js @@ -20,7 +20,7 @@ import { aggregationTypeTransform } from '@kbn/ml-anomaly-utils'; /** * Service for carrying out Elasticsearch queries to obtain data for the Ml Results dashboards. */ -export function resultsServiceProvider(mlApiServices) { +export function resultsServiceProvider(mlApi) { const SAMPLER_TOP_TERMS_SHARD_SIZE = 20000; const ENTITY_AGGREGATION_SIZE = 10; const AGGREGATION_MIN_DOC_COUNT = 1; @@ -84,7 +84,7 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices.results + mlApi.results .anomalySearch( { size: 0, @@ -264,7 +264,7 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices.results + mlApi.results .anomalySearch( { size: 0, @@ -406,7 +406,7 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices.results + mlApi.results .anomalySearch( { size: 0, @@ -483,7 +483,7 @@ export function resultsServiceProvider(mlApiServices) { return new Promise((resolve, reject) => { const obj = { success: true, results: {} }; - mlApiServices + mlApi .overallBuckets({ jobId: jobIds, topN: topN, @@ -592,7 +592,7 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices.results + mlApi.results .anomalySearch( { size: 0, @@ -755,7 +755,7 @@ export function resultsServiceProvider(mlApiServices) { }); } - mlApiServices.results + mlApi.results .anomalySearch( { size: maxResults !== undefined ? maxResults : 100, @@ -883,7 +883,7 @@ export function resultsServiceProvider(mlApiServices) { } } - mlApiServices.results + mlApi.results .anomalySearch( { size: maxResults !== undefined ? maxResults : 100, @@ -962,7 +962,7 @@ export function resultsServiceProvider(mlApiServices) { mustCriteria.push(query); } - mlApiServices + mlApi .esSearch({ index, size: 0, @@ -1140,7 +1140,7 @@ export function resultsServiceProvider(mlApiServices) { body.aggs.sample.aggs.byTime.aggs.entities.aggs.metric = metricAgg; } - mlApiServices + mlApi .esSearch({ index, body, @@ -1240,7 +1240,7 @@ export function resultsServiceProvider(mlApiServices) { }, }); } - mlApiServices.results + mlApi.results .anomalySearch( { size: 0, diff --git a/x-pack/plugins/ml/public/application/settings/anomaly_detection_settings.tsx b/x-pack/plugins/ml/public/application/settings/anomaly_detection_settings.tsx index 5161963e90a46..e5fce41df2e18 100644 --- a/x-pack/plugins/ml/public/application/settings/anomaly_detection_settings.tsx +++ b/x-pack/plugins/ml/public/application/settings/anomaly_detection_settings.tsx @@ -22,14 +22,14 @@ import { import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import { useMlApiContext } from '../contexts/kibana'; +import { useMlApi } from '../contexts/kibana'; import { AnomalyDetectionSettingsContext } from './anomaly_detection_settings_context'; import { useToastNotificationService } from '../services/toast_notification_service'; import { ML_PAGES } from '../../../common/constants/locator'; import { useCreateAndNavigateToMlLink } from '../contexts/kibana/use_create_url'; export const AnomalyDetectionSettings: FC = () => { - const ml = useMlApiContext(); + const mlApi = useMlApi(); const [calendarsCount, setCalendarsCount] = useState(0); const [filterListsCount, setFilterListsCount] = useState(0); @@ -53,7 +53,7 @@ export const AnomalyDetectionSettings: FC = () => { // Obtain the counts of calendars and filter lists. if (canGetCalendars === true) { try { - const calendars = await ml.calendars(); + const calendars = await mlApi.calendars(); setCalendarsCount(calendars.length); } catch (e) { displayErrorToast( @@ -67,7 +67,7 @@ export const AnomalyDetectionSettings: FC = () => { if (canGetFilters === true) { try { - const filterLists = await ml.filters.filtersStats(); + const filterLists = await mlApi.filters.filtersStats(); setFilterListsCount(filterLists.length); } catch (e) { displayErrorToast( diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js index 79f4d82093f21..51939aaba639a 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.js @@ -72,7 +72,7 @@ class NewCalendarUI extends Component { async formSetup() { try { const { jobIds, groupIds, calendars } = await getCalendarSettingsData( - this.props.kibana.services.mlServices.mlApiServices + this.props.kibana.services.mlServices.mlApi ); const jobIdOptions = jobIds.map((jobId) => ({ label: jobId })); @@ -145,7 +145,7 @@ class NewCalendarUI extends Component { }; onCreate = async () => { - const ml = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; const { formCalendarId } = this.state; if (this.isDuplicateId()) { @@ -161,7 +161,7 @@ class NewCalendarUI extends Component { this.setState({ saving: true }); try { - await ml.addCalendar(calendar); + await mlApi.addCalendar(calendar); await this.returnToCalendarsManagementPage(); } catch (error) { this.setState({ saving: false }); @@ -177,12 +177,12 @@ class NewCalendarUI extends Component { }; onEdit = async () => { - const ml = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; const calendar = this.setUpCalendarForApi(); this.setState({ saving: true }); try { - await ml.updateCalendar(calendar); + await mlApi.updateCalendar(calendar); await this.returnToCalendarsManagementPage(); } catch (error) { this.setState({ saving: false }); diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js index 1e538668d9ac3..1ec652475e3a3 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/new_calendar.test.js @@ -84,7 +84,7 @@ const mockKibanaContext = { docLinks: { links: { ml: { calendars: 'test' } } }, notifications: { toasts: { addDanger: mockAddDanger, addError: jest.fn() } }, mlServices: { - mlApiServices: { + mlApi: { calendars: () => { return Promise.resolve([]); }, diff --git a/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js b/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js index 34fa2f5292f62..b4c655b755b99 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/edit/utils.js @@ -8,9 +8,9 @@ import { isJobIdValid } from '../../../../../common/util/job_utils'; import { i18n } from '@kbn/i18n'; -function getJobIds(mlApiServices) { +function getJobIds(mlApi) { return new Promise((resolve, reject) => { - mlApiServices.jobs + mlApi.jobs .jobsSummary() .then((resp) => { resolve(resp.map((job) => job.id)); @@ -29,9 +29,9 @@ function getJobIds(mlApiServices) { }); } -function getGroupIds(mlApiServices) { +function getGroupIds(mlApi) { return new Promise((resolve, reject) => { - mlApiServices.jobs + mlApi.jobs .groups() .then((resp) => { resolve(resp.map((group) => group.id)); @@ -50,9 +50,9 @@ function getGroupIds(mlApiServices) { }); } -function getCalendars(mlApiServices) { +function getCalendars(mlApi) { return new Promise((resolve, reject) => { - mlApiServices + mlApi .calendars() .then((resp) => { resolve(resp); @@ -71,13 +71,13 @@ function getCalendars(mlApiServices) { }); } -export function getCalendarSettingsData(mlApiServices) { +export function getCalendarSettingsData(mlApi) { return new Promise(async (resolve, reject) => { try { const [jobIds, groupIds, calendars] = await Promise.all([ - getJobIds(mlApiServices), - getGroupIds(mlApiServices), - getCalendars(mlApiServices), + getJobIds(mlApi), + getGroupIds(mlApi), + getCalendars(mlApi), ]); resolve({ diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js index 413aae794fc15..f49ed3bdac194 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.js @@ -38,11 +38,11 @@ export class CalendarsListUI extends Component { } loadCalendars = async () => { - const ml = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; this.setState({ loading: true }); try { - const calendars = await ml.calendars(); + const calendars = await mlApi.calendars(); this.setState({ calendars, @@ -81,12 +81,12 @@ export class CalendarsListUI extends Component { }; deleteCalendars = () => { - const ml = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; const toasts = this.props.kibana.services.notifications.toasts; const { selectedForDeletion } = this.state; this.closeDestroyModal(); - deleteCalendars(ml, toasts, selectedForDeletion, this.loadCalendars); + deleteCalendars(mlApi, toasts, selectedForDeletion, this.loadCalendars); }; addRequiredFieldsToList = (calendarsList = []) => { diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js index 970c1afbe4fbc..c00b86cf8b231 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/calendars_list.test.js @@ -12,7 +12,7 @@ import { cloneDeep } from 'lodash'; import { CalendarsList } from './calendars_list'; // Mocking the child components to just assert that they get the data -// received via the async call using mlApiServices in the main component. +// received via the async call using mlApi in the main component. jest.mock('../../../components/help_menu', () => ({ HelpMenu: ({ docLink }) =>
, })); @@ -79,7 +79,7 @@ const mockCalendarsFn = jest.fn(() => Promise.resolve(cloneDeep(mockCalendars))) const mockKibanaProp = { services: { docLinks: { links: { ml: { calendars: 'https://calendars' } } }, - mlServices: { mlApiServices: { calendars: mockCalendarsFn } }, + mlServices: { mlApi: { calendars: mockCalendarsFn } }, data: { query: { timefilter: { diff --git a/x-pack/plugins/ml/public/application/settings/calendars/list/delete_calendars.js b/x-pack/plugins/ml/public/application/settings/calendars/list/delete_calendars.js index 13de491f10825..a88ba97c55b8c 100644 --- a/x-pack/plugins/ml/public/application/settings/calendars/list/delete_calendars.js +++ b/x-pack/plugins/ml/public/application/settings/calendars/list/delete_calendars.js @@ -8,12 +8,7 @@ import { i18n } from '@kbn/i18n'; import { extractErrorMessage } from '@kbn/ml-error-utils'; -export async function deleteCalendars( - mlApiServices, - toastNotifications, - calendarsToDelete, - callback -) { +export async function deleteCalendars(mlApi, toastNotifications, calendarsToDelete, callback) { if (calendarsToDelete === undefined || calendarsToDelete.length === 0) { return; } @@ -37,7 +32,7 @@ export async function deleteCalendars( for (const calendar of calendarsToDelete) { const calendarId = calendar.calendar_id; try { - await mlApiServices.deleteCalendar({ calendarId }); + await mlApi.deleteCalendar({ calendarId }); } catch (error) { console.log('Error deleting calendar:', error); toastNotifications.addDanger({ diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.js index ba68b1ef94453..d8cff2e08ab89 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_list_modal.js @@ -51,7 +51,7 @@ export class DeleteFilterListModal extends Component { const { selectedFilterLists, refreshFilterLists } = this.props; await deleteFilterLists( this.context.services.notifications.toasts, - this.context.services.mlServices.mlApiServices, + this.context.services.mlServices.mlApi, selectedFilterLists ); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_lists.js b/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_lists.js index 6334442a8e14f..67701701736ef 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_lists.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/components/delete_filter_list_modal/delete_filter_lists.js @@ -7,7 +7,7 @@ import { i18n } from '@kbn/i18n'; -export async function deleteFilterLists(toastNotifications, mlApiServices, filterListsToDelete) { +export async function deleteFilterLists(toastNotifications, mlApi, filterListsToDelete) { if (filterListsToDelete === undefined || filterListsToDelete.length === 0) { return; } @@ -28,7 +28,7 @@ export async function deleteFilterLists(toastNotifications, mlApiServices, filte for (const filterList of filterListsToDelete) { const filterId = filterList.filter_id; try { - await mlApiServices.filters.deleteFilter(filterId); + await mlApi.filters.deleteFilter(filterId); } catch (resp) { console.log('Error deleting filter list:', resp); toastNotifications.addDanger( diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js index 2f53963a5b3f2..c203da50ce0bd 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.js @@ -114,8 +114,8 @@ export class EditFilterListUI extends Component { }; loadFilterList = (filterId) => { - const ml = this.props.kibana.services.mlServices.mlApiServices; - ml.filters + const mlApi = this.props.kibana.services.mlServices.mlApi; + mlApi.filters .filters({ filterId }) .then((filter) => { this.setLoadedFilterState(filter); @@ -286,7 +286,7 @@ export class EditFilterListUI extends Component { const filterId = this.props.filterId !== undefined ? this.props.filterId : newFilterId; saveFilterList( this.props.kibana.services.notifications.toasts, - this.props.kibana.services.mlServices.mlApiServices, + this.props.kibana.services.mlServices.mlApi, filterId, description, items, diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js index a277457151fa7..16dd5f67dbd67 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/edit_filter_list.test.js @@ -35,7 +35,7 @@ const mockKibanaContext = { docLinks: { links: { ml: { customRules: 'test' } } }, notifications: { toasts: { addDanger: jest.fn(), addError: jest.fn() } }, mlServices: { - mlApiServices: { + mlApi: { filters: { filters: mockFilters, }, diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js index e1f42e2e636ad..721f472827b98 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/edit/utils.js @@ -17,7 +17,7 @@ export function isValidFilterListId(id) { // original filter list to which edits are being applied, is defined with a filter_id property. export function saveFilterList( toastNotifications, - mlApiServices, + mlApi, filterId, description, items, @@ -26,7 +26,7 @@ export function saveFilterList( return new Promise((resolve, reject) => { if (loadedFilterList === undefined || loadedFilterList.filter_id === undefined) { // Create a new filter. - addFilterList(toastNotifications, mlApiServices, filterId, description, items) + addFilterList(toastNotifications, mlApi, filterId, description, items) .then((newFilter) => { resolve(newFilter); }) @@ -35,7 +35,7 @@ export function saveFilterList( }); } else { // Edit to existing filter. - updateFilterList(mlApiServices, loadedFilterList, description, items) + updateFilterList(mlApi, loadedFilterList, description, items) .then((updatedFilter) => { resolve(updatedFilter); }) @@ -46,7 +46,7 @@ export function saveFilterList( }); } -export function addFilterList(toastNotifications, mlApiServices, filterId, description, items) { +export function addFilterList(toastNotifications, mlApi, filterId, description, items) { const filterWithIdExistsErrorMessage = i18n.translate( 'xpack.ml.settings.filterLists.filterWithIdExistsErrorMessage', { @@ -59,13 +59,13 @@ export function addFilterList(toastNotifications, mlApiServices, filterId, descr return new Promise((resolve, reject) => { // First check the filterId isn't already in use by loading the current list of filters. - mlApiServices.filters + mlApi.filters .filtersStats() .then((filterLists) => { const savedFilterIds = filterLists.map((filterList) => filterList.filter_id); if (savedFilterIds.indexOf(filterId) === -1) { // Save the new filter. - mlApiServices.filters + mlApi.filters .addFilter(filterId, description, items) .then((newFilter) => { resolve(newFilter); @@ -84,14 +84,14 @@ export function addFilterList(toastNotifications, mlApiServices, filterId, descr }); } -export function updateFilterList(mlApiServices, loadedFilterList, description, items) { +export function updateFilterList(mlApi, loadedFilterList, description, items) { return new Promise((resolve, reject) => { // Get items added and removed from loaded filter. const loadedItems = loadedFilterList.items; const addItems = items.filter((item) => loadedItems.includes(item) === false); const removeItems = loadedItems.filter((item) => items.includes(item) === false); - mlApiServices.filters + mlApi.filters .updateFilter(loadedFilterList.filter_id, description, addItems, removeItems) .then((updatedFilter) => { resolve(updatedFilter); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js index c955cce8f79d4..fdf3597a2fcfa 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.js @@ -62,9 +62,9 @@ export class FilterListsUI extends Component { }; refreshFilterLists = () => { - const ml = this.props.kibana.services.mlServices.mlApiServices; + const mlApi = this.props.kibana.services.mlServices.mlApi; // Load the list of filters. - ml.filters + mlApi.filters .filtersStats() .then((filterLists) => { this.setFilterLists(filterLists); diff --git a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js index e4a27809019b5..a4c49a79b89dd 100644 --- a/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js +++ b/x-pack/plugins/ml/public/application/settings/filter_lists/list/filter_lists.test.js @@ -12,7 +12,7 @@ import '@testing-library/jest-dom/extend-expect'; import { FilterLists } from './filter_lists'; // Mocking the child components to just assert that they get the data -// received via the async call using mlApiServices in the main component. +// received via the async call using mlApi in the main component. jest.mock('../../../components/help_menu', () => ({ HelpMenu: ({ docLink }) =>
, })); @@ -46,7 +46,7 @@ const mockKibanaProp = { services: { docLinks: { links: { ml: { customRules: 'https://customRules' } } }, mlServices: { - mlApiServices: { + mlApi: { filters: { filtersStats: () => { return Promise.resolve([mockTestFilter]); diff --git a/x-pack/plugins/ml/public/application/settings/settings.test.tsx b/x-pack/plugins/ml/public/application/settings/settings.test.tsx index 38ef8c784c114..2344455beb348 100644 --- a/x-pack/plugins/ml/public/application/settings/settings.test.tsx +++ b/x-pack/plugins/ml/public/application/settings/settings.test.tsx @@ -19,7 +19,7 @@ jest.mock('../contexts/kibana', () => ({ useNotifications: () => ({ toasts: { addDanger: jest.fn(), addError: jest.fn() }, }), - useMlApiContext: jest.fn(), + useMlApi: jest.fn(), useMlKibana: () => ({ services: { docLinks: { diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js index 8402f2cc1e410..fe6b132635301 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/forecasting_modal.js @@ -82,7 +82,7 @@ export class ForecastingModal extends Component { static contextType = context; componentDidMount() { - this.mlForecastService = forecastServiceFactory(this.context.services.mlServices.mlApiServices); + this.mlForecastService = forecastServiceFactory(this.context.services.mlServices.mlApi); } addMessage = (message, status, clearFirst = false) => { @@ -170,7 +170,7 @@ export class ForecastingModal extends Component { jobOpeningState: PROGRESS_STATES.WAITING, }); - this.context.services.mlServices.mlApiServices + this.context.services.mlServices.mlApi .openJob({ jobId: this.props.job.job_id }) .then(() => { // If open was successful run the forecast, then close the job again. @@ -227,7 +227,7 @@ export class ForecastingModal extends Component { if (closeJob === true) { this.setState({ jobClosingState: PROGRESS_STATES.WAITING }); - this.context.services.mlServices.mlApiServices + this.context.services.mlServices.mlApi .closeJob({ jobId: this.props.job.job_id }) .then(() => { this.setState({ jobClosingState: PROGRESS_STATES.DONE }); @@ -308,7 +308,7 @@ export class ForecastingModal extends Component { if (closeJobAfterRunning === true) { this.setState({ jobClosingState: PROGRESS_STATES.WAITING }); - this.context.services.mlServices.mlApiServices + this.context.services.mlServices.mlApi .closeJob({ jobId: this.props.job.job_id }) .then(() => { this.setState({ @@ -434,7 +434,7 @@ export class ForecastingModal extends Component { // of partitioning fields. const entityFieldNames = entities.map((entity) => entity.fieldName); if (entityFieldNames.length > 0) { - this.context.services.mlServices.mlApiServices + this.context.services.mlServices.mlApi .getCardinalityOfFields({ index: job.datafeed_config.indices, fieldNames: entityFieldNames, diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/modal.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/modal.js index 9e9a525031b8a..465373a928cf5 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/modal.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/forecasting_modal/modal.js @@ -34,19 +34,19 @@ export function Modal(props) { const [mlNodesAvailable, setMlNodesAvailable] = useState(false); const { services: { - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); useEffect( function prepMlNodeCheck() { - getMlNodeCount(mlApiServices) + getMlNodeCount(mlApi) .then(({ count, lazyNodeCount }) => { setMlNodesAvailable(count !== 0 || lazyNodeCount !== 0); }) .catch(console.error); }, - [mlApiServices] + [mlApi] ); return ( diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/series_controls/series_controls.tsx b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/series_controls/series_controls.tsx index 1d9d61e3ddc32..4c6d2356f3e6c 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/series_controls/series_controls.tsx +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/series_controls/series_controls.tsx @@ -101,7 +101,7 @@ export const SeriesControls: FC> = ({ const { services: { mlServices: { - mlApiServices: { results: mlResultsService }, + mlApi: { results: mlResultsService }, }, }, } = useMlKibana(); diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js index 7882fdfc21513..20d94aaabc3bb 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.js @@ -167,7 +167,7 @@ class TimeseriesChartIntl extends Component { this.mlTimeSeriesExplorer = timeSeriesExplorerServiceFactory( constructorContext.services.uiSettings, - constructorContext.services.mlServices.mlApiServices, + constructorContext.services.mlServices.mlApi, constructorContext.services.mlServices.mlResultsService ); this.getTimeBuckets = timeBucketsServiceFactory( diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js index 1e9da4aa72787..d9ec6dea88497 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.js @@ -53,7 +53,7 @@ function getTimeseriesChartPropsMock() { const kibanaReactContextMock = createKibanaReactContext({ mlServices: { - mlApiServices: {}, + mlApi: {}, mlResultsService: {}, }, notifications: { toasts: { addDanger: jest.fn(), addSuccess: jest.fn() } }, diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_with_tooltip.tsx b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_with_tooltip.tsx index 14c57cbb6c20e..f69632033b702 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_with_tooltip.tsx +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/components/timeseries_chart/timeseries_chart_with_tooltip.tsx @@ -61,7 +61,7 @@ export const TimeSeriesChartWithTooltips: FC = const { toasts: toastNotifications } = useNotifications(); const { services: { - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlKibana(); @@ -103,7 +103,7 @@ export const TimeSeriesChartWithTooltips: FC = */ const loadAnnotations = async (jobId: string) => { try { - const resp = await mlApiServices.annotations.getAnnotations({ + const resp = await mlApi.annotations.getAnnotations({ jobIds: [jobId], earliestMs: searchBounds.min.valueOf(), latestMs: searchBounds.max.valueOf(), diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js index 4bfcb8e7fd98c..c4951b9041fc1 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js @@ -143,7 +143,7 @@ export class TimeSeriesExplorer extends React.Component { dataViewsService; toastNotificationService; - mlApiServices; + mlApi; mlForecastService; mlIndexUtils; mlJobService; @@ -157,19 +157,19 @@ export class TimeSeriesExplorer extends React.Component { this.toastNotificationService = toastNotificationServiceProvider( constructorContext.services.notifications.toasts ); - this.mlApiServices = constructorContext.services.mlServices.mlApiServices; - this.mlForecastService = forecastServiceFactory(this.mlApiServices); + this.mlApi = constructorContext.services.mlServices.mlApi; + this.mlForecastService = forecastServiceFactory(this.mlApi); this.mlIndexUtils = indexServiceFactory(this.dataViewsService); - this.mlJobService = mlJobServiceFactory(this.toastNotificationService, this.mlApiServices); - this.mlResultsService = mlResultsServiceProvider(this.mlApiServices); + this.mlJobService = mlJobServiceFactory(this.toastNotificationService, this.mlApi); + this.mlResultsService = mlResultsServiceProvider(this.mlApi); this.mlTimeSeriesExplorer = timeSeriesExplorerServiceFactory( constructorContext.services.uiSettings, - this.mlApiServices, + this.mlApi, this.mlResultsService ); this.mlTimeSeriesSearchService = timeSeriesSearchServiceFactory( this.mlResultsService, - this.mlApiServices + this.mlApi ); } @@ -331,8 +331,8 @@ export class TimeSeriesExplorer extends React.Component { const selectedJob = mlJobService.getJob(selectedJobId); const entityControls = this.getControlsForDetector(); - const ml = this.mlApiServices; - return ml.results + const mlApi = this.mlApi; + return mlApi.results .getAnomaliesTableData( [selectedJob.job_id], this.getCriteriaFields(selectedDetectorIndex, entityControls), diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_embeddable_chart/timeseriesexplorer_embeddable_chart.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_embeddable_chart/timeseriesexplorer_embeddable_chart.js index c574e5d1ce741..3839c9831c86b 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_embeddable_chart/timeseriesexplorer_embeddable_chart.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_embeddable_chart/timeseriesexplorer_embeddable_chart.js @@ -272,7 +272,7 @@ export class TimeSeriesExplorerEmbeddableChart extends React.Component { } = this.props; const entityControls = this.getControlsForDetector(); - return this.context.services.mlServices.mlApiServices.results + return this.context.services.mlServices.mlApi.results .getAnomaliesTableData( [selectedJob.job_id], this.getCriteriaFields(selectedDetectorIndex, entityControls), @@ -641,10 +641,10 @@ export class TimeSeriesExplorerEmbeddableChart extends React.Component { this.mlTimeSeriesExplorer = timeSeriesExplorerServiceFactory( this.context.services.uiSettings, - this.context.services.mlServices.mlApiServices, + this.context.services.mlServices.mlApi, this.context.services.mlServices.mlResultsService ); - this.mlForecastService = forecastServiceFactory(this.context.services.mlServices.mlApiServices); + this.mlForecastService = forecastServiceFactory(this.context.services.mlServices.mlApi); // Listen for context chart updates. this.subscriptions.add( diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/time_series_search_service.ts b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/time_series_search_service.ts index 929ff04656a18..213d5e0bff575 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/time_series_search_service.ts +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer_utils/time_series_search_service.ts @@ -12,7 +12,7 @@ import { map } from 'rxjs'; import type { MlEntityField, ES_AGGREGATION } from '@kbn/ml-anomaly-utils'; import type { Job } from '../../../../common/types/anomaly_detection_jobs'; import type { ModelPlotOutput } from '../../services/results_service/result_service_rx'; -import type { MlApiServices } from '../../services/ml_api_service'; +import type { MlApi } from '../../services/ml_api_service'; import { type MlResultsService, mlResultsServiceProvider } from '../../services/results_service'; import { buildConfigFromDetector } from '../../util/chart_config_builder'; import { @@ -29,10 +29,7 @@ interface TimeSeriesExplorerChartDetails { }; } -export function timeSeriesSearchServiceFactory( - mlResultsService: MlResultsService, - mlApiServices: MlApiServices -) { +export function timeSeriesSearchServiceFactory(mlResultsService: MlResultsService, mlApi: MlApi) { function getMetricData( job: Job, detectorIndex: number, @@ -172,7 +169,7 @@ export function timeSeriesSearchServiceFactory( resolve(obj); } else { const entityFieldNames: string[] = blankEntityFields.map((f) => f.fieldName); - mlApiServices + mlApi .getCardinalityOfFields({ index: chartConfig.datafeedConfig.indices.join(','), fieldNames: entityFieldNames, @@ -211,15 +208,15 @@ export type MlTimeSeriesSearchService = ReturnType timeSeriesSearchServiceFactory(mlResultsService, mlApiServices), - [mlApiServices, mlResultsService] + () => timeSeriesSearchServiceFactory(mlResultsService, mlApi), + [mlApi, mlResultsService] ); return mlForecastService; } diff --git a/x-pack/plugins/ml/public/application/util/get_services.ts b/x-pack/plugins/ml/public/application/util/get_services.ts index 330bdc17c8fe9..031504509dff7 100644 --- a/x-pack/plugins/ml/public/application/util/get_services.ts +++ b/x-pack/plugins/ml/public/application/util/get_services.ts @@ -14,7 +14,7 @@ import { MlLicense } from '../../../common/license'; import { MlCapabilitiesService } from '../capabilities/check_capabilities'; import { fieldFormatServiceFactory } from '../services/field_format_service_factory'; import { HttpService } from '../services/http_service'; -import { mlApiServicesProvider } from '../services/ml_api_service'; +import { mlApiProvider } from '../services/ml_api_service'; import { mlUsageCollectionProvider } from '../services/usage_collection'; import { mlJobServiceFactory } from '../services/job_service'; import { toastNotificationServiceProvider } from '../services/toast_notification_service'; @@ -29,9 +29,9 @@ export function getMlGlobalServices( usageCollection?: UsageCollectionSetup ) { const httpService = new HttpService(coreStart.http); - const mlApiServices = mlApiServicesProvider(httpService); + const mlApi = mlApiProvider(httpService); const toastNotificationService = toastNotificationServiceProvider(coreStart.notifications.toasts); - const mlJobService = mlJobServiceFactory(toastNotificationService, mlApiServices); + const mlJobService = mlJobServiceFactory(toastNotificationService, mlApi); // Note on the following services: // - `mlIndexUtils` is just instantiated here to be passed on to `mlFieldFormatService`, // but it's not being made available as part of global services. Since it's just @@ -42,14 +42,14 @@ export function getMlGlobalServices( // its own context or possibly without having a singleton like state at all, since the // way this manages its own state right now doesn't consider React component lifecycles. const mlIndexUtils = indexServiceFactory(dataViews); - const mlFieldFormatService = fieldFormatServiceFactory(mlApiServices, mlIndexUtils, mlJobService); + const mlFieldFormatService = fieldFormatServiceFactory(mlApi, mlIndexUtils, mlJobService); return { httpService, - mlApiServices, + mlApi, mlFieldFormatService, mlUsageCollection: mlUsageCollectionProvider(usageCollection), - mlCapabilities: new MlCapabilitiesService(mlApiServices), + mlCapabilities: new MlCapabilitiesService(mlApi), mlLicense: new MlLicense(), }; } diff --git a/x-pack/plugins/ml/public/application/util/time_series_explorer_service.ts b/x-pack/plugins/ml/public/application/util/time_series_explorer_service.ts index 05763f62d082c..c0c7995f1b310 100644 --- a/x-pack/plugins/ml/public/application/util/time_series_explorer_service.ts +++ b/x-pack/plugins/ml/public/application/util/time_series_explorer_service.ts @@ -29,11 +29,11 @@ import { MAX_SCHEDULED_EVENTS, TIME_FIELD_NAME, } from '../timeseriesexplorer/timeseriesexplorer_constants'; -import type { MlApiServices } from '../services/ml_api_service'; +import type { MlApi } from '../services/ml_api_service'; import { useMlResultsService, type MlResultsService } from '../services/results_service'; import { forecastServiceFactory } from '../services/forecast_service'; import { timeSeriesSearchServiceFactory } from '../timeseriesexplorer/timeseriesexplorer_utils/time_series_search_service'; -import { useMlApiContext, useMlKibana } from '../contexts/kibana'; +import { useMlApi, useMlKibana } from '../contexts/kibana'; export interface Interval { asMilliseconds: () => number; @@ -59,12 +59,12 @@ export interface FocusData { export function timeSeriesExplorerServiceFactory( uiSettings: IUiSettingsClient, - mlApiServices: MlApiServices, + mlApi: MlApi, mlResultsService: MlResultsService ) { const timeBuckets = timeBucketsServiceFactory(uiSettings); - const mlForecastService = forecastServiceFactory(mlApiServices); - const mlTimeSeriesSearchService = timeSeriesSearchServiceFactory(mlResultsService, mlApiServices); + const mlForecastService = forecastServiceFactory(mlApi); + const mlTimeSeriesSearchService = timeSeriesSearchServiceFactory(mlResultsService, mlApi); function getAutoZoomDuration(bucketSpan: Job['analysis_config']['bucket_span']) { // function getAutoZoomDuration(selectedJob: Job) { @@ -511,7 +511,7 @@ export function timeSeriesExplorerServiceFactory( esFunctionToPlotIfMetric ), // Query 2 - load all the records across selected time range for the chart anomaly markers. - mlApiServices.results.getAnomalyRecords$( + mlApi.results.getAnomalyRecords$( [selectedJob.job_id], criteriaFields, 0, @@ -530,7 +530,7 @@ export function timeSeriesExplorerServiceFactory( MAX_SCHEDULED_EVENTS ), // Query 4 - load any annotations for the selected job. - mlApiServices.annotations + mlApi.annotations .getAnnotations$({ jobIds: [selectedJob.job_id], earliestMs: searchBounds.min.valueOf(), @@ -647,10 +647,10 @@ export function timeSeriesExplorerServiceFactory( export function useTimeSeriesExplorerService(): TimeSeriesExplorerService { const { services } = useMlKibana(); - const mlApiServices = useMlApiContext(); + const mlApi = useMlApi(); const mlResultsService = useMlResultsService(); return useMemo( - () => timeSeriesExplorerServiceFactory(services.uiSettings, mlApiServices, mlResultsService), + () => timeSeriesExplorerServiceFactory(services.uiSettings, mlApi, mlResultsService), // initialize only once // eslint-disable-next-line react-hooks/exhaustive-deps [] diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_initializer.test.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_initializer.test.tsx index 4c68437933175..c5dc902ed5264 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_initializer.test.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_initializer.test.tsx @@ -7,7 +7,7 @@ import { render, screen, act } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import type { MlApiServices } from '../../application/services/ml_api_service'; +import type { MlApi } from '../../application/services/ml_api_service'; import { AnomalyChartsInitializer } from './anomaly_charts_initializer'; import { I18nProvider } from '@kbn/i18n-react'; @@ -44,7 +44,7 @@ describe('AnomalyChartsInitializer', () => { initialInput={input} onCreate={(params) => onCreate(params)} onCancel={onCancel} - adJobsApiService={adJobsApiService as unknown as MlApiServices['jobs']} + adJobsApiService={adJobsApiService as unknown as MlApi['jobs']} /> , defaultOptions diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_initializer.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_initializer.tsx index 93bf3110b3776..862d0425523aa 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_initializer.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_charts/anomaly_charts_initializer.tsx @@ -29,7 +29,7 @@ import { ML_PAGES } from '../../../common/constants/locator'; import { getDefaultExplorerChartsPanelTitle } from './utils'; import { useMlLink } from '../../application/contexts/kibana'; import { getJobSelectionErrors } from '../utils'; -import type { MlApiServices } from '../../application/services/ml_api_service'; +import type { MlApi } from '../../application/services/ml_api_service'; export const MAX_ANOMALY_CHARTS_ALLOWED = 50; export interface AnomalyChartsInitializerProps { @@ -42,7 +42,7 @@ export interface AnomalyChartsInitializerProps { maxSeriesToPlot?: number; }) => void; onCancel: () => void; - adJobsApiService: MlApiServices['jobs']; + adJobsApiService: MlApi['jobs']; } export const AnomalyChartsInitializer: FC = ({ diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_charts/get_anomaly_charts_services_dependencies.ts b/x-pack/plugins/ml/public/embeddables/anomaly_charts/get_anomaly_charts_services_dependencies.ts index b7eec6ab24f5f..f5270ab01ef9f 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_charts/get_anomaly_charts_services_dependencies.ts +++ b/x-pack/plugins/ml/public/embeddables/anomaly_charts/get_anomaly_charts_services_dependencies.ts @@ -19,7 +19,7 @@ export const getAnomalyChartsServiceDependencies = async ( { AnomalyDetectorService }, { fieldFormatServiceFactory }, { indexServiceFactory }, - { mlApiServicesProvider }, + { mlApiProvider }, { mlJobServiceFactory }, { mlResultsServiceProvider }, { toastNotificationServiceProvider }, @@ -34,13 +34,13 @@ export const getAnomalyChartsServiceDependencies = async ( ]); const httpService = new HttpService(coreStart.http); const anomalyDetectorService = new AnomalyDetectorService(httpService); - const mlApiServices = mlApiServicesProvider(httpService); + const mlApi = mlApiProvider(httpService); const toastNotificationService = toastNotificationServiceProvider(coreStart.notifications.toasts); - const mlJobService = mlJobServiceFactory(toastNotificationService, mlApiServices); - const mlResultsService = mlResultsServiceProvider(mlApiServices); + const mlJobService = mlJobServiceFactory(toastNotificationService, mlApi); + const mlResultsService = mlResultsServiceProvider(mlApi); const anomalyExplorerService = new AnomalyExplorerChartsService( pluginsStart.data.query.timefilter.timefilter, - mlApiServices, + mlApi, mlResultsService ); @@ -54,7 +54,7 @@ export const getAnomalyChartsServiceDependencies = async ( // its own context or possibly without having a singleton like state at all, since the // way this manages its own state right now doesn't consider React component lifecycles. const mlIndexUtils = indexServiceFactory(pluginsStart.data.dataViews); - const mlFieldFormatService = fieldFormatServiceFactory(mlApiServices, mlIndexUtils, mlJobService); + const mlFieldFormatService = fieldFormatServiceFactory(mlApi, mlIndexUtils, mlJobService); const anomalyChartsEmbeddableServices: AnomalyChartsEmbeddableServices = [ coreStart, diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable_factory.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable_factory.tsx index 6de07c5db851e..34390075f927b 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable_factory.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_embeddable_factory.tsx @@ -59,7 +59,7 @@ export const getServices = async ( [coreStart, pluginsStart], { AnomalyDetectorService }, { AnomalyTimelineService }, - { mlApiServicesProvider }, + { mlApiProvider }, { mlResultsServiceProvider }, ] = await Promise.all([ getStartServices(), @@ -74,7 +74,7 @@ export const getServices = async ( const anomalyTimelineService = new AnomalyTimelineService( pluginsStart.data.query.timefilter.timefilter, coreStart.uiSettings, - mlResultsServiceProvider(mlApiServicesProvider(httpService)) + mlResultsServiceProvider(mlApiProvider(httpService)) ); return [ diff --git a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx index ceb22e0172c8d..21df1ad4f18bb 100644 --- a/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx +++ b/x-pack/plugins/ml/public/embeddables/anomaly_swimlane/anomaly_swimlane_initializer.tsx @@ -26,7 +26,7 @@ import { i18n } from '@kbn/i18n'; import useMountedState from 'react-use/lib/useMountedState'; import { useMlLink } from '../../application/contexts/kibana'; import { ML_PAGES } from '../../../common/constants/locator'; -import type { MlApiServices } from '../../application/services/ml_api_service'; +import type { MlApi } from '../../application/services/ml_api_service'; import { extractInfluencers } from '../../../common/util/job_utils'; import { JobSelectorControl } from '../../alerting/job_selector'; import type { SwimlaneType } from '../../application/explorer/explorer_constants'; @@ -43,7 +43,7 @@ export interface AnomalySwimlaneInitializerProps { >; onCreate: (swimlaneProps: ExplicitInput) => void; onCancel: () => void; - adJobsApiService: MlApiServices['jobs']; + adJobsApiService: MlApi['jobs']; } export const AnomalySwimlaneInitializer: FC = ({ diff --git a/x-pack/plugins/ml/public/embeddables/job_creation/aiops/flyout/create_job.tsx b/x-pack/plugins/ml/public/embeddables/job_creation/aiops/flyout/create_job.tsx index d52aed02d88a3..e4a3e0d05cbde 100644 --- a/x-pack/plugins/ml/public/embeddables/job_creation/aiops/flyout/create_job.tsx +++ b/x-pack/plugins/ml/public/embeddables/job_creation/aiops/flyout/create_job.tsx @@ -52,11 +52,11 @@ export const CreateJob: FC = ({ dataView, field, query, timeRange }) => { uiSettings, dashboardService, notifications: { toasts }, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlFromLensKibanaContext(); const toastNotificationService = toastNotificationServiceProvider(toasts); - const mlJobService = mlJobServiceFactory(toastNotificationService, mlApiServices); + const mlJobService = mlJobServiceFactory(toastNotificationService, mlApi); const [categorizationType, setCategorizationType] = useState( CATEGORIZATION_TYPE.COUNT @@ -77,7 +77,7 @@ export const CreateJob: FC = ({ dataView, field, query, timeRange }) => { const toggleStopOnWarn = useCallback(() => setStopOnWarn(!stopOnWarn), [stopOnWarn]); useMemo(() => { - const newJobCapsService = new NewJobCapsService(mlApiServices); + const newJobCapsService = new NewJobCapsService(mlApi); newJobCapsService.initializeFromDataVIew(dataView).then(() => { const options: EuiComboBoxOptionOption[] = [ ...createFieldOptions(newJobCapsService.categoryFields, []), @@ -86,7 +86,7 @@ export const CreateJob: FC = ({ dataView, field, query, timeRange }) => { })); setCategoryFieldsOptions(options); }); - }, [dataView, mlApiServices]); + }, [dataView, mlApi]); const quickJobCreator = useMemo( () => @@ -96,10 +96,10 @@ export const CreateJob: FC = ({ dataView, field, query, timeRange }) => { data.query.timefilter.timefilter, dashboardService, data, - mlApiServices, + mlApi, mlJobService ), - [dashboardService, data, mlApiServices, mlJobService, uiSettings] + [dashboardService, data, mlApi, mlJobService, uiSettings] ); function createADJobInWizard() { diff --git a/x-pack/plugins/ml/public/embeddables/job_creation/common/job_details.tsx b/x-pack/plugins/ml/public/embeddables/job_creation/common/job_details.tsx index 9c3ba23b57382..3bfa1a0caf799 100644 --- a/x-pack/plugins/ml/public/embeddables/job_creation/common/job_details.tsx +++ b/x-pack/plugins/ml/public/embeddables/job_creation/common/job_details.tsx @@ -80,7 +80,7 @@ export const JobDetails: FC> = ({ services: { share, application, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlFromLensKibanaContext(); @@ -185,7 +185,7 @@ export const JobDetails: FC> = ({ }) ); } else { - mlApiServices.jobs + mlApi.jobs .jobsExist([jobId]) .then((resp) => { if (resp[jobId].exists) { diff --git a/x-pack/plugins/ml/public/embeddables/job_creation/lens/lens_vis_layer_selection_flyout/layer/compatible_layer.tsx b/x-pack/plugins/ml/public/embeddables/job_creation/lens/lens_vis_layer_selection_flyout/layer/compatible_layer.tsx index 47a410c2e6360..967a9dbb84304 100644 --- a/x-pack/plugins/ml/public/embeddables/job_creation/lens/lens_vis_layer_selection_flyout/layer/compatible_layer.tsx +++ b/x-pack/plugins/ml/public/embeddables/job_creation/lens/lens_vis_layer_selection_flyout/layer/compatible_layer.tsx @@ -37,11 +37,11 @@ export const CompatibleLayer: FC = ({ layer, layerIndex, embeddable }) => lens, dashboardService, notifications: { toasts }, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlFromLensKibanaContext(); const toastNotificationService = toastNotificationServiceProvider(toasts); - const mlJobService = mlJobServiceFactory(toastNotificationService, mlApiServices); + const mlJobService = mlJobServiceFactory(toastNotificationService, mlApi); const quickJobCreator = useMemo( () => @@ -51,7 +51,7 @@ export const CompatibleLayer: FC = ({ layer, layerIndex, embeddable }) => uiSettings, data.query.timefilter.timefilter, dashboardService, - mlApiServices, + mlApi, mlJobService ), // eslint-disable-next-line react-hooks/exhaustive-deps diff --git a/x-pack/plugins/ml/public/embeddables/job_creation/map/map_vis_layer_selection_flyout/layer/compatible_layer.tsx b/x-pack/plugins/ml/public/embeddables/job_creation/map/map_vis_layer_selection_flyout/layer/compatible_layer.tsx index 76beaa6788f13..c91785e91573a 100644 --- a/x-pack/plugins/ml/public/embeddables/job_creation/map/map_vis_layer_selection_flyout/layer/compatible_layer.tsx +++ b/x-pack/plugins/ml/public/embeddables/job_creation/map/map_vis_layer_selection_flyout/layer/compatible_layer.tsx @@ -54,11 +54,11 @@ export const CompatibleLayer: FC = ({ embeddable, layer, layerIndex }) => uiSettings, dashboardService, notifications: { toasts }, - mlServices: { mlApiServices }, + mlServices: { mlApi }, }, } = useMlFromLensKibanaContext(); const toastNotificationService = toastNotificationServiceProvider(toasts); - const mlJobService = mlJobServiceFactory(toastNotificationService, mlApiServices); + const mlJobService = mlJobServiceFactory(toastNotificationService, mlApi); const quickJobCreator = useMemo( () => @@ -67,7 +67,7 @@ export const CompatibleLayer: FC = ({ embeddable, layer, layerIndex }) => uiSettings, data.query.timefilter.timefilter, dashboardService, - mlApiServices, + mlApi, mlJobService ), // eslint-disable-next-line react-hooks/exhaustive-deps diff --git a/x-pack/plugins/ml/public/embeddables/single_metric_viewer/get_services.ts b/x-pack/plugins/ml/public/embeddables/single_metric_viewer/get_services.ts index f4460331e6256..180b29dbd0d99 100644 --- a/x-pack/plugins/ml/public/embeddables/single_metric_viewer/get_services.ts +++ b/x-pack/plugins/ml/public/embeddables/single_metric_viewer/get_services.ts @@ -25,7 +25,7 @@ export const getMlServices = async ( { fieldFormatServiceFactory }, { indexServiceFactory }, { timeSeriesExplorerServiceFactory }, - { mlApiServicesProvider }, + { mlApiProvider }, { mlJobServiceFactory }, { mlResultsServiceProvider }, { MlCapabilitiesService }, @@ -48,20 +48,20 @@ export const getMlServices = async ( const httpService = new HttpService(coreStart.http); const anomalyDetectorService = new AnomalyDetectorService(httpService); - const mlApiServices = mlApiServicesProvider(httpService); + const mlApi = mlApiProvider(httpService); const toastNotificationService = toastNotificationServiceProvider(coreStart.notifications.toasts); - const mlJobService = mlJobServiceFactory(toastNotificationService, mlApiServices); - const mlResultsService = mlResultsServiceProvider(mlApiServices); - const mlTimeSeriesSearchService = timeSeriesSearchServiceFactory(mlResultsService, mlApiServices); + const mlJobService = mlJobServiceFactory(toastNotificationService, mlApi); + const mlResultsService = mlResultsServiceProvider(mlApi); + const mlTimeSeriesSearchService = timeSeriesSearchServiceFactory(mlResultsService, mlApi); const mlTimeSeriesExplorerService = timeSeriesExplorerServiceFactory( coreStart.uiSettings, - mlApiServices, + mlApi, mlResultsService ); - const mlCapabilities = new MlCapabilitiesService(mlApiServices); + const mlCapabilities = new MlCapabilitiesService(mlApi); const anomalyExplorerService = new AnomalyExplorerChartsService( pluginsStart.data.query.timefilter.timefilter, - mlApiServices, + mlApi, mlResultsService ); // Note on the following services: @@ -74,11 +74,11 @@ export const getMlServices = async ( // its own context or possibly without having a singleton like state at all, since the // way this manages its own state right now doesn't consider React component lifecycles. const mlIndexUtils = indexServiceFactory(pluginsStart.data.dataViews); - const mlFieldFormatService = fieldFormatServiceFactory(mlApiServices, mlIndexUtils, mlJobService); + const mlFieldFormatService = fieldFormatServiceFactory(mlApi, mlIndexUtils, mlJobService); return { anomalyDetectorService, anomalyExplorerService, - mlApiServices, + mlApi, mlCapabilities, mlFieldFormatService, mlJobService, diff --git a/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_embeddable_factory.tsx b/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_embeddable_factory.tsx index 2655e78222746..8f81be21a8ccb 100644 --- a/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_embeddable_factory.tsx +++ b/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_embeddable_factory.tsx @@ -74,13 +74,13 @@ export const getSingleMetricViewerEmbeddableFactory = ( const { resolveEmbeddableSingleMetricViewerUserInput } = await import( './single_metric_viewer_setup_flyout' ); - const [coreStart, { data, share }, { mlApiServices }] = services; + const [coreStart, { data, share }, { mlApi }] = services; const result = await resolveEmbeddableSingleMetricViewerUserInput( coreStart, parentApi, uuid, { data, share }, - mlApiServices, + mlApi, { ...serializeTitles(), ...serializeSingleMetricViewerState(), diff --git a/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_initializer.tsx b/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_initializer.tsx index 9f21ca3f4af75..c14bfc1cb1744 100644 --- a/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_initializer.tsx +++ b/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_initializer.tsx @@ -26,7 +26,7 @@ import useMountedState from 'react-use/lib/useMountedState'; import { extractErrorMessage } from '@kbn/ml-error-utils'; import type { MlJob } from '@elastic/elasticsearch/lib/api/types'; import type { TimeRangeBounds } from '@kbn/ml-time-buckets'; -import type { MlApiServices } from '../../application/services/ml_api_service'; +import type { MlApi } from '../../application/services/ml_api_service'; import type { SingleMetricViewerEmbeddableInput } from '..'; import { ML_PAGES } from '../../../common/constants/locator'; import { SeriesControls } from '../../application/timeseriesexplorer/components/series_controls'; @@ -42,7 +42,7 @@ import { getDefaultSingleMetricViewerPanelTitle } from './get_default_panel_titl export interface SingleMetricViewerInitializerProps { bounds: TimeRangeBounds; initialInput?: Partial; - mlApiServices: MlApiServices; + mlApi: MlApi; onCreate: (props: SingleMetricViewerEmbeddableUserInput) => void; onCancel: () => void; } @@ -52,7 +52,7 @@ export const SingleMetricViewerInitializer: FC { const isMounted = useMountedState(); const newJobUrl = useMlLink({ page: ML_PAGES.ANOMALY_DETECTION_CREATE_JOB }); @@ -79,7 +79,7 @@ export const SingleMetricViewerInitializer: FC { const errorMsg = extractErrorMessage(error); setErrorMessage(errorMsg); @@ -100,7 +100,7 @@ export const SingleMetricViewerInitializer: FC { diff --git a/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_setup_flyout.tsx b/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_setup_flyout.tsx index 292ec390eb974..9fbb6fbd2b162 100644 --- a/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_setup_flyout.tsx +++ b/x-pack/plugins/ml/public/embeddables/single_metric_viewer/single_metric_viewer_setup_flyout.tsx @@ -14,14 +14,14 @@ import type { DataPublicPluginStart } from '@kbn/data-plugin/public'; import type { SharePluginStart } from '@kbn/share-plugin/public'; import type { SingleMetricViewerEmbeddableUserInput, SingleMetricViewerEmbeddableInput } from '..'; import { SingleMetricViewerInitializer } from './single_metric_viewer_initializer'; -import type { MlApiServices } from '../../application/services/ml_api_service'; +import type { MlApi } from '../../application/services/ml_api_service'; export async function resolveEmbeddableSingleMetricViewerUserInput( coreStart: CoreStart, parentApi: unknown, focusedPanelId: string, services: { data: DataPublicPluginStart; share?: SharePluginStart }, - mlApiServices: MlApiServices, + mlApi: MlApi, input?: Partial ): Promise { const { http, overlays, ...startServices } = coreStart; @@ -35,7 +35,7 @@ export async function resolveEmbeddableSingleMetricViewerUserInput( toMountPoint( { diff --git a/x-pack/plugins/ml/public/embeddables/types.ts b/x-pack/plugins/ml/public/embeddables/types.ts index 3a3353c24b4dd..b7d7dea505f0b 100644 --- a/x-pack/plugins/ml/public/embeddables/types.ts +++ b/x-pack/plugins/ml/public/embeddables/types.ts @@ -33,7 +33,7 @@ import type { AnomalyExplorerChartsService } from '../application/services/anoma import type { AnomalyTimelineService } from '../application/services/anomaly_timeline_service'; import type { MlFieldFormatService } from '../application/services/field_format_service'; import type { MlJobService } from '../application/services/job_service'; -import type { MlApiServices } from '../application/services/ml_api_service'; +import type { MlApi } from '../application/services/ml_api_service'; import type { MlResultsService } from '../application/services/results_service'; import type { MlTimeSeriesSearchService } from '../application/timeseriesexplorer/timeseriesexplorer_utils/time_series_search_service'; import type { TimeSeriesExplorerService } from '../application/util/time_series_explorer_service'; @@ -235,13 +235,13 @@ export interface AnomalyChartsServices { anomalyExplorerService: AnomalyExplorerChartsService; mlFieldFormatService: MlFieldFormatService; mlResultsService: MlResultsService; - mlApiServices?: MlApiServices; + mlApi?: MlApi; } export interface SingleMetricViewerServices { anomalyExplorerService: AnomalyExplorerChartsService; anomalyDetectorService: AnomalyDetectorService; - mlApiServices: MlApiServices; + mlApi: MlApi; mlCapabilities: MlCapabilitiesService; mlFieldFormatService: MlFieldFormatService; mlJobService: MlJobService; diff --git a/x-pack/plugins/ml/public/maps/anomaly_job_selector.tsx b/x-pack/plugins/ml/public/maps/anomaly_job_selector.tsx index 0b842d6c38b1f..75cd10b322fc8 100644 --- a/x-pack/plugins/ml/public/maps/anomaly_job_selector.tsx +++ b/x-pack/plugins/ml/public/maps/anomaly_job_selector.tsx @@ -11,12 +11,12 @@ import type { EuiComboBoxOptionOption } from '@elastic/eui'; import { EuiComboBox, EuiFormRow } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { isEqual } from 'lodash'; -import type { MlApiServices } from '../application/services/ml_api_service'; +import type { MlApi } from '../application/services/ml_api_service'; import { AnomalyJobSelectorEmptyState } from './anomaly_job_selector_empty_state'; interface Props { onJobChange: (jobId: string) => void; - mlJobsService: MlApiServices['jobs']; + mlJobsService: MlApi['jobs']; jobsManagementPath?: string; canCreateJobs: boolean; } diff --git a/x-pack/plugins/ml/public/maps/anomaly_layer_wizard_factory.tsx b/x-pack/plugins/ml/public/maps/anomaly_layer_wizard_factory.tsx index f9cb8ba97fbb5..fdc4f532b8a4f 100644 --- a/x-pack/plugins/ml/public/maps/anomaly_layer_wizard_factory.tsx +++ b/x-pack/plugins/ml/public/maps/anomaly_layer_wizard_factory.tsx @@ -24,7 +24,7 @@ import { AnomalySource } from './anomaly_source'; import { HttpService } from '../application/services/http_service'; import type { MlPluginStart, MlStartDependencies } from '../plugin'; -import type { MlApiServices } from '../application/services/ml_api_service'; +import type { MlApi } from '../application/services/ml_api_service'; export const ML_ANOMALY = 'ML_ANOMALIES'; @@ -41,7 +41,7 @@ export class AnomalyLayerWizardFactory { } private async getServices(): Promise<{ - mlJobsService: MlApiServices['jobs']; + mlJobsService: MlApi['jobs']; mlLocator?: LocatorPublic; }> { const [coreStart, pluginStart] = await this.getStartServices(); diff --git a/x-pack/plugins/ml/public/maps/anomaly_source.tsx b/x-pack/plugins/ml/public/maps/anomaly_source.tsx index 780ecd3cc7352..c426cdcd78919 100644 --- a/x-pack/plugins/ml/public/maps/anomaly_source.tsx +++ b/x-pack/plugins/ml/public/maps/anomaly_source.tsx @@ -35,7 +35,7 @@ import { ML_PAGES } from '../../common/constants/locator'; import type { MlAnomalyLayersType } from './util'; import { getResultsForJobId, ML_ANOMALY_LAYERS } from './util'; import { UpdateAnomalySourceEditor } from './update_anomaly_source_editor'; -import type { MlApiServices } from '../application/services/ml_api_service'; +import type { MlApi } from '../application/services/ml_api_service'; const RESULT_LIMIT = 1000; @@ -45,7 +45,7 @@ export interface AnomalySourceDescriptor extends AbstractSourceDescriptor { } export class AnomalySource implements IVectorSource { - static mlResultsService: MlApiServices['results']; + static mlResultsService: MlApi['results']; static mlLocator?: LocatorPublic; static createDescriptor(descriptor: Partial) { diff --git a/x-pack/plugins/ml/public/maps/anomaly_source_factory.ts b/x-pack/plugins/ml/public/maps/anomaly_source_factory.ts index 6edd7839fbfae..60390e030a61b 100644 --- a/x-pack/plugins/ml/public/maps/anomaly_source_factory.ts +++ b/x-pack/plugins/ml/public/maps/anomaly_source_factory.ts @@ -12,7 +12,7 @@ import type { SerializableRecord } from '@kbn/utility-types'; import { HttpService } from '../application/services/http_service'; import type { MlPluginStart, MlStartDependencies } from '../plugin'; import { ML_APP_LOCATOR } from '../../common/constants/locator'; -import type { MlApiServices } from '../application/services/ml_api_service'; +import type { MlApi } from '../application/services/ml_api_service'; export class AnomalySourceFactory { public readonly type = SOURCE_TYPES.ES_ML_ANOMALIES; @@ -22,15 +22,15 @@ export class AnomalySourceFactory { ) {} private async getServices(): Promise<{ - mlResultsService: MlApiServices['results']; + mlResultsService: MlApi['results']; mlLocator?: LocatorPublic; }> { const [coreStart, pluginStart] = await this.getStartServices(); - const { mlApiServicesProvider } = await import('../application/services/ml_api_service'); + const { mlApiProvider } = await import('../application/services/ml_api_service'); const mlLocator = pluginStart.share.url.locators.get(ML_APP_LOCATOR); const httpService = new HttpService(coreStart.http); - const mlResultsService = mlApiServicesProvider(httpService).results; + const mlResultsService = mlApiProvider(httpService).results; return { mlResultsService, mlLocator }; } diff --git a/x-pack/plugins/ml/public/maps/create_anomaly_source_editor.tsx b/x-pack/plugins/ml/public/maps/create_anomaly_source_editor.tsx index b57afdcfcb2db..48107a2ba3d3f 100644 --- a/x-pack/plugins/ml/public/maps/create_anomaly_source_editor.tsx +++ b/x-pack/plugins/ml/public/maps/create_anomaly_source_editor.tsx @@ -13,11 +13,11 @@ import { AnomalyJobSelector } from './anomaly_job_selector'; import { LayerSelector } from './layer_selector'; import type { MlAnomalyLayersType } from './util'; import { ML_ANOMALY_LAYERS } from './util'; -import type { MlApiServices } from '../application/services/ml_api_service'; +import type { MlApi } from '../application/services/ml_api_service'; interface Props { onSourceConfigChange: (sourceConfig: Partial | null) => void; - mlJobsService: MlApiServices['jobs']; + mlJobsService: MlApi['jobs']; jobsManagementPath?: string; canCreateJobs: boolean; } diff --git a/x-pack/plugins/ml/public/maps/util.ts b/x-pack/plugins/ml/public/maps/util.ts index 7666552e40e93..f661c08b6c5f6 100644 --- a/x-pack/plugins/ml/public/maps/util.ts +++ b/x-pack/plugins/ml/public/maps/util.ts @@ -22,7 +22,7 @@ import { LAYER_TYPE, SOURCE_TYPES, SCALING_TYPES } from '@kbn/maps-plugin/common import { type MLAnomalyDoc, ML_SEVERITY_COLOR_RAMP } from '@kbn/ml-anomaly-utils'; import { formatHumanReadableDateTimeSeconds } from '@kbn/ml-date-utils'; import { SEARCH_QUERY_LANGUAGE } from '@kbn/ml-query-utils'; -import type { MlApiServices } from '../application/services/ml_api_service'; +import type { MlApi } from '../application/services/ml_api_service'; import { tabColor } from '../../common/util/group_color_utils'; import { getIndexPattern } from '../application/explorer/reducers/explorer_reducer/get_index_pattern'; import { AnomalySource } from './anomaly_source'; @@ -162,7 +162,7 @@ export function getInitialSourceIndexFieldLayers(sourceIndexWithGeoFields: Sourc } export async function getResultsForJobId( - mlResultsService: MlApiServices['results'], + mlResultsService: MlApi['results'], jobId: string, locationType: MlAnomalyLayersType, searchFilters: VectorSourceRequestMeta diff --git a/x-pack/plugins/ml/public/plugin.ts b/x-pack/plugins/ml/public/plugin.ts index 456259fd6d28d..7246f60337dd9 100644 --- a/x-pack/plugins/ml/public/plugin.ts +++ b/x-pack/plugins/ml/public/plugin.ts @@ -70,7 +70,7 @@ import { initExperimentalFeatures, } from '../common/constants/app'; import type { ElasticModels } from './application/services/elastic_models_service'; -import type { MlApiServices } from './application/services/ml_api_service'; +import type { MlApi } from './application/services/ml_api_service'; import type { MlCapabilities } from '../common/types/capabilities'; import { AnomalySwimLane } from './shared_components'; import { getMlServices } from './embeddables/single_metric_viewer/get_services'; @@ -314,13 +314,13 @@ export class MlPlugin implements Plugin { ): { locator?: LocatorPublic; elasticModels?: ElasticModels; - mlApi?: MlApiServices; + mlApi?: MlApi; components: { AnomalySwimLane: typeof AnomalySwimLane }; } { return { locator: this.locator, elasticModels: this.sharedMlServices?.elasticModels, - mlApi: this.sharedMlServices?.mlApiServices, + mlApi: this.sharedMlServices?.mlApi, components: { AnomalySwimLane, }, diff --git a/x-pack/plugins/ml/public/shared_components/single_metric_viewer/single_metric_viewer.tsx b/x-pack/plugins/ml/public/shared_components/single_metric_viewer/single_metric_viewer.tsx index 2cf5edfd0608d..96e678407f626 100644 --- a/x-pack/plugins/ml/public/shared_components/single_metric_viewer/single_metric_viewer.tsx +++ b/x-pack/plugins/ml/public/shared_components/single_metric_viewer/single_metric_viewer.tsx @@ -102,7 +102,7 @@ const SingleMetricViewerWrapper: FC = ({ >(); const isMounted = useMountedState(); - const { mlApiServices, mlTimeSeriesExplorerService, toastNotificationService } = mlServices; + const { mlApi, mlTimeSeriesExplorerService, toastNotificationService } = mlServices; const startServices = pick(coreStart, 'analytics', 'i18n', 'theme'); const datePickerDeps: DatePickerDependencies = { ...pick(coreStart, ['http', 'notifications', 'theme', 'uiSettings', 'i18n']), @@ -116,11 +116,11 @@ const SingleMetricViewerWrapper: FC = ({ useEffect( function setUpSelectedJob() { async function fetchSelectedJob() { - if (mlApiServices && selectedJobId !== undefined) { + if (mlApi && selectedJobId !== undefined) { try { const [{ jobs }, { jobs: jobStats }] = await Promise.all([ - mlApiServices.getJobs({ jobId: selectedJobId }), - mlApiServices.getJobStats({ jobId: selectedJobId }), + mlApi.getJobs({ jobId: selectedJobId }), + mlApi.getJobStats({ jobId: selectedJobId }), ]); setSelectedJobWrapper({ job: jobs[0], stats: jobStats[0] }); } catch (e) { @@ -135,7 +135,7 @@ const SingleMetricViewerWrapper: FC = ({ } fetchSelectedJob(); }, - [selectedJobId, mlApiServices, isMounted, onError] + [selectedJobId, mlApi, isMounted, onError] ); // eslint-disable-next-line react-hooks/exhaustive-deps const resizeHandler = useCallback( diff --git a/x-pack/plugins/ml/public/ui_actions/create_single_metric_viewer.tsx b/x-pack/plugins/ml/public/ui_actions/create_single_metric_viewer.tsx index ceae89e121fb7..721f830e01627 100644 --- a/x-pack/plugins/ml/public/ui_actions/create_single_metric_viewer.tsx +++ b/x-pack/plugins/ml/public/ui_actions/create_single_metric_viewer.tsx @@ -11,7 +11,7 @@ import type { EmbeddableApiContext } from '@kbn/presentation-publishing'; import type { UiActionsActionDefinition } from '@kbn/ui-actions-plugin/public'; import { IncompatibleActionError } from '@kbn/ui-actions-plugin/public'; import { HttpService } from '../application/services/http_service'; -import type { MlApiServices } from '../application/services/ml_api_service'; +import type { MlApi } from '../application/services/ml_api_service'; import { ML_APP_NAME, PLUGIN_ICON, PLUGIN_ID } from '../../common/constants/app'; import { ANOMALY_SINGLE_METRIC_VIEWER_EMBEDDABLE_TYPE } from '../embeddables'; import type { SingleMetricViewerEmbeddableApi } from '../embeddables/types'; @@ -66,16 +66,16 @@ export function createAddSingleMetricViewerPanelAction( const { resolveEmbeddableSingleMetricViewerUserInput } = await import( '../embeddables/single_metric_viewer/single_metric_viewer_setup_flyout' ); - const { mlApiServicesProvider } = await import('../application/services/ml_api_service'); + const { mlApiProvider } = await import('../application/services/ml_api_service'); const httpService = new HttpService(coreStart.http); - const mlApiServices: MlApiServices = mlApiServicesProvider(httpService); + const mlApi: MlApi = mlApiProvider(httpService); const initialState = await resolveEmbeddableSingleMetricViewerUserInput( coreStart, context.embeddable, context.embeddable.uuid, { data, share }, - mlApiServices + mlApi ); presentationContainerParent.addNewPanel({ From 3e47faff40b3b686ba71dc01fac36be660658971 Mon Sep 17 00:00:00 2001 From: "Quynh Nguyen (Quinn)" <43350163+qn895@users.noreply.github.com> Date: Wed, 4 Sep 2024 07:47:17 -0500 Subject: [PATCH 10/48] [ES|QL] Add named time system suggestions for date expressions (#192012) ## Summary This PR fixes a regression where named time system suggestions like (?t_start, ?t_end or Choose from time picker) were not being suggested for date expressions https://github.com/user-attachments/assets/cef899d8-b432-49a9-b09c-0fb5f719a721 This might have been introduced in https://github.com/elastic/kibana/pull/189941/files#diff-2a96c81cce17aff8cb8f0254f313903c2312b770ae08b3f4b938af0824d2e0fcL1149 ### Checklist Delete any items that are not applicable to this PR. - [ ] Any text added follows [EUI's writing guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses sentence case text and includes [i18n support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md) - [ ] [Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html) was added for features that require explanation or tutorials - [ ] [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 - [ ] [Flaky Test Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was used on any tests changed - [ ] Any UI touched in this PR is usable by keyboard only (learn more about [keyboard accessibility](https://webaim.org/techniques/keyboard/)) - [ ] Any UI touched in this PR does not create any new axe failures (run axe in browser: [FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/), [Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US)) - [ ] If a plugin configuration key changed, check if it needs to be allowlisted in the cloud and added to the [docker list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker) - [ ] This renders correctly on smaller devices using a responsive layout. (You can test this [in your browser](https://www.browserstack.com/guide/responsive-testing-on-local-server)) - [ ] This was checked for [cross-browser compatibility](https://www.elastic.co/support/matrix#matrix_browsers) ### Risk Matrix Delete this section if it is not applicable to this PR. Before closing this PR, invite QA, stakeholders, and other developers to identify risks that should be tested prior to the change/feature release. When forming the risk matrix, consider some of the following examples and how they may potentially impact the change: | Risk | Probability | Severity | Mitigation/Notes | |---------------------------|-------------|----------|-------------------------| | Multiple Spaces—unexpected behavior in non-default Kibana Space. | Low | High | Integration tests will verify that all features are still supported in non-default Kibana Space and when user switches between spaces. | | Multiple nodes—Elasticsearch polling might have race conditions when multiple Kibana nodes are polling for the same tasks. | High | Low | Tasks are idempotent, so executing them multiple times will not result in logical error, but will degrade performance. To test for this case we add plenty of unit tests around this logic and document manual testing procedure. | | Code should gracefully handle cases when feature X or plugin Y are disabled. | Medium | High | Unit tests will verify that any feature flag or plugin combination still results in our service operational. | | [See more potential risk examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) | ### For maintainers - [ ] This was checked for breaking API changes and was [labeled appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process) --------- Co-authored-by: Elastic Machine --- .../src/autocomplete/autocomplete.test.ts | 14 ++++++++++++++ .../src/autocomplete/autocomplete.ts | 4 ++++ 2 files changed, 18 insertions(+) diff --git a/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.test.ts b/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.test.ts index 9f558c7c17470..3e5171d37c49c 100644 --- a/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.test.ts +++ b/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.test.ts @@ -12,6 +12,7 @@ import { timeUnitsToSuggest } from '../definitions/literals'; import { commandDefinitions as unmodifiedCommandDefinitions } from '../definitions/commands'; import { ADD_DATE_HISTOGRAM_SNIPPET, + getDateLiterals, getSafeInsertText, TIME_SYSTEM_PARAMS, TRIGGER_SUGGESTION_COMMAND, @@ -141,6 +142,19 @@ describe('autocomplete', () => { ['and', 'or', 'not'] ), ]); + + const expectedComparisonWithDateSuggestions = [ + ...getDateLiterals(), + ...getFieldNamesByType(['date']), + // all functions compatible with a keywordField type + ...getFunctionSignaturesByReturnType('where', ['date'], { scalar: true }), + ]; + testSuggestions('from a | where dateField == /', expectedComparisonWithDateSuggestions); + + testSuggestions('from a | where dateField < /', expectedComparisonWithDateSuggestions); + + testSuggestions('from a | where dateField >= /', expectedComparisonWithDateSuggestions); + const expectedComparisonWithTextFieldSuggestions = [ ...getFieldNamesByType(['text', 'keyword', 'ip', 'version']), ...getFunctionSignaturesByReturnType('where', ['text', 'keyword', 'ip', 'version'], { diff --git a/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.ts b/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.ts index b2808ee2c1156..9346e093c7eb9 100644 --- a/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.ts +++ b/packages/kbn-esql-validation-autocomplete/src/autocomplete/autocomplete.ts @@ -1102,6 +1102,7 @@ async function getBuiltinFunctionNextArgument( } else { const finalType = nestedType || nodeArgType || 'any'; const supportedTypes = getSupportedTypesForBinaryOperators(fnDef, finalType as string); + suggestions.push( ...(await getFieldsOrFunctionsSuggestions( // this is a special case with AND/OR @@ -1232,8 +1233,11 @@ async function getFieldsOrFunctionsSuggestions( } } } + // could also be in stats (bucket) but our autocomplete is not great yet + const displayDateSuggestions = types.includes('date') && ['where', 'eval'].includes(commandName); const suggestions = filteredFieldsByType.concat( + displayDateSuggestions ? getDateLiterals() : [], functions ? getCompatibleFunctionDefinition(commandName, optionName, types, ignoreFn) : [], variables ? pushItUpInTheList(buildVariablesDefinitions(filteredVariablesByType), functions) From 4ca6f1d77d6290a743ae56f4775c6e0267982e1b Mon Sep 17 00:00:00 2001 From: Robert Jaszczurek <92210485+rbrtj@users.noreply.github.com> Date: Wed, 4 Sep 2024 14:47:58 +0200 Subject: [PATCH 11/48] [ML] Trained models - fix download state responsiveness (#191900) ## Summary Fix for [#1284](https://github.com/elastic/ml-team/issues/1284) https://github.com/user-attachments/assets/3b829777-4ff9-4272-80dd-d27bccdb9fb5 ### Checklist Delete any items that are not applicable to this PR. - [X] This renders correctly on smaller devices using a responsive layout. (You can test this [in your browser](https://www.browserstack.com/guide/responsive-testing-on-local-server)) --- .../ml/public/application/model_management/models_list.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/plugins/ml/public/application/model_management/models_list.tsx b/x-pack/plugins/ml/public/application/model_management/models_list.tsx index c7622501d072b..a7d969d013a25 100644 --- a/x-pack/plugins/ml/public/application/model_management/models_list.tsx +++ b/x-pack/plugins/ml/public/application/model_management/models_list.tsx @@ -707,7 +707,7 @@ export const ModelsList: FC = ({ ); return ( - + {isDownloadInProgress ? ( Date: Wed, 4 Sep 2024 15:21:17 +0200 Subject: [PATCH 12/48] [Dataset quality] Enable page for synthetics (#191846) Closes https://github.com/elastic/observability-dev/issues/3457. This PR enables Dataset quality for being used for synthetics datasets. ### Changes - Added `synthetics` to `KNOWN_TYPES` array. - Permissions were updated in `Data_quality` plugin. https://github.com/user-attachments/assets/e9945012-166b-4704-bb73-11e6fe6eed76 --- packages/kbn-apm-synthtrace-client/index.ts | 1 + .../src/lib/synthetics/index.ts | 103 ++++++++++++ packages/kbn-apm-synthtrace/README.md | 1 + packages/kbn-apm-synthtrace/index.ts | 1 + .../kbn-apm-synthtrace/src/cli/scenario.ts | 8 +- .../src/cli/utils/bootstrap.ts | 9 + .../src/cli/utils/get_synthetics_es_client.ts | 33 ++++ .../src/cli/utils/start_live_data_upload.ts | 7 +- .../src/cli/utils/synthtrace_worker.ts | 10 +- .../src/lib/logs/logs_synthtrace_es_client.ts | 25 +-- .../data_stream_get_routing_transform.ts | 25 +++ .../synthetics_synthtrace_es_client.ts | 42 +++++ .../scenarios/degraded_synthetics_monitors.ts | 159 ++++++++++++++++++ .../helpers/get_at_index_or_random.ts | 13 ++ .../src/scenarios/helpers/logs_mock_data.ts | 5 +- x-pack/plugins/data_quality/server/plugin.ts | 7 + .../dataset_quality/common/constants.ts | 2 +- .../authentication.ts | 12 +- .../common/config.ts | 22 ++- .../data_streams/data_stream_details.spec.ts | 14 +- .../data_streams/data_stream_settings.spec.ts | 16 +- .../tests/data_streams/degraded_docs.spec.ts | 6 +- .../degraded_field_values.spec.ts | 4 +- .../data_streams/degraded_fields.spec.ts | 9 +- .../tests/data_streams/stats.spec.ts | 81 +++++++-- .../integration_dashboards.spec.ts | 2 +- .../tests/integrations/integrations.spec.ts | 2 +- 27 files changed, 542 insertions(+), 77 deletions(-) create mode 100644 packages/kbn-apm-synthtrace-client/src/lib/synthetics/index.ts create mode 100644 packages/kbn-apm-synthtrace/src/cli/utils/get_synthetics_es_client.ts create mode 100644 packages/kbn-apm-synthtrace/src/lib/shared/data_stream_get_routing_transform.ts create mode 100644 packages/kbn-apm-synthtrace/src/lib/synthetics/synthetics_synthtrace_es_client.ts create mode 100644 packages/kbn-apm-synthtrace/src/scenarios/degraded_synthetics_monitors.ts create mode 100644 packages/kbn-apm-synthtrace/src/scenarios/helpers/get_at_index_or_random.ts diff --git a/packages/kbn-apm-synthtrace-client/index.ts b/packages/kbn-apm-synthtrace-client/index.ts index 71321a8f3c67a..2553d3b08bfab 100644 --- a/packages/kbn-apm-synthtrace-client/index.ts +++ b/packages/kbn-apm-synthtrace-client/index.ts @@ -35,3 +35,4 @@ export { appendHash, hashKeysOf } from './src/lib/utils/hash'; export type { ESDocumentWithOperation, SynthtraceESAction, SynthtraceGenerator } from './src/types'; export { log, type LogDocument, LONG_FIELD_NAME } from './src/lib/logs'; export { type AssetDocument } from './src/lib/assets'; +export { syntheticsMonitor, type SyntheticsMonitorDocument } from './src/lib/synthetics'; diff --git a/packages/kbn-apm-synthtrace-client/src/lib/synthetics/index.ts b/packages/kbn-apm-synthtrace-client/src/lib/synthetics/index.ts new file mode 100644 index 0000000000000..381c171ba5e02 --- /dev/null +++ b/packages/kbn-apm-synthtrace-client/src/lib/synthetics/index.ts @@ -0,0 +1,103 @@ +/* + * 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 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { Fields } from '../entity'; +import { Serializable } from '../serializable'; + +export type SyntheticsMonitorDocument = Fields & + Partial<{ + 'data_stream.namespace': string; + 'data_stream.type': string; + 'data_stream.dataset': string; + 'monitor.id': string; + 'monitor.origin': string; + 'monitor.name': string; + 'monitor.type': string; + 'monitor.check_group': string; + 'monitor.timespan.lt': string; + 'monitor.timespan.gte': string; + 'monitor.duration.us'?: number; + 'monitor.ip'?: string; + 'monitor.project.name'?: string; + 'monitor.project.id'?: string; + 'monitor.fleet_managed'?: boolean; + 'monitor.status'?: string; + 'synthetics.type'?: string; + 'synthetics.step.index'?: number; + 'observer.os.name'?: string; + 'observer.product'?: string; + }>; + +type MonitorDataStream = + | 'http' + | 'tcp' + | 'icmp' + | 'browser' + | 'browser.screenshot' + | 'browser.network'; + +class SyntheticsMonitor extends Serializable { + constructor(fields: SyntheticsMonitorDocument) { + super({ + ...fields, + }); + } + + namespace(value: string) { + this.fields['data_stream.namespace'] = value; + return this; + } + + dataset(value: MonitorDataStream) { + this.fields['data_stream.dataset'] = value; + + if (value === 'browser.screenshot' || value === 'browser.network') { + this.fields['monitor.type'] = 'browser'; + return this; + } + + this.fields['monitor.type'] = value; + return this; + } + + name(value: string) { + this.fields['monitor.name'] = value; + return this; + } + + origin(value: string) { + this.fields['monitor.origin'] = value; + return this; + } + + ip(value: string) { + this.fields['monitor.ip'] = value; + return this; + } + + status(value: string) { + this.fields['monitor.status'] = value; + return this; + } + + timestamp(time: number) { + super.timestamp(time); + return this; + } +} + +function create(): SyntheticsMonitor { + return new SyntheticsMonitor({ + 'data_stream.namespace': 'default', + 'data_stream.type': 'synthetics', + }).dataset('http'); +} + +export const syntheticsMonitor = { + create, +}; diff --git a/packages/kbn-apm-synthtrace/README.md b/packages/kbn-apm-synthtrace/README.md index 6daad014ff0e5..a9704b1905d1b 100644 --- a/packages/kbn-apm-synthtrace/README.md +++ b/packages/kbn-apm-synthtrace/README.md @@ -22,6 +22,7 @@ This library can currently be used in two ways: - `Timerange`: an object that will return an array of timestamps based on an interval and a rate. These timestamps can be used to generate events/metricsets. - `Transaction`, `Span`, `APMError` and `Metricset`: events/metricsets that occur on an instance. For more background, see the [explanation of the APM data model](https://www.elastic.co/guide/en/apm/get-started/7.15/apm-data-model.html) - `Log`: An instance of Log generating Service which supports additional helpers to customise fields like `messages`, `logLevel` +- `SyntheticsMonitor`: An instance of Synthetic monitor. For more information see [Synthetic monitoring](https://www.elastic.co/guide/en/observability/current/monitor-uptime-synthetics.html). #### Example diff --git a/packages/kbn-apm-synthtrace/index.ts b/packages/kbn-apm-synthtrace/index.ts index 459e3802ae660..22b947cd1bbf3 100644 --- a/packages/kbn-apm-synthtrace/index.ts +++ b/packages/kbn-apm-synthtrace/index.ts @@ -15,6 +15,7 @@ export { InfraSynthtraceKibanaClient } from './src/lib/infra/infra_synthtrace_ki export { MonitoringSynthtraceEsClient } from './src/lib/monitoring/monitoring_synthtrace_es_client'; export { LogsSynthtraceEsClient } from './src/lib/logs/logs_synthtrace_es_client'; export { AssetsSynthtraceEsClient } from './src/lib/assets/assets_synthtrace_es_client'; +export { SyntheticsSynthtraceEsClient } from './src/lib/synthetics/synthetics_synthtrace_es_client'; export { addObserverVersionTransform, deleteSummaryFieldTransform, diff --git a/packages/kbn-apm-synthtrace/src/cli/scenario.ts b/packages/kbn-apm-synthtrace/src/cli/scenario.ts index c12d8333071c6..ba5e17deb1c18 100644 --- a/packages/kbn-apm-synthtrace/src/cli/scenario.ts +++ b/packages/kbn-apm-synthtrace/src/cli/scenario.ts @@ -7,7 +7,12 @@ */ import { Timerange } from '@kbn/apm-synthtrace-client'; -import { ApmSynthtraceEsClient, InfraSynthtraceEsClient, LogsSynthtraceEsClient } from '../..'; +import { + ApmSynthtraceEsClient, + InfraSynthtraceEsClient, + LogsSynthtraceEsClient, + SyntheticsSynthtraceEsClient, +} from '../..'; import { AssetsSynthtraceEsClient } from '../lib/assets/assets_synthtrace_es_client'; import { Logger } from '../lib/utils/create_logger'; import { ScenarioReturnType } from '../lib/utils/with_client'; @@ -18,6 +23,7 @@ interface EsClients { logsEsClient: LogsSynthtraceEsClient; infraEsClient: InfraSynthtraceEsClient; assetsEsClient: AssetsSynthtraceEsClient; + syntheticsEsClient: SyntheticsSynthtraceEsClient; } type Generate = (options: { diff --git a/packages/kbn-apm-synthtrace/src/cli/utils/bootstrap.ts b/packages/kbn-apm-synthtrace/src/cli/utils/bootstrap.ts index be9f0a313fe0a..5119625b7f261 100644 --- a/packages/kbn-apm-synthtrace/src/cli/utils/bootstrap.ts +++ b/packages/kbn-apm-synthtrace/src/cli/utils/bootstrap.ts @@ -14,6 +14,7 @@ import { getKibanaClient } from './get_kibana_client'; import { getServiceUrls } from './get_service_urls'; import { RunOptions } from './parse_run_cli_flags'; import { getAssetsEsClient } from './get_assets_es_client'; +import { getSyntheticsEsClient } from './get_synthetics_es_client'; export async function bootstrap(runOptions: RunOptions) { const logger = createLogger(runOptions.logLevel); @@ -61,11 +62,18 @@ export async function bootstrap(runOptions: RunOptions) { concurrency: runOptions.concurrency, }); + const syntheticsEsClient = getSyntheticsEsClient({ + target: esUrl, + logger, + concurrency: runOptions.concurrency, + }); + if (runOptions.clean) { await apmEsClient.clean(); await logsEsClient.clean(); await infraEsClient.clean(); await assetsEsClient.clean(); + await syntheticsEsClient.clean(); } return { @@ -74,6 +82,7 @@ export async function bootstrap(runOptions: RunOptions) { logsEsClient, infraEsClient, assetsEsClient, + syntheticsEsClient, version, kibanaUrl, esUrl, diff --git a/packages/kbn-apm-synthtrace/src/cli/utils/get_synthetics_es_client.ts b/packages/kbn-apm-synthtrace/src/cli/utils/get_synthetics_es_client.ts new file mode 100644 index 0000000000000..0310dfc40dd74 --- /dev/null +++ b/packages/kbn-apm-synthtrace/src/cli/utils/get_synthetics_es_client.ts @@ -0,0 +1,33 @@ +/* + * 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 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { Client } from '@elastic/elasticsearch'; +import { Logger } from '../../lib/utils/create_logger'; +import { RunOptions } from './parse_run_cli_flags'; +import { getEsClientTlsSettings } from './ssl'; +import { SyntheticsSynthtraceEsClient } from '../../lib/synthetics/synthetics_synthtrace_es_client'; + +export function getSyntheticsEsClient({ + target, + logger, + concurrency, +}: Pick & { + target: string; + logger: Logger; +}) { + const client = new Client({ + node: target, + tls: getEsClientTlsSettings(target), + }); + + return new SyntheticsSynthtraceEsClient({ + client, + logger, + concurrency, + }); +} diff --git a/packages/kbn-apm-synthtrace/src/cli/utils/start_live_data_upload.ts b/packages/kbn-apm-synthtrace/src/cli/utils/start_live_data_upload.ts index fd7ddc6b42b36..253113532795d 100644 --- a/packages/kbn-apm-synthtrace/src/cli/utils/start_live_data_upload.ts +++ b/packages/kbn-apm-synthtrace/src/cli/utils/start_live_data_upload.ts @@ -25,9 +25,8 @@ export async function startLiveDataUpload({ }) { const file = runOptions.file; - const { logger, apmEsClient, logsEsClient, infraEsClient, assetsEsClient } = await bootstrap( - runOptions - ); + const { logger, apmEsClient, logsEsClient, infraEsClient, assetsEsClient, syntheticsEsClient } = + await bootstrap(runOptions); const scenario = await getScenario({ file, logger }); const { generate } = await scenario({ ...runOptions, logger }); @@ -65,7 +64,7 @@ export async function startLiveDataUpload({ const generatorsAndClients = generate({ range: timerange(bucketFrom.getTime(), bucketTo.getTime()), - clients: { logsEsClient, apmEsClient, infraEsClient, assetsEsClient }, + clients: { logsEsClient, apmEsClient, infraEsClient, assetsEsClient, syntheticsEsClient }, }); const generatorsAndClientsArray = castArray(generatorsAndClients); diff --git a/packages/kbn-apm-synthtrace/src/cli/utils/synthtrace_worker.ts b/packages/kbn-apm-synthtrace/src/cli/utils/synthtrace_worker.ts index fc7c70b0d6bc7..784931b5f6139 100644 --- a/packages/kbn-apm-synthtrace/src/cli/utils/synthtrace_worker.ts +++ b/packages/kbn-apm-synthtrace/src/cli/utils/synthtrace_worker.ts @@ -17,6 +17,7 @@ import { RunOptions } from './parse_run_cli_flags'; import { getLogsEsClient } from './get_logs_es_client'; import { getInfraEsClient } from './get_infra_es_client'; import { getAssetsEsClient } from './get_assets_es_client'; +import { getSyntheticsEsClient } from './get_synthetics_es_client'; export interface WorkerData { bucketFrom: Date; @@ -56,6 +57,12 @@ async function start() { logger, }); + const syntheticsEsClient = getSyntheticsEsClient({ + concurrency: runOptions.concurrency, + target: esUrl, + logger, + }); + const file = runOptions.file; const scenario = await logger.perf('get_scenario', () => getScenario({ file, logger })); @@ -70,6 +77,7 @@ async function start() { logsEsClient, infraEsClient, assetsEsClient, + syntheticsEsClient, }); } @@ -78,7 +86,7 @@ async function start() { const generatorsAndClients = logger.perf('generate_scenario', () => generate({ range: timerange(bucketFrom, bucketTo), - clients: { logsEsClient, apmEsClient, infraEsClient, assetsEsClient }, + clients: { logsEsClient, apmEsClient, infraEsClient, assetsEsClient, syntheticsEsClient }, }) ); diff --git a/packages/kbn-apm-synthtrace/src/lib/logs/logs_synthtrace_es_client.ts b/packages/kbn-apm-synthtrace/src/lib/logs/logs_synthtrace_es_client.ts index 95f8917c26658..3f1d5ea418026 100644 --- a/packages/kbn-apm-synthtrace/src/lib/logs/logs_synthtrace_es_client.ts +++ b/packages/kbn-apm-synthtrace/src/lib/logs/logs_synthtrace_es_client.ts @@ -7,14 +7,14 @@ */ import { Client } from '@elastic/elasticsearch'; -import { ESDocumentWithOperation } from '@kbn/apm-synthtrace-client'; -import { pipeline, Readable, Transform } from 'stream'; +import { pipeline, Readable } from 'stream'; import { LogDocument } from '@kbn/apm-synthtrace-client/src/lib/logs'; import { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/types'; import { SynthtraceEsClient, SynthtraceEsClientOptions } from '../shared/base_client'; import { getSerializeTransform } from '../shared/get_serialize_transform'; import { Logger } from '../utils/create_logger'; import { indexTemplates, IndexTemplateName } from './custom_logsdb_index_templates'; +import { getRoutingTransform } from '../shared/data_stream_get_routing_transform'; export type LogsSynthtraceEsClientOptions = Omit; @@ -66,7 +66,7 @@ function logsPipeline() { return pipeline( base, getSerializeTransform(), - getRoutingTransform(), + getRoutingTransform('logs'), (err: unknown) => { if (err) { throw err; @@ -75,22 +75,3 @@ function logsPipeline() { ); }; } - -function getRoutingTransform() { - return new Transform({ - objectMode: true, - transform(document: ESDocumentWithOperation, encoding, callback) { - if ( - 'data_stream.type' in document && - 'data_stream.dataset' in document && - 'data_stream.namespace' in document - ) { - document._index = `${document['data_stream.type']}-${document['data_stream.dataset']}-${document['data_stream.namespace']}`; - } else { - throw new Error('Cannot determine index for event'); - } - - callback(null, document); - }, - }); -} diff --git a/packages/kbn-apm-synthtrace/src/lib/shared/data_stream_get_routing_transform.ts b/packages/kbn-apm-synthtrace/src/lib/shared/data_stream_get_routing_transform.ts new file mode 100644 index 0000000000000..3e653e71b9862 --- /dev/null +++ b/packages/kbn-apm-synthtrace/src/lib/shared/data_stream_get_routing_transform.ts @@ -0,0 +1,25 @@ +/* + * 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 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { ESDocumentWithOperation, Fields } from '@kbn/apm-synthtrace-client'; +import { Transform } from 'stream'; + +export function getRoutingTransform(dataStreamType: string) { + return new Transform({ + objectMode: true, + transform(document: ESDocumentWithOperation, encoding, callback) { + if ('data_stream.dataset' in document && 'data_stream.namespace' in document) { + document._index = `${dataStreamType}-${document['data_stream.dataset']}-${document['data_stream.namespace']}`; + } else { + throw new Error('Cannot determine index for event'); + } + + callback(null, document); + }, + }); +} diff --git a/packages/kbn-apm-synthtrace/src/lib/synthetics/synthetics_synthtrace_es_client.ts b/packages/kbn-apm-synthtrace/src/lib/synthetics/synthetics_synthtrace_es_client.ts new file mode 100644 index 0000000000000..65fd66538a757 --- /dev/null +++ b/packages/kbn-apm-synthtrace/src/lib/synthetics/synthetics_synthtrace_es_client.ts @@ -0,0 +1,42 @@ +/* + * 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 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { Client } from '@elastic/elasticsearch'; +import { SyntheticsMonitorDocument } from '@kbn/apm-synthtrace-client'; +import { pipeline, Readable } from 'stream'; +import { SynthtraceEsClient, SynthtraceEsClientOptions } from '../shared/base_client'; +import { getSerializeTransform } from '../shared/get_serialize_transform'; +import { Logger } from '../utils/create_logger'; +import { getRoutingTransform } from '../shared/data_stream_get_routing_transform'; + +export type SyntheticsSynthtraceEsClientOptions = Omit; + +export class SyntheticsSynthtraceEsClient extends SynthtraceEsClient { + constructor(options: { client: Client; logger: Logger } & SyntheticsSynthtraceEsClientOptions) { + super({ + ...options, + pipeline: syntheticsPipeline(), + }); + this.dataStreams = ['synthetics-*-*']; + } +} + +function syntheticsPipeline() { + return (base: Readable) => { + return pipeline( + base, + getSerializeTransform(), + getRoutingTransform('synthetics'), + (err: unknown) => { + if (err) { + throw err; + } + } + ); + }; +} diff --git a/packages/kbn-apm-synthtrace/src/scenarios/degraded_synthetics_monitors.ts b/packages/kbn-apm-synthtrace/src/scenarios/degraded_synthetics_monitors.ts new file mode 100644 index 0000000000000..3be1ac53a6518 --- /dev/null +++ b/packages/kbn-apm-synthtrace/src/scenarios/degraded_synthetics_monitors.ts @@ -0,0 +1,159 @@ +/* + * 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 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ +import { + generateShortId, + SyntheticsMonitorDocument, + syntheticsMonitor, +} from '@kbn/apm-synthtrace-client'; +import { Scenario } from '../cli/scenario'; +import { withClient } from '../lib/utils/with_client'; +import { getIpAddress } from './helpers/logs_mock_data'; +import { getAtIndexOrRandom } from './helpers/get_at_index_or_random'; + +const MORE_THAN_1024_CHARS = + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?'; + +const MONITOR_NAMES = Array(4) + .fill(null) + .map((_, idx) => `synth-monitor-${idx}`); + +const ORIGINS = Array(4) + .fill(null) + .map((_, idx) => `synth-origin-${idx}`); + +const STATUS = ['up', 'down', 'disabled']; + +const OS = ['linux', 'windows', 'mac']; + +const scenario: Scenario = async (runOptions) => { + return { + generate: ({ range, clients: { syntheticsEsClient } }) => { + const { logger } = runOptions; + + const constructSyntheticsMonitorCommonData = (isMalformed?: boolean) => { + const index = Math.floor(Math.random() * 4); + const monitorName = getAtIndexOrRandom(MONITOR_NAMES, index); + const origin = getAtIndexOrRandom(ORIGINS, index); + const ip = getIpAddress(index); + const status = getAtIndexOrRandom(STATUS, index); + const os = getAtIndexOrRandom(OS, index); + + const commonSyntheticsMonitorEntryFields: SyntheticsMonitorDocument = { + 'monitor.id': generateShortId(), + 'monitor.check_group': generateShortId(), + 'monitor.timespan.lt': '2024-08-30T11:03:33.594Z', + 'monitor.timespan.gte': '2024-08-30T11:02:33.594Z', + }; + + return { + index, + monitorName, + origin, + ip, + status, + os, + commonLongEntryFields: commonSyntheticsMonitorEntryFields, + }; + }; + + const datasetSynth1Monitors = (timestamp: number) => { + const { monitorName, origin, ip, status, commonLongEntryFields } = + constructSyntheticsMonitorCommonData(); + + return syntheticsMonitor + .create() + .dataset('http') + .name(monitorName) + .origin(origin) + .ip(ip) + .defaults(commonLongEntryFields) + .timestamp(timestamp) + .status(status); + }; + + const datasetSynth2Monitors = (i: number, timestamp: number) => { + const { monitorName, origin, commonLongEntryFields } = + constructSyntheticsMonitorCommonData(); + const isMalformed = i % 90 === 0; + return syntheticsMonitor + .create() + .dataset('browser') + .name(monitorName) + .origin(origin) + .defaults({ + ...commonLongEntryFields, + 'synthetics.type': isMalformed + ? MORE_THAN_1024_CHARS // "ignore_above": 1024 in mapping + : 'step/metrics', + }) + .timestamp(timestamp); + }; + + const datasetSynth3Monitors = (i: number, timestamp: number) => { + const { monitorName, origin, os, commonLongEntryFields } = + constructSyntheticsMonitorCommonData(); + const isMalformed = i % 60 === 0; + return syntheticsMonitor + .create() + .dataset('browser.screenshot') + .name(monitorName) + .origin(origin) + .defaults({ + ...commonLongEntryFields, + 'synthetics.type': 'step/screenshot_ref', + 'observer.os.name': isMalformed + ? MORE_THAN_1024_CHARS // "ignore_above": 1024 in mapping + : os, + }) + .timestamp(timestamp); + }; + + const datasetSynth4Monitors = (i: number, timestamp: number) => { + const { monitorName, origin, commonLongEntryFields } = + constructSyntheticsMonitorCommonData(); + const isMalformed = i % 30 === 0; + return syntheticsMonitor + .create() + .dataset('browser.network') + .name(monitorName) + .origin(origin) + .defaults({ + ...commonLongEntryFields, + 'synthetics.type': isMalformed + ? MORE_THAN_1024_CHARS // "ignore_above": 1024 in mapping + : 'journey/network_info', + 'observer.product': isMalformed + ? MORE_THAN_1024_CHARS // "ignore_above": 1024 in mapping + : `synth-product-${i}`, + }) + .timestamp(timestamp); + }; + + const monitors = range + .interval('1m') + .rate(1) + .generator((timestamp) => { + return Array(200) + .fill(0) + .flatMap((_, index) => [ + datasetSynth1Monitors(timestamp), + datasetSynth2Monitors(index, timestamp), + datasetSynth3Monitors(index, timestamp), + datasetSynth4Monitors(index, timestamp), + ]); + }); + + return withClient( + syntheticsEsClient, + logger.perf('generating_synthetics_monitors', () => monitors) + ); + }, + }; +}; + +export default scenario; diff --git a/packages/kbn-apm-synthtrace/src/scenarios/helpers/get_at_index_or_random.ts b/packages/kbn-apm-synthtrace/src/scenarios/helpers/get_at_index_or_random.ts new file mode 100644 index 0000000000000..2a8e1d60062e3 --- /dev/null +++ b/packages/kbn-apm-synthtrace/src/scenarios/helpers/get_at_index_or_random.ts @@ -0,0 +1,13 @@ +/* + * 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 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { randomInt } from 'crypto'; + +// Utility function to get a random element from an array +export const getAtIndexOrRandom = (values: T[], index?: number) => + values[index ?? randomInt(values.length)]; diff --git a/packages/kbn-apm-synthtrace/src/scenarios/helpers/logs_mock_data.ts b/packages/kbn-apm-synthtrace/src/scenarios/helpers/logs_mock_data.ts index 052ccce76499f..894f72b7d317d 100644 --- a/packages/kbn-apm-synthtrace/src/scenarios/helpers/logs_mock_data.ts +++ b/packages/kbn-apm-synthtrace/src/scenarios/helpers/logs_mock_data.ts @@ -10,16 +10,13 @@ import { generateShortId } from '@kbn/apm-synthtrace-client'; import { faker } from '@faker-js/faker'; import { randomInt } from 'crypto'; import moment from 'moment'; +import { getAtIndexOrRandom } from './get_at_index_or_random'; const { internet: { ipv4, userAgent, httpMethod, httpStatusCode }, word: { noun, verb }, } = faker; -// Utility function to get a random element from an array -const getAtIndexOrRandom = (values: T[], index?: number) => - values[index ?? randomInt(values.length)]; - // Arrays for data const LOG_LEVELS: string[] = ['FATAL', 'ERROR', 'WARN', 'INFO', 'DEBUG', 'TRACE']; diff --git a/x-pack/plugins/data_quality/server/plugin.ts b/x-pack/plugins/data_quality/server/plugin.ts index 088905b8975d4..1b7e9cface597 100644 --- a/x-pack/plugins/data_quality/server/plugin.ts +++ b/x-pack/plugins/data_quality/server/plugin.ts @@ -39,6 +39,13 @@ export class DataQualityPlugin implements Plugin { ['metrics-*-*']: ['read'], }, }, + { + ui: [], + requiredClusterPrivileges: [], + requiredIndexPrivileges: { + ['synthetics-*-*']: ['read'], + }, + }, ], }); } diff --git a/x-pack/plugins/observability_solution/dataset_quality/common/constants.ts b/x-pack/plugins/observability_solution/dataset_quality/common/constants.ts index 895381703742e..1b822c6c111d9 100644 --- a/x-pack/plugins/observability_solution/dataset_quality/common/constants.ts +++ b/x-pack/plugins/observability_solution/dataset_quality/common/constants.ts @@ -42,4 +42,4 @@ export const MAX_DEGRADED_FIELDS = 1000; export const MASKED_FIELD_PLACEHOLDER = ''; export const UNKOWN_FIELD_PLACEHOLDER = ''; -export const KNOWN_TYPES: DataStreamType[] = ['logs', 'metrics', 'traces']; +export const KNOWN_TYPES: DataStreamType[] = ['logs', 'metrics', 'traces', 'synthetics']; diff --git a/x-pack/plugins/observability_solution/dataset_quality/server/test_helpers/create_dataset_quality_users/authentication.ts b/x-pack/plugins/observability_solution/dataset_quality/server/test_helpers/create_dataset_quality_users/authentication.ts index b5b177c644f59..bca3556b63771 100644 --- a/x-pack/plugins/observability_solution/dataset_quality/server/test_helpers/create_dataset_quality_users/authentication.ts +++ b/x-pack/plugins/observability_solution/dataset_quality/server/test_helpers/create_dataset_quality_users/authentication.ts @@ -10,20 +10,20 @@ export enum DatasetQualityUsername { viewerUser = 'viewer', readUser = 'readUser', editorUser = 'editor', - datasetQualityLogsUser = 'dataset_quality_logs_user', + datasetQualityMonitorUser = 'dataset_quality_monitor_user', } export enum DatasetQualityCustomRolename { - datasetQualityLogsUser = 'dataset_quality_logs_user', + datasetQualityMonitorUser = 'dataset_quality_monitor_user', datasetQualityReadUser = 'dataset_quality_read_user', } export const customRoles = { - [DatasetQualityCustomRolename.datasetQualityLogsUser]: { + [DatasetQualityCustomRolename.datasetQualityMonitorUser]: { elasticsearch: { indices: [ { - names: ['logs-*-*'], + names: ['logs-*-*', 'metrics-*-*', 'traces-*-*', 'synthetics-*-*'], privileges: ['monitor', 'view_index_metadata'], }, ], @@ -55,9 +55,9 @@ export const users: Record< [DatasetQualityUsername.editorUser]: { builtInRoleNames: ['editor'], }, - [DatasetQualityUsername.datasetQualityLogsUser]: { + [DatasetQualityUsername.datasetQualityMonitorUser]: { builtInRoleNames: ['editor'], - customRoleNames: [DatasetQualityCustomRolename.datasetQualityLogsUser], + customRoleNames: [DatasetQualityCustomRolename.datasetQualityMonitorUser], }, [DatasetQualityUsername.readUser]: { customRoleNames: [DatasetQualityCustomRolename.datasetQualityReadUser], diff --git a/x-pack/test/dataset_quality_api_integration/common/config.ts b/x-pack/test/dataset_quality_api_integration/common/config.ts index 3807addecbc71..f8e3fdc92016a 100644 --- a/x-pack/test/dataset_quality_api_integration/common/config.ts +++ b/x-pack/test/dataset_quality_api_integration/common/config.ts @@ -5,7 +5,12 @@ * 2.0. */ -import { LogLevel, LogsSynthtraceEsClient, createLogger } from '@kbn/apm-synthtrace'; +import { + LogLevel, + LogsSynthtraceEsClient, + SyntheticsSynthtraceEsClient, + createLogger, +} from '@kbn/apm-synthtrace'; import { createDatasetQualityUsers } from '@kbn/dataset-quality-plugin/server/test_helpers/create_dataset_quality_users'; import { DATASET_QUALITY_TEST_PASSWORD, @@ -55,7 +60,7 @@ export type DatasetQualityApiClientKey = | 'readUser' | 'adminUser' | 'writeUser' - | 'datasetQualityLogsUser'; + | 'datasetQualityMonitorUser'; export type DatasetQualityApiClient = Record< DatasetQualityApiClientKey, @@ -72,6 +77,9 @@ export interface CreateTest { logSynthtraceEsClient: ( context: InheritedFtrProviderContext ) => Promise; + syntheticsSynthtraceEsClient: ( + context: InheritedFtrProviderContext + ) => SyntheticsSynthtraceEsClient; datasetQualityApiClient: (context: InheritedFtrProviderContext) => DatasetQualityApiClient; packageService: ({ getService }: FtrProviderContext) => ReturnType; }; @@ -133,6 +141,12 @@ export function createTestConfig( logger: createLogger(LogLevel.info), refreshAfterIndex: true, }), + syntheticsSynthtraceEsClient: (context: InheritedFtrProviderContext) => + new SyntheticsSynthtraceEsClient({ + client: context.getService('es'), + logger: createLogger(LogLevel.info), + refreshAfterIndex: true, + }), datasetQualityApiClient: async (_: InheritedFtrProviderContext) => { const { username, password } = servers.kibana; const esUrl = format(esServer); @@ -164,9 +178,9 @@ export function createTestConfig( kibanaServer, username: DatasetQualityUsername.editorUser, }), - datasetQualityLogsUser: await getDatasetQualityApiClient({ + datasetQualityMonitorUser: await getDatasetQualityApiClient({ kibanaServer, - username: DatasetQualityUsername.datasetQualityLogsUser, + username: DatasetQualityUsername.datasetQualityMonitorUser, }), }; }, diff --git a/x-pack/test/dataset_quality_api_integration/tests/data_streams/data_stream_details.spec.ts b/x-pack/test/dataset_quality_api_integration/tests/data_streams/data_stream_details.spec.ts index dd34769fe717e..44e1dc08689b2 100644 --- a/x-pack/test/dataset_quality_api_integration/tests/data_streams/data_stream_details.spec.ts +++ b/x-pack/test/dataset_quality_api_integration/tests/data_streams/data_stream_details.spec.ts @@ -73,7 +73,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { it('returns error when dataStream param is not provided', async () => { const expectedMessage = 'Data Stream name cannot be empty'; const err = await expectToReject(() => - callApiAs('datasetQualityLogsUser', encodeURIComponent(' ')) + callApiAs('datasetQualityMonitorUser', encodeURIComponent(' ')) ); expect(err.res.status).to.be(400); expect(err.res.body.message.indexOf(expectedMessage)).to.greaterThan(-1); @@ -82,18 +82,24 @@ export default function ApiTest({ getService }: FtrProviderContext) { it('returns {} if matching data stream is not available', async () => { const nonExistentDataSet = 'Non-existent'; const nonExistentDataStream = `${type}-${nonExistentDataSet}-${namespace}`; - const resp = await callApiAs('datasetQualityLogsUser', nonExistentDataStream); + const resp = await callApiAs('datasetQualityMonitorUser', nonExistentDataStream); expect(resp.body).empty(); }); it('returns "sizeBytes" correctly', async () => { - const resp = await callApiAs('datasetQualityLogsUser', `${type}-${dataset}-${namespace}`); + const resp = await callApiAs( + 'datasetQualityMonitorUser', + `${type}-${dataset}-${namespace}` + ); expect(isNaN(resp.body.sizeBytes as number)).to.be(false); expect(resp.body.sizeBytes).to.be.greaterThan(0); }); it('returns service.name and host.name correctly', async () => { - const resp = await callApiAs('datasetQualityLogsUser', `${type}-${dataset}-${namespace}`); + const resp = await callApiAs( + 'datasetQualityMonitorUser', + `${type}-${dataset}-${namespace}` + ); expect(resp.body.services).to.eql({ ['service.name']: [serviceName] }); expect(resp.body.hosts?.['host.name']).to.eql([hostName]); }); diff --git a/x-pack/test/dataset_quality_api_integration/tests/data_streams/data_stream_settings.spec.ts b/x-pack/test/dataset_quality_api_integration/tests/data_streams/data_stream_settings.spec.ts index 3ba9965d980a4..eafc966dc4bda 100644 --- a/x-pack/test/dataset_quality_api_integration/tests/data_streams/data_stream_settings.spec.ts +++ b/x-pack/test/dataset_quality_api_integration/tests/data_streams/data_stream_settings.spec.ts @@ -97,7 +97,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { it('returns error when dataStream param is not provided', async () => { const expectedMessage = 'Data Stream name cannot be empty'; const err = await expectToReject(() => - callApiAs('datasetQualityLogsUser', encodeURIComponent(' ')) + callApiAs('datasetQualityMonitorUser', encodeURIComponent(' ')) ); expect(err.res.status).to.be(400); expect(err.res.body.message.indexOf(expectedMessage)).to.greaterThan(-1); @@ -106,7 +106,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { it('returns only privileges if matching data stream is not available', async () => { const nonExistentDataSet = 'Non-existent'; const nonExistentDataStream = `${type}-${nonExistentDataSet}-${namespace}`; - const resp = await callApiAs('datasetQualityLogsUser', nonExistentDataStream); + const resp = await callApiAs('datasetQualityMonitorUser', nonExistentDataStream); expect(resp.body).eql(defaultDataStreamPrivileges); }); @@ -115,7 +115,10 @@ export default function ApiTest({ getService }: FtrProviderContext) { esClient, `${type}-${dataset}-${namespace}` ); - const resp = await callApiAs('datasetQualityLogsUser', `${type}-${dataset}-${namespace}`); + const resp = await callApiAs( + 'datasetQualityMonitorUser', + `${type}-${dataset}-${namespace}` + ); expect(resp.body.createdOn).to.be(Number(dataStreamSettings?.index?.creation_date)); }); @@ -125,7 +128,10 @@ export default function ApiTest({ getService }: FtrProviderContext) { esClient, `${type}-${dataset}-${namespace}` ); - const resp = await callApiAs('datasetQualityLogsUser', `${type}-${dataset}-${namespace}`); + const resp = await callApiAs( + 'datasetQualityMonitorUser', + `${type}-${dataset}-${namespace}` + ); expect(resp.body.createdOn).to.be(Number(dataStreamSettings?.index?.creation_date)); }); @@ -135,7 +141,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { `${type}-${integrationDataset}-${namespace}` ); const resp = await callApiAs( - 'datasetQualityLogsUser', + 'datasetQualityMonitorUser', `${type}-${integrationDataset}-${namespace}` ); expect(resp.body.createdOn).to.be(Number(dataStreamSettings?.index?.creation_date)); diff --git a/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_docs.spec.ts b/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_docs.spec.ts index 149f07a98a2f3..92aa69610a66d 100644 --- a/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_docs.spec.ts +++ b/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_docs.spec.ts @@ -74,7 +74,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { }); it('returns stats correctly', async () => { - const stats = await callApiAs('datasetQualityLogsUser'); + const stats = await callApiAs('datasetQualityMonitorUser'); expect(stats.body.degradedDocs.length).to.be(2); const degradedDocsStats = stats.body.degradedDocs.reduce( @@ -105,7 +105,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { describe('and there are not log documents', () => { it('returns stats correctly', async () => { - const stats = await callApiAs('datasetQualityLogsUser'); + const stats = await callApiAs('datasetQualityMonitorUser'); expect(stats.body.degradedDocs.length).to.be(0); }); @@ -154,7 +154,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { }); it('returns counts and list of datasets correctly', async () => { - const stats = await callApiAs('datasetQualityLogsUser'); + const stats = await callApiAs('datasetQualityMonitorUser'); expect(stats.body.degradedDocs.length).to.be(18); const expected = { diff --git a/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_field_values.spec.ts b/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_field_values.spec.ts index a9f676cde946a..6eae916116e5c 100644 --- a/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_field_values.spec.ts +++ b/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_field_values.spec.ts @@ -79,7 +79,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { it('returns no values when provided field has no degraded values', async () => { const resp = await callApiAs({ - user: 'datasetQualityLogsUser', + user: 'datasetQualityMonitorUser', dataStream: degradedFieldsDatastream, degradedField: regularFieldName, }); @@ -88,7 +88,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { it('returns values when provided field has degraded values', async () => { const resp = await callApiAs({ - user: 'datasetQualityLogsUser', + user: 'datasetQualityMonitorUser', dataStream: degradedFieldsDatastream, degradedField: degradedFieldName, }); diff --git a/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_fields.spec.ts b/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_fields.spec.ts index 1f00722f57e15..fe6022067776f 100644 --- a/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_fields.spec.ts +++ b/x-pack/test/dataset_quality_api_integration/tests/data_streams/degraded_fields.spec.ts @@ -87,14 +87,17 @@ export default function ApiTest({ getService }: FtrProviderContext) { }); it('returns no results when dataStream does not have any degraded fields', async () => { - const resp = await callApiAs('datasetQualityLogsUser', `${type}-${dataset}-${namespace}`); + const resp = await callApiAs( + 'datasetQualityMonitorUser', + `${type}-${dataset}-${namespace}` + ); expect(resp.body.degradedFields.length).to.be(0); }); it('returns results when dataStream do have degraded fields', async () => { const expectedDegradedFields = ['log.level', 'trace.id']; const resp = await callApiAs( - 'datasetQualityLogsUser', + 'datasetQualityMonitorUser', `${type}-${degradedFieldDataset}-${namespace}` ); const degradedFields = resp.body.degradedFields.map((field: DegradedField) => field.name); @@ -117,7 +120,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { ]; const resp = await callApiAs( - 'datasetQualityLogsUser', + 'datasetQualityMonitorUser', `${type}-${degradedFieldDataset}-${namespace}` ); diff --git a/x-pack/test/dataset_quality_api_integration/tests/data_streams/stats.spec.ts b/x-pack/test/dataset_quality_api_integration/tests/data_streams/stats.spec.ts index 25a7f419f2746..c7d44c26b230b 100644 --- a/x-pack/test/dataset_quality_api_integration/tests/data_streams/stats.spec.ts +++ b/x-pack/test/dataset_quality_api_integration/tests/data_streams/stats.spec.ts @@ -5,24 +5,29 @@ * 2.0. */ -import { log, timerange } from '@kbn/apm-synthtrace-client'; +import { log, syntheticsMonitor, timerange } from '@kbn/apm-synthtrace-client'; import expect from '@kbn/expect'; +import rison from '@kbn/rison'; import { DatasetQualityApiClientKey } from '../../common/config'; import { FtrProviderContext } from '../../common/ftr_provider_context'; import { cleanLogIndexTemplate, addIntegrationToLogIndexTemplate } from './es_utils'; export default function ApiTest({ getService }: FtrProviderContext) { const registry = getService('registry'); - const synthtrace = getService('logSynthtraceEsClient'); + const logsSynthtrace = getService('logSynthtraceEsClient'); + const syntheticsSynthrace = getService('syntheticsSynthtraceEsClient'); const datasetQualityApiClient = getService('datasetQualityApiClient'); const es = getService('es'); - async function callApiAs(user: DatasetQualityApiClientKey) { + async function callApiAs( + user: DatasetQualityApiClientKey, + types: Array<'logs' | 'metrics' | 'traces' | 'synthetics'> = ['logs'] + ) { return await datasetQualityApiClient[user]({ endpoint: 'GET /internal/dataset_quality/data_streams/stats', params: { query: { - types: ['logs'], + types: rison.encodeArray(types), }, }, }); @@ -35,7 +40,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { rate = 1, dataset = 'synth.1', }: { from?: string; to?: string; interval?: string; rate?: number; dataset?: string } = {}) { - await synthtrace.index([ + await logsSynthtrace.index([ timerange(from, to) .interval(interval) .rate(rate) @@ -84,18 +89,18 @@ export default function ApiTest({ getService }: FtrProviderContext) { it('returns non empty stats for an authorized user', async () => { await ingestDocuments(); - const stats = await callApiAs('datasetQualityLogsUser'); + const stats = await callApiAs('datasetQualityMonitorUser'); expect(stats.body.dataStreamsStats[0].size).not.empty(); expect(stats.body.dataStreamsStats[0].sizeBytes).greaterThan(0); expect(stats.body.dataStreamsStats[0].lastActivity).greaterThan(0); }); - it('get list of privileged data streams for datasetQualityLogsUser', async () => { + it('get list of privileged data streams for datasetQualityMonitorUser', async () => { // Index only one document to logs-test-1-default and logs-test-1-default data stream using synthtrace await ingestDocuments({ dataset: 'test.1' }); await ingestDocuments({ dataset: 'test.2' }); - const resp = await callApiAs('datasetQualityLogsUser'); + const resp = await callApiAs('datasetQualityMonitorUser'); expect(resp.body.datasetUserPrivileges.canMonitor).to.be(true); expect( @@ -112,7 +117,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { }); after(async () => { - await synthtrace.clean(); + await logsSynthtrace.clean(); await cleanLogIndexTemplate({ esClient: es }); }); }); @@ -124,7 +129,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { before(async () => { await addIntegrationToLogIndexTemplate({ esClient: es, name: integration }); - await synthtrace.index([ + await logsSynthtrace.index([ timerange('2023-11-20T15:00:00.000Z', '2023-11-20T15:01:00.000Z') .interval('1m') .rate(1) @@ -137,7 +142,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { }); it('returns stats correctly', async () => { - const stats = await callApiAs('datasetQualityLogsUser'); + const stats = await callApiAs('datasetQualityMonitorUser'); expect(stats.body.dataStreamsStats.length).to.be(1); expect(stats.body.dataStreamsStats[0].integration).to.be(integration); @@ -148,14 +153,14 @@ export default function ApiTest({ getService }: FtrProviderContext) { }); after(async () => { - await synthtrace.clean(); + await logsSynthtrace.clean(); await cleanLogIndexTemplate({ esClient: es }); }); }); describe('and uncategorized datastreams', () => { before(async () => { - await synthtrace.index([ + await logsSynthtrace.index([ timerange('2023-11-20T15:00:00.000Z', '2023-11-20T15:01:00.000Z') .interval('1m') .rate(1) @@ -168,7 +173,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { }); it('returns stats correctly', async () => { - const stats = await callApiAs('datasetQualityLogsUser'); + const stats = await callApiAs('datasetQualityMonitorUser'); expect(stats.body.dataStreamsStats.length).to.be(1); expect(stats.body.dataStreamsStats[0].integration).not.ok(); @@ -179,7 +184,53 @@ export default function ApiTest({ getService }: FtrProviderContext) { }); after(async () => { - await synthtrace.clean(); + await logsSynthtrace.clean(); + }); + }); + + describe('and multiple dataStream types are requested', () => { + before(async () => { + await logsSynthtrace.index([ + timerange('2023-11-20T15:00:00.000Z', '2023-11-20T15:01:00.000Z') + .interval('1m') + .rate(1) + .generator((timestamp) => [ + log.create().message('This is a log message').timestamp(timestamp).defaults({ + 'log.file.path': '/my-service.log', + }), + ]), + ]); + await syntheticsSynthrace.index([ + timerange('2023-11-20T15:00:00.000Z', '2023-11-20T15:01:00.000Z') + .interval('1m') + .rate(1) + .generator((timestamp) => [ + syntheticsMonitor.create().dataset('http').timestamp(timestamp), + ]), + ]); + }); + + it('returns stats correctly', async () => { + const stats = await callApiAs('datasetQualityMonitorUser', ['logs', 'synthetics']); + + expect(stats.body.dataStreamsStats.length).to.be(2); + expect(stats.body.dataStreamsStats[0].size).not.empty(); + expect(stats.body.dataStreamsStats[0].sizeBytes).greaterThan(0); + expect(stats.body.dataStreamsStats[0].lastActivity).greaterThan(0); + expect(stats.body.dataStreamsStats[0].totalDocs).greaterThan(0); + expect(stats.body.dataStreamsStats[0].name).match(new RegExp(/^logs-[\w.]+-[\w.]+/)); + expect(stats.body.dataStreamsStats[1].size).not.empty(); + expect(stats.body.dataStreamsStats[1].sizeBytes).greaterThan(0); + expect(stats.body.dataStreamsStats[1].lastActivity).greaterThan(0); + expect(stats.body.dataStreamsStats[1].totalDocs).greaterThan(0); + expect(stats.body.dataStreamsStats[1].name).match( + new RegExp(/^synthetics-[\w.]+-[\w.]+/) + ); + }); + + after(async () => { + await logsSynthtrace.clean(); + await syntheticsSynthrace.clean(); }); }); }); diff --git a/x-pack/test/dataset_quality_api_integration/tests/integrations/integration_dashboards.spec.ts b/x-pack/test/dataset_quality_api_integration/tests/integrations/integration_dashboards.spec.ts index 63b1b029acdeb..70567202c4341 100644 --- a/x-pack/test/dataset_quality_api_integration/tests/integrations/integration_dashboards.spec.ts +++ b/x-pack/test/dataset_quality_api_integration/tests/integrations/integration_dashboards.spec.ts @@ -18,7 +18,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { const integrationPackages = ['nginx', 'apm']; async function callApiAs(integration: string) { - const user = 'datasetQualityLogsUser' as DatasetQualityApiClientKey; + const user = 'datasetQualityMonitorUser' as DatasetQualityApiClientKey; return await datasetQualityApiClient[user]({ endpoint: 'GET /internal/dataset_quality/integrations/{integration}/dashboards', params: { diff --git a/x-pack/test/dataset_quality_api_integration/tests/integrations/integrations.spec.ts b/x-pack/test/dataset_quality_api_integration/tests/integrations/integrations.spec.ts index 2176dbd1fa95d..909e15ee60461 100644 --- a/x-pack/test/dataset_quality_api_integration/tests/integrations/integrations.spec.ts +++ b/x-pack/test/dataset_quality_api_integration/tests/integrations/integrations.spec.ts @@ -35,7 +35,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { ]; async function callApiAs() { - const user = 'datasetQualityLogsUser' as DatasetQualityApiClientKey; + const user = 'datasetQualityMonitorUser' as DatasetQualityApiClientKey; return await datasetQualityApiClient[user]({ endpoint: 'GET /internal/dataset_quality/integrations', From e88499a27c7ae1ec668d6b4fe0e11ce9a487d0be Mon Sep 17 00:00:00 2001 From: Shahzad Date: Wed, 4 Sep 2024 15:37:51 +0200 Subject: [PATCH 13/48] [Uptime] Remove unnecessary queries !! (#191722) ## Summary We added these clauses 4 years ago in a follow up to https://github.com/elastic/beats/pull/14778 !! Since monitor.timespan is now always present in docs , we don't need these queries !! I found these sometimes to be very slow while investigating slow performance of queries in a trace !! ### Autorefresh interval !! Also updated auto refresh interval to 5 minutes, based on multiple customers feedback, default 1 minute is too aggressive !! --- .../common/constants/client_defaults.ts | 4 +- .../use_url_params.test.tsx.snap | 4 +- .../get_supported_url_params.test.ts.snap | 8 +- .../lib/requests/search/query_context.test.ts | 95 ------------------- .../lib/requests/search/query_context.ts | 34 ------- 5 files changed, 8 insertions(+), 137 deletions(-) delete mode 100644 x-pack/plugins/observability_solution/uptime/server/legacy_uptime/lib/requests/search/query_context.test.ts diff --git a/x-pack/plugins/observability_solution/uptime/common/constants/client_defaults.ts b/x-pack/plugins/observability_solution/uptime/common/constants/client_defaults.ts index 41a5f7c64abed..f627180991025 100644 --- a/x-pack/plugins/observability_solution/uptime/common/constants/client_defaults.ts +++ b/x-pack/plugins/observability_solution/uptime/common/constants/client_defaults.ts @@ -12,9 +12,9 @@ export const CLIENT_DEFAULTS = { // 15 minutes ABSOLUTE_DATE_RANGE_END: 1000 * 60 * 15, /** - * The application auto refreshes every 60s by default. + * The application auto refreshes every 5mins by default. */ - AUTOREFRESH_INTERVAL: 60 * 1000, + AUTOREFRESH_INTERVAL: 5 * 60 * 1000, /** * The application's autorefresh feature is enabled. */ diff --git a/x-pack/plugins/observability_solution/uptime/public/legacy_uptime/hooks/__snapshots__/use_url_params.test.tsx.snap b/x-pack/plugins/observability_solution/uptime/public/legacy_uptime/hooks/__snapshots__/use_url_params.test.tsx.snap index 8cc0e164a7e48..9ac11e14be2a7 100644 --- a/x-pack/plugins/observability_solution/uptime/public/legacy_uptime/hooks/__snapshots__/use_url_params.test.tsx.snap +++ b/x-pack/plugins/observability_solution/uptime/public/legacy_uptime/hooks/__snapshots__/use_url_params.test.tsx.snap @@ -81,7 +81,7 @@ exports[`useUrlParams deletes keys that do not have truthy values 1`] = ` } >
- {"pagination":"foo","absoluteDateRangeStart":20,"absoluteDateRangeEnd":20,"autorefreshInterval":60000,"autorefreshIsPaused":false,"dateRangeStart":"now-12","dateRangeEnd":"now","filters":"","excludedFilters":"","search":"","statusFilter":"","focusConnectorField":false,"query":""} + {"pagination":"foo","absoluteDateRangeStart":20,"absoluteDateRangeEnd":20,"autorefreshInterval":300000,"autorefreshIsPaused":false,"dateRangeStart":"now-12","dateRangeEnd":"now","filters":"","excludedFilters":"","search":"","statusFilter":"","focusConnectorField":false,"query":""}