Skip to content

Commit

Permalink
use locator for create job redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
darnautov committed Dec 28, 2023
1 parent 527062d commit 80da1c4
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import { i18n } from '@kbn/i18n';
import { RuleTypeParamsExpressionProps } from '@kbn/triggers-actions-ui-plugin/public';
import { isDefined } from '@kbn/ml-is-defined';
import { ML_ANOMALY_RESULT_TYPE, ML_ANOMALY_THRESHOLD } from '@kbn/ml-anomaly-utils';
import { ML_PAGES } from '../../../common/constants/locator';
import type { MlCoreSetup } from '../../plugin';
import { JobSelectorControl } from '../job_selector';
import { useMlKibana } from '../../application/contexts/kibana';
import { jobsApiProvider } from '../../application/services/ml_api_service/jobs';
Expand All @@ -33,7 +35,9 @@ import { getLookbackInterval, getTopNBuckets } from '../../../common/util/alerts
import { parseInterval } from '../../../common/util/parse_interval';

export type MlAnomalyAlertTriggerProps =
RuleTypeParamsExpressionProps<MlAnomalyDetectionAlertParams>;
RuleTypeParamsExpressionProps<MlAnomalyDetectionAlertParams> & {
getStartServices: MlCoreSetup['getStartServices'];
};

const MlAnomalyAlertTrigger: FC<MlAnomalyAlertTriggerProps> = ({
ruleParams,
Expand All @@ -42,10 +46,32 @@ const MlAnomalyAlertTrigger: FC<MlAnomalyAlertTriggerProps> = ({
errors,
ruleInterval,
alertNotifyWhen,
getStartServices,
}) => {
const {
services: { http },
} = useMlKibana();

const [newJobUrl, setNewJobUrl] = useState<string | undefined>(undefined);

useEffect(() => {
let mounted = true;

getStartServices().then((startServices) => {
const locator = startServices[2].locator;
if (!locator) return;
locator.getUrl({ page: ML_PAGES.ANOMALY_DETECTION_CREATE_JOB }).then((url) => {
if (mounted) {
setNewJobUrl(url);
}
});
});

return () => {
mounted = false;
};
}, [getStartServices]);

const mlHttpService = useMemo(() => new HttpService(http), [http]);
const adJobsApiService = useMemo(() => jobsApiProvider(mlHttpService), [mlHttpService]);
const alertingApiService = useMemo(() => alertingApiProvider(mlHttpService), [mlHttpService]);
Expand Down Expand Up @@ -159,7 +185,7 @@ const MlAnomalyAlertTrigger: FC<MlAnomalyAlertTriggerProps> = ({
return (
<EuiForm data-test-subj={'mlAnomalyAlertForm'}>
<JobSelectorControl
allowCreateNew
createJobUrl={newJobUrl}
jobsAndGroupIds={jobsAndGroupIds}
adJobsApiService={adJobsApiService}
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,20 @@
* 2.0.
*/

import { TriggersAndActionsUIPublicPluginSetup } from '@kbn/triggers-actions-ui-plugin/public';
import { PluginSetupContract as AlertingSetup } from '@kbn/alerting-plugin/public';
import {
type RuleTypeParamsExpressionProps,
type TriggersAndActionsUIPublicPluginSetup,
} from '@kbn/triggers-actions-ui-plugin/public';
import { i18n } from '@kbn/i18n';
import { lazy } from 'react';
import React, { lazy } from 'react';
import type { MlCoreSetup } from '../../plugin';
import { ML_ALERT_TYPES } from '../../../common';
import type { MlAnomalyDetectionAlertParams } from '../../../common/types/alerts';
import { validateLookbackInterval, validateTopNBucket } from '../validators';

export function registerAnomalyDetectionRule(
triggersActionsUi: TriggersAndActionsUIPublicPluginSetup,
alerting?: AlertingSetup
getStartServices: MlCoreSetup['getStartServices']
) {
triggersActionsUi.ruleTypeRegistry.register({
id: ML_ALERT_TYPES.ANOMALY_DETECTION,
Expand All @@ -26,7 +29,10 @@ export function registerAnomalyDetectionRule(
documentationUrl(docLinks) {
return docLinks.links.ml.alertingRules;
},
ruleParamsExpression: lazy(() => import('./ml_anomaly_alert_trigger')),
ruleParamsExpression: (props: RuleTypeParamsExpressionProps<MlAnomalyDetectionAlertParams>) => {
const MlAlertTrigger = lazy(() => import('./ml_anomaly_alert_trigger'));
return <MlAlertTrigger {...props} getStartServices={getStartServices} />;
},
validate: (ruleParams: MlAnomalyDetectionAlertParams) => {
const validationResult = {
errors: {
Expand Down
34 changes: 25 additions & 9 deletions x-pack/plugins/ml/public/alerting/job_selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import React, { FC, ReactNode, useCallback, useEffect, useMemo, useState } from
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n-react';
import { EuiComboBox, EuiComboBoxOptionOption, EuiComboBoxProps, EuiFormRow } from '@elastic/eui';
import useMountedState from 'react-use/lib/useMountedState';
import { useMlKibana } from '../application/contexts/kibana';
import { JobId } from '../../common/types/anomaly_detection_jobs';
import { MlApiServices } from '../application/services/ml_api_service';
import { ALL_JOBS_SELECTION } from '../../common/constants/alerts';
Expand All @@ -34,7 +36,7 @@ export interface JobSelectorControlProps {
*/
allowSelectAll?: boolean;
/** Adds an option to create a new anomaly detection job */
allowCreateNew?: boolean;
createJobUrl?: string;
/**
* Available options to select. By default suggest all existing jobs.
*/
Expand All @@ -49,9 +51,17 @@ export const JobSelectorControl: FC<JobSelectorControlProps> = ({
multiSelect = false,
label,
allowSelectAll = false,
allowCreateNew = false,
createJobUrl,
options: defaultOptions,
}) => {
const {
services: {
application: { navigateToUrl },
},
} = useMlKibana();

const isMounted = useMountedState();

const [options, setOptions] = useState<Array<EuiComboBoxOptionOption<string>>>([]);
const jobIds = useMemo(() => new Set(), []);
const groupIds = useMemo(() => new Set(), []);
Expand All @@ -77,6 +87,8 @@ export const JobSelectorControl: FC<JobSelectorControlProps> = ({
groupIds.add(v);
});

if (!isMounted()) return;

setOptions([
...(allowSelectAll
? [
Expand All @@ -101,7 +113,7 @@ export const JobSelectorControl: FC<JobSelectorControlProps> = ({
defaultMessage: 'Jobs',
}),
options: [
...(allowCreateNew
...(createJobUrl
? [
{
label: i18n.translate('xpack.ml.jobSelector.createNewLabel', {
Expand All @@ -128,19 +140,23 @@ export const JobSelectorControl: FC<JobSelectorControlProps> = ({
} catch (e) {
// TODO add error handling
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [adJobsApiService]);
}, [adJobsApiService, allowSelectAll, createJobUrl, groupIds, isMounted, jobIds, multiSelect]);

// eslint-disable-next-line react-hooks/exhaustive-deps
const onSelectionChange: EuiComboBoxProps<string>['onChange'] = useCallback(
((selectionUpdate) => {
(async (selectionUpdate) => {
if (selectionUpdate.some((selectedOption) => selectedOption.value === ALL_JOBS_SELECTION)) {
onChange({ jobIds: [ALL_JOBS_SELECTION] });
return;
}

if (selectionUpdate.some((selectedOption) => selectedOption.value === 'createNew')) {
if (
!!createJobUrl &&
selectionUpdate.some((selectedOption) => selectedOption.value === 'createNew')
) {
// Redirect to the job wizard page
await navigateToUrl(createJobUrl);
return;
}

const selectedJobIds: JobId[] = [];
Expand All @@ -159,14 +175,14 @@ export const JobSelectorControl: FC<JobSelectorControlProps> = ({
...(selectedGroupIds.length > 0 ? { groupIds: selectedGroupIds } : {}),
});
}) as Exclude<EuiComboBoxProps<string>['onChange'], undefined>,
[jobIds, groupIds, defaultOptions]
[jobIds, groupIds, defaultOptions, createJobUrl]
);

useEffect(() => {
if (defaultOptions) return;
fetchOptions();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}, [createJobUrl]);

return (
<EuiFormRow
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/ml/public/alerting/register_ml_alerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function registerMlAlerts(
getStartServices: MlCoreSetup['getStartServices'],
alerting?: AlertingSetup
) {
registerAnomalyDetectionRule(triggersActionsUi, alerting);
registerAnomalyDetectionRule(triggersActionsUi, getStartServices);

registerJobsHealthAlertingRule(triggersActionsUi, alerting);

Expand Down

0 comments on commit 80da1c4

Please sign in to comment.