From 0559699fd4ee61583c41a381d084879e346f7ced Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Thu, 29 Aug 2024 15:49:24 +0100 Subject: [PATCH 1/2] [ML] Renaming ML API service --- .../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 | 4 +-- .../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 | 4 +-- .../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 | 17 +++++------ .../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 | 6 ++-- .../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, 820 insertions(+), 869 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 d9d98029c3eee..0b86c381fd16d 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 5b7d4b3be128c..a1667328fb1c2 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..e9e8520c38dfb 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,7 +27,7 @@ type ExportableConfigs = | DataFrameAnalyticsConfig[]; export class JobsExportService { - constructor(private _mlApiServices: MlApiServices) {} + constructor(private _mlApiServices: MlApi) {} public async exportAnomalyDetectionJobs(jobIds: string[]) { const configs = await Promise.all( 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..94049cbbf761a 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 _mlApiServices: MlApi) { this._runtimeMappings = this._indexPattern.getComputedFields().runtimeFields as RuntimeMappings; this._indexPatternTitle = _indexPattern.title; } 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 6ab1aae6be895..aa8f906e44726 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..6717a3040c093 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 _mlApiServices: 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._mlApiServices = 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') { 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..408c4c05247bd 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 _mlApiServices: 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._mlApiServices = jobCreator.mlApi; this._mlJobService = jobCreator.mlJobService; this._jobId = jobCreator.jobId; this._datafeedId = jobCreator.datafeedId; 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 3b1e06f62538a..b4b2a5ac1dd30 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 f79a078a1546c3e1fd645b6aff996c8e4486c5a0 Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Thu, 29 Aug 2024 16:19:04 +0100 Subject: [PATCH 2/2] missed _mlApiServices --- .../export_jobs_flyout/jobs_export_service.ts | 10 ++++------ .../index_based/data_loader/data_loader.ts | 4 ++-- .../jobs/new_job/common/chart_loader/chart_loader.ts | 6 +++--- .../jobs/new_job/common/job_runner/job_runner.ts | 8 ++++---- 4 files changed, 13 insertions(+), 15 deletions(-) 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 e9e8520c38dfb..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 @@ -27,18 +27,16 @@ type ExportableConfigs = | DataFrameAnalyticsConfig[]; export class JobsExportService { - constructor(private _mlApiServices: MlApi) {} + 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/datavisualizer/index_based/data_loader/data_loader.ts b/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts index 94049cbbf761a..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 @@ -24,7 +24,7 @@ export class DataLoader { private _indexPatternTitle: IndexPatternTitle = ''; private _maxExamples: number = MAX_EXAMPLES_DEFAULT; - constructor(private _indexPattern: DataView, private _mlApiServices: MlApi) { + 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/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 6717a3040c093..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 @@ -28,7 +28,7 @@ const eq = (newArgs: any[], lastArgs: any[]) => isEqual(newArgs, lastArgs); export class ChartLoader { protected _dataView: DataView; - protected _mlApiServices: MlApi; + protected _mlApi: MlApi; private _timeFieldName: string = ''; private _query: object = {}; @@ -39,7 +39,7 @@ export class ChartLoader { private _getCategoryFields; constructor(mlApi: MlApi, indexPattern: DataView, query: object) { - this._mlApiServices = mlApi; + this._mlApi = mlApi; this._dataView = indexPattern; this._query = query; @@ -163,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/job_runner/job_runner.ts b/x-pack/plugins/ml/public/application/jobs/new_job/common/job_runner/job_runner.ts index 408c4c05247bd..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 @@ -22,7 +22,7 @@ export type ProgressSubscriber = (progress: number) => void; export type JobAssignmentSubscriber = (assigned: boolean) => void; export class JobRunner { - private _mlApiServices: MlApi; + 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.mlApi; + 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) {