From 3418d9a44f457cd8862b68d41b5d54be1bab22d9 Mon Sep 17 00:00:00 2001 From: "Quynh Nguyen (Quinn)" <43350163+qn895@users.noreply.github.com> Date: Wed, 3 May 2023 14:02:46 -0500 Subject: [PATCH] [APM] Fix comparison option showing in individual transaction page (#155915) ## Summary This PR fixes `Expected bounds` showing as a comparison option in the individual transaction page. Currently, it will show the bounds of the overall job, and not of the individual transaction, which is incorrect. ### Checklist Delete any items that are not applicable to this PR. - [ ] Any text added follows [EUI's writing guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses sentence case text and includes [i18n support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md) - [ ] [Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html) was added for features that require explanation or tutorials - [ ] [Unit or functional tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html) were updated or added to match the most common scenarios - [ ] Any UI touched in this PR is usable by keyboard only (learn more about [keyboard accessibility](https://webaim.org/techniques/keyboard/)) - [ ] Any UI touched in this PR does not create any new axe failures (run axe in browser: [FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/), [Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US)) - [ ] If a plugin configuration key changed, check if it needs to be allowlisted in the cloud and added to the [docker list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker) - [ ] This renders correctly on smaller devices using a responsive layout. (You can test this [in your browser](https://www.browserstack.com/guide/responsive-testing-on-local-server)) - [ ] This was checked for [cross-browser compatibility](https://www.elastic.co/support/matrix#matrix_browsers) ### Risk Matrix Delete this section if it is not applicable to this PR. Before closing this PR, invite QA, stakeholders, and other developers to identify risks that should be tested prior to the change/feature release. When forming the risk matrix, consider some of the following examples and how they may potentially impact the change: | Risk | Probability | Severity | Mitigation/Notes | |---------------------------|-------------|----------|-------------------------| | Multiple Spaces—unexpected behavior in non-default Kibana Space. | Low | High | Integration tests will verify that all features are still supported in non-default Kibana Space and when user switches between spaces. | | Multiple nodes—Elasticsearch polling might have race conditions when multiple Kibana nodes are polling for the same tasks. | High | Low | Tasks are idempotent, so executing them multiple times will not result in logical error, but will degrade performance. To test for this case we add plenty of unit tests around this logic and document manual testing procedure. | | Code should gracefully handle cases when feature X or plugin Y are disabled. | Medium | High | Unit tests will verify that any feature flag or plugin combination still results in our service operational. | | [See more potential risk examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) | ### For maintainers - [ ] This was checked for breaking API changes and was [labeled appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process) --------- Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com> (cherry picked from commit 5778f31ab8a14fe99bab655bdbb87e4d55641357) --- .../time_comparison/get_comparison_options.ts | 17 +- .../shared/time_comparison/index.test.tsx | 239 +++++++++++++++++- .../shared/time_comparison/index.tsx | 14 +- 3 files changed, 254 insertions(+), 16 deletions(-) diff --git a/x-pack/plugins/apm/public/components/shared/time_comparison/get_comparison_options.ts b/x-pack/plugins/apm/public/components/shared/time_comparison/get_comparison_options.ts index 0eff4bc9b591f..8e5b02e6513b7 100644 --- a/x-pack/plugins/apm/public/components/shared/time_comparison/get_comparison_options.ts +++ b/x-pack/plugins/apm/public/components/shared/time_comparison/get_comparison_options.ts @@ -50,7 +50,7 @@ function formatDate({ )} - ${previousPeriodEnd.format(dateFormat)}`; } -function isDefined(argument: T | undefined | null): argument is T { +export function isDefined(argument: T | undefined | null): argument is T { return argument !== undefined && argument !== null; } @@ -143,11 +143,9 @@ export function getComparisonOptions({ comparisonTypes = [TimeRangeComparisonEnum.PeriodBefore]; } - const hasMLJobsMatchingEnv = - Array.isArray(anomalyDetectionJobsData?.jobs) && - anomalyDetectionJobsData?.jobs.some( - (j) => j.environment === preferredEnvironment - ); + const hasMLJob = + isDefined(anomalyDetectionJobsData) && + anomalyDetectionJobsData.jobs.length > 0; const comparisonOptions = getSelectOptions({ comparisonTypes, @@ -156,9 +154,12 @@ export function getComparisonOptions({ msDiff, }); - if (showSelectedBoundsOption) { + if (showSelectedBoundsOption && hasMLJob) { const disabled = - anomalyDetectionJobsStatus === 'success' && !hasMLJobsMatchingEnv; + anomalyDetectionJobsStatus === 'success' && + !anomalyDetectionJobsData.jobs.some( + (j) => j.environment === preferredEnvironment + ); comparisonOptions.push({ value: TimeRangeComparisonEnum.ExpectedBounds, text: disabled diff --git a/x-pack/plugins/apm/public/components/shared/time_comparison/index.test.tsx b/x-pack/plugins/apm/public/components/shared/time_comparison/index.test.tsx index 3d0c0b0cd9d8f..f21eb712874b0 100644 --- a/x-pack/plugins/apm/public/components/shared/time_comparison/index.test.tsx +++ b/x-pack/plugins/apm/public/components/shared/time_comparison/index.test.tsx @@ -16,8 +16,43 @@ import { import { TimeComparison } from '.'; import * as urlHelpers from '../links/url_helpers'; import moment from 'moment'; -import { MockApmPluginContextWrapper } from '../../../context/apm_plugin/mock_apm_plugin_context'; +import { + mockApmPluginContextValue, + MockApmPluginContextWrapper, +} from '../../../context/apm_plugin/mock_apm_plugin_context'; import { ENVIRONMENT_ALL } from '../../../../common/environment_filter_values'; +import * as useAnomalyDetectionJobsContextModule from '../../../context/anomaly_detection_jobs/use_anomaly_detection_jobs_context'; +import * as useEnvironmentContextModule from '../../../context/environments_context/use_environments_context'; +import type { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plugin_context'; +import { merge } from 'lodash'; +import type { ApmMlJob } from '../../../../common/anomaly_detection/apm_ml_job'; +import { FETCH_STATUS } from '../../../hooks/use_fetcher'; + +const ML_AD_JOBS = { + jobs: [ + { + jobId: 'apm-prod-9f5f-apm_tx_metrics', + jobState: 'opened', + datafeedId: 'datafeed-apm-prod-9f5f-apm_tx_metrics', + datafeedState: 'started', + version: 3, + environment: 'prod', + bucketSpan: '15m', + }, + { + jobId: 'apm-staging-4fec-apm_tx_metrics', + jobState: 'opened', + datafeedId: 'datafeed-apm-staging-4fec-apm_tx_metrics', + datafeedState: 'started', + version: 3, + environment: 'staging', + bucketSpan: '15m', + }, + ] as ApmMlJob[], + hasLegacyJobs: false, +}; + +const NO_ML_AD_JOBS = { jobs: [] as ApmMlJob[], hasLegacyJobs: false }; function getWrapper({ rangeFrom, @@ -25,21 +60,27 @@ function getWrapper({ offset, comparisonEnabled, environment = ENVIRONMENT_ALL.value, + url = '/services', + mockPluginContext = undefined, + params = '', }: { rangeFrom: string; rangeTo: string; offset?: string; comparisonEnabled?: boolean; environment?: string; + url?: string; + params?: string; + mockPluginContext?: ApmPluginContextValue; }) { return ({ children }: { children?: ReactNode }) => { return ( - + {children} @@ -48,6 +89,27 @@ function getWrapper({ } describe('TimeComparison component', () => { + const mockMLJobs = () => { + jest + .spyOn( + useAnomalyDetectionJobsContextModule, + 'useAnomalyDetectionJobsContext' + ) + .mockReturnValue( + // @ts-ignore mocking only partial data + { + anomalyDetectionJobsStatus: FETCH_STATUS.SUCCESS, + anomalyDetectionJobsData: ML_AD_JOBS, + } + ); + + jest + .spyOn(useEnvironmentContextModule, 'useEnvironmentsContext') + .mockReturnValue({ + // @ts-ignore mocking only partial data + preferredEnvironment: 'prod', + }); + }; beforeAll(() => { moment.tz.setDefault('Europe/Amsterdam'); }); @@ -56,8 +118,179 @@ describe('TimeComparison component', () => { const spy = jest.spyOn(urlHelpers, 'replace'); beforeEach(() => { jest.resetAllMocks(); + mockMLJobs(); }); + describe('ML expected model bounds', () => { + const pluginContextCanGetMlJobs = merge({}, mockApmPluginContextValue, { + core: { + application: { capabilities: { ml: { canGetJobs: true } } }, + }, + }) as unknown as ApmPluginContextValue; + + it('shows disabled option for expected bounds when there are ML jobs available with sufficient permission', () => { + jest + .spyOn(useEnvironmentContextModule, 'useEnvironmentsContext') + .mockReturnValueOnce( + // @ts-ignore mocking only partial data + { + preferredEnvironment: ENVIRONMENT_ALL.value, + } + ); + + const Wrapper = getWrapper({ + url: '/services/frontend/transactions', + rangeFrom: '2020-05-27T16:32:46.747Z', + rangeTo: '2021-06-04T16:32:46.747Z', + comparisonEnabled: true, + offset: '32227200000ms', + mockPluginContext: pluginContextCanGetMlJobs, + }); + const component = render(, { + wrapper: Wrapper, + }); + expect(spy).not.toHaveBeenCalled(); + expectTextsInDocument(component, [ + '20/05/19 18:32 - 27/05/20 18:32', + 'Expected bounds (Anomaly detection must be enabled for env)', + ]); + expect( + (component.getByTestId('comparisonSelect') as HTMLSelectElement) + .selectedIndex + ).toEqual(0); + }); + + it('shows enabled option for expected bounds when there are ML jobs available matching the preferred environment', () => { + jest + .spyOn(useEnvironmentContextModule, 'useEnvironmentsContext') + .mockReturnValueOnce({ + // @ts-ignore mocking only partial data + preferredEnvironment: 'prod', + }); + + const Wrapper = getWrapper({ + url: '/services/frontend/overview', + rangeFrom: '2020-05-27T16:32:46.747Z', + rangeTo: '2021-06-04T16:32:46.747Z', + comparisonEnabled: true, + offset: '32227200000ms', + mockPluginContext: pluginContextCanGetMlJobs, + environment: 'prod', + }); + const component = render(, { + wrapper: Wrapper, + }); + expect(spy).not.toHaveBeenCalled(); + expectTextsInDocument(component, [ + '20/05/19 18:32 - 27/05/20 18:32', + 'Expected bounds', + ]); + expect( + (component.getByTestId('comparisonSelect') as HTMLSelectElement) + .selectedIndex + ).toEqual(0); + }); + + it('does not show option for expected bounds when there are no ML jobs available', () => { + jest + .spyOn( + useAnomalyDetectionJobsContextModule, + 'useAnomalyDetectionJobsContext' + ) + .mockReturnValue( + // @ts-ignore mocking only partial data + { + anomalyDetectionJobsStatus: FETCH_STATUS.SUCCESS, + anomalyDetectionJobsData: NO_ML_AD_JOBS, + } + ); + + const Wrapper = getWrapper({ + url: '/services/frontend/transactions', + rangeFrom: '2020-05-27T16:32:46.747Z', + rangeTo: '2021-06-04T16:32:46.747Z', + comparisonEnabled: true, + offset: '32227200000ms', + mockPluginContext: pluginContextCanGetMlJobs, + }); + const component = render(, { + wrapper: Wrapper, + }); + expect(spy).not.toHaveBeenCalled(); + expectTextsNotInDocument(component, [ + 'Expected bounds', + 'Expected bounds (Anomaly detection must be enabled for env)', + ]); + expectTextsInDocument(component, ['20/05/19 18:32 - 27/05/20 18:32']); + expect( + (component.getByTestId('comparisonSelect') as HTMLSelectElement) + .selectedIndex + ).toEqual(0); + }); + + it('does not show option for expected bounds for pages other than overall transactions and overview', () => { + const urlsWithoutExpectedBoundsOptions = [ + '/services/frontend/dependencies', + '/services/frontend/transactions/view', + ]; + + urlsWithoutExpectedBoundsOptions.forEach((url) => { + const Wrapper = getWrapper({ + url, + rangeFrom: '2020-05-27T16:32:46.747Z', + rangeTo: '2021-06-04T16:32:46.747Z', + comparisonEnabled: true, + offset: '32227200000ms', + mockPluginContext: pluginContextCanGetMlJobs, + params: '&transactionName=createOrder&transactionType=request', + }); + const component = render(, { + wrapper: Wrapper, + }); + expect(spy).not.toHaveBeenCalled(); + expectTextsNotInDocument(component, [ + 'Expected bounds', + 'Expected bounds (Anomaly detection must be enabled for env)', + ]); + }); + }); + + it('does not show option for expected bounds if user does not have access to ML jobs', () => { + jest + .spyOn(useEnvironmentContextModule, 'useEnvironmentsContext') + .mockReturnValueOnce( + // @ts-ignore mocking only partial data + { + preferredEnvironment: ENVIRONMENT_ALL.value, + } + ); + + const Wrapper = getWrapper({ + url: '/services/frontend/transactions', + rangeFrom: '2020-05-27T16:32:46.747Z', + rangeTo: '2021-06-04T16:32:46.747Z', + comparisonEnabled: true, + offset: '32227200000ms', + mockPluginContext: merge({}, mockApmPluginContextValue, { + core: { + application: { capabilities: { ml: { canGetJobs: false } } }, + }, + }) as unknown as ApmPluginContextValue, + }); + const component = render(, { + wrapper: Wrapper, + }); + expect(spy).not.toHaveBeenCalled(); + expectTextsNotInDocument(component, [ + 'Expected bounds', + 'Expected bounds (Anomaly detection must be enabled for env)', + ]); + expect( + (component.getByTestId('comparisonSelect') as HTMLSelectElement) + .selectedIndex + ).toEqual(0); + }); + }); describe('Time range is between 0 - 25 hours', () => { it('sets default values', () => { const Wrapper = getWrapper({ diff --git a/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx b/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx index 6a72731a74236..f637db9c0c153 100644 --- a/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/time_comparison/index.tsx @@ -60,11 +60,15 @@ export function TimeComparison() { const comparisonOptions = useMemo(() => { const matchingRoutes = apmRouter.getRoutesToMatch(location.pathname); // Only show the "Expected bounds" option in Overview and Transactions tabs - const showExpectedBoundsForThisTab = matchingRoutes.some( - (d) => - d.path === '/services/{serviceName}/overview' || - d.path === '/services/{serviceName}/transactions' - ); + const showExpectedBoundsForThisTab = + !matchingRoutes.some( + (d) => d.path === '/services/{serviceName}/transactions/view' + ) && + matchingRoutes.some( + (d) => + d.path === '/services/{serviceName}/overview' || + d.path === '/services/{serviceName}/transactions' + ); const timeComparisonOptions = getComparisonOptions({ start,