Skip to content

Commit

Permalink
refactor locator
Browse files Browse the repository at this point in the history
  • Loading branch information
walterra committed Sep 24, 2024
1 parent 4f8243a commit fbf35d4
Show file tree
Hide file tree
Showing 18 changed files with 56 additions and 63 deletions.
28 changes: 26 additions & 2 deletions x-pack/packages/ml/locator/use_ml_href.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,46 @@
* 2.0.
*/

import { useMemo } from 'react';
import type { DependencyList } from 'react';

import type { LocatorPublic } from '@kbn/share-plugin/public';
import type { SharePluginStart } from '@kbn/share-plugin/public';
import { useKibana } from '@kbn/kibana-react-plugin/public';

import { MlLocatorDefinition } from './ml_locator';
import type { MlLocatorParams } from './types';

function useKibanaShareService() {
const {
services: { share },
} = useKibana<{
share: SharePluginStart;
}>();

if (!share) {
throw new Error('Kibana share service not available.');
}

return share;
}

/**
* Provides a URL to ML plugin page
* TODO remove basePath parameter
*/
export const useMlHref = (
mlLocator: LocatorPublic<MlLocatorParams> | undefined,
basePath: string | undefined,
params: MlLocatorParams,
dependencies?: DependencyList
) => {
const share = useKibanaShareService();

const mlLocator = useMemo(
() => share.url.locators.create(new MlLocatorDefinition()),
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);

return mlLocator
? mlLocator.useUrl(params, undefined, dependencies)
: basePath !== undefined
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { isDefined } from '@kbn/ml-is-defined';
import { ML_ANOMALY_RESULT_TYPE, ML_ANOMALY_THRESHOLD } from '@kbn/ml-anomaly-utils';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { parseInterval } from '@kbn/ml-parse-interval';
import { ML_PAGES } from '@kbn/ml-locator';
import { MlLocatorDefinition, ML_PAGES } from '@kbn/ml-locator';

import type { MlCapabilities } from '../../../common/types/capabilities';
import type { MlCoreSetup } from '../../plugin';
Expand Down Expand Up @@ -66,7 +66,8 @@ const MlAnomalyAlertTrigger: FC<MlAnomalyAlertTriggerProps> = ({
if (!mlCapabilities.canCreateJob) return;

getStartServices().then((startServices) => {
const locator = startServices[2].locator;
const share = startServices[1].share;
const locator = share.url.locators.create(new MlLocatorDefinition());
if (!locator) return;
locator.getUrl({ page: ML_PAGES.ANOMALY_DETECTION_CREATE_JOB }).then((url) => {
if (mounted) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,11 @@ export class AnomalyLayerWizardFactory {
}> {
const [coreStart, pluginStart] = await this.getStartServices();
const { jobsApiProvider } = await import('../application/services/ml_api_service/jobs');
const { MlLocatorDefinition } = await import('@kbn/ml-locator');

const httpService = new HttpService(coreStart.http);
const mlJobsService = jobsApiProvider(httpService);
pluginStart.share.url.locators.create(new MlLocatorDefinition());
const mlLocator = pluginStart.share.url.locators.get(ML_APP_LOCATOR);

return { mlJobsService, mlLocator };
Expand Down
3 changes: 0 additions & 3 deletions x-pack/plugins/ml/public/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
* 2.0.
*/

import { sharePluginMock } from '@kbn/share-plugin/public/mocks';
import { type ElasticModels } from './application/services/elastic_models_service';
import type { MlPluginSetup, MlPluginStart } from './plugin';
import type { AnomalySwimLane } from './shared_components';
Expand All @@ -28,14 +27,12 @@ const createElasticModelsMock = (): jest.Mocked<ElasticModels> => {

const createSetupContract = (): jest.Mocked<MlPluginSetup> => {
return {
locator: sharePluginMock.createLocator(),
elasticModels: createElasticModelsMock(),
};
};

const createStartContract = (): jest.Mocked<MlPluginStart> => {
return {
locator: sharePluginMock.createLocator(),
elasticModels: createElasticModelsMock(),
components: {
AnomalySwimLane: jest.fn() as unknown as jest.Mocked<typeof AnomalySwimLane>,
Expand Down
17 changes: 2 additions & 15 deletions x-pack/plugins/ml/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { take } from 'rxjs';
import type { ObservabilityAIAssistantPublicStart } from '@kbn/observability-ai-assistant-plugin/public';
import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/public';
import type { ManagementSetup } from '@kbn/management-plugin/public';
import type { LocatorPublic, SharePluginSetup, SharePluginStart } from '@kbn/share-plugin/public';
import type { SharePluginSetup, SharePluginStart } from '@kbn/share-plugin/public';
import type { DataPublicPluginStart } from '@kbn/data-plugin/public';
import type { HomePublicPluginSetup } from '@kbn/home-plugin/public';
import type { EmbeddableSetup, EmbeddableStart } from '@kbn/embeddable-plugin/public';
Expand Down Expand Up @@ -52,7 +52,6 @@ import type { PresentationUtilPluginStart } from '@kbn/presentation-util-plugin/
import type { DataViewEditorStart } from '@kbn/data-view-editor-plugin/public';
import type { FieldFormatsRegistry } from '@kbn/field-formats-plugin/common';
import { ENABLE_ESQL } from '@kbn/esql-utils';
import { MlLocatorDefinition, type MlLocator, type MlLocatorParams } from '@kbn/ml-locator';
import type { MlSharedServices } from './application/services/get_shared_ml_services';
import { getMlSharedServices } from './application/services/get_shared_ml_services';
import { registerManagementSection } from './application/management';
Expand Down Expand Up @@ -121,8 +120,6 @@ export type MlCoreSetup = CoreSetup<MlStartDependencies, MlPluginStart>;
export class MlPlugin implements Plugin<MlPluginSetup, MlPluginStart> {
private appUpdater$ = new BehaviorSubject<AppUpdater>(() => ({}));

private locator: undefined | MlLocator;

private sharedMlServices: MlSharedServices | undefined;

private isServerless: boolean = false;
Expand All @@ -141,10 +138,7 @@ export class MlPlugin implements Plugin<MlPluginSetup, MlPluginStart> {
initExperimentalFeatures(this.experimentalFeatures, initializerContext.config.get());
}

setup(
core: MlCoreSetup,
pluginsSetup: MlSetupDependencies
): { locator?: LocatorPublic<MlLocatorParams>; elasticModels?: ElasticModels } {
setup(core: MlCoreSetup, pluginsSetup: MlSetupDependencies): { elasticModels?: ElasticModels } {
this.sharedMlServices = getMlSharedServices(core.http);

core.application.register({
Expand Down Expand Up @@ -198,10 +192,6 @@ export class MlPlugin implements Plugin<MlPluginSetup, MlPluginStart> {
},
});

if (pluginsSetup.share) {
this.locator = pluginsSetup.share.url.locators.create(new MlLocatorDefinition());
}

if (pluginsSetup.management) {
registerManagementSection(
pluginsSetup.management,
Expand Down Expand Up @@ -300,7 +290,6 @@ export class MlPlugin implements Plugin<MlPluginSetup, MlPluginStart> {
.subscribe();

return {
locator: this.locator,
elasticModels: this.sharedMlServices.elasticModels,
};
}
Expand All @@ -309,13 +298,11 @@ export class MlPlugin implements Plugin<MlPluginSetup, MlPluginStart> {
core: CoreStart,
deps: MlStartDependencies
): {
locator?: LocatorPublic<MlLocatorParams>;
elasticModels?: ElasticModels;
mlApi?: MlApi;
components: { AnomalySwimLane: typeof AnomalySwimLane };
} {
return {
locator: this.locator,
elasticModels: this.sharedMlServices?.elasticModels,
mlApi: this.sharedMlServices?.mlApi,
components: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ export function MLExplorerLink({ jobId, external, children }: Props) {
}

export function useExplorerHref({ jobId }: { jobId: string }) {
const {
core,
plugins: { ml },
} = useApmPluginContext();
const { core } = useApmPluginContext();
const { urlParams } = useLegacyUrlParams();

const {
Expand All @@ -45,7 +42,7 @@ export function useExplorerHref({ jobId }: { jobId: string }) {
rangeTo = 'now',
} = urlParams;

const href = useMlHref(ml?.locator, core.http.basePath.get(), {
const href = useMlHref(core.http.basePath.get(), {
page: ML_PAGES.ANOMALY_EXPLORER,
pageState: {
jobIds: [jobId],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ function useSingleMetricHref({
serviceName?: string;
transactionType?: string;
}) {
const {
core,
plugins: { ml },
} = useApmPluginContext();
const { core } = useApmPluginContext();
const { urlParams } = useLegacyUrlParams();

const {
Expand All @@ -71,7 +68,7 @@ function useSingleMetricHref({
}
: {};

const href = useMlHref(ml?.locator, core.http.basePath.get(), {
const href = useMlHref(core.http.basePath.get(), {
page: ML_PAGES.SINGLE_METRIC_VIEWER,
pageState: {
jobIds: [jobId],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ import { useApmPluginContext } from '../context/apm_plugin/use_apm_plugin_contex
import { useLegacyUrlParams } from '../context/url_params_context/use_url_params';

export function useMlManageJobsHref({ jobId }: { jobId?: string } = {}) {
const {
core,
plugins: { ml },
} = useApmPluginContext();
const { core } = useApmPluginContext();

const { urlParams } = useLegacyUrlParams();

Expand All @@ -23,7 +20,7 @@ export function useMlManageJobsHref({ jobId }: { jobId?: string } = {}) {
rangeTo = 'now',
} = urlParams;

const mlADLink = useMlHref(ml?.locator, core.http.basePath.get(), {
const mlADLink = useMlHref(core.http.basePath.get(), {
page: ML_PAGES.ANOMALY_DETECTION_JOBS_MANAGE,
pageState: {
groupIds: ['apm'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const LogEntryCategoriesResultsContent: React.FunctionComponent<
useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_results', delay: 15000 });

const {
services: { ml, http },
services: { http },
} = useKibanaContextForPlugin();

const { logViewStatus } = useLogViewContext();
Expand Down Expand Up @@ -197,7 +197,7 @@ export const LogEntryCategoriesResultsContent: React.FunctionComponent<
autoRefresh.isPaused ? null : autoRefresh.interval
);

const analyzeInMlLink = useMlHref(ml?.locator, http.basePath.get(), {
const analyzeInMlLink = useMlHref(http.basePath.get(), {
page: ML_PAGES.ANOMALY_EXPLORER,
pageState: {
jobIds: [jobIds[logEntryCategoriesJobType]],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,10 @@ export const AnalyzeCategoryDatasetInMlAction: React.FunctionComponent<{
timeRange: TimeRange;
}> = ({ categorizationJobId, categoryId, dataset, timeRange }) => {
const {
services: { ml, http, application },
services: { http, application },
} = useKibanaContextForPlugin();

const viewAnomalyInMachineLearningLink = useMlHref(
ml?.locator,
http.basePath.get(),
{
page: ML_PAGES.SINGLE_METRIC_VIEWER,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export const LogEntryExampleMessage: React.FunctionComponent<Props> = ({
anomaly,
}) => {
const {
services: { ml, http, application },
services: { http, application },
} = useKibanaContextForPlugin();
const [isHovered, setIsHovered] = useState(false);
const [isMenuOpen, setIsMenuOpen] = useState(false);
Expand Down Expand Up @@ -122,7 +122,7 @@ export const LogEntryExampleMessage: React.FunctionComponent<Props> = ({
},
});

const viewAnomalyInMachineLearningLink = useMlHref(ml?.locator, http.basePath.get(), {
const viewAnomalyInMachineLearningLink = useMlHref(http.basePath.get(), {
page: ML_PAGES.SINGLE_METRIC_VIEWER,
pageState: {
jobIds: [anomaly.jobId],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import { CoreStart } from '@kbn/core/public';
import { EuiThemeProvider } from '@kbn/kibana-react-plugin/common';
import { createKibanaReactContext } from '@kbn/kibana-react-plugin/public';
import { MlLocatorDefinition } from '@kbn/ml-plugin/public';
import { MlLocatorDefinition } from '@kbn/ml-locator';
import { UrlService } from '@kbn/share-plugin/common/url_service';
import { createMemoryHistory } from 'history';
import { merge } from 'lodash';
Expand Down
3 changes: 2 additions & 1 deletion x-pack/plugins/security_solution/kibana.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"navigation",
"ruleRegistry",
"sessionView",
"share",
"spaces",
"taskManager",
"threatIntelligence",
Expand Down Expand Up @@ -87,4 +88,4 @@
"common"
]
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import React from 'react';
import { EuiLink } from '@elastic/eui';
import { useMlHref } from '@kbn/ml-plugin/public';
import { useMlHref } from '@kbn/ml-locator';
import type { Anomaly } from '../types';
import { useKibana } from '../../../lib/kibana';

Expand All @@ -25,11 +25,10 @@ export const ExplorerLink: React.FC<ExplorerLinkProps> = ({
linkName,
}) => {
const {
services: { ml, http },
services: { http },
} = useKibana();

const explorerUrl = useMlHref(
ml,
http.basePath.get(),
{
page: 'explorer',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
import styled from 'styled-components';
import { useMlHref, ML_PAGES } from '@kbn/ml-locator';
import { PopoverItems } from '../../popover_items';
import { useBasePath, useKibana } from '../../../lib/kibana';
import { useBasePath } from '../../../lib/kibana';
import * as i18n from './translations';
import { JobSwitch } from './job_switch';
import type { SecurityJob } from '../types';
Expand All @@ -43,12 +43,7 @@ interface JobNameProps {
}

const JobName = ({ id, name, description, basePath }: JobNameProps) => {
const {
services: { ml },
} = useKibana();

const jobUrl = useMlHref(
ml?.locator,
basePath,
{
page: ML_PAGES.ANOMALY_DETECTION_JOBS_MANAGE,
Expand Down Expand Up @@ -190,11 +185,7 @@ export const JobsTable = React.memo(JobsTableComponent);
JobsTable.displayName = 'JobsTable';

export const NoItemsMessage = React.memo(({ basePath }: { basePath: string }) => {
const {
services: { ml },
} = useKibana();

const createNewAnomalyDetectionJoUrl = useMlHref(ml?.locator, basePath, {
const createNewAnomalyDetectionJoUrl = useMlHref(basePath, {
page: ML_PAGES.ANOMALY_DETECTION_CREATE_JOB_SELECT_INDEX,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@ interface MlJobLinkProps {

const MlJobLinkComponent: React.FC<MlJobLinkProps> = ({ jobId, jobName }) => {
const {
services: { http, ml },
services: { http },
} = useKibana();
const jobUrl = useMlHref(
ml?.locator,
http.basePath.get(),
{
page: ML_PAGES.ANOMALY_DETECTION_JOBS_MANAGE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,10 @@ export const EntityAnalyticsAnomalies = () => {
const [recentlyEnabledJobIds, setRecentlyEnabledJobIds] = useState<string[]>([]);

const {
services: { ml, http, docLinks },
services: { http, docLinks },
} = useKibana();

const jobsUrl = useMlHref(ml?.locator, http.basePath.get(), {
const jobsUrl = useMlHref(http.basePath.get(), {
page: ML_PAGES.ANOMALY_DETECTION_JOBS_MANAGE,
});

Expand Down
Loading

0 comments on commit fbf35d4

Please sign in to comment.