Skip to content

Commit

Permalink
[ML] Renaming ML API service (elastic#191742)
Browse files Browse the repository at this point in the history
Addresses the comment from the description of this
[PR](elastic#189729):
`We have a bit of a mix of naming: ml, mlApiServices, useMlApiContext()
for the same thing`

Renames:
`useMlApiContext` -> `useMlApi`
`ml` -> `mlApi`
`mlApiServices` -> `mlApi`
`MlApiServices ` -> `MlApi`

E.g. we can now use 
`const mlApi = useMlApi();`

Rather than:
`const ml = useMlApiContext();`
or
`const mlServices = useMlApiContext();`
or
```
  const {
    services: {
      mlServices: { mlApiServices },
    },
  } = useMlKibana();
```
  • Loading branch information
jgowdyelastic authored Sep 4, 2024
1 parent e9eb03a commit 8c67fec
Show file tree
Hide file tree
Showing 229 changed files with 827 additions and 878 deletions.
4 changes: 2 additions & 2 deletions x-pack/plugins/ml/public/alerting/job_selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -54,7 +54,7 @@ export class MlCapabilitiesService {

private _subscription: Subscription | undefined;

constructor(private readonly mlApiServices: MlApiServices) {
constructor(private readonly mlApi: MlApi) {
this.init();
}

Expand All @@ -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) => {
Expand Down Expand Up @@ -197,11 +197,11 @@ export function checkGetManagementMlJobsResolver({ mlCapabilities }: MlGlobalSer
}

export function checkCreateJobsCapabilitiesResolver(
mlApiServices: MlApiServices,
mlApi: MlApi,
redirectToJobsManagementPage: () => Promise<void>
): Promise<MlCapabilities> {
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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<MlCapabilitiesResponse> {
return ml.checkMlCapabilities();
export function getCapabilities(mlApi: MlApi): Promise<MlCapabilitiesResponse> {
return mlApi.checkMlCapabilities();
}
Original file line number Diff line number Diff line change
Expand Up @@ -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({}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,10 +136,10 @@ export class AnnotationFlyoutUI extends Component<CommonProps & Props> {

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',
Expand Down Expand Up @@ -241,9 +241,9 @@ export class AnnotationFlyoutUI extends Component<CommonProps & Props> {
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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
}

Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -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]
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -73,7 +73,7 @@ export const CustomUrlList: FC<CustomUrlListProps> = ({
data: { dataViews },
},
} = useMlKibana();
const ml = useMlApiContext();
const mlApi = useMlApi();
const { displayErrorToast } = useToastNotificationService();
const [expandedUrlIndex, setExpandedUrlIndex] = useState<number | null>(null);

Expand Down Expand Up @@ -162,7 +162,7 @@ export const CustomUrlList: FC<CustomUrlListProps> = ({
if (index < customUrls.length) {
try {
const testUrl = await getTestUrl(
ml,
mlApi,
job,
customUrl,
timefieldName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<string> {
Expand Down Expand Up @@ -455,7 +455,7 @@ async function getAnomalyDetectionJobTestUrl(

let resp;
try {
resp = await ml.results.anomalySearch(
resp = await mlApi.results.anomalySearch(
{
body,
},
Expand All @@ -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];
Expand All @@ -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
Expand All @@ -520,7 +520,7 @@ async function getAnomalyDetectionJobTestUrl(
}

async function getDataFrameAnalyticsTestUrl(
ml: MlApiServices,
mlApi: MlApi,
job: DataFrameAnalyticsConfig,
customUrl: MlKibanaUrlConfig,
timeFieldName: string | null,
Expand All @@ -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,
Expand Down Expand Up @@ -594,7 +594,7 @@ async function getDataFrameAnalyticsTestUrl(
}

export function getTestUrl(
ml: MlApiServices,
mlApi: MlApi,
job: Job | DataFrameAnalyticsConfig,
customUrl: MlUrlConfig,
timeFieldName: string | null,
Expand All @@ -603,7 +603,7 @@ export function getTestUrl(
) {
if (isDataFrameAnalyticsConfigs(job) || isPartialDFAJob) {
return getDataFrameAnalyticsTestUrl(
ml,
mlApi,
job as DataFrameAnalyticsConfig,
customUrl,
timeFieldName,
Expand All @@ -612,5 +612,5 @@ export function getTestUrl(
);
}

return getAnomalyDetectionJobTestUrl(ml, job, customUrl);
return getAnomalyDetectionJobTestUrl(mlApi, job, customUrl);
}
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export class CustomUrls extends Component<CustomUrlsProps, CustomUrlsState> {
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;
Expand All @@ -194,7 +194,7 @@ export class CustomUrls extends Component<CustomUrlsProps, CustomUrlsState> {
buildCustomUrlFromSettings(dashboard, this.state.editorSettings as CustomUrlSettings).then(
(customUrl) => {
getTestUrl(
ml,
mlApi,
job,
customUrl,
timefieldName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -252,7 +252,7 @@ export const DeleteSpaceAwareItemCheckModal: FC<Props> = ({

const {
savedObjects: { canDeleteMLSpaceAwareItems, removeItemFromCurrentSpace },
} = useMlApiContext();
} = useMlApi();
const { displayErrorToast, displaySuccessToast } = useToastNotificationService();

// delay showing the modal to avoid flickering
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string[]>([]);
const [dfaJobIds, setDfaJobIds] = useState<string[]>([]);
const [selectedJobIds, setSelectedJobIds] = useState<string[]>([]);
Expand Down
Loading

0 comments on commit 8c67fec

Please sign in to comment.