Skip to content

Commit

Permalink
[8.16] [Entity Inventory] Add basic telemetry (#197055) (#198047)
Browse files Browse the repository at this point in the history
# Backport

This will backport the following commits from `main` to `8.16`:
- [[Entity Inventory] Add basic telemetry
(#197055)](#197055)

<!--- Backport version: 8.9.8 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Irene
Blanco","email":"[email protected]"},"sourceCommit":{"committedDate":"2024-10-25T14:49:49Z","message":"[Entity
Inventory] Add basic telemetry (#197055)\n\n## Summary\r\n\r\nCloses
https://github.com/elastic/kibana/issues/195608.\r\n\r\nIn this PR, we
introduce basic telemetry tracking for the new
Inventory\r\nplugin.\r\nThese events will help us gain insight into how
users are interacting\r\nwith the Inventory feature, including the state
of the views, search\r\nbehaviors, and entity type
filtering.\r\n\r\n\r\n**New events**\r\n- Entity Inventory Viewed\r\n-
Entity Inventory Search Query Submitted\r\n- Entity Inventory Entity
Type Filtered\r\n- Entity View
Clicked\r\n\r\n\r\n![Untitled-2024-07-24-1420](https://github.com/user-attachments/assets/6e85ea00-c626-4bc1-a4f8-9907674eb264)\r\n\r\n\r\n~**New
attribute added to global context**~\r\n- ~eem_enabled~\r\n\r\n~It will
only be populated if the Inventory plugin is accessible to\r\nusers and
after they access the Observability solution.\r\nIf EEM is not enabled
and the user enables it, the property will be\r\nupdated
accordingly.~\r\n\r\nDetails about not implementing `eem_enabled` can be
found in
[this\r\ncomment](https://github.com/elastic/kibana/pull/197055#issuecomment-2432123047).","sha":"7d673b84c3ecec2f6da81b57196301c6e7fe384a","branchLabelMapping":{"^v9.0.0$":"main","^v8.17.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","backport
missing","v9.0.0","telemetry","backport:prev-minor","ci:project-deploy-observability","Team:obs-ux-infra_services","v8.16.0"],"number":197055,"url":"https://github.com/elastic/kibana/pull/197055","mergeCommit":{"message":"[Entity
Inventory] Add basic telemetry (#197055)\n\n## Summary\r\n\r\nCloses
https://github.com/elastic/kibana/issues/195608.\r\n\r\nIn this PR, we
introduce basic telemetry tracking for the new
Inventory\r\nplugin.\r\nThese events will help us gain insight into how
users are interacting\r\nwith the Inventory feature, including the state
of the views, search\r\nbehaviors, and entity type
filtering.\r\n\r\n\r\n**New events**\r\n- Entity Inventory Viewed\r\n-
Entity Inventory Search Query Submitted\r\n- Entity Inventory Entity
Type Filtered\r\n- Entity View
Clicked\r\n\r\n\r\n![Untitled-2024-07-24-1420](https://github.com/user-attachments/assets/6e85ea00-c626-4bc1-a4f8-9907674eb264)\r\n\r\n\r\n~**New
attribute added to global context**~\r\n- ~eem_enabled~\r\n\r\n~It will
only be populated if the Inventory plugin is accessible to\r\nusers and
after they access the Observability solution.\r\nIf EEM is not enabled
and the user enables it, the property will be\r\nupdated
accordingly.~\r\n\r\nDetails about not implementing `eem_enabled` can be
found in
[this\r\ncomment](https://github.com/elastic/kibana/pull/197055#issuecomment-2432123047).","sha":"7d673b84c3ecec2f6da81b57196301c6e7fe384a"}},"sourceBranch":"main","suggestedTargetBranches":["8.16"],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","labelRegex":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/197055","number":197055,"mergeCommit":{"message":"[Entity
Inventory] Add basic telemetry (#197055)\n\n## Summary\r\n\r\nCloses
https://github.com/elastic/kibana/issues/195608.\r\n\r\nIn this PR, we
introduce basic telemetry tracking for the new
Inventory\r\nplugin.\r\nThese events will help us gain insight into how
users are interacting\r\nwith the Inventory feature, including the state
of the views, search\r\nbehaviors, and entity type
filtering.\r\n\r\n\r\n**New events**\r\n- Entity Inventory Viewed\r\n-
Entity Inventory Search Query Submitted\r\n- Entity Inventory Entity
Type Filtered\r\n- Entity View
Clicked\r\n\r\n\r\n![Untitled-2024-07-24-1420](https://github.com/user-attachments/assets/6e85ea00-c626-4bc1-a4f8-9907674eb264)\r\n\r\n\r\n~**New
attribute added to global context**~\r\n- ~eem_enabled~\r\n\r\n~It will
only be populated if the Inventory plugin is accessible to\r\nusers and
after they access the Observability solution.\r\nIf EEM is not enabled
and the user enables it, the property will be\r\nupdated
accordingly.~\r\n\r\nDetails about not implementing `eem_enabled` can be
found in
[this\r\ncomment](https://github.com/elastic/kibana/pull/197055#issuecomment-2432123047).","sha":"7d673b84c3ecec2f6da81b57196301c6e7fe384a"}},{"branch":"8.16","label":"v8.16.0","labelRegex":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"}]}]
BACKPORT-->

---------

Co-authored-by: Irene Blanco <[email protected]>
  • Loading branch information
crespocarlos and iblancof authored Oct 29, 2024
1 parent 6f333b8 commit 512cabc
Show file tree
Hide file tree
Showing 16 changed files with 549 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import type { UnifiedSearchPublicPluginStart } from '@kbn/unified-search-plugin/
import type { SharePluginStart } from '@kbn/share-plugin/public';
import type { SpacesPluginStart } from '@kbn/spaces-plugin/public';
import type { InventoryKibanaContext } from '../public/hooks/use_kibana';
import type { ITelemetryClient } from '../public/services/telemetry/types';
import { ITelemetryClient } from '../public/services/telemetry/types';

export function getMockInventoryContext(): InventoryKibanaContext {
const coreStart = coreMock.createStart();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,22 @@ interface EntityNameProps {
}

export function EntityName({ entity }: EntityNameProps) {
const { services } = useKibana();
const {
services: { telemetry, share },
} = useKibana();

const assetDetailsLocator =
services.share?.url.locators.get<AssetDetailsLocatorParams>(ASSET_DETAILS_LOCATOR_ID);
share?.url.locators.get<AssetDetailsLocatorParams>(ASSET_DETAILS_LOCATOR_ID);

const serviceOverviewLocator =
services.share?.url.locators.get<ServiceOverviewParams>('serviceOverviewLocator');
share?.url.locators.get<ServiceOverviewParams>('serviceOverviewLocator');

const handleLinkClick = useCallback(() => {
telemetry.reportEntityViewClicked({
view_type: 'detail',
entity_type: entity['entity.type'],
});
}, [entity, telemetry]);

const getEntityRedirectUrl = useCallback(() => {
const type = entity[ENTITY_TYPE];
Expand All @@ -58,7 +67,12 @@ export function EntityName({ entity }: EntityNameProps) {
}, [entity, assetDetailsLocator, serviceOverviewLocator]);

return (
<EuiLink data-test-subj="entityNameLink" href={getEntityRedirectUrl()}>
// eslint-disable-next-line @elastic/eui/href-or-on-click
<EuiLink
data-test-subj="entityNameLink"
href={getEntityRedirectUrl()}
onClick={handleLinkClick}
>
<EuiFlexGroup gutterSize="s" alignItems="center">
<EuiFlexItem grow={0}>
<EntityIcon entity={entity} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,13 @@ export function EntitiesGrid({
}

const columnEntityTableId = columnId as EntityColumnIds;
const entityType = entity[ENTITY_TYPE];

switch (columnEntityTableId) {
case 'alertsCount':
return entity?.alertsCount ? <AlertsBadge entity={entity} /> : null;

case ENTITY_TYPE:
const entityType = entity[columnEntityTableId];
return (
<BadgeFilterWithPopover
field={ENTITY_TYPE}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/
import { i18n } from '@kbn/i18n';
import React from 'react';
import React, { useEffect } from 'react';
import { EuiFlexGroup, EuiFlexItem, EuiEmptyPrompt, EuiLoadingLogo } from '@elastic/eui';
import {
FeatureFeedbackButton,
Expand All @@ -18,6 +18,7 @@ import { useEntityManager } from '../../hooks/use_entity_manager';
import { Welcome } from '../entity_enablement/welcome_modal';
import { useInventoryAbortableAsync } from '../../hooks/use_inventory_abortable_async';
import { EmptyState } from '../empty_states/empty_state';
import { useIsLoadingComplete } from '../../hooks/use_is_loading_complete';

const pageTitle = (
<EuiFlexGroup gutterSize="s">
Expand All @@ -36,7 +37,7 @@ const INVENTORY_FEEDBACK_LINK = 'https://ela.st/feedback-new-inventory';

export function InventoryPageTemplate({ children }: { children: React.ReactNode }) {
const {
services: { observabilityShared, inventoryAPIClient, kibanaEnvironment },
services: { observabilityShared, inventoryAPIClient, kibanaEnvironment, telemetry },
} = useKibana();

const { PageTemplate: ObservabilityPageTemplate } = observabilityShared.navigation;
Expand All @@ -62,6 +63,23 @@ export function InventoryPageTemplate({ children }: { children: React.ReactNode
[inventoryAPIClient]
);

const isLoadingComplete = useIsLoadingComplete({
loadingStates: [isEnablementLoading, hasDataLoading],
});

useEffect(() => {
if (isLoadingComplete) {
const viewState = isEntityManagerEnabled
? value.hasData
? 'populated'
: 'empty'
: 'eem_disabled';
telemetry.reportEntityInventoryViewed({
view_state: viewState,
});
}
}, [isEntityManagerEnabled, value.hasData, telemetry, isLoadingComplete]);

if (isEnablementLoading || hasDataLoading) {
return (
<ObservabilityPageTemplate
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ import { SearchBarOwnProps } from '@kbn/unified-search-plugin/public/search_bar'
import deepEqual from 'fast-deep-equal';
import React, { useCallback, useEffect } from 'react';
import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import { Query } from '@kbn/es-query';
import { EntityType } from '../../../common/entities';
import { useInventorySearchBarContext } from '../../context/inventory_search_bar_context_provider';
import { useAdHocInventoryDataView } from '../../hooks/use_adhoc_inventory_data_view';
import { useInventoryParams } from '../../hooks/use_inventory_params';
import { useKibana } from '../../hooks/use_kibana';
import { EntityTypesControls } from './entity_types_controls';
import { DiscoverButton } from './discover_button';
import { getKqlFieldsWithFallback } from '../../utils/get_kql_field_names_with_fallback';

export function SearchBar() {
const { searchBarContentSubject$ } = useInventorySearchBarContext();
Expand All @@ -25,6 +27,7 @@ export function SearchBar() {
data: {
query: { queryString: queryStringService },
},
telemetry,
},
} = useKibana();

Expand All @@ -51,11 +54,41 @@ export function SearchBar() {
syncSearchBarWithUrl();
}, [syncSearchBarWithUrl]);

const registerSearchSubmittedEvent = useCallback(
({
searchQuery,
searchIsUpdate,
searchEntityTypes,
}: {
searchQuery?: Query;
searchEntityTypes?: string[];
searchIsUpdate?: boolean;
}) => {
telemetry.reportEntityInventorySearchQuerySubmitted({
kuery_fields: getKqlFieldsWithFallback(searchQuery?.query as string),
entity_types: searchEntityTypes || [],
action: searchIsUpdate ? 'submit' : 'refresh',
});
},
[telemetry]
);

const registerEntityTypeFilteredEvent = useCallback(
({ filterEntityTypes, filterKuery }: { filterEntityTypes: string[]; filterKuery?: string }) => {
telemetry.reportEntityInventoryEntityTypeFiltered({
entity_types: filterEntityTypes,
kuery_fields: filterKuery ? getKqlFieldsWithFallback(filterKuery) : [],
});
},
[telemetry]
);

const handleEntityTypesChange = useCallback(
(nextEntityTypes: EntityType[]) => {
searchBarContentSubject$.next({ kuery, entityTypes: nextEntityTypes, refresh: false });
registerEntityTypeFilteredEvent({ filterEntityTypes: nextEntityTypes, filterKuery: kuery });
},
[kuery, searchBarContentSubject$]
[kuery, registerEntityTypeFilteredEvent, searchBarContentSubject$]
);

const handleQuerySubmit = useCallback<NonNullable<SearchBarOwnProps['onQuerySubmit']>>(
Expand All @@ -65,8 +98,14 @@ export function SearchBar() {
entityTypes,
refresh: !isUpdate,
});

registerSearchSubmittedEvent({
searchQuery: query,
searchEntityTypes: entityTypes,
searchIsUpdate: isUpdate,
});
},
[entityTypes, searchBarContentSubject$]
[entityTypes, registerSearchSubmittedEvent, searchBarContentSubject$]
);

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { useIsLoadingComplete } from './use_is_loading_complete';

describe('useIsLoadingComplete', () => {
describe('initialization', () => {
it('should initialize with undefined', () => {
const { result } = renderHook(() => useIsLoadingComplete({ loadingStates: [false, false] }));
expect(result.current).toBeUndefined();
});

it('should handle an empty array of loadingStates', () => {
const { result } = renderHook(() => useIsLoadingComplete({ loadingStates: [] }));
expect(result.current).toBeUndefined();
});

it('should handle a single loading state that is false', () => {
const { result } = renderHook(() => useIsLoadingComplete({ loadingStates: [false] }));
expect(result.current).toBeUndefined();
});
});

describe('loading states', () => {
it('should set isLoadingComplete to false when some loadingStates are true', () => {
const { result } = renderHook(() => useIsLoadingComplete({ loadingStates: [true, false] }));
expect(result.current).toBe(false);
});

it('should set isLoadingComplete to false when all loadingStates are true', () => {
const { result } = renderHook(() => useIsLoadingComplete({ loadingStates: [true, true] }));
expect(result.current).toBe(false);
});

it('should handle a single loading state that is true', () => {
const { result } = renderHook(() => useIsLoadingComplete({ loadingStates: [true] }));
expect(result.current).toBe(false);
});
});

describe('loading completion', () => {
it('should set isLoadingComplete to true when all loadingStates are false after being true', () => {
const { result, rerender } = renderHook(
({ loadingStates }) => useIsLoadingComplete({ loadingStates }),
{
initialProps: { loadingStates: [true, false] },
}
);

expect(result.current).toBe(false);

rerender({ loadingStates: [false, false] });

expect(result.current).toBe(true);
});

it('should set isLoadingComplete to true when all loadingStates are false after being mixed', () => {
const { result, rerender } = renderHook(
({ loadingStates }) => useIsLoadingComplete({ loadingStates }),
{
initialProps: { loadingStates: [true, false] },
}
);

expect(result.current).toBe(false);

rerender({ loadingStates: [false, false] });

expect(result.current).toBe(true);
});
});

describe('mixed states', () => {
it('should not change isLoadingComplete if loadingStates are mixed', () => {
const { result, rerender } = renderHook(
({ loadingStates }) => useIsLoadingComplete({ loadingStates }),
{
initialProps: { loadingStates: [true, true] },
}
);

expect(result.current).toBe(false);

rerender({ loadingStates: [true, false] });

expect(result.current).toBe(false);
});

it('should not change isLoadingComplete if loadingStates change from all true to mixed', () => {
const { result, rerender } = renderHook(
({ loadingStates }) => useIsLoadingComplete({ loadingStates }),
{
initialProps: { loadingStates: [true, true] },
}
);

expect(result.current).toBe(false);

rerender({ loadingStates: [true, false] });

expect(result.current).toBe(false);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useState, useEffect } from 'react';

interface UseIsLoadingCompleteProps {
loadingStates: boolean[];
}

export const useIsLoadingComplete = ({ loadingStates }: UseIsLoadingCompleteProps) => {
const [isLoadingComplete, setIsLoadingComplete] = useState<boolean | undefined>(undefined);

useEffect(() => {
const someLoading = loadingStates.some((loading) => loading);
const allLoaded = loadingStates.every((loading) => !loading);

if (isLoadingComplete === undefined && someLoading) {
setIsLoadingComplete(false);
} else if (isLoadingComplete === false && allLoaded) {
setIsLoadingComplete(true);
}
}, [isLoadingComplete, loadingStates]);

return isLoadingComplete;
};
11 changes: 8 additions & 3 deletions x-pack/plugins/observability_solution/inventory/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export class InventoryPlugin
this.kibanaVersion = context.env.packageInfo.version;
this.isServerlessEnv = context.env.packageInfo.buildFlavor === 'serverless';
}

setup(
coreSetup: CoreSetup<InventoryStartDependencies, InventoryPublicStart>,
pluginsSetup: InventorySetupDependencies
Expand All @@ -58,6 +59,13 @@ export class InventoryPlugin
'observability:entityCentricExperience',
true
);

this.telemetry.setup({
analytics: coreSetup.analytics,
});

const telemetry = this.telemetry.start();

const getStartServices = coreSetup.getStartServices();

const hideInventory$ = from(getStartServices).pipe(
Expand Down Expand Up @@ -105,9 +113,6 @@ export class InventoryPlugin

pluginsSetup.observabilityShared.navigation.registerSections(sections$);

this.telemetry.setup({ analytics: coreSetup.analytics });
const telemetry = this.telemetry.start();

const isCloudEnv = !!pluginsSetup.cloud?.isCloudEnabled;
const isServerlessEnv = pluginsSetup.cloud?.isServerlessEnabled || this.isServerlessEnv;

Expand Down
Loading

0 comments on commit 512cabc

Please sign in to comment.