@@ -59,7 +59,7 @@ export const PersonalDashboardLayout: React.FC = ({ diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/layout/personal_dashboard_sidebar/private_sources_sidebar.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/layout/personal_dashboard_sidebar/private_sources_sidebar.test.tsx index 9fa4d4dd1b237..8f2ecf012e1ea 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/layout/personal_dashboard_sidebar/private_sources_sidebar.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/layout/personal_dashboard_sidebar/private_sources_sidebar.test.tsx @@ -30,7 +30,7 @@ import { PrivateSourcesSidebar } from './private_sources_sidebar'; describe('PrivateSourcesSidebar', () => { const mockValues = { - account: { canCreatePersonalSources: true }, + account: { canCreatePrivateSources: true }, contentSource: {}, }; @@ -55,7 +55,7 @@ describe('PrivateSourcesSidebar', () => { }); it('uses correct title and description when private sources are disabled', () => { - setMockValues({ ...mockValues, account: { canCreatePersonalSources: false } }); + setMockValues({ ...mockValues, account: { canCreatePrivateSources: false } }); const wrapper = shallow(); expect(wrapper.find(ViewContentHeader).prop('title')).toEqual(PRIVATE_VIEW_ONLY_PAGE_TITLE); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/layout/personal_dashboard_sidebar/private_sources_sidebar.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/layout/personal_dashboard_sidebar/private_sources_sidebar.tsx index ac497f5ae3a28..6cd7a10fc7ade 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/layout/personal_dashboard_sidebar/private_sources_sidebar.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/components/layout/personal_dashboard_sidebar/private_sources_sidebar.tsx @@ -24,13 +24,13 @@ import { ViewContentHeader } from '../../shared/view_content_header'; export const PrivateSourcesSidebar = () => { const { - account: { canCreatePersonalSources }, + account: { canCreatePrivateSources }, } = useValues(AppLogic); - const PAGE_TITLE = canCreatePersonalSources + const PAGE_TITLE = canCreatePrivateSources ? PRIVATE_CAN_CREATE_PAGE_TITLE : PRIVATE_VIEW_ONLY_PAGE_TITLE; - const PAGE_DESCRIPTION = canCreatePersonalSources + const PAGE_DESCRIPTION = canCreatePrivateSources ? PRIVATE_CAN_CREATE_PAGE_DESCRIPTION : PRIVATE_VIEW_ONLY_PAGE_DESCRIPTION; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/index.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/index.tsx index 26f82ca5371d6..1ed77ea0fb1fd 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/index.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/index.tsx @@ -23,7 +23,7 @@ import { SOURCES_PATH, SOURCE_ADDED_PATH, OAUTH_AUTHORIZE_PATH, - PERSONAL_SOURCES_PATH, + PRIVATE_SOURCES_PATH, ORG_SETTINGS_PATH, USERS_AND_ROLES_PATH, SECURITY_PATH, @@ -94,8 +94,8 @@ export const WorkplaceSearchConfigured: React.FC = (props) => { - - + + diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/routes.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/routes.test.tsx index b89a1451f7e57..b69303aae2106 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/routes.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/routes.test.tsx @@ -19,7 +19,7 @@ import { getSourcesPath, GROUPS_PATH, SOURCES_PATH, - PERSONAL_SOURCES_PATH, + PRIVATE_SOURCES_PATH, SOURCE_DETAILS_PATH, } from './routes'; @@ -40,7 +40,7 @@ describe('getContentSourcePath', () => { const wrapper = shallow(); const path = wrapper.find(EuiLink).prop('href'); - expect(path).toEqual(`${PERSONAL_SOURCES_PATH}/123`); + expect(path).toEqual(`${PRIVATE_SOURCES_PATH}/123`); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/routes.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/routes.ts index edd33ac885569..cd699f7df86cb 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/routes.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/routes.ts @@ -60,7 +60,7 @@ export const GROUP_PATH = `${GROUPS_PATH}/:groupId`; export const GROUP_SOURCE_PRIORITIZATION_PATH = `${GROUPS_PATH}/:groupId/source_prioritization`; export const SOURCES_PATH = '/sources'; -export const PERSONAL_SOURCES_PATH = `${PERSONAL_PATH}${SOURCES_PATH}`; +export const PRIVATE_SOURCES_PATH = `${PERSONAL_PATH}${SOURCES_PATH}`; export const SOURCE_ADDED_PATH = `${SOURCES_PATH}/added`; export const ADD_SOURCE_PATH = `${SOURCES_PATH}/add`; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/utils/read_uploaded_file_as_base64.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/utils/read_uploaded_file_as_base64.test.ts index 9f612a7432ec5..2aedbbb798f58 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/utils/read_uploaded_file_as_base64.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/utils/read_uploaded_file_as_base64.test.ts @@ -15,7 +15,7 @@ describe('readUploadedFileAsBase64', () => { }); it('throws an error if the file cannot be read', async () => { - const badFile = ('causes an error' as unknown) as File; + const badFile = 'causes an error' as unknown as File; await expect(readUploadedFileAsBase64(badFile)).rejects.toThrow(); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/account_settings/account_settings.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/account_settings/account_settings.tsx index 2e92a00e3aa12..fb5a3e34a9db7 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/account_settings/account_settings.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/account_settings/account_settings.tsx @@ -24,9 +24,10 @@ export const AccountSettings: React.FC = () => { }, [security.authc]); const PersonalInfo = useMemo(() => security.uiApi.components.getPersonalInfo, [security.uiApi]); - const ChangePassword = useMemo(() => security.uiApi.components.getChangePassword, [ - security.uiApi, - ]); + const ChangePassword = useMemo( + () => security.uiApi.components.getChangePassword, + [security.uiApi] + ); if (!currentUser) { return null; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_list.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_list.tsx index 165586dcc3903..08e002ee432a9 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_list.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_list.tsx @@ -20,7 +20,7 @@ import { } from '@elastic/eui'; import { AppLogic } from '../../../../app_logic'; -import noSharedSourcesIcon from '../../../../assets/share_circle.svg'; +import noOrgSourcesIcon from '../../../../assets/share_circle.svg'; import { WorkplaceSearchPageTemplate, PersonalDashboardLayout, @@ -46,9 +46,8 @@ import { } from './constants'; export const AddSourceList: React.FC = () => { - const { contentSources, dataLoading, availableSources, configuredSources } = useValues( - SourcesLogic - ); + const { contentSources, dataLoading, availableSources, configuredSources } = + useValues(SourcesLogic); const { initializeSources, resetSourcesState } = useActions(SourcesLogic); @@ -143,7 +142,7 @@ export const AddSourceList: React.FC = () => { {ADD_SOURCE_EMPTY_TITLE}} body={

{ADD_SOURCE_EMPTY_BODY}

} /> diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.test.ts index 63eba575f0c37..5ff3964b8f83a 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.test.ts @@ -23,7 +23,7 @@ import { AppLogic } from '../../../../app_logic'; import { ADD_GITHUB_PATH, SOURCES_PATH, - PERSONAL_SOURCES_PATH, + PRIVATE_SOURCES_PATH, getSourcesPath, } from '../../../../routes'; import { CustomSource } from '../../../../types'; @@ -321,7 +321,7 @@ describe('AddSourceLogic', () => { expect(navigateToUrl).toHaveBeenCalledWith(getSourcesPath(SOURCES_PATH, true)); }); - it('redirects to private dashboard when account context', async () => { + it('redirects to personal dashboard when account context', async () => { const accountQueryString = '?state=%7B%22action%22:%22create%22,%22context%22:%22account%22,%22service_type%22:%22gmail%22,%22csrf_token%22:%22token%3D%3D%22,%22index_permissions%22:false%7D&code=code'; @@ -379,7 +379,7 @@ describe('AddSourceLogic', () => { const githubQueryString = getGithubQueryString('account'); AddSourceLogic.actions.saveSourceParams(githubQueryString, errorParams, false); - expect(navigateToUrl).toHaveBeenCalledWith(PERSONAL_SOURCES_PATH); + expect(navigateToUrl).toHaveBeenCalledWith(PRIVATE_SOURCES_PATH); expect(setErrorMessage).toHaveBeenCalledWith( PERSONAL_DASHBOARD_SOURCE_ERROR(GITHUB_ERROR) ); @@ -569,9 +569,7 @@ describe('AddSourceLogic', () => { expect(clearFlashMessages).toHaveBeenCalled(); expect(AddSourceLogic.values.buttonLoading).toEqual(true); - expect( - http.put - ).toHaveBeenCalledWith( + expect(http.put).toHaveBeenCalledWith( `/internal/workplace_search/org/settings/connectors/${sourceConfigData.serviceType}`, { body: JSON.stringify(params) } ); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts index e63e58adb38e2..6f09cbb15c7db 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/add_source_logic.ts @@ -25,7 +25,7 @@ import { CUSTOM_SERVICE_TYPE, WORKPLACE_SEARCH_URL_PREFIX } from '../../../../co import { SOURCES_PATH, ADD_GITHUB_PATH, - PERSONAL_SOURCES_PATH, + PRIVATE_SOURCES_PATH, getSourcesPath, } from '../../../../routes'; import { CustomSource } from '../../../../types'; @@ -62,11 +62,7 @@ export interface OauthParams { export interface AddSourceActions { initializeAddSource: (addSourceProps: AddSourceProps) => { addSourceProps: AddSourceProps }; - setAddSourceProps: ({ - addSourceProps, - }: { - addSourceProps: AddSourceProps; - }) => { + setAddSourceProps: ({ addSourceProps }: { addSourceProps: AddSourceProps }) => { addSourceProps: AddSourceProps; }; setAddSourceStep(addSourceCurrentStep: AddSourceSteps): AddSourceSteps; @@ -521,7 +517,7 @@ export const AddSourceLogic = kea = ({ name, onFormCreated, header }) => { const [formLoading, setFormLoading] = useState(false); - const { - getPreContentSourceConfigData, - setSelectedGithubOrganizations, - createContentSource, - } = useActions(AddSourceLogic); + const { getPreContentSourceConfigData, setSelectedGithubOrganizations, createContentSource } = + useActions(AddSourceLogic); const { currentServiceType, githubOrganizations, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/connect_instance.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/connect_instance.tsx index 8a632dfe12959..5428e63a101b4 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/connect_instance.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/connect_instance.tsx @@ -82,9 +82,8 @@ export const ConnectInstance: React.FC = ({ setSourceIndexPermissionsValue, } = useActions(AddSourceLogic); - const { loginValue, passwordValue, indexPermissionsValue, subdomainValue } = useValues( - AddSourceLogic - ); + const { loginValue, passwordValue, indexPermissionsValue, subdomainValue } = + useValues(AddSourceLogic); const { isOrganization } = useValues(AppLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/constants.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/constants.ts index a2e6de8d9c7f5..079cb5e1a5a3d 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/constants.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/constants.ts @@ -19,7 +19,7 @@ export const ADD_SOURCE_ORG_SOURCE_DESCRIPTION = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.contentSource.addSourceList.orgSourceDescription', { defaultMessage: - 'Shared content sources are available to your entire organization or can be assigned to specific user groups.', + 'Organizational content sources are available to your entire organization or can be assigned to specific user groups.', } ); @@ -41,7 +41,7 @@ export const ADD_SOURCE_NO_SOURCES_TITLE = i18n.translate( export const ADD_SOURCE_ORG_SOURCES_TITLE = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.contentSource.addSourceList.orgSourcesTitle', { - defaultMessage: 'Add a shared content source', + defaultMessage: 'Add an organizational content source', } ); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/reauthenticate.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/reauthenticate.tsx index fa604ef758a44..f6c34a3eec4ca 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/reauthenticate.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/reauthenticate.tsx @@ -30,7 +30,7 @@ interface ReauthenticateProps { export const Reauthenticate: React.FC = ({ name, header }) => { const { search } = useLocation() as Location; - const { sourceId } = (parseQueryParams(search) as unknown) as SourceQueryParams; + const { sourceId } = parseQueryParams(search) as unknown as SourceQueryParams; const [formLoading, setFormLoading] = useState(false); const { getSourceReConnectData } = useActions(AddSourceLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/save_config.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/save_config.tsx index 053a3b6b0e6bb..3320f43ed771a 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/save_config.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/add_source/save_config.tsx @@ -67,13 +67,8 @@ export const SaveConfig: React.FC = ({ const { setClientIdValue, setClientSecretValue, setBaseUrlValue } = useActions(AddSourceLogic); - const { - sourceConfigData, - buttonLoading, - clientIdValue, - clientSecretValue, - baseUrlValue, - } = useValues(AddSourceLogic); + const { sourceConfigData, buttonLoading, clientIdValue, clientSecretValue, baseUrlValue } = + useValues(AddSourceLogic); const { accountContextOnly, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/display_settings.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/display_settings.tsx index ae47e20026b68..c5836dc939f2a 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/display_settings.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/display_settings.tsx @@ -44,9 +44,8 @@ interface DisplaySettingsProps { } export const DisplaySettings: React.FC = ({ tabId }) => { - const { initializeDisplaySettings, setServerData, handleSelectedTabChanged } = useActions( - DisplaySettingsLogic - ); + const { initializeDisplaySettings, setServerData, handleSelectedTabChanged } = + useActions(DisplaySettingsLogic); const { dataLoading, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/field_editor_modal.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/field_editor_modal.tsx index 132adedb829ac..794b54eb59f36 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/field_editor_modal.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/field_editor_modal.tsx @@ -36,9 +36,8 @@ import { DisplaySettingsLogic } from './display_settings_logic'; const emptyField = { fieldName: '', label: '' }; export const FieldEditorModal: React.FC = () => { - const { toggleFieldEditorModal, addDetailField, updateDetailField } = useActions( - DisplaySettingsLogic - ); + const { toggleFieldEditorModal, addDetailField, updateDetailField } = + useActions(DisplaySettingsLogic); const { searchResultConfig: { detailFields }, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/result_detail.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/result_detail.tsx index 6832f075476e7..df80a454cc6f7 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/result_detail.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/display_settings/result_detail.tsx @@ -34,12 +34,8 @@ import { DisplaySettingsLogic } from './display_settings_logic'; import { ExampleResultDetailCard } from './example_result_detail_card'; export const ResultDetail: React.FC = () => { - const { - toggleFieldEditorModal, - setDetailFields, - openEditDetailField, - removeDetailField, - } = useActions(DisplaySettingsLogic); + const { toggleFieldEditorModal, setDetailFields, openEditDetailField, removeDetailField } = + useActions(DisplaySettingsLogic); const { searchResultConfig: { detailFields }, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts index 549ffe0546d7c..af9d85237335c 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.test.ts @@ -40,12 +40,8 @@ import { SchemaLogic, dataTypeOptions } from './schema_logic'; describe('SchemaLogic', () => { const { http } = mockHttpValues; - const { - clearFlashMessages, - flashAPIErrors, - flashSuccessToast, - setErrorMessage, - } = mockFlashMessageHelpers; + const { clearFlashMessages, flashAPIErrors, flashSuccessToast, setErrorMessage } = + mockFlashMessageHelpers; const { mount } = new LogicMounter(SchemaLogic); const defaultValues = { diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts index 173f5df162caa..d664197afaa26 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/schema/schema_logic.ts @@ -44,13 +44,10 @@ interface SchemaActions { onSchemaSetSuccess(schemaProps: SchemaResponseProps): SchemaResponseProps; onSchemaSetFormErrors(errors: string[]): string[]; updateNewFieldType(newFieldType: SchemaType): SchemaType; - onFieldUpdate({ - schema, - formUnchanged, - }: { + onFieldUpdate({ schema, formUnchanged }: { schema: Schema; formUnchanged: boolean }): { schema: Schema; formUnchanged: boolean; - }): { schema: Schema; formUnchanged: boolean }; + }; onIndexingComplete(numDocumentsWithErrors: number): number; resetMostRecentIndexJob(emptyReindexJob: IndexJob): IndexJob; setFieldName(rawFieldName: string): string; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_added.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_added.tsx index 77b3931050483..c4f97eb718452 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_added.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_added.tsx @@ -26,7 +26,7 @@ import { AddSourceLogic, OauthParams } from './add_source/add_source_logic'; */ export const SourceAdded: React.FC = () => { const { search } = useLocation() as Location; - const params = (parseQueryParams(search) as unknown) as OauthParams; + const params = parseQueryParams(search) as unknown as OauthParams; const state = JSON.parse(params.state); const isOrganization = state.context !== 'account'; const { setChromeIsVisible } = useValues(KibanaLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_content.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_content.tsx index 78d4d36cf0995..fdeb325730470 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_content.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/components/source_content.tsx @@ -59,9 +59,8 @@ const MAX_LENGTH = 28; export const SourceContent: React.FC = () => { const [searchTerm, setSearchTerm] = useState(''); - const { setActivePage, searchContentSourceDocuments, setContentFilterValue } = useActions( - SourceLogic - ); + const { setActivePage, searchContentSourceDocuments, setContentFilterValue } = + useActions(SourceLogic); const { contentSource: { id, serviceType, urlField, titleField, urlFieldIsLinkable, isFederatedSource }, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/constants.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/constants.ts index 55e7f5938a305..001f06261de4b 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/constants.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/constants.ts @@ -448,10 +448,10 @@ export const PRIVATE_HEADER_DESCRIPTION = i18n.translate( } ); -export const PRIVATE_SHARED_SOURCES_TITLE = i18n.translate( - 'xpack.enterpriseSearch.workplaceSearch.sources.private.privateShared.header.title', +export const PRIVATE_ORG_SOURCES_TITLE = i18n.translate( + 'xpack.enterpriseSearch.workplaceSearch.sources.private.privateOrg.header.title', { - defaultMessage: 'Shared content sources', + defaultMessage: 'Organizational content sources', } ); @@ -461,15 +461,15 @@ export const PRIVATE_EMPTY_TITLE = i18n.translate( defaultMessage: 'You have no private sources', } ); -export const SHARED_EMPTY_TITLE = i18n.translate( - 'xpack.enterpriseSearch.workplaceSearch.sources.shared.empty.title', +export const ORG_SOURCES_EMPTY_TITLE = i18n.translate( + 'xpack.enterpriseSearch.workplaceSearch.sources.org.empty.title', { defaultMessage: 'No content source available', } ); -export const SHARED_EMPTY_DESCRIPTION = i18n.translate( - 'xpack.enterpriseSearch.workplaceSearch.sources.shared.empty.description', +export const ORG_SOURCES_EMPTY_DESCRIPTION = i18n.translate( + 'xpack.enterpriseSearch.workplaceSearch.sources.org.empty.description', { defaultMessage: 'Once content sources are shared with you, they will be displayed here, and available via the search experience.', @@ -526,8 +526,8 @@ export const UNDERSTAND_BUTTON = i18n.translate( } ); -export const PRIVATE_DASHBOARD_READ_ONLY_MODE_WARNING = i18n.translate( - 'xpack.enterpriseSearch.workplaceSearch.privateDashboard.readOnlyMode.warning', +export const PERSONAL_DASHBOARD_READ_ONLY_MODE_WARNING = i18n.translate( + 'xpack.enterpriseSearch.workplaceSearch.personalDashboard.readOnlyMode.warning', { defaultMessage: 'Workplace Search is currently available for search only, due to regular maintenance. Contact your system administrator for more information.', diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.test.tsx index e2b0dfba1fa97..dffddade5925d 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.test.tsx @@ -23,7 +23,7 @@ import { SourcesView } from './sources_view'; describe('PrivateSources', () => { const mockValues = { - account: { canCreatePersonalSources: false, groups: [] }, + account: { canCreatePrivateSources: false, groups: [] }, dataLoading: false, contentSources: [], privateContentSources: [], @@ -42,15 +42,15 @@ describe('PrivateSources', () => { expect(wrapper.find(SourcesView)).toHaveLength(1); }); - it('renders only shared sources section when canCreatePersonalSources is false', () => { + it('renders only organizational sources section when canCreatePrivateSources is false', () => { setMockValues({ ...mockValues }); const wrapper = shallow(); expect(wrapper.find(ContentSection)).toHaveLength(1); }); - it('renders both shared and private sources sections when canCreatePersonalSources is true', () => { - setMockValues({ ...mockValues, account: { canCreatePersonalSources: true, groups: [] } }); + it('renders both organizational and private sources sections when canCreatePrivateSources is true', () => { + setMockValues({ ...mockValues, account: { canCreatePrivateSources: true, groups: [] } }); const wrapper = shallow(); expect(wrapper.find(ContentSection)).toHaveLength(2); @@ -61,7 +61,7 @@ describe('PrivateSources', () => { ...mockValues, privateContentSources: ['source1', 'source2'], hasPlatinumLicense: false, - account: { canCreatePersonalSources: true, groups: [] }, + account: { canCreatePrivateSources: true, groups: [] }, }); const wrapper = shallow(); @@ -71,7 +71,7 @@ describe('PrivateSources', () => { it('renders an action button when user can add private sources', () => { setMockValues({ ...mockValues, - account: { canCreatePersonalSources: true, groups: [] }, + account: { canCreatePrivateSources: true, groups: [] }, serviceTypes: [{ configured: true }], }); const wrapper = shallow(); @@ -82,7 +82,7 @@ describe('PrivateSources', () => { it('renders empty prompts if no sources are available', () => { setMockValues({ ...mockValues, - account: { canCreatePersonalSources: true, groups: [] }, + account: { canCreatePrivateSources: true, groups: [] }, }); const wrapper = shallow(); @@ -92,7 +92,7 @@ describe('PrivateSources', () => { it('renders SourcesTable if sources are available', () => { setMockValues({ ...mockValues, - account: { canCreatePersonalSources: true, groups: [] }, + account: { canCreatePrivateSources: true, groups: [] }, contentSources: ['1', '2'], privateContentSources: ['1', '2'], }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.tsx index 57574ce14df67..c9f55ff656561 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/private_sources.tsx @@ -15,7 +15,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { LicensingLogic } from '../../../shared/licensing'; import { EuiButtonTo } from '../../../shared/react_router_helpers'; import { AppLogic } from '../../app_logic'; -import noSharedSourcesIcon from '../../assets/share_circle.svg'; +import noOrgSourcesIcon from '../../assets/share_circle.svg'; import { PersonalDashboardLayout } from '../../components/layout'; import { ContentSection } from '../../components/shared/content_section'; import { SourcesTable } from '../../components/shared/sources_table'; @@ -27,10 +27,10 @@ import { PRIVATE_LINK_TITLE, PRIVATE_HEADER_TITLE, PRIVATE_HEADER_DESCRIPTION, - PRIVATE_SHARED_SOURCES_TITLE, + PRIVATE_ORG_SOURCES_TITLE, PRIVATE_EMPTY_TITLE, - SHARED_EMPTY_TITLE, - SHARED_EMPTY_DESCRIPTION, + ORG_SOURCES_EMPTY_TITLE, + ORG_SOURCES_EMPTY_DESCRIPTION, LICENSE_CALLOUT_TITLE, LICENSE_CALLOUT_DESCRIPTION, } from './constants'; @@ -46,18 +46,17 @@ export const PrivateSources: React.FC = () => { return resetSourcesState; }, []); - const { dataLoading, contentSources, serviceTypes, privateContentSources } = useValues( - SourcesLogic - ); + const { dataLoading, contentSources, serviceTypes, privateContentSources } = + useValues(SourcesLogic); const { - account: { canCreatePersonalSources, groups }, + account: { canCreatePrivateSources, groups }, } = useValues(AppLogic); const hasConfiguredConnectors = serviceTypes.some(({ configured }) => configured); - const canAddSources = canCreatePersonalSources && hasConfiguredConnectors; + const canAddSources = canCreatePrivateSources && hasConfiguredConnectors; const hasPrivateSources = privateContentSources?.length > 0; - const hasSharedSources = contentSources.length > 0; + const hasOrgSources = contentSources.length > 0; const licenseCallout = ( <> @@ -106,30 +105,30 @@ export const PrivateSources: React.FC = () => { ); - const sharedSourcesEmptyState = ( + const orgSourcesEmptyState = ( {SHARED_EMPTY_TITLE}} - body={

{SHARED_EMPTY_DESCRIPTION}

} + iconType={noOrgSourcesIcon} + title={

{ORG_SOURCES_EMPTY_TITLE}

} + body={

{ORG_SOURCES_EMPTY_DESCRIPTION}

} />
); - const sharedSourcesTable = ( + const orgSourcesTable = ( ); - const sharedSourcesSection = ( + const orgSourcesSection = ( { ) } > - {hasSharedSources ? sharedSourcesTable : sharedSourcesEmptyState} + {hasOrgSources ? orgSourcesTable : orgSourcesEmptyState} ); @@ -148,8 +147,8 @@ export const PrivateSources: React.FC = () => { {hasPrivateSources && !hasPlatinumLicense && licenseCallout} - {canCreatePersonalSources && privateSourcesSection} - {sharedSourcesSection} + {canCreatePrivateSources && privateSourcesSection} + {orgSourcesSection} ); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.test.ts index 94ec730ef256c..0d8d5684c4a4c 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.test.ts @@ -26,12 +26,8 @@ import { SourceLogic } from './source_logic'; describe('SourceLogic', () => { const { http } = mockHttpValues; - const { - clearFlashMessages, - flashAPIErrors, - flashSuccessToast, - setErrorMessage, - } = mockFlashMessageHelpers; + const { clearFlashMessages, flashAPIErrors, flashSuccessToast, setErrorMessage } = + mockFlashMessageHelpers; const { navigateToUrl } = mockKibanaValues; const { mount, getListeners } = new LogicMounter(SourceLogic); @@ -202,7 +198,7 @@ describe('SourceLogic', () => { AppLogic.values.isOrganization = false; http.get.mockReturnValue(mock404); - SourceLogic.actions.initializeSource('404ing_personal_source'); + SourceLogic.actions.initializeSource('404ing_private_source'); await expectedAsyncError(mock404); expect(navigateToUrl).toHaveBeenCalledWith('/p/sources'); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.ts index 5c947b68f2333..c31eacda69515 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/source_logic.ts @@ -19,7 +19,7 @@ import { import { HttpLogic } from '../../../shared/http'; import { KibanaLogic } from '../../../shared/kibana'; import { AppLogic } from '../../app_logic'; -import { PERSONAL_SOURCES_PATH, SOURCES_PATH, getSourcesPath } from '../../routes'; +import { PRIVATE_SOURCES_PATH, SOURCES_PATH, getSourcesPath } from '../../routes'; import { ContentSourceFullData, Meta, DocumentSummaryItem, SourceContentItem } from '../../types'; export interface SourceActions { @@ -169,7 +169,7 @@ export const SourceLogic = kea>({ } } catch (e) { if (e?.response?.status === 404) { - const redirect = isOrganization ? SOURCES_PATH : PERSONAL_SOURCES_PATH; + const redirect = isOrganization ? SOURCES_PATH : PRIVATE_SOURCES_PATH; KibanaLogic.values.navigateToUrl(redirect); setErrorMessage( i18n.translate('xpack.enterpriseSearch.workplaceSearch.sources.notFoundErrorMessage', { diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/sources_router.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/sources_router.test.tsx index eb6a9949eb07c..00cf56001f73b 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/sources_router.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/sources_router.test.tsx @@ -14,14 +14,14 @@ import { Route, Switch, Redirect } from 'react-router-dom'; import { shallow } from 'enzyme'; -import { ADD_SOURCE_PATH, PERSONAL_SOURCES_PATH, SOURCES_PATH, getSourcesPath } from '../../routes'; +import { ADD_SOURCE_PATH, PRIVATE_SOURCES_PATH, SOURCES_PATH, getSourcesPath } from '../../routes'; import { SourcesRouter } from './sources_router'; describe('SourcesRouter', () => { const resetSourcesState = jest.fn(); const mockValues = { - account: { canCreatePersonalSources: true }, + account: { canCreatePrivateSources: true }, isOrganization: true, hasPlatinumLicense: true, }; @@ -50,17 +50,17 @@ describe('SourcesRouter', () => { }); it('redirects when cannot create sources', () => { - setMockValues({ ...mockValues, account: { canCreatePersonalSources: false } }); + setMockValues({ ...mockValues, account: { canCreatePrivateSources: false } }); const wrapper = shallow(); expect(wrapper.find(Redirect).last().prop('from')).toEqual( getSourcesPath(ADD_SOURCE_PATH, false) ); - expect(wrapper.find(Redirect).last().prop('to')).toEqual(PERSONAL_SOURCES_PATH); + expect(wrapper.find(Redirect).last().prop('to')).toEqual(PRIVATE_SOURCES_PATH); }); - it('does not render the router until canCreatePersonalSources is fetched', () => { - setMockValues({ ...mockValues, account: {} }); // canCreatePersonalSources is undefined + it('does not render the router until canCreatePrivateSources is fetched', () => { + setMockValues({ ...mockValues, account: {} }); // canCreatePrivateSources is undefined const wrapper = shallow(); expect(wrapper.html()).toEqual(null); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/sources_router.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/sources_router.tsx index 0171717490c9b..2d47bab00810c 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/sources_router.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/content_sources/sources_router.tsx @@ -16,7 +16,7 @@ import { AppLogic } from '../../app_logic'; import { ADD_SOURCE_PATH, SOURCE_DETAILS_PATH, - PERSONAL_SOURCES_PATH, + PRIVATE_SOURCES_PATH, SOURCES_PATH, getSourcesPath, } from '../../routes'; @@ -35,7 +35,7 @@ export const SourcesRouter: React.FC = () => { const { hasPlatinumLicense } = useValues(LicensingLogic); const { resetSourcesState } = useActions(SourcesLogic); const { - account: { canCreatePersonalSources }, + account: { canCreatePrivateSources }, isOrganization, } = useValues(AppLogic); @@ -49,18 +49,18 @@ export const SourcesRouter: React.FC = () => { /** * When opening `workplace_search/p/sources/add` as a bookmark or reloading this page, - * Sources router first get rendered *before* it receives the canCreatePersonalSources value. - * This results in canCreatePersonalSources always being undefined on the first render, + * Sources router first get rendered *before* it receives the canCreatePrivateSources value. + * This results in canCreatePrivateSources always being undefined on the first render, * and user always getting redirected to `workplace_search/p/sources`. * Here we check for this value being present before we render any routes. */ - if (canCreatePersonalSources === undefined) { + if (canCreatePrivateSources === undefined) { return null; } return ( - + @@ -93,12 +93,12 @@ export const SourcesRouter: React.FC = () => { ); })} - {canCreatePersonalSources ? ( + {canCreatePrivateSources ? ( ) : ( - + )} diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/__mocks__/group_logic.mock.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/__mocks__/group_logic.mock.ts index d4c1ce9dc8a29..d4d66005ecdc5 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/__mocks__/group_logic.mock.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/__mocks__/group_logic.mock.ts @@ -11,7 +11,7 @@ export const mockGroupValues = { group: {} as GroupDetails, dataLoading: true, managerModalFormErrors: [], - sharedSourcesModalVisible: false, + orgSourcesModalVisible: false, confirmDeleteModalVisible: false, groupNameInputValue: '', selectedGroupSources: [], diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_manager_modal.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_manager_modal.test.tsx index 5619698335b30..2b22823219410 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_manager_modal.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_manager_modal.test.tsx @@ -23,7 +23,7 @@ const saveItems = jest.fn(); const props = { children: <>, - label: 'shared content sources', + label: 'organizational content sources', allItems: [], numSelected: 1, hideModal, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_manager_modal.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_manager_modal.tsx index 10d115c8e60ab..b5d23895e9efd 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_manager_modal.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_manager_modal.tsx @@ -26,7 +26,7 @@ import { import { i18n } from '@kbn/i18n'; import { EuiButtonTo } from '../../../../shared/react_router_helpers'; -import noSharedSourcesIcon from '../../../assets/share_circle.svg'; +import noOrgSourcesIcon from '../../../assets/share_circle.svg'; import { UPDATE_BUTTON, CANCEL_BUTTON } from '../../../constants'; import { SOURCES_PATH } from '../../../routes'; import { Group } from '../../../types'; @@ -36,7 +36,7 @@ import { GroupsLogic } from '../groups_logic'; const ADD_SOURCE_BUTTON_TEXT = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.groups.groupManagerUpdateAddSourceButton', { - defaultMessage: 'Add a Shared Source', + defaultMessage: 'Add an organizational source', } ); const EMPTY_STATE_TITLE = i18n.translate( @@ -48,7 +48,7 @@ const EMPTY_STATE_TITLE = i18n.translate( const EMPTY_STATE_BODY = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.groups.groupManagerSourceEmpty.body', { - defaultMessage: 'Looks like you have not added any shared content sources yet.', + defaultMessage: 'Looks like you have not added any organizational content sources yet.', } ); @@ -103,7 +103,7 @@ export const GroupManagerModal: React.FC = ({ {EMPTY_STATE_TITLE}} body={EMPTY_STATE_BODY} actions={sourcesButton} diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_overview.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_overview.test.tsx index ed0246702d7a5..e1ecc47f02669 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_overview.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_overview.test.tsx @@ -20,7 +20,7 @@ import { SourcesTable } from '../../../components/shared/sources_table'; import { GroupOverview } from './group_overview'; const deleteGroup = jest.fn(); -const showSharedSourcesModal = jest.fn(); +const showOrgSourcesModal = jest.fn(); const showConfirmDeleteModal = jest.fn(); const hideConfirmDeleteModal = jest.fn(); const updateGroupName = jest.fn(); @@ -37,7 +37,7 @@ describe('GroupOverview', () => { beforeEach(() => { setMockActions({ deleteGroup, - showSharedSourcesModal, + showOrgSourcesModal, showConfirmDeleteModal, hideConfirmDeleteModal, updateGroupName, diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_overview.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_overview.tsx index 5714cc965827e..c5febf37e1fbb 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_overview.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_overview.tsx @@ -25,7 +25,7 @@ import { i18n } from '@kbn/i18n'; import { EuiButtonTo } from '../../../../shared/react_router_helpers'; import { TruncatedContent } from '../../../../shared/truncate'; -import noSharedSourcesIcon from '../../../assets/share_circle.svg'; +import noOrgSourcesIcon from '../../../assets/share_circle.svg'; import { WorkplaceSearchPageTemplate } from '../../../components/layout'; import { ContentSection } from '../../../components/shared/content_section'; import { SourcesTable } from '../../../components/shared/sources_table'; @@ -55,7 +55,7 @@ const GROUP_USERS_DESCRIPTION = i18n.translate( const MANAGE_SOURCES_BUTTON_TEXT = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.groups.overview.manageSourcesButtonText', { - defaultMessage: 'Manage shared content sources', + defaultMessage: 'Manage organizational content sources', } ); const MANAGE_USERS_BUTTON_TEXT = i18n.translate( @@ -110,7 +110,7 @@ const CONFIRM_TITLE_TEXT = i18n.translate( export const GroupOverview: React.FC = () => { const { deleteGroup, - showSharedSourcesModal, + showOrgSourcesModal, showConfirmDeleteModal, hideConfirmDeleteModal, updateGroupName, @@ -159,7 +159,7 @@ export const GroupOverview: React.FC = () => { const hasContentSources = contentSources?.length > 0; const manageSourcesButton = ( - + {MANAGE_SOURCES_BUTTON_TEXT} ); @@ -185,7 +185,7 @@ export const GroupOverview: React.FC = () => { <> {GROUP_SOURCES_TITLE}} body={

{EMPTY_SOURCES_DESCRIPTION}

} actions={manageSourcesButton} diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_row.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_row.tsx index 8d3c7dfa7622b..effacfa3aa4f8 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_row.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_row.tsx @@ -25,7 +25,7 @@ const DAYS_CUTOFF = 8; export const NO_SOURCES_MESSAGE = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.groups.noSourcesMessage', { - defaultMessage: 'No shared content sources', + defaultMessage: 'No organizational content sources', } ); export const NO_USERS_MESSAGE = i18n.translate( diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_row_sources_dropdown.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_row_sources_dropdown.tsx index 77d7de91caf7c..aa25deff49e3d 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_row_sources_dropdown.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_row_sources_dropdown.tsx @@ -37,7 +37,7 @@ export const GroupRowSourcesDropdown: React.FC = ( const contentSourceCountHeading = ( {i18n.translate('xpack.enterpriseSearch.workplaceSearch.groups.contentSourceCountHeading', { - defaultMessage: '{numSources} shared content sources', + defaultMessage: '{numSources} organizational content sources', values: { numSources: groupSources.length }, })} diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.test.tsx index ba667c6d8152d..49dc7223e54e6 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.test.tsx @@ -18,7 +18,7 @@ import { GroupSourcePrioritization } from './group_source_prioritization'; const updatePriority = jest.fn(); const saveGroupSourcePrioritization = jest.fn(); -const showSharedSourcesModal = jest.fn(); +const showOrgSourcesModal = jest.fn(); const mockValues = { group: groups[0], @@ -36,7 +36,7 @@ describe('GroupSourcePrioritization', () => { setMockActions({ updatePriority, saveGroupSourcePrioritization, - showSharedSourcesModal, + showOrgSourcesModal, }); setMockValues(mockValues); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.tsx index 0fdaf2adde869..615e7b22b343f 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/group_source_prioritization.tsx @@ -36,7 +36,7 @@ import { GroupLogic } from '../group_logic'; const HEADER_TITLE = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.groups.sourceProioritization.headerTitle', { - defaultMessage: 'Shared content source prioritization', + defaultMessage: 'Organizational content source prioritization', } ); const HEADER_DESCRIPTION = i18n.translate( @@ -54,7 +54,7 @@ const ZERO_STATE_TITLE = i18n.translate( const ZERO_STATE_BUTTON_TEXT = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.groups.sourceProioritization.zeroStateButtonText', { - defaultMessage: 'Add shared content sources', + defaultMessage: 'Add organizational content sources', } ); const SOURCE_TABLE_HEADER = i18n.translate( @@ -71,9 +71,8 @@ const PRIORITY_TABLE_HEADER = i18n.translate( ); export const GroupSourcePrioritization: React.FC = () => { - const { updatePriority, saveGroupSourcePrioritization, showSharedSourcesModal } = useActions( - GroupLogic - ); + const { updatePriority, saveGroupSourcePrioritization, showOrgSourcesModal } = + useActions(GroupLogic); const { group: { contentSources = [], name: groupName }, @@ -118,7 +117,7 @@ export const GroupSourcePrioritization: React.FC = () => { )} } - actions={{ZERO_STATE_BUTTON_TEXT}} + actions={{ZERO_STATE_BUTTON_TEXT}} />
diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/shared_sources_modal.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/org_sources_modal.test.tsx similarity index 83% rename from x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/shared_sources_modal.test.tsx rename to x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/org_sources_modal.test.tsx index 02f0b53af97cc..3059274686045 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/shared_sources_modal.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/org_sources_modal.test.tsx @@ -13,23 +13,23 @@ import React from 'react'; import { shallow } from 'enzyme'; import { GroupManagerModal } from './group_manager_modal'; -import { SharedSourcesModal } from './shared_sources_modal'; +import { OrgSourcesModal } from './org_sources_modal'; import { SourcesList } from './sources_list'; const group = groups[0]; const addGroupSource = jest.fn(); const selectAllSources = jest.fn(); -const hideSharedSourcesModal = jest.fn(); +const hideOrgSourcesModal = jest.fn(); const removeGroupSource = jest.fn(); const saveGroupSources = jest.fn(); -describe('SharedSourcesModal', () => { +describe('OrgSourcesModal', () => { it('renders', () => { setMockActions({ addGroupSource, selectAllSources, - hideSharedSourcesModal, + hideOrgSourcesModal, removeGroupSource, saveGroupSources, }); @@ -40,7 +40,7 @@ describe('SharedSourcesModal', () => { contentSources: group.contentSources, }); - const wrapper = shallow(); + const wrapper = shallow(); expect(wrapper.find(SourcesList)).toHaveLength(1); expect(wrapper.find(GroupManagerModal)).toHaveLength(1); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/shared_sources_modal.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/org_sources_modal.tsx similarity index 91% rename from x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/shared_sources_modal.tsx rename to x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/org_sources_modal.tsx index 631c4f80f36b0..23598433d426b 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/shared_sources_modal.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/components/org_sources_modal.tsx @@ -21,15 +21,15 @@ import { SourcesList } from './sources_list'; const MODAL_LABEL = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.groups.sourcesModalLabel', { - defaultMessage: 'shared content sources', + defaultMessage: 'organizational content sources', } ); -export const SharedSourcesModal: React.FC = () => { +export const OrgSourcesModal: React.FC = () => { const { addGroupSource, selectAllSources, - hideSharedSourcesModal, + hideOrgSourcesModal, removeGroupSource, saveGroupSources, } = useActions(GroupLogic); @@ -43,7 +43,7 @@ export const SharedSourcesModal: React.FC = () => { label={MODAL_LABEL} allItems={contentSources} numSelected={selectedGroupSources.length} - hideModal={hideSharedSourcesModal} + hideModal={hideOrgSourcesModal} selectAll={selectAllSources} saveItems={saveGroupSources} > diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.test.ts index 088936443ccd3..6f811ce364290 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.test.ts @@ -24,12 +24,8 @@ describe('GroupLogic', () => { const { mount } = new LogicMounter(GroupLogic); const { http } = mockHttpValues; const { navigateToUrl } = mockKibanaValues; - const { - clearFlashMessages, - flashAPIErrors, - flashSuccessToast, - setQueuedErrorMessage, - } = mockFlashMessageHelpers; + const { clearFlashMessages, flashAPIErrors, flashSuccessToast, setQueuedErrorMessage } = + mockFlashMessageHelpers; const group = groups[0]; const sourceIds = ['123', '124']; @@ -114,7 +110,7 @@ describe('GroupLogic', () => { GroupLogic.actions.onGroupSourcesSaved(group); expect(GroupLogic.values.group).toEqual(group); - expect(GroupLogic.values.sharedSourcesModalVisible).toEqual(false); + expect(GroupLogic.values.orgSourcesModalVisible).toEqual(false); expect(GroupLogic.values.selectedGroupSources).toEqual(sourceIds); expect(GroupLogic.values.cachedSourcePriorities).toEqual(sourcePriorities); expect(GroupLogic.values.activeSourcePriorities).toEqual(sourcePriorities); @@ -130,11 +126,11 @@ describe('GroupLogic', () => { }); }); - describe('hideSharedSourcesModal', () => { + describe('hideOrgSourcesModal', () => { it('sets reducers', () => { - GroupLogic.actions.hideSharedSourcesModal(group); + GroupLogic.actions.hideOrgSourcesModal(group); - expect(GroupLogic.values.sharedSourcesModalVisible).toEqual(false); + expect(GroupLogic.values.orgSourcesModalVisible).toEqual(false); expect(GroupLogic.values.selectedGroupSources).toEqual(sourceIds); }); }); @@ -284,7 +280,7 @@ describe('GroupLogic', () => { await nextTick(); expect(onGroupSourcesSavedSpy).toHaveBeenCalledWith(group); expect(flashSuccessToast).toHaveBeenCalledWith( - 'Successfully updated shared content sources.' + 'Successfully updated organizational content sources.' ); }); @@ -321,7 +317,7 @@ describe('GroupLogic', () => { await nextTick(); expect(flashSuccessToast).toHaveBeenCalledWith( - 'Successfully updated shared source prioritization.' + 'Successfully updated organizational source prioritization.' ); expect(onGroupPrioritiesChangedSpy).toHaveBeenCalledWith(group); }); @@ -345,11 +341,11 @@ describe('GroupLogic', () => { }); }); - describe('showSharedSourcesModal', () => { + describe('showOrgSourcesModal', () => { it('sets reducer and clears flash messages', () => { - GroupLogic.actions.showSharedSourcesModal(); + GroupLogic.actions.showOrgSourcesModal(); - expect(GroupLogic.values.sharedSourcesModalVisible).toEqual(true); + expect(GroupLogic.values.orgSourcesModalVisible).toEqual(true); expect(clearFlashMessages).toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.ts index 96b9213d30afc..3ba7d68d0b3e9 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_logic.ts @@ -32,13 +32,13 @@ interface GroupActions { removeGroupSource(sourceId: string): string; onGroupSourcesSaved(group: GroupDetails): GroupDetails; setGroupModalErrors(errors: string[]): string[]; - hideSharedSourcesModal(group: GroupDetails): GroupDetails; + hideOrgSourcesModal(group: GroupDetails): GroupDetails; selectAllSources(contentSources: ContentSourceDetails[]): ContentSourceDetails[]; updatePriority(id: string, boost: number): { id: string; boost: number }; resetGroup(): void; showConfirmDeleteModal(): void; hideConfirmDeleteModal(): void; - showSharedSourcesModal(): void; + showOrgSourcesModal(): void; resetFlashMessages(): void; initializeGroup(groupId: string): { groupId: string }; deleteGroup(): void; @@ -51,7 +51,7 @@ interface GroupValues { group: GroupDetails; dataLoading: boolean; managerModalFormErrors: string[]; - sharedSourcesModalVisible: boolean; + orgSourcesModalVisible: boolean; confirmDeleteModalVisible: boolean; groupNameInputValue: string; selectedGroupSources: string[]; @@ -71,13 +71,13 @@ export const GroupLogic = kea>({ removeGroupSource: (sourceId) => sourceId, onGroupSourcesSaved: (group) => group, setGroupModalErrors: (errors) => errors, - hideSharedSourcesModal: (group) => group, + hideOrgSourcesModal: (group) => group, selectAllSources: (contentSources) => contentSources, updatePriority: (id, boost) => ({ id, boost }), resetGroup: () => true, showConfirmDeleteModal: () => true, hideConfirmDeleteModal: () => true, - showSharedSourcesModal: () => true, + showOrgSourcesModal: () => true, resetFlashMessages: () => true, initializeGroup: (groupId) => ({ groupId }), deleteGroup: () => true, @@ -109,11 +109,11 @@ export const GroupLogic = kea>({ setGroupModalErrors: (_, errors) => errors, }, ], - sharedSourcesModalVisible: [ + orgSourcesModalVisible: [ false, { - showSharedSourcesModal: () => true, - hideSharedSourcesModal: () => false, + showOrgSourcesModal: () => true, + hideOrgSourcesModal: () => false, onGroupSourcesSaved: () => false, }, ], @@ -138,7 +138,7 @@ export const GroupLogic = kea>({ onInitializeGroup: (_, { contentSources }) => contentSources.map(({ id }) => id), onGroupSourcesSaved: (_, { contentSources }) => contentSources.map(({ id }) => id), selectAllSources: (_, contentSources) => contentSources.map(({ id }) => id), - hideSharedSourcesModal: (_, { contentSources }) => contentSources.map(({ id }) => id), + hideOrgSourcesModal: (_, { contentSources }) => contentSources.map(({ id }) => id), addGroupSource: (state, sourceId) => [...state, sourceId].sort(), removeGroupSource: (state, sourceId) => state.filter((id) => id !== sourceId), }, @@ -257,7 +257,7 @@ export const GroupLogic = kea>({ const GROUP_SOURCES_UPDATED_MESSAGE = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.groups.groupSourcesUpdated', { - defaultMessage: 'Successfully updated shared content sources.', + defaultMessage: 'Successfully updated organizational content sources.', } ); flashSuccessToast(GROUP_SOURCES_UPDATED_MESSAGE); @@ -289,7 +289,7 @@ export const GroupLogic = kea>({ const GROUP_PRIORITIZATION_UPDATED_MESSAGE = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.groups.groupPrioritizationUpdated', { - defaultMessage: 'Successfully updated shared source prioritization.', + defaultMessage: 'Successfully updated organizational source prioritization.', } ); @@ -302,7 +302,7 @@ export const GroupLogic = kea>({ showConfirmDeleteModal: () => { clearFlashMessages(); }, - showSharedSourcesModal: () => { + showOrgSourcesModal: () => { clearFlashMessages(); }, resetFlashMessages: () => { diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_router.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_router.test.tsx index 9ea0908a0f014..393b5a7e194de 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_router.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_router.test.tsx @@ -17,7 +17,7 @@ import { shallow } from 'enzyme'; import { GroupOverview } from './components/group_overview'; import { GroupSourcePrioritization } from './components/group_source_prioritization'; -import { SharedSourcesModal } from './components/shared_sources_modal'; +import { OrgSourcesModal } from './components/org_sources_modal'; import { GroupRouter } from './group_router'; describe('GroupRouter', () => { @@ -26,7 +26,7 @@ describe('GroupRouter', () => { beforeEach(() => { setMockValues({ - sharedSourcesModalVisible: false, + orgSourcesModalVisible: false, group: groups[0], }); @@ -47,12 +47,12 @@ describe('GroupRouter', () => { it('renders modal', () => { setMockValues({ - sharedSourcesModalVisible: true, + orgSourcesModalVisible: true, group: groups[0], }); const wrapper = shallow(); - expect(wrapper.find(SharedSourcesModal)).toHaveLength(1); + expect(wrapper.find(OrgSourcesModal)).toHaveLength(1); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_router.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_router.tsx index 341e20099c6c2..ffdfb9c378614 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_router.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/group_router.tsx @@ -14,14 +14,14 @@ import { GROUP_SOURCE_PRIORITIZATION_PATH, GROUP_PATH } from '../../routes'; import { GroupOverview } from './components/group_overview'; import { GroupSourcePrioritization } from './components/group_source_prioritization'; -import { SharedSourcesModal } from './components/shared_sources_modal'; +import { OrgSourcesModal } from './components/org_sources_modal'; import { GroupLogic } from './group_logic'; export const GroupRouter: React.FC = () => { const { groupId } = useParams() as { groupId: string }; const { initializeGroup, resetGroup } = useActions(GroupLogic); - const { sharedSourcesModalVisible } = useValues(GroupLogic); + const { orgSourcesModalVisible } = useValues(GroupLogic); useEffect(() => { initializeGroup(groupId); @@ -38,7 +38,7 @@ export const GroupRouter: React.FC = () => {
- {sharedSourcesModalVisible && } + {orgSourcesModalVisible && } ); }; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/groups.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/groups.tsx index 1a4c4f51e93ea..5ecaef95c8be1 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/groups.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/groups/groups.tsx @@ -112,7 +112,7 @@ export const Groups: React.FC = () => { }), description: i18n.translate('xpack.enterpriseSearch.workplaceSearch.groups.description', { defaultMessage: - 'Assign shared content sources and users to groups to create relevant search experiences for various internal teams.', + 'Assign organizational content sources and users to groups to create relevant search experiences for various internal teams.', }), rightSideItems: headerActions, }} diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/not_found/not_found.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/not_found/not_found.tsx index ef55668775513..e5a162baa2871 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/not_found/not_found.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/not_found/not_found.tsx @@ -12,7 +12,7 @@ import { PageTemplateProps } from '../../../shared/layout'; import { NotFoundPrompt } from '../../../shared/not_found'; import { SendWorkplaceSearchTelemetry } from '../../../shared/telemetry'; import { WorkplaceSearchPageTemplate, PersonalDashboardLayout } from '../../components/layout'; -import { PERSONAL_SOURCES_PATH } from '../../routes'; +import { PRIVATE_SOURCES_PATH } from '../../routes'; interface Props { isOrganization?: boolean; @@ -25,7 +25,7 @@ export const NotFound: React.FC = ({ isOrganization = true, pageChrome = diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/oauth_authorize/oauth_authorize.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/oauth_authorize/oauth_authorize.tsx index 972f1951d47b8..5c3114ae3199e 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/oauth_authorize/oauth_authorize.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/oauth_authorize/oauth_authorize.tsx @@ -48,9 +48,8 @@ import { OAuthAuthorizeLogic } from './oauth_authorize_logic'; export const OAuthAuthorize: React.FC = () => { const { search } = useLocation() as Location; - const { initializeOAuthPreAuth, allowOAuthAuthorization, denyOAuthAuthorization } = useActions( - OAuthAuthorizeLogic - ); + const { initializeOAuthPreAuth, allowOAuthAuthorization, denyOAuthAuthorization } = + useActions(OAuthAuthorizeLogic); const { buttonLoading, dataLoading, cachedPreAuth, hasError } = useValues(OAuthAuthorizeLogic); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/__mocks__/overview_logic.mock.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/__mocks__/overview_logic.mock.ts index 7e30826c5e7ec..72ad157dd06bf 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/__mocks__/overview_logic.mock.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/__mocks__/overview_logic.mock.ts @@ -17,7 +17,7 @@ export const mockOverviewValues = { hasUsers: false, isOldAccount: false, pendingInvitationsCount: 0, - personalSourcesCount: 0, + privateSourcesCount: 0, sourcesCount: 0, dataLoading: true, }; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/onboarding_steps.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/onboarding_steps.test.tsx index b62f022d85e38..f4f87f48f6395 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/onboarding_steps.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/onboarding_steps.test.tsx @@ -21,19 +21,19 @@ import { OnboardingSteps, OrgNameOnboarding } from './onboarding_steps'; const account = { id: '1', isAdmin: true, - canCreatePersonalSources: true, + canCreatePrivateSources: true, groups: [], }; describe('OnboardingSteps', () => { - describe('Shared Sources', () => { + describe('Organizational Sources', () => { it('renders 0 sources state', () => { const wrapper = shallow(); expect(wrapper.find(OnboardingCard)).toHaveLength(2); expect(wrapper.find(OnboardingCard).first().prop('actionPath')).toBe(ADD_SOURCE_PATH); expect(wrapper.find(OnboardingCard).first().prop('description')).toBe( - 'Add shared sources for your organization to start searching.' + 'Add organizational sources for your organization to start searching.' ); }); @@ -42,7 +42,7 @@ describe('OnboardingSteps', () => { const wrapper = shallow(); expect(wrapper.find(OnboardingCard).first().prop('description')).toEqual( - 'You have added 2 shared sources. Happy searching.' + 'You have added 2 organizational sources. Happy searching.' ); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/onboarding_steps.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/onboarding_steps.tsx index b908211b83a43..13288bce98200 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/onboarding_steps.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/onboarding_steps.tsx @@ -24,7 +24,7 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { EuiButtonTo } from '../../../shared/react_router_helpers'; import { TelemetryLogic } from '../../../shared/telemetry'; import { AppLogic } from '../../app_logic'; -import sharedSourcesIcon from '../../components/shared/assets/source_icons/share_circle.svg'; +import orgSourcesIcon from '../../components/shared/assets/source_icons/share_circle.svg'; import { ContentSection } from '../../components/shared/content_section'; import { ADD_SOURCE_PATH, USERS_AND_ROLES_PATH, ORG_SETTINGS_PATH } from '../../routes'; @@ -33,7 +33,7 @@ import { OverviewLogic } from './overview_logic'; const SOURCES_TITLE = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.overviewOnboardingSourcesCard.title', - { defaultMessage: 'Shared sources' } + { defaultMessage: 'Organizational sources' } ); const USERS_TITLE = i18n.translate( @@ -53,7 +53,7 @@ const INVITE_MORE_USERS_BUTTON = i18n.translate( const ONBOARDING_SOURCES_CARD_DESCRIPTION = i18n.translate( 'xpack.enterpriseSearch.workplaceSearch.overviewOnboardingSourcesCard.description', - { defaultMessage: 'Add shared sources for your organization to start searching.' } + { defaultMessage: 'Add organizational sources for your organization to start searching.' } ); const ADD_FIRST_SOURCES_BUTTON = i18n.translate( @@ -87,7 +87,7 @@ export const OnboardingSteps: React.FC = () => { 'xpack.enterpriseSearch.workplaceSearch.sourcesOnboardingCard.description', { defaultMessage: - 'You have added {sourcesCount, number} shared {sourcesCount, plural, one {source} other {sources}}. Happy searching.', + 'You have added {sourcesCount, number} organizational {sourcesCount, plural, one {source} other {sources}}. Happy searching.', values: { sourcesCount }, } ); @@ -97,8 +97,8 @@ export const OnboardingSteps: React.FC = () => { { - const { sourcesCount, pendingInvitationsCount, accountsCount, personalSourcesCount } = useValues( - OverviewLogic - ); + const { sourcesCount, pendingInvitationsCount, accountsCount, privateSourcesCount } = + useValues(OverviewLogic); return ( { { 'xpack.enterpriseSearch.workplaceSearch.organizationStats.privateSources', { defaultMessage: 'Private sources' } )} - count={personalSourcesCount} + count={privateSourcesCount} /> diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/overview_logic.test.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/overview_logic.test.ts index f10918a1afe2d..64e87b77bacef 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/overview_logic.test.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/overview_logic.test.ts @@ -33,7 +33,7 @@ describe('OverviewLogic', () => { hasUsers: true, isOldAccount: true, pendingInvitationsCount: 1, - personalSourcesCount: 1, + privateSourcesCount: 1, sourcesCount: 1, }; @@ -52,7 +52,7 @@ describe('OverviewLogic', () => { expect(OverviewLogic.values.sourcesCount).toEqual(1); expect(OverviewLogic.values.pendingInvitationsCount).toEqual(1); expect(OverviewLogic.values.accountsCount).toEqual(1); - expect(OverviewLogic.values.personalSourcesCount).toEqual(1); + expect(OverviewLogic.values.privateSourcesCount).toEqual(1); expect(OverviewLogic.values.activityFeed).toEqual(feed); }); }); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/overview_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/overview_logic.ts index 196de02646804..1d79e66e778fb 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/overview_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/overview/overview_logic.ts @@ -19,7 +19,7 @@ interface OverviewServerData { sourcesCount: number; pendingInvitationsCount: number; accountsCount: number; - personalSourcesCount: number; + privateSourcesCount: number; activityFeed: FeedActivity[]; } @@ -75,10 +75,10 @@ export const OverviewLogic = kea> setServerData: (_, { accountsCount }) => accountsCount, }, ], - personalSourcesCount: [ + privateSourcesCount: [ 0, { - setServerData: (_, { personalSourcesCount }) => personalSourcesCount, + setServerData: (_, { privateSourcesCount }) => privateSourcesCount, }, ], activityFeed: [ diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.test.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.test.tsx index 94c21f3b5524f..289a5d9212284 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.test.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.test.tsx @@ -102,9 +102,11 @@ describe('GroupAssignmentSelector', () => { it('handles group checkbox click', async () => { const wrapper = shallow(); await waitFor(() => - ((wrapper.find(EuiComboBox).props() as unknown) as { - onChange: (a: EuiComboBoxOptionOption[]) => void; - }).onChange([{ label: groups[0].name, value: groups[0].name }]) + ( + wrapper.find(EuiComboBox).props() as unknown as { + onChange: (a: EuiComboBoxOptionOption[]) => void; + } + ).onChange([{ label: groups[0].name, value: groups[0].name }]) ); wrapper.update(); diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.tsx index b53b092eced2d..5d8ef7ababc8c 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/group_assignment_selector.tsx @@ -25,13 +25,11 @@ import { import { RoleMappingsLogic } from './role_mappings_logic'; export const GroupAssignmentSelector: React.FC = () => { - const { handleAllGroupsSelectionChange, handleGroupSelectionChange } = useActions( - RoleMappingsLogic - ); + const { handleAllGroupsSelectionChange, handleGroupSelectionChange } = + useActions(RoleMappingsLogic); - const { includeInAllGroups, availableGroups, selectedGroups, selectedOptions } = useValues( - RoleMappingsLogic - ); + const { includeInAllGroups, availableGroups, selectedGroups, selectedOptions } = + useValues(RoleMappingsLogic); const hasGroupAssignment = selectedGroups.size > 0 || includeInAllGroups; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings_logic.ts b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings_logic.ts index 55f82a07bf405..29103aa0c39af 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings_logic.ts +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/role_mappings_logic.ts @@ -47,11 +47,9 @@ interface RoleMappingsActions extends RoleMappingsBaseActions { setDefaultGroup(availableGroups: RoleGroup[]): { availableGroups: RoleGroup[] }; setRoleMapping(roleMapping: WSRoleMapping): { roleMapping: WSRoleMapping }; setSingleUserRoleMapping(data?: UserMapping): { singleUserRoleMapping: UserMapping }; - setRoleMappings({ - roleMappings, - }: { + setRoleMappings({ roleMappings }: { roleMappings: WSRoleMapping[] }): { roleMappings: WSRoleMapping[]; - }): { roleMappings: WSRoleMapping[] }; + }; setRoleMappingsData(data: RoleMappingsServerDetails): RoleMappingsServerDetails; handleAllGroupsSelectionChange(selected: boolean): { selected: boolean }; handleGroupSelectionChange(groupIds: string[]): { groupIds: string[] }; diff --git a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/user.tsx b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/user.tsx index 6447f43e6ed4d..33785b4a4ce0e 100644 --- a/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/user.tsx +++ b/x-pack/plugins/enterprise_search/public/applications/workplace_search/views/role_mappings/user.tsx @@ -24,7 +24,7 @@ import { Role } from '../../types'; import { GroupAssignmentSelector } from './group_assignment_selector'; import { RoleMappingsLogic } from './role_mappings_logic'; -const roleTypes = (['admin', 'user'] as unknown) as Role[]; +const roleTypes = ['admin', 'user'] as unknown as Role[]; export const User: React.FC = () => { const { diff --git a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts index d656c0f889635..3f2a038d8bff3 100644 --- a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts +++ b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.test.ts @@ -100,7 +100,7 @@ describe('callEnterpriseSearchConfigAPI', () => { id: 'some-id-string', groups: ['Default', 'Cats'], is_admin: true, - can_create_personal_sources: true, + can_create_private_sources: true, can_create_invitations: true, is_curated: false, viewed_onboarding_page: true, @@ -114,7 +114,7 @@ describe('callEnterpriseSearchConfigAPI', () => { }); it('calls the config API endpoint', async () => { - ((fetch as unknown) as jest.Mock).mockImplementationOnce((url: string) => { + (fetch as unknown as jest.Mock).mockImplementationOnce((url: string) => { expect(url).toEqual('http://localhost:3002/api/ent/v2/internal/client_config'); return Promise.resolve(new Response(JSON.stringify(mockResponse))); }); @@ -130,7 +130,7 @@ describe('callEnterpriseSearchConfigAPI', () => { }); it('falls back without error when data is unavailable', async () => { - ((fetch as unknown) as jest.Mock).mockReturnValueOnce(Promise.resolve(new Response('{}'))); + (fetch as unknown as jest.Mock).mockReturnValueOnce(Promise.resolve(new Response('{}'))); expect(await callEnterpriseSearchConfigAPI(mockDependencies)).toEqual({ access: { @@ -183,7 +183,7 @@ describe('callEnterpriseSearchConfigAPI', () => { id: undefined, groups: [], isAdmin: false, - canCreatePersonalSources: false, + canCreatePrivateSources: false, viewedOnboardingPage: false, }, }, @@ -198,13 +198,13 @@ describe('callEnterpriseSearchConfigAPI', () => { }); it('handles server errors', async () => { - ((fetch as unknown) as jest.Mock).mockReturnValueOnce(Promise.reject('500')); + (fetch as unknown as jest.Mock).mockReturnValueOnce(Promise.reject('500')); expect(await callEnterpriseSearchConfigAPI(mockDependencies)).toEqual({}); expect(mockDependencies.log.error).toHaveBeenCalledWith( 'Could not perform access check to Enterprise Search: 500' ); - ((fetch as unknown) as jest.Mock).mockReturnValueOnce(Promise.resolve('Bad Data')); + (fetch as unknown as jest.Mock).mockReturnValueOnce(Promise.resolve('Bad Data')); expect(await callEnterpriseSearchConfigAPI(mockDependencies)).toEqual({}); expect(mockDependencies.log.error).toHaveBeenCalledWith( 'Could not perform access check to Enterprise Search: TypeError: response.json is not a function' @@ -222,7 +222,7 @@ describe('callEnterpriseSearchConfigAPI', () => { ); // Timeout - ((fetch as unknown) as jest.Mock).mockImplementationOnce(async () => { + (fetch as unknown as jest.Mock).mockImplementationOnce(async () => { jest.advanceTimersByTime(250); return Promise.reject({ name: 'AbortError' }); }); diff --git a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.ts b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.ts index fb3c3b14911a5..146b06e4d9a4c 100644 --- a/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.ts +++ b/x-pack/plugins/enterprise_search/server/lib/enterprise_search_config_api.ts @@ -124,10 +124,10 @@ export const callEnterpriseSearchConfigAPI = async ({ id: data?.current_user?.workplace_search?.account?.id, groups: data?.current_user?.workplace_search?.account?.groups || [], isAdmin: !!data?.current_user?.workplace_search?.account?.is_admin, - canCreatePersonalSources: !!data?.current_user?.workplace_search?.account - ?.can_create_personal_sources, - viewedOnboardingPage: !!data?.current_user?.workplace_search?.account - ?.viewed_onboarding_page, + canCreatePrivateSources: + !!data?.current_user?.workplace_search?.account?.can_create_private_sources, + viewedOnboardingPage: + !!data?.current_user?.workplace_search?.account?.viewed_onboarding_page, }, }, }; diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.test.ts index db554d1cec93f..018ab433536b2 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.test.ts @@ -60,8 +60,7 @@ describe('crawler crawl rules routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'put', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', }); registerCrawlerCrawlRulesRoutes({ @@ -105,8 +104,7 @@ describe('crawler crawl rules routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'delete', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', }); registerCrawlerCrawlRulesRoutes({ diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.ts index a360129b07523..7c82c73db7263 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_crawl_rules.ts @@ -38,8 +38,7 @@ export function registerCrawlerCrawlRulesRoutes({ router.put( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', validate: { params: schema.object({ engineName: schema.string(), @@ -64,8 +63,7 @@ export function registerCrawlerCrawlRulesRoutes({ router.delete( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/crawl_rules/{crawlRuleId}', validate: { params: schema.object({ engineName: schema.string(), diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.test.ts index d59a8e32045ec..6fb7e99400877 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.test.ts @@ -58,8 +58,7 @@ describe('crawler entry point routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'put', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', }); registerCrawlerEntryPointRoutes({ @@ -100,8 +99,7 @@ describe('crawler entry point routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'delete', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', }); registerCrawlerEntryPointRoutes({ diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.ts index 224a79bbf6cb8..a6d6fdb24b41f 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_entry_points.ts @@ -36,8 +36,7 @@ export function registerCrawlerEntryPointRoutes({ router.put( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', validate: { params: schema.object({ engineName: schema.string(), @@ -59,8 +58,7 @@ export function registerCrawlerEntryPointRoutes({ router.delete( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/entry_points/{entryPointId}', validate: { params: schema.object({ engineName: schema.string(), diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.test.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.test.ts index 88fef87e60470..a37a8311093c7 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.test.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.test.ts @@ -58,8 +58,7 @@ describe('crawler sitemap routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'put', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', }); registerCrawlerSitemapRoutes({ @@ -100,8 +99,7 @@ describe('crawler sitemap routes', () => { jest.clearAllMocks(); mockRouter = new MockRouter({ method: 'delete', - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', }); registerCrawlerSitemapRoutes({ diff --git a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.ts b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.ts index c3ae90349b95a..b63473888eecc 100644 --- a/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.ts +++ b/x-pack/plugins/enterprise_search/server/routes/app_search/crawler_sitemaps.ts @@ -36,8 +36,7 @@ export function registerCrawlerSitemapRoutes({ router.put( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', validate: { params: schema.object({ engineName: schema.string(), @@ -59,8 +58,7 @@ export function registerCrawlerSitemapRoutes({ router.delete( { - path: - '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', + path: '/internal/app_search/engines/{engineName}/crawler/domains/{domainId}/sitemaps/{sitemapId}', validate: { params: schema.object({ engineName: schema.string(), diff --git a/x-pack/plugins/event_log/server/es/init.ts b/x-pack/plugins/event_log/server/es/init.ts index bc1b36ab3e375..f15b9f89887c5 100644 --- a/x-pack/plugins/event_log/server/es/init.ts +++ b/x-pack/plugins/event_log/server/es/init.ts @@ -96,8 +96,9 @@ class EsInitializationSteps { } asyncForEach(Object.keys(indices), async (indexName: string) => { try { - const hidden: string | boolean | undefined = (indices[indexName] - ?.settings as IndicesIndexStatePrefixedSettings)?.index?.hidden; + const hidden: string | boolean | undefined = ( + indices[indexName]?.settings as IndicesIndexStatePrefixedSettings + )?.index?.hidden; // Check to see if this index template is hidden if (hidden !== true && hidden !== 'true') { diff --git a/x-pack/plugins/event_log/server/event_log_client.test.ts b/x-pack/plugins/event_log/server/event_log_client.test.ts index 6babfef9bd8a8..0acb53e93b81a 100644 --- a/x-pack/plugins/event_log/server/event_log_client.test.ts +++ b/x-pack/plugins/event_log/server/event_log_client.test.ts @@ -322,7 +322,7 @@ function fakeEvent(overrides = {}) { function FakeRequest(): KibanaRequest { const savedObjectGetter = jest.fn(); - return ({ + return { headers: {}, getBasePath: () => '', path: '/', @@ -336,5 +336,5 @@ function FakeRequest(): KibanaRequest { }, }, getSavedObjectsClient: () => savedObjectGetter, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; } diff --git a/x-pack/plugins/event_log/server/event_log_start_service.test.ts b/x-pack/plugins/event_log/server/event_log_start_service.test.ts index 0815673d546b2..1534623100f5d 100644 --- a/x-pack/plugins/event_log/server/event_log_start_service.test.ts +++ b/x-pack/plugins/event_log/server/event_log_start_service.test.ts @@ -44,7 +44,7 @@ describe('EventLogClientService', () => { function fakeRequest(): KibanaRequest { const savedObjectsClient = savedObjectsClientMock.create(); - return ({ + return { headers: {}, getBasePath: () => '', path: '/', @@ -58,5 +58,5 @@ function fakeRequest(): KibanaRequest { }, }, getSavedObjectsClient: () => savedObjectsClient, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; } diff --git a/x-pack/plugins/event_log/server/event_logger.test.ts b/x-pack/plugins/event_log/server/event_logger.test.ts index 9dcfa37ae76b1..d90fd93c60043 100644 --- a/x-pack/plugins/event_log/server/event_logger.test.ts +++ b/x-pack/plugins/event_log/server/event_logger.test.ts @@ -188,7 +188,7 @@ describe('EventLogger', () => { service.registerProviderActions('provider', ['action-a']); eventLogger = service.getLogger({}); - eventLogger.logEvent(({ event: { PROVIDER: 'provider' } } as unknown) as IEvent); + eventLogger.logEvent({ event: { PROVIDER: 'provider' } } as unknown as IEvent); let message = await waitForLogMessage(systemLogger); expect(message).toMatch(/invalid event logged.*provider.*undefined.*/); diff --git a/x-pack/plugins/event_log/server/routes/_mock_handler_arguments.ts b/x-pack/plugins/event_log/server/routes/_mock_handler_arguments.ts index 7563359e2dd16..3cd8e5eaae2ba 100644 --- a/x-pack/plugins/event_log/server/routes/_mock_handler_arguments.ts +++ b/x-pack/plugins/event_log/server/routes/_mock_handler_arguments.ts @@ -18,13 +18,13 @@ export function mockHandlerArguments( res?: Array> ): [RequestHandlerContext, KibanaRequest, KibanaResponseFactory] { return [ - ({ + { eventLog: { getEventLogClient() { return eventLogClient; }, }, - } as unknown) as RequestHandlerContext, + } as unknown as RequestHandlerContext, req as KibanaRequest, mockResponseFactory(res), ]; @@ -39,7 +39,7 @@ export const mockResponseFactory = (resToMock: Array { - return ({ + return { registerProvider: jest.fn(), registerDefaultProvider: jest.fn(), getProvidersClient: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; }; export const savedObjectProviderRegistryMock = { diff --git a/x-pack/plugins/event_log/server/saved_object_provider_registry.test.ts b/x-pack/plugins/event_log/server/saved_object_provider_registry.test.ts index c9a7d4f855153..d3b4ec4648b9f 100644 --- a/x-pack/plugins/event_log/server/saved_object_provider_registry.test.ts +++ b/x-pack/plugins/event_log/server/saved_object_provider_registry.test.ts @@ -83,7 +83,7 @@ describe('SavedObjectProviderRegistry', () => { function fakeRequest(): KibanaRequest { const savedObjectsClient = savedObjectsClientMock.create(); - return ({ + return { headers: {}, getBasePath: () => '', path: '/', @@ -97,5 +97,5 @@ function fakeRequest(): KibanaRequest { }, }, getSavedObjectsClient: () => savedObjectsClient, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; } diff --git a/x-pack/plugins/features/server/feature_privilege_iterator/sub_feature_privilege_iterator.ts b/x-pack/plugins/features/server/feature_privilege_iterator/sub_feature_privilege_iterator.ts index 4e43643338830..8dffd553bfe14 100644 --- a/x-pack/plugins/features/server/feature_privilege_iterator/sub_feature_privilege_iterator.ts +++ b/x-pack/plugins/features/server/feature_privilege_iterator/sub_feature_privilege_iterator.ts @@ -19,17 +19,18 @@ export type SubFeaturePrivilegeIterator = ( licenseHasAtLeast: (licenseType: LicenseType) => boolean | undefined ) => IterableIterator; -const subFeaturePrivilegeIterator: SubFeaturePrivilegeIterator = function* subFeaturePrivilegeIterator( - feature: KibanaFeature, - licenseHasAtLeast: (licenseType: LicenseType) => boolean | undefined -): IterableIterator { - for (const subFeature of feature.subFeatures) { - for (const group of subFeature.privilegeGroups) { - yield* group.privileges.filter( - (privilege) => !privilege.minimumLicense || licenseHasAtLeast(privilege.minimumLicense) - ); +const subFeaturePrivilegeIterator: SubFeaturePrivilegeIterator = + function* subFeaturePrivilegeIterator( + feature: KibanaFeature, + licenseHasAtLeast: (licenseType: LicenseType) => boolean | undefined + ): IterableIterator { + for (const subFeature of feature.subFeatures) { + for (const group of subFeature.privilegeGroups) { + yield* group.privileges.filter( + (privilege) => !privilege.minimumLicense || licenseHasAtLeast(privilege.minimumLicense) + ); + } } - } -}; + }; export { subFeaturePrivilegeIterator }; diff --git a/x-pack/plugins/features/server/feature_schema.ts b/x-pack/plugins/features/server/feature_schema.ts index 96d79982afcf1..2694620c62d3f 100644 --- a/x-pack/plugins/features/server/feature_schema.ts +++ b/x-pack/plugins/features/server/feature_schema.ts @@ -152,11 +152,10 @@ const kibanaIndependentSubFeaturePrivilegeSchema = schema.object({ ui: listOfCapabilitiesSchema, }); -const kibanaMutuallyExclusiveSubFeaturePrivilegeSchema = kibanaIndependentSubFeaturePrivilegeSchema.extends( - { +const kibanaMutuallyExclusiveSubFeaturePrivilegeSchema = + kibanaIndependentSubFeaturePrivilegeSchema.extends({ minimumLicense: schema.never(), - } -); + }); const kibanaSubFeatureSchema = schema.object({ name: schema.string(), diff --git a/x-pack/plugins/features/server/plugin.ts b/x-pack/plugins/features/server/plugin.ts index c1fbc4b8a5edb..b11c77b60e66d 100644 --- a/x-pack/plugins/features/server/plugin.ts +++ b/x-pack/plugins/features/server/plugin.ts @@ -85,8 +85,8 @@ export interface PluginStartContract { * Represents Features Plugin instance that will be managed by the Kibana plugin system. */ export class FeaturesPlugin - implements - Plugin, RecursiveReadonly> { + implements Plugin, RecursiveReadonly> +{ private readonly logger: Logger; private readonly featureRegistry: FeatureRegistry = new FeatureRegistry(); private isReportingEnabled: boolean = false; diff --git a/x-pack/plugins/file_upload/public/components/json_upload_and_parse.tsx b/x-pack/plugins/file_upload/public/components/json_upload_and_parse.tsx index 28e99e7ffb18b..1fd96544918c8 100644 --- a/x-pack/plugins/file_upload/public/components/json_upload_and_parse.tsx +++ b/x-pack/plugins/file_upload/public/components/json_upload_and_parse.tsx @@ -100,9 +100,9 @@ export class JsonUploadAndParse extends Component { + > +{ public setup() {} public start(core: CoreStart, plugins: FileUploadStartDependencies): FileUploadStartApi { diff --git a/x-pack/plugins/file_upload/server/capabilities.test.ts b/x-pack/plugins/file_upload/server/capabilities.test.ts index 2fc666c837961..53f9da26060af 100644 --- a/x-pack/plugins/file_upload/server/capabilities.test.ts +++ b/x-pack/plugins/file_upload/server/capabilities.test.ts @@ -61,7 +61,7 @@ describe('setupCapabilities', () => { const security = securityMock.createStart(); security.authz.mode.useRbacForRequest.mockReturnValue(true); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); @@ -104,7 +104,7 @@ describe('setupCapabilities', () => { const mockCheckPrivileges = jest.fn().mockResolvedValue({ hasAllRequested: false }); security.authz.checkPrivilegesDynamicallyWithRequest.mockReturnValue(mockCheckPrivileges); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); @@ -146,7 +146,7 @@ describe('setupCapabilities', () => { const mockCheckPrivileges = jest.fn().mockResolvedValue({ hasAllRequested: true }); security.authz.checkPrivilegesDynamicallyWithRequest.mockReturnValue(mockCheckPrivileges); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); @@ -192,7 +192,7 @@ describe('setupCapabilities', () => { .mockRejectedValue(new Error('this should not have been called')); security.authz.checkPrivilegesDynamicallyWithRequest.mockReturnValue(mockCheckPrivileges); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); @@ -229,7 +229,7 @@ describe('setupCapabilities', () => { const security = securityMock.createStart(); security.authz.mode.useRbacForRequest.mockReturnValue(false); coreSetup.getStartServices.mockResolvedValue([ - (undefined as unknown) as CoreStart, + undefined as unknown as CoreStart, { security }, undefined, ]); diff --git a/x-pack/plugins/file_upload/server/routes.ts b/x-pack/plugins/file_upload/server/routes.ts index c957916e7f321..cb7c37a586b64 100644 --- a/x-pack/plugins/file_upload/server/routes.ts +++ b/x-pack/plugins/file_upload/server/routes.ts @@ -187,9 +187,8 @@ export function fileUploadRoutes(coreSetup: CoreSetup, logge }, async (context, request, response) => { try { - const { - body: indexExists, - } = await context.core.elasticsearch.client.asCurrentUser.indices.exists(request.body); + const { body: indexExists } = + await context.core.elasticsearch.client.asCurrentUser.indices.exists(request.body); return response.ok({ body: { exists: indexExists } }); } catch (e) { return response.customError(wrapError(e)); diff --git a/x-pack/plugins/fleet/common/services/decode_cloud_id.ts b/x-pack/plugins/fleet/common/services/decode_cloud_id.ts index e4952e6b22356..2afc15e8f71b5 100644 --- a/x-pack/plugins/fleet/common/services/decode_cloud_id.ts +++ b/x-pack/plugins/fleet/common/services/decode_cloud_id.ts @@ -6,9 +6,7 @@ */ // decodeCloudId decodes the c.id into c.esURL and c.kibURL -export function decodeCloudId( - cid: string -): +export function decodeCloudId(cid: string): | { host: string; defaultPort: string; diff --git a/x-pack/plugins/fleet/common/services/package_to_package_policy.test.ts b/x-pack/plugins/fleet/common/services/package_to_package_policy.test.ts index 0e5cab08edfb7..275cf237a9621 100644 --- a/x-pack/plugins/fleet/common/services/package_to_package_policy.test.ts +++ b/x-pack/plugins/fleet/common/services/package_to_package_policy.test.ts @@ -58,25 +58,25 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns empty array for packages with a config template but no inputs', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, policy_templates: [{ name: 'test_template', inputs: [] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([]); }); it('returns inputs with no streams for packages with no streams', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, policy_templates: [{ name: 'test_template', inputs: [{ type: 'foo' }] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([{ type: 'foo', enabled: true, policy_template: 'test_template', streams: [] }]); expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, policy_templates: [{ name: 'test_template', inputs: [{ type: 'foo' }, { type: 'bar' }] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([ { type: 'foo', enabled: true, policy_template: 'test_template', streams: [] }, { type: 'bar', enabled: true, policy_template: 'test_template', streams: [] }, @@ -85,7 +85,7 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns inputs with streams for packages with streams', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, data_streams: [ { type: 'logs', dataset: 'foo', streams: [{ input: 'foo' }] }, @@ -93,7 +93,7 @@ describe('Fleet - packageToPackagePolicy', () => { { type: 'logs', dataset: 'bar2', streams: [{ input: 'bar' }] }, ], policy_templates: [{ name: 'test_template', inputs: [{ type: 'foo' }, { type: 'bar' }] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([ { type: 'foo', @@ -127,7 +127,7 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns inputs with streams configurations for packages with stream vars', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, data_streams: [ { @@ -157,7 +157,7 @@ describe('Fleet - packageToPackagePolicy', () => { }, ], policy_templates: [{ name: 'test_template', inputs: [{ type: 'foo' }, { type: 'bar' }] }], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([ { type: 'foo', @@ -193,7 +193,7 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns inputs with streams configurations for packages with stream and input vars', () => { expect( - packageToPackagePolicyInputs(({ + packageToPackagePolicyInputs({ ...mockPackage, data_streams: [ { @@ -268,7 +268,7 @@ describe('Fleet - packageToPackagePolicy', () => { ], }, ], - } as unknown) as PackageInfo) + } as unknown as PackageInfo) ).toEqual([ { type: 'foo', @@ -399,10 +399,10 @@ describe('Fleet - packageToPackagePolicy', () => { }); it('returns package policy with inputs', () => { - const mockPackageWithPolicyTemplates = ({ + const mockPackageWithPolicyTemplates = { ...mockPackage, policy_templates: [{ inputs: [{ type: 'foo' }] }], - } as unknown) as PackageInfo; + } as unknown as PackageInfo; expect( packageToPackagePolicy(mockPackageWithPolicyTemplates, '1', '2', 'default', 'pkgPolicy-1') @@ -424,7 +424,7 @@ describe('Fleet - packageToPackagePolicy', () => { it('returns package policy with multiple policy templates (aka has integrations', () => { expect( packageToPackagePolicy( - (AWS_PACKAGE as unknown) as PackageInfo, + AWS_PACKAGE as unknown as PackageInfo, 'some-agent-policy-id', 'some-output-id', 'default', diff --git a/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts b/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts index 30bd9f071feb8..306d31879e0c6 100644 --- a/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts +++ b/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts @@ -15,7 +15,7 @@ import { AWS_PACKAGE, INVALID_AWS_POLICY, VALID_AWS_POLICY } from './fixtures/aw describe('Fleet - validatePackagePolicy()', () => { describe('works for packages with single policy template (aka no integrations)', () => { - const mockPackage = ({ + const mockPackage = { name: 'mock-package', title: 'Mock package', version: '0.0.0', @@ -152,7 +152,7 @@ describe('Fleet - validatePackagePolicy()', () => { ], }, ], - } as unknown) as PackageInfo; + } as unknown as PackageInfo; const validPackagePolicy: NewPackagePolicy = { name: 'pkgPolicy1-1', @@ -544,7 +544,7 @@ describe('Fleet - validatePackagePolicy()', () => { validPackagePolicy, { ...mockPackage, - policy_templates: [({ inputs: [] } as unknown) as RegistryPolicyTemplate], + policy_templates: [{ inputs: [] } as unknown as RegistryPolicyTemplate], }, safeLoad ) @@ -562,7 +562,7 @@ describe('Fleet - validatePackagePolicy()', () => { expect( validatePackagePolicy( INVALID_AWS_POLICY as NewPackagePolicy, - (AWS_PACKAGE as unknown) as PackageInfo, + AWS_PACKAGE as unknown as PackageInfo, safeLoad ) ).toMatchSnapshot(); @@ -573,7 +573,7 @@ describe('Fleet - validatePackagePolicy()', () => { validationHasErrors( validatePackagePolicy( VALID_AWS_POLICY as NewPackagePolicy, - (AWS_PACKAGE as unknown) as PackageInfo, + AWS_PACKAGE as unknown as PackageInfo, safeLoad ) ) diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx index bce48d3108aa7..050177850818a 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/package_policy_input_panel.tsx @@ -86,9 +86,10 @@ export const PackagePolicyInputPanel: React.FunctionComponent<{ const errorCount = countValidationErrors(inputValidationResults); const hasErrors = forceShowErrors && errorCount; - const hasInputStreams = useMemo(() => packageInputStreams.length > 0, [ - packageInputStreams.length, - ]); + const hasInputStreams = useMemo( + () => packageInputStreams.length > 0, + [packageInputStreams.length] + ); const inputStreams = useMemo( () => packageInputStreams diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx index 5e00bce5d6c69..a83f6902ed056 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/index.tsx @@ -91,9 +91,10 @@ export const CreatePackagePolicyPage: React.FunctionComponent = () => { const { search } = useLocation(); const queryParams = useMemo(() => new URLSearchParams(search), [search]); - const queryParamsPolicyId = useMemo(() => queryParams.get('policyId') ?? undefined, [ - queryParams, - ]); + const queryParamsPolicyId = useMemo( + () => queryParams.get('policyId') ?? undefined, + [queryParams] + ); /** * Please note: policyId can come from one of two sources. The URL param (in the URL path) or diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx index e2f5a7249ff0a..63cf1a0c87b29 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/step_select_agent_policy.tsx @@ -65,9 +65,8 @@ export const StepSelectAgentPolicy: React.FunctionComponent<{ // Create new agent policy flyout state const hasWriteCapabilites = useCapabilities().write; - const [isCreateAgentPolicyFlyoutOpen, setIsCreateAgentPolicyFlyoutOpen] = useState( - false - ); + const [isCreateAgentPolicyFlyoutOpen, setIsCreateAgentPolicyFlyoutOpen] = + useState(false); // Fetch package info const { diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/index.tsx index 9d3fe64b6639d..eec7d80b75c4b 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/details_page/index.tsx @@ -312,7 +312,7 @@ export const AgentPolicyDetailsPage: React.FunctionComponent = () => { {content} diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx index 040070bcff7c4..d887076568a68 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.tsx @@ -97,9 +97,8 @@ export const EditPackagePolicyForm = memo<{ inputs: [], version: '', }); - const [originalPackagePolicy, setOriginalPackagePolicy] = useState< - GetOnePackagePolicyResponse['item'] - >(); + const [originalPackagePolicy, setOriginalPackagePolicy] = + useState(); const [dryRunData, setDryRunData] = useState(); const policyId = agentPolicy?.id ?? ''; @@ -110,10 +109,8 @@ export const EditPackagePolicyForm = memo<{ setIsLoadingData(true); setLoadingError(undefined); try { - const { - data: packagePolicyData, - error: packagePolicyError, - } = await sendGetOnePackagePolicy(packagePolicyId); + const { data: packagePolicyData, error: packagePolicyError } = + await sendGetOnePackagePolicy(packagePolicyId); if (packagePolicyError) { throw packagePolicyError; diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/list_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/list_page/index.tsx index 10859e32f0080..b940086effeaa 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/list_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/list_page/index.tsx @@ -78,7 +78,11 @@ export const AgentPolicyListPage: React.FunctionComponent<{}> = () => { ); // Fetch agent policies - const { isLoading, data: agentPolicyData, resendRequest } = useGetAgentPolicies({ + const { + isLoading, + data: agentPolicyData, + resendRequest, + } = useGetAgentPolicies({ page: pagination.currentPage, perPage: pagination.pageSize, sortField: sorting?.field, diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/agent_logs.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/agent_logs.tsx index f927bdcc2e518..783a960aff120 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/agent_logs.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/agent_logs.tsx @@ -245,9 +245,10 @@ export const AgentLogsUI: React.FunctionComponent = memo( // Set absolute height on logs component (needed to render correctly in Safari) // based on available height, or 600px, whichever is greater const [logsPanelRef, { height: measuredlogPanelHeight }] = useMeasure(); - const logPanelHeight = useMemo(() => Math.max(measuredlogPanelHeight, 600), [ - measuredlogPanelHeight, - ]); + const logPanelHeight = useMemo( + () => Math.max(measuredlogPanelHeight, 600), + [measuredlogPanelHeight] + ); if (!isLogFeatureAvailable) { return ( diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/index.tsx index c138d23cce93b..5411e6313ebb7 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/index.tsx @@ -22,59 +22,58 @@ import { DEFAULT_LOGS_STATE, STATE_STORAGE_KEY } from './constants'; import type { AgentLogsProps, AgentLogsState } from './agent_logs'; import { AgentLogsUI, AgentLogsUrlStateHelper } from './agent_logs'; -export const AgentLogs: React.FunctionComponent< - Pick -> = memo(({ agent, agentPolicy }) => { - const stateContainer = useMemo( - () => - createStateContainer< - AgentLogsState, - { - update: PureTransition]>; - } - >( - { - ...DEFAULT_LOGS_STATE, - ...getStateFromKbnUrl(STATE_STORAGE_KEY, window.location.href, { - getFromHashQuery: false, - }), - }, - { - update: (state) => (updatedState) => ({ ...state, ...updatedState }), - } - ), - [] - ); +export const AgentLogs: React.FunctionComponent> = + memo(({ agent, agentPolicy }) => { + const stateContainer = useMemo( + () => + createStateContainer< + AgentLogsState, + { + update: PureTransition]>; + } + >( + { + ...DEFAULT_LOGS_STATE, + ...getStateFromKbnUrl(STATE_STORAGE_KEY, window.location.href, { + getFromHashQuery: false, + }), + }, + { + update: (state) => (updatedState) => ({ ...state, ...updatedState }), + } + ), + [] + ); - const AgentLogsConnected = useMemo( - () => - AgentLogsUrlStateHelper.connect((state) => ({ - state: state || DEFAULT_LOGS_STATE, - }))(AgentLogsUI), - [] - ); + const AgentLogsConnected = useMemo( + () => + AgentLogsUrlStateHelper.connect((state) => ({ + state: state || DEFAULT_LOGS_STATE, + }))(AgentLogsUI), + [] + ); - const [isSyncReady, setIsSyncReady] = useState(false); + const [isSyncReady, setIsSyncReady] = useState(false); - useEffect(() => { - const stateStorage = createKbnUrlStateStorage(); - const { start, stop } = syncState({ - storageKey: STATE_STORAGE_KEY, - stateContainer: stateContainer as INullableBaseStateContainer, - stateStorage, - }); - start(); - setIsSyncReady(true); + useEffect(() => { + const stateStorage = createKbnUrlStateStorage(); + const { start, stop } = syncState({ + storageKey: STATE_STORAGE_KEY, + stateContainer: stateContainer as INullableBaseStateContainer, + stateStorage, + }); + start(); + setIsSyncReady(true); - return () => { - stop(); - stateContainer.set(DEFAULT_LOGS_STATE); - }; - }, [stateContainer]); + return () => { + stop(); + stateContainer.set(DEFAULT_LOGS_STATE); + }; + }, [stateContainer]); - return ( - - {isSyncReady ? : null} - - ); -}); + return ( + + {isSyncReady ? : null} + + ); + }); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/index.tsx index d2342dafca2eb..f3430110ba283 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/agent_details_page/index.tsx @@ -254,7 +254,7 @@ export const AgentDetailsPage: React.FunctionComponent = () => { {isLoading && isInitialRequest ? ( diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/index.tsx index 494541a00fc0a..18a684baad60d 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agents/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agents/index.tsx @@ -39,9 +39,10 @@ export const AgentsApp: React.FunctionComponent = () => { perPage: 1000, }); - const agentPolicies = useMemo(() => agentPoliciesRequest.data?.items || [], [ - agentPoliciesRequest.data, - ]); + const agentPolicies = useMemo( + () => agentPoliciesRequest.data?.items || [], + [agentPoliciesRequest.data] + ); const fleetStatus = useFleetStatus(); diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx index 26869f8fea574..fadcbdd70c28d 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/index.tsx @@ -79,6 +79,13 @@ const FlexItemWithMinWidth = styled(EuiFlexItem)` min-width: 0px; `; +// to limit size of iconpanel, making the header too big +const FlexItemWithMaxHeight = styled(EuiFlexItem)` + @media (min-width: 768px) { + max-height: 60px; + } +`; + function Breadcrumbs({ packageTitle }: { packageTitle: string }) { useBreadcrumbs('integration_details_overview', { pkgTitle: packageTitle }); return null; @@ -117,9 +124,11 @@ export function Detail() { semverLt(packageInfo.savedObject.attributes.version, packageInfo.latestVersion); // Fetch package info - const { data: packageInfoData, error: packageInfoError, isLoading } = useGetPackageInfoByKey( - pkgkey - ); + const { + data: packageInfoData, + error: packageInfoError, + isLoading, + } = useGetPackageInfoByKey(pkgkey); const showCustomTab = useUIExtension(packageInfoData?.response.name ?? '', 'package-detail-custom') !== undefined; @@ -173,7 +182,7 @@ export function Detail() { - + {isLoading || !packageInfo ? ( ) : ( @@ -184,7 +193,7 @@ export function Detail() { icons={integrationInfo?.icons || packageInfo.icons} /> )} - + diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/overview/overview.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/overview/overview.tsx index 945859ac81ffd..0b477fee2ba77 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/overview/overview.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/overview/overview.tsx @@ -27,10 +27,10 @@ const LeftColumn = styled(EuiFlexItem)` `; export const OverviewPage: React.FC = memo(({ packageInfo, integrationInfo }) => { - const screenshots = useMemo(() => integrationInfo?.screenshots || packageInfo.screenshots || [], [ - integrationInfo, - packageInfo.screenshots, - ]); + const screenshots = useMemo( + () => integrationInfo?.screenshots || packageInfo.screenshots || [], + [integrationInfo, packageInfo.screenshots] + ); return ( diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx index 07a61410e9a6b..92b4012011fc8 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/package_policies.tsx @@ -84,9 +84,10 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps const { search } = useLocation(); const history = useHistory(); const queryParams = useMemo(() => new URLSearchParams(search), [search]); - const agentPolicyIdFromParams = useMemo(() => queryParams.get('addAgentToPolicyId'), [ - queryParams, - ]); + const agentPolicyIdFromParams = useMemo( + () => queryParams.get('addAgentToPolicyId'), + [queryParams] + ); const [flyoutOpenForPolicyId, setFlyoutOpenForPolicyId] = useState( agentPolicyIdFromParams ); @@ -94,7 +95,11 @@ export const PackagePoliciesPage = ({ name, version }: PackagePoliciesPanelProps const getPackageInstallStatus = useGetPackageInstallStatus(); const packageInstallStatus = getPackageInstallStatus(name); const { pagination, pageSizeOptions, setPagination } = useUrlPagination(); - const { data, isLoading, resendRequest: refreshPolicies } = usePackagePoliciesWithAgentPolicy({ + const { + data, + isLoading, + resendRequest: refreshPolicies, + } = usePackagePoliciesWithAgentPolicy({ page: pagination.currentPage, perPage: pagination.pageSize, kuery: `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name: ${name}`, diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/use_package_policies_with_agent_policy.ts b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/use_package_policies_with_agent_policy.ts index 33c1d3ff77302..4f6f456bf82cd 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/use_package_policies_with_agent_policy.ts +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/policies/use_package_policies_with_agent_policy.ts @@ -74,18 +74,16 @@ export const usePackagePoliciesWithAgentPolicy = ( .join(' or ')}) `; }, [packagePoliciesData]); - const { - data: agentPoliciesData, - isLoading: isLoadingAgentPolicies, - } = useConditionalRequest({ - path: agentPolicyRouteService.getListPath(), - method: 'get', - query: { - perPage: 100, - kuery: agentPoliciesFilter, - }, - shouldSendRequest: !!packagePoliciesData?.items.length, - } as SendConditionalRequestConfig); + const { data: agentPoliciesData, isLoading: isLoadingAgentPolicies } = + useConditionalRequest({ + path: agentPolicyRouteService.getListPath(), + method: 'get', + query: { + perPage: 100, + kuery: agentPoliciesFilter, + }, + shouldSendRequest: !!packagePoliciesData?.items.length, + } as SendConditionalRequestConfig); const [enrichedData, setEnrichedData] = useState(); diff --git a/x-pack/plugins/fleet/public/components/package_icon.tsx b/x-pack/plugins/fleet/public/components/package_icon.tsx index bb84a79056978..df0bd9864b60f 100644 --- a/x-pack/plugins/fleet/public/components/package_icon.tsx +++ b/x-pack/plugins/fleet/public/components/package_icon.tsx @@ -12,9 +12,8 @@ import { EuiIcon } from '@elastic/eui'; import type { UsePackageIconType } from '../hooks'; import { usePackageIconType } from '../hooks'; -export const PackageIcon: React.FunctionComponent< - UsePackageIconType & Omit -> = ({ packageName, integrationName, version, icons, tryApi, ...euiIconProps }) => { - const iconType = usePackageIconType({ packageName, integrationName, version, icons, tryApi }); - return ; -}; +export const PackageIcon: React.FunctionComponent> = + ({ packageName, integrationName, version, icons, tryApi, ...euiIconProps }) => { + const iconType = usePackageIconType({ packageName, integrationName, version, icons, tryApi }); + return ; + }; diff --git a/x-pack/plugins/fleet/public/components/package_policy_delete_provider.tsx b/x-pack/plugins/fleet/public/components/package_policy_delete_provider.tsx index 86f064405497b..e2522f40ef966 100644 --- a/x-pack/plugins/fleet/public/components/package_policy_delete_provider.tsx +++ b/x-pack/plugins/fleet/public/components/package_policy_delete_provider.tsx @@ -63,15 +63,16 @@ export const PackagePolicyDeleteProvider: React.FunctionComponent = ({ ); const deletePackagePoliciesPrompt = useMemo( - (): DeletePackagePoliciesPrompt => (packagePoliciesToDelete, onSuccess = () => undefined) => { - if (!Array.isArray(packagePoliciesToDelete) || packagePoliciesToDelete.length === 0) { - throw new Error('No package policies specified for deletion'); - } - setIsModalOpen(true); - setPackagePolicies(packagePoliciesToDelete); - fetchAgentsCount(); - onSuccessCallback.current = onSuccess; - }, + (): DeletePackagePoliciesPrompt => + (packagePoliciesToDelete, onSuccess = () => undefined) => { + if (!Array.isArray(packagePoliciesToDelete) || packagePoliciesToDelete.length === 0) { + throw new Error('No package policies specified for deletion'); + } + setIsModalOpen(true); + setPackagePolicies(packagePoliciesToDelete); + fetchAgentsCount(); + onSuccessCallback.current = onSuccess; + }, [fetchAgentsCount] ); diff --git a/x-pack/plugins/fleet/public/constants/page_paths.ts b/x-pack/plugins/fleet/public/constants/page_paths.ts index 93ef0d56b17a6..e430e58d297f9 100644 --- a/x-pack/plugins/fleet/public/constants/page_paths.ts +++ b/x-pack/plugins/fleet/public/constants/page_paths.ts @@ -81,10 +81,9 @@ export const INTEGRATIONS_ROUTING_PATHS = { export const pagePathGetters: { [key in StaticPage]: () => [string, string]; -} & - { - [key in DynamicPage]: (values: DynamicPagePathValues) => [string, string]; - } = { +} & { + [key in DynamicPage]: (values: DynamicPagePathValues) => [string, string]; +} = { base: () => [FLEET_BASE_PATH, '/'], overview: () => [FLEET_BASE_PATH, '/'], integrations: () => [INTEGRATIONS_BASE_PATH, '/'], diff --git a/x-pack/plugins/fleet/public/services/ui_extensions.test.ts b/x-pack/plugins/fleet/public/services/ui_extensions.test.ts index d23219c1f653b..779fd28ebcd18 100644 --- a/x-pack/plugins/fleet/public/services/ui_extensions.test.ts +++ b/x-pack/plugins/fleet/public/services/ui_extensions.test.ts @@ -31,7 +31,7 @@ describe('UI Extension services', () => { it('should store an extension points', () => { const LazyCustomView = lazy(async () => { - return { default: ((() => {}) as unknown) as PackagePolicyEditExtensionComponent }; + return { default: (() => {}) as unknown as PackagePolicyEditExtensionComponent }; }); register({ view: 'package-policy-edit', @@ -48,10 +48,10 @@ describe('UI Extension services', () => { it('should throw if extension point has already registered', () => { const LazyCustomView = lazy(async () => { - return { default: ((() => {}) as unknown) as PackagePolicyEditExtensionComponent }; + return { default: (() => {}) as unknown as PackagePolicyEditExtensionComponent }; }); const LazyCustomView2 = lazy(async () => { - return { default: ((() => {}) as unknown) as PackagePolicyEditExtensionComponent }; + return { default: (() => {}) as unknown as PackagePolicyEditExtensionComponent }; }); register({ diff --git a/x-pack/plugins/fleet/public/types/ui_extensions.ts b/x-pack/plugins/fleet/public/types/ui_extensions.ts index 40e92fe86555d..d365b798fe83e 100644 --- a/x-pack/plugins/fleet/public/types/ui_extensions.ts +++ b/x-pack/plugins/fleet/public/types/ui_extensions.ts @@ -22,7 +22,8 @@ export interface UIExtensionsStorage { * UI Component Extension is used on the pages displaying the ability to edit an * Integration Policy */ -export type PackagePolicyEditExtensionComponent = ComponentType; +export type PackagePolicyEditExtensionComponent = + ComponentType; export interface PackagePolicyEditExtensionComponentProps { /** The current integration policy being edited */ @@ -66,7 +67,8 @@ export interface PackagePolicyEditTabsExtension { * UI Component Extension is used on the pages displaying the ability to Create an * Integration Policy */ -export type PackagePolicyCreateExtensionComponent = ComponentType; +export type PackagePolicyCreateExtensionComponent = + ComponentType; export interface PackagePolicyCreateExtensionComponentProps { /** The integration policy being created */ diff --git a/x-pack/plugins/fleet/server/collectors/agent_collectors.ts b/x-pack/plugins/fleet/server/collectors/agent_collectors.ts index 716c81573e85a..43c15e603a87a 100644 --- a/x-pack/plugins/fleet/server/collectors/agent_collectors.ts +++ b/x-pack/plugins/fleet/server/collectors/agent_collectors.ts @@ -37,14 +37,8 @@ export const getAgentUsage = async ( }; } - const { - total, - inactive, - online, - error, - offline, - updating, - } = await AgentService.getAgentStatusForAgentPolicy(esClient); + const { total, inactive, online, error, offline, updating } = + await AgentService.getAgentStatusForAgentPolicy(esClient); return { total_enrolled: total, healthy: online, diff --git a/x-pack/plugins/fleet/server/index.test.ts b/x-pack/plugins/fleet/server/index.test.ts index 924fecc311073..659c7d2761d02 100644 --- a/x-pack/plugins/fleet/server/index.test.ts +++ b/x-pack/plugins/fleet/server/index.test.ts @@ -21,7 +21,9 @@ const applyConfigDeprecations = (settings: Record = {}) => { deprecation, path: '', })), - () => ({ message }) => deprecationMessages.push(message) + () => + ({ message }) => + deprecationMessages.push(message) ); return { messages: deprecationMessages, diff --git a/x-pack/plugins/fleet/server/plugin.ts b/x-pack/plugins/fleet/server/plugin.ts index 9991f4ee20980..6aad028666ee8 100644 --- a/x-pack/plugins/fleet/server/plugin.ts +++ b/x-pack/plugins/fleet/server/plugin.ts @@ -159,7 +159,8 @@ export interface FleetStartContract { } export class FleetPlugin - implements AsyncPlugin { + implements AsyncPlugin +{ private licensing$!: Observable; private config$: Observable; private configInitialValue: FleetConfigType; diff --git a/x-pack/plugins/fleet/server/routes/agent/actions_handlers.test.ts b/x-pack/plugins/fleet/server/routes/agent/actions_handlers.test.ts index 3f300aef692ff..b31cda7cbf61d 100644 --- a/x-pack/plugins/fleet/server/routes/agent/actions_handlers.test.ts +++ b/x-pack/plugins/fleet/server/routes/agent/actions_handlers.test.ts @@ -73,13 +73,13 @@ describe('test actions handlers', () => { const mockRequest = httpServerMock.createKibanaRequest(postNewAgentActionRequest); - const agentAction = ({ + const agentAction = { type: 'POLICY_CHANGE', id: 'action1', sent_at: '2020-03-14T19:45:02.620Z', timestamp: '2019-01-04T14:32:03.36764-05:00', created_at: '2020-03-14T19:45:02.620Z', - } as unknown) as AgentAction; + } as unknown as AgentAction; const actionsService: ActionsService = { getAgent: jest.fn().mockReturnValueOnce({ @@ -90,7 +90,7 @@ describe('test actions handlers', () => { const postNewAgentActionHandler = postNewAgentActionHandlerBuilder(actionsService); await postNewAgentActionHandler( - ({ + { core: { savedObjects: { client: mockSavedObjectsClient, @@ -101,13 +101,13 @@ describe('test actions handlers', () => { }, }, }, - } as unknown) as RequestHandlerContext, + } as unknown as RequestHandlerContext, mockRequest, mockResponse ); - const expectedAgentActionResponse = (mockResponse.ok.mock.calls[0][0] - ?.body as unknown) as PostNewAgentActionResponse; + const expectedAgentActionResponse = mockResponse.ok.mock.calls[0][0] + ?.body as unknown as PostNewAgentActionResponse; expect(expectedAgentActionResponse.item).toEqual(agentAction); }); diff --git a/x-pack/plugins/fleet/server/routes/agent/handlers.ts b/x-pack/plugins/fleet/server/routes/agent/handlers.ts index fd4721309eebb..14b26d2c7ba85 100644 --- a/x-pack/plugins/fleet/server/routes/agent/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent/handlers.ts @@ -28,53 +28,51 @@ import { defaultIngestErrorHandler } from '../../errors'; import { licenseService } from '../../services'; import * as AgentService from '../../services/agents'; -export const getAgentHandler: RequestHandler< - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - const esClient = context.core.elasticsearch.client.asCurrentUser; +export const getAgentHandler: RequestHandler> = + async (context, request, response) => { + const soClient = context.core.savedObjects.client; + const esClient = context.core.elasticsearch.client.asCurrentUser; + + try { + const body: GetOneAgentResponse = { + item: await AgentService.getAgentById(esClient, request.params.agentId), + }; - try { - const body: GetOneAgentResponse = { - item: await AgentService.getAgentById(esClient, request.params.agentId), - }; + return response.ok({ body }); + } catch (error) { + if (soClient.errors.isNotFoundError(error)) { + return response.notFound({ + body: { message: `Agent ${request.params.agentId} not found` }, + }); + } - return response.ok({ body }); - } catch (error) { - if (soClient.errors.isNotFoundError(error)) { - return response.notFound({ - body: { message: `Agent ${request.params.agentId} not found` }, - }); + return defaultIngestErrorHandler({ error, response }); } + }; - return defaultIngestErrorHandler({ error, response }); - } -}; +export const deleteAgentHandler: RequestHandler> = + async (context, request, response) => { + const esClient = context.core.elasticsearch.client.asCurrentUser; -export const deleteAgentHandler: RequestHandler< - TypeOf -> = async (context, request, response) => { - const esClient = context.core.elasticsearch.client.asCurrentUser; + try { + await AgentService.deleteAgent(esClient, request.params.agentId); - try { - await AgentService.deleteAgent(esClient, request.params.agentId); + const body = { + action: 'deleted', + }; - const body = { - action: 'deleted', - }; + return response.ok({ body }); + } catch (error) { + if (error.isBoom) { + return response.customError({ + statusCode: error.output.statusCode, + body: { message: `Agent ${request.params.agentId} not found` }, + }); + } - return response.ok({ body }); - } catch (error) { - if (error.isBoom) { - return response.customError({ - statusCode: error.output.statusCode, - body: { message: `Agent ${request.params.agentId} not found` }, - }); + return defaultIngestErrorHandler({ error, response }); } - - return defaultIngestErrorHandler({ error, response }); - } -}; + }; export const updateAgentHandler: RequestHandler< TypeOf, diff --git a/x-pack/plugins/fleet/server/routes/output/handler.ts b/x-pack/plugins/fleet/server/routes/output/handler.ts index ebd3d213d33c3..0c56d55423e4b 100644 --- a/x-pack/plugins/fleet/server/routes/output/handler.ts +++ b/x-pack/plugins/fleet/server/routes/output/handler.ts @@ -31,28 +31,27 @@ export const getOutputsHandler: RequestHandler = async (context, request, respon } }; -export const getOneOuputHandler: RequestHandler< - TypeOf -> = async (context, request, response) => { - const soClient = context.core.savedObjects.client; - try { - const output = await outputService.get(soClient, request.params.outputId); +export const getOneOuputHandler: RequestHandler> = + async (context, request, response) => { + const soClient = context.core.savedObjects.client; + try { + const output = await outputService.get(soClient, request.params.outputId); - const body: GetOneOutputResponse = { - item: output, - }; + const body: GetOneOutputResponse = { + item: output, + }; - return response.ok({ body }); - } catch (error) { - if (error.isBoom && error.output.statusCode === 404) { - return response.notFound({ - body: { message: `Output ${request.params.outputId} not found` }, - }); - } + return response.ok({ body }); + } catch (error) { + if (error.isBoom && error.output.statusCode === 404) { + return response.notFound({ + body: { message: `Output ${request.params.outputId} not found` }, + }); + } - return defaultIngestErrorHandler({ error, response }); - } -}; + return defaultIngestErrorHandler({ error, response }); + } + }; export const putOuputHandler: RequestHandler< TypeOf, diff --git a/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts b/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts index fb28c7e2f5155..729417fa96060 100644 --- a/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts +++ b/x-pack/plugins/fleet/server/routes/package_policy/handlers.test.ts @@ -28,51 +28,54 @@ type PackagePolicyServicePublicInterface = Omit< const packagePolicyServiceMock = packagePolicyService as jest.Mocked; -jest.mock('../../services/package_policy', (): { - packagePolicyService: jest.Mocked; -} => { - return { - packagePolicyService: { - compilePackagePolicyInputs: jest.fn((packageInfo, vars, dataInputs) => - Promise.resolve(dataInputs) - ), - buildPackagePolicyFromPackage: jest.fn(), - bulkCreate: jest.fn(), - create: jest.fn((soClient, esClient, newData) => - Promise.resolve({ - ...newData, - inputs: newData.inputs.map((input) => ({ - ...input, - streams: input.streams.map((stream) => ({ - id: stream.data_stream.dataset, - ...stream, +jest.mock( + '../../services/package_policy', + (): { + packagePolicyService: jest.Mocked; + } => { + return { + packagePolicyService: { + compilePackagePolicyInputs: jest.fn((packageInfo, vars, dataInputs) => + Promise.resolve(dataInputs) + ), + buildPackagePolicyFromPackage: jest.fn(), + bulkCreate: jest.fn(), + create: jest.fn((soClient, esClient, newData) => + Promise.resolve({ + ...newData, + inputs: newData.inputs.map((input) => ({ + ...input, + streams: input.streams.map((stream) => ({ + id: stream.data_stream.dataset, + ...stream, + })), })), - })), - id: '1', - revision: 1, - updated_at: new Date().toISOString(), - updated_by: 'elastic', - created_at: new Date().toISOString(), - created_by: 'elastic', - }) - ), - delete: jest.fn(), - get: jest.fn(), - getByIDs: jest.fn(), - list: jest.fn(), - listIds: jest.fn(), - update: jest.fn(), - // @ts-ignore - runExternalCallbacks: jest.fn((callbackType, packagePolicy, context, request) => - callbackType === 'postPackagePolicyDelete' - ? Promise.resolve(undefined) - : Promise.resolve(packagePolicy) - ), - upgrade: jest.fn(), - getUpgradeDryRunDiff: jest.fn(), - }, - }; -}); + id: '1', + revision: 1, + updated_at: new Date().toISOString(), + updated_by: 'elastic', + created_at: new Date().toISOString(), + created_by: 'elastic', + }) + ), + delete: jest.fn(), + get: jest.fn(), + getByIDs: jest.fn(), + list: jest.fn(), + listIds: jest.fn(), + update: jest.fn(), + // @ts-ignore + runExternalCallbacks: jest.fn((callbackType, packagePolicy, context, request) => + callbackType === 'postPackagePolicyDelete' + ? Promise.resolve(undefined) + : Promise.resolve(packagePolicy) + ), + upgrade: jest.fn(), + getUpgradeDryRunDiff: jest.fn(), + }, + }; + } +); jest.mock('../../services/epm/packages', () => { return { diff --git a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_11_0.ts b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_11_0.ts index 0c7b20ed28261..c17a167184b4b 100644 --- a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_11_0.ts +++ b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_11_0.ts @@ -13,9 +13,8 @@ import type { PackagePolicy } from '../../../../common'; export const migratePackagePolicyToV7110: SavedObjectMigrationFn = ( packagePolicyDoc ) => { - const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = cloneDeep( - packagePolicyDoc - ); + const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = + cloneDeep(packagePolicyDoc); if (packagePolicyDoc.attributes.package?.name === 'endpoint') { const input = updatedPackagePolicyDoc.attributes.inputs[0]; const popup = { diff --git a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_12_0.ts b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_12_0.ts index 9d961af74a12a..4fc8c15044e82 100644 --- a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_12_0.ts +++ b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_12_0.ts @@ -13,9 +13,8 @@ import type { PackagePolicy } from '../../../../common'; export const migratePackagePolicyToV7120: SavedObjectMigrationFn = ( packagePolicyDoc ) => { - const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = cloneDeep( - packagePolicyDoc - ); + const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = + cloneDeep(packagePolicyDoc); if (packagePolicyDoc.attributes.package?.name === 'endpoint') { const input = updatedPackagePolicyDoc.attributes.inputs[0]; const ransomware = { diff --git a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_14_0.ts b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_14_0.ts index 2f281bcf86a95..a56ef13375149 100644 --- a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_14_0.ts +++ b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_14_0.ts @@ -14,9 +14,8 @@ export const migrateEndpointPackagePolicyToV7140: SavedObjectMigrationFn< PackagePolicy, PackagePolicy > = (packagePolicyDoc) => { - const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = cloneDeep( - packagePolicyDoc - ); + const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = + cloneDeep(packagePolicyDoc); if (packagePolicyDoc.attributes.package?.name === 'endpoint') { const input = updatedPackagePolicyDoc.attributes.inputs[0]; if (input && input.config) { diff --git a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_15_0.ts b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_15_0.ts index 9ccafc58989f3..7f96cda589462 100644 --- a/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_15_0.ts +++ b/x-pack/plugins/fleet/server/saved_objects/migrations/security_solution/to_v7_15_0.ts @@ -17,9 +17,8 @@ export const migratePackagePolicyToV7150: SavedObjectMigrationFn = cloneDeep( - packagePolicyDoc - ); + const updatedPackagePolicyDoc: SavedObjectUnsanitizedDoc = + cloneDeep(packagePolicyDoc); const input = updatedPackagePolicyDoc.attributes.inputs[0]; const memory = { diff --git a/x-pack/plugins/fleet/server/services/agent_policy.test.ts b/x-pack/plugins/fleet/server/services/agent_policy.test.ts index 3267b2b7e2665..59e0f6fd7840e 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy.test.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy.test.ts @@ -70,7 +70,7 @@ jest.mock('./agents'); jest.mock('./package_policy'); function getAgentPolicyUpdateMock() { - return (agentPolicyUpdateEventHandler as unknown) as jest.Mock< + return agentPolicyUpdateEventHandler as unknown as jest.Mock< typeof agentPolicyUpdateEventHandler >; } @@ -79,7 +79,7 @@ function getAgentPolicyCreateMock() { const soClient = savedObjectsClientMock.create(); soClient.create.mockImplementation(async (type, attributes) => { return { - attributes: (attributes as unknown) as NewAgentPolicy, + attributes: attributes as unknown as NewAgentPolicy, id: 'mocked', type: 'mocked', references: [], diff --git a/x-pack/plugins/fleet/server/services/agent_policy.ts b/x-pack/plugins/fleet/server/services/agent_policy.ts index 8539db05ffb54..9fe275bb9a3c9 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy.ts @@ -617,14 +617,15 @@ class AgentPolicyService { } if (agentPolicy.package_policies && agentPolicy.package_policies.length) { - const deletedPackagePolicies: DeletePackagePoliciesResponse = await packagePolicyService.delete( - soClient, - esClient, - agentPolicy.package_policies as string[], - { - skipUnassignFromAgentPolicies: true, - } - ); + const deletedPackagePolicies: DeletePackagePoliciesResponse = + await packagePolicyService.delete( + soClient, + esClient, + agentPolicy.package_policies as string[], + { + skipUnassignFromAgentPolicies: true, + } + ); try { await packagePolicyService.runDeleteExternalCallbacks(deletedPackagePolicies); } catch (error) { @@ -677,7 +678,7 @@ class AgentPolicyService { '@timestamp': new Date().toISOString(), revision_idx: fullPolicy.revision, coordinator_idx: 0, - data: (fullPolicy as unknown) as FleetServerPolicy['data'], + data: fullPolicy as unknown as FleetServerPolicy['data'], policy_id: fullPolicy.id, default_fleet_server: policy.is_default_fleet_server === true, }; diff --git a/x-pack/plugins/fleet/server/services/agent_policy_update.ts b/x-pack/plugins/fleet/server/services/agent_policy_update.ts index fe3a3907b9d29..9703467d84c18 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy_update.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy_update.ts @@ -13,7 +13,7 @@ import { unenrollForAgentPolicyId } from './agents'; import { agentPolicyService } from './agent_policy'; import { appContextService } from './app_context'; -const fakeRequest = ({ +const fakeRequest = { headers: {}, getBasePath: () => '', path: '/', @@ -26,7 +26,7 @@ const fakeRequest = ({ url: '/', }, }, -} as unknown) as KibanaRequest; +} as unknown as KibanaRequest; export async function agentPolicyUpdateEventHandler( soClient: SavedObjectsClientContract, diff --git a/x-pack/plugins/fleet/server/services/agents/crud.ts b/x-pack/plugins/fleet/server/services/agents/crud.ts index 2a69f983ec894..03647c52e05f0 100644 --- a/x-pack/plugins/fleet/server/services/agents/crud.ts +++ b/x-pack/plugins/fleet/server/services/agents/crud.ts @@ -29,25 +29,29 @@ function _joinFilters(filters: Array): KueryNode try { return filters .filter((filter) => filter !== undefined) - .reduce((acc: KueryNode | undefined, kuery: string | KueryNode | undefined): - | KueryNode - | undefined => { - if (kuery === undefined) { - return acc; - } - const kueryNode: KueryNode = - typeof kuery === 'string' ? fromKueryExpression(removeSOAttributes(kuery)) : kuery; - - if (!acc) { - return kueryNode; - } - - return { - type: 'function', - function: 'and', - arguments: [acc, kueryNode], - }; - }, undefined as KueryNode | undefined); + .reduce( + ( + acc: KueryNode | undefined, + kuery: string | KueryNode | undefined + ): KueryNode | undefined => { + if (kuery === undefined) { + return acc; + } + const kueryNode: KueryNode = + typeof kuery === 'string' ? fromKueryExpression(removeSOAttributes(kuery)) : kuery; + + if (!acc) { + return kueryNode; + } + + return { + type: 'function', + function: 'and', + arguments: [acc, kueryNode], + }; + }, + undefined as KueryNode | undefined + ); } catch (err) { throw new IngestManagerError(`Kuery is malformed: ${err.message}`); } diff --git a/x-pack/plugins/fleet/server/services/agents/crud_so.ts b/x-pack/plugins/fleet/server/services/agents/crud_so.ts index 246c91bbef518..aa3cb4e4ec1a7 100644 --- a/x-pack/plugins/fleet/server/services/agents/crud_so.ts +++ b/x-pack/plugins/fleet/server/services/agents/crud_so.ts @@ -25,27 +25,31 @@ const INACTIVE_AGENT_CONDITION = `NOT (${ACTIVE_AGENT_CONDITION})`; function _joinFilters(filters: Array) { return filters .filter((filter) => filter !== undefined) - .reduce((acc: KueryNode | undefined, kuery: string | KueryNode | undefined): - | KueryNode - | undefined => { - if (kuery === undefined) { - return acc; - } - const kueryNode: KueryNode = - typeof kuery === 'string' - ? fromKueryExpression(normalizeKuery(AGENT_SAVED_OBJECT_TYPE, kuery)) - : kuery; - - if (!acc) { - return kueryNode; - } - - return { - type: 'function', - function: 'and', - arguments: [acc, kueryNode], - }; - }, undefined as KueryNode | undefined); + .reduce( + ( + acc: KueryNode | undefined, + kuery: string | KueryNode | undefined + ): KueryNode | undefined => { + if (kuery === undefined) { + return acc; + } + const kueryNode: KueryNode = + typeof kuery === 'string' + ? fromKueryExpression(normalizeKuery(AGENT_SAVED_OBJECT_TYPE, kuery)) + : kuery; + + if (!acc) { + return kueryNode; + } + + return { + type: 'function', + function: 'and', + arguments: [acc, kueryNode], + }; + }, + undefined as KueryNode | undefined + ); } export async function listAgents( diff --git a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts index b666a1678ea6a..cc2357351f6df 100644 --- a/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts +++ b/x-pack/plugins/fleet/server/services/api_keys/enrollment_api_key.ts @@ -22,7 +22,8 @@ import { escapeSearchQueryPhrase } from '../saved_object'; import { invalidateAPIKeys } from './security'; -const uuidRegex = /^\([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}\)$/; +const uuidRegex = + /^\([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}\)$/; export async function listEnrollmentApiKeys( esClient: ElasticsearchClient, diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/default_settings.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/default_settings.ts index 2dced977229e1..e7fccb22566a5 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/default_settings.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/default_settings.ts @@ -53,9 +53,10 @@ export function buildDefaultSettings({ `large amount of default fields detected for index template ${templateName} in package ${packageName}, applying the first ${QUERY_DEFAULT_FIELD_LIMIT} fields` ); } - const defaultFieldNames = (defaultFields.length > QUERY_DEFAULT_FIELD_LIMIT - ? defaultFields.slice(0, QUERY_DEFAULT_FIELD_LIMIT) - : defaultFields + const defaultFieldNames = ( + defaultFields.length > QUERY_DEFAULT_FIELD_LIMIT + ? defaultFields.slice(0, QUERY_DEFAULT_FIELD_LIMIT) + : defaultFields ).map((field) => field.name); return { diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts index 6febd27286ad1..34dcd5427d655 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/transform.test.ts @@ -50,7 +50,7 @@ describe('test transform install', () => { }); test('can install new versions and removes older version', async () => { - const previousInstallation: Installation = ({ + const previousInstallation: Installation = { installed_es: [ { id: 'metrics-endpoint.policy-0.16.0-dev.0', @@ -61,9 +61,9 @@ describe('test transform install', () => { type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; - const currentInstallation: Installation = ({ + const currentInstallation: Installation = { installed_es: [ { id: 'metrics-endpoint.policy-0.16.0-dev.0', @@ -82,7 +82,7 @@ describe('test transform install', () => { type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; (getAsset as jest.MockedFunction) .mockReturnValueOnce(Buffer.from('{"content": "data"}', 'utf8')) .mockReturnValueOnce(Buffer.from('{"content": "data"}', 'utf8')); @@ -91,14 +91,14 @@ describe('test transform install', () => { .mockReturnValueOnce(Promise.resolve(previousInstallation)) .mockReturnValueOnce(Promise.resolve(currentInstallation)); - (getInstallationObject as jest.MockedFunction< - typeof getInstallationObject - >).mockReturnValueOnce( - Promise.resolve(({ + ( + getInstallationObject as jest.MockedFunction + ).mockReturnValueOnce( + Promise.resolve({ attributes: { installed_es: previousInstallation.installed_es, }, - } as unknown) as SavedObject) + } as unknown as SavedObject) ); esClient.transform.getTransform.mockReturnValueOnce( @@ -115,7 +115,7 @@ describe('test transform install', () => { ); await installTransform( - ({ + { name: 'endpoint', version: '0.16.0-dev.0', data_streams: [ @@ -148,7 +148,7 @@ describe('test transform install', () => { path: 'metadata_current', }, ], - } as unknown) as RegistryPackage, + } as unknown as RegistryPackage, [ 'endpoint-0.16.0-dev.0/data_stream/policy/elasticsearch/ingest_pipeline/default.json', 'endpoint-0.16.0-dev.0/elasticsearch/transform/metadata/default.json', @@ -275,18 +275,18 @@ describe('test transform install', () => { }); test('can install new version and when no older version', async () => { - const previousInstallation: Installation = ({ + const previousInstallation: Installation = { installed_es: [], - } as unknown) as Installation; + } as unknown as Installation; - const currentInstallation: Installation = ({ + const currentInstallation: Installation = { installed_es: [ { id: 'metrics-endpoint.metadata-current-default-0.16.0-dev.0', type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; (getAsset as jest.MockedFunction).mockReturnValueOnce( Buffer.from('{"content": "data"}', 'utf8') ); @@ -294,16 +294,16 @@ describe('test transform install', () => { .mockReturnValueOnce(Promise.resolve(previousInstallation)) .mockReturnValueOnce(Promise.resolve(currentInstallation)); - (getInstallationObject as jest.MockedFunction< - typeof getInstallationObject - >).mockReturnValueOnce( - Promise.resolve(({ + ( + getInstallationObject as jest.MockedFunction + ).mockReturnValueOnce( + Promise.resolve({ attributes: { installed_es: [] }, - } as unknown) as SavedObject) + } as unknown as SavedObject) ); await installTransform( - ({ + { name: 'endpoint', version: '0.16.0-dev.0', data_streams: [ @@ -322,7 +322,7 @@ describe('test transform install', () => { path: 'metadata_current', }, ], - } as unknown) as RegistryPackage, + } as unknown as RegistryPackage, ['endpoint-0.16.0-dev.0/elasticsearch/transform/metadata_current/default.json'], esClient, savedObjectsClient @@ -360,29 +360,29 @@ describe('test transform install', () => { }); test('can removes older version when no new install in package', async () => { - const previousInstallation: Installation = ({ + const previousInstallation: Installation = { installed_es: [ { id: 'endpoint.metadata-current-default-0.15.0-dev.0', type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; - const currentInstallation: Installation = ({ + const currentInstallation: Installation = { installed_es: [], - } as unknown) as Installation; + } as unknown as Installation; (getInstallation as jest.MockedFunction) .mockReturnValueOnce(Promise.resolve(previousInstallation)) .mockReturnValueOnce(Promise.resolve(currentInstallation)); - (getInstallationObject as jest.MockedFunction< - typeof getInstallationObject - >).mockReturnValueOnce( - Promise.resolve(({ + ( + getInstallationObject as jest.MockedFunction + ).mockReturnValueOnce( + Promise.resolve({ attributes: { installed_es: currentInstallation.installed_es }, - } as unknown) as SavedObject) + } as unknown as SavedObject) ); esClient.transform.getTransform.mockReturnValueOnce( @@ -399,7 +399,7 @@ describe('test transform install', () => { ); await installTransform( - ({ + { name: 'endpoint', version: '0.16.0-dev.0', data_streams: [ @@ -432,7 +432,7 @@ describe('test transform install', () => { path: 'metadata_current', }, ], - } as unknown) as RegistryPackage, + } as unknown as RegistryPackage, [], esClient, savedObjectsClient @@ -489,18 +489,18 @@ describe('test transform install', () => { }); test('ignore already exists error if saved object and ES transforms are out of sync', async () => { - const previousInstallation: Installation = ({ + const previousInstallation: Installation = { installed_es: [], - } as unknown) as Installation; + } as unknown as Installation; - const currentInstallation: Installation = ({ + const currentInstallation: Installation = { installed_es: [ { id: 'metrics-endpoint.metadata-current-default-0.16.0-dev.0', type: ElasticsearchAssetType.transform, }, ], - } as unknown) as Installation; + } as unknown as Installation; (getAsset as jest.MockedFunction).mockReturnValueOnce( Buffer.from('{"content": "data"}', 'utf8') ); @@ -508,12 +508,12 @@ describe('test transform install', () => { .mockReturnValueOnce(Promise.resolve(previousInstallation)) .mockReturnValueOnce(Promise.resolve(currentInstallation)); - (getInstallationObject as jest.MockedFunction< - typeof getInstallationObject - >).mockReturnValueOnce( - Promise.resolve(({ + ( + getInstallationObject as jest.MockedFunction + ).mockReturnValueOnce( + Promise.resolve({ attributes: { installed_es: [] }, - } as unknown) as SavedObject) + } as unknown as SavedObject) ); esClient.transport.request.mockImplementationOnce(() => @@ -528,7 +528,7 @@ describe('test transform install', () => { ); await installTransform( - ({ + { name: 'endpoint', version: '0.16.0-dev.0', data_streams: [ @@ -547,7 +547,7 @@ describe('test transform install', () => { path: 'metadata_current', }, ], - } as unknown) as RegistryPackage, + } as unknown as RegistryPackage, ['endpoint-0.16.0-dev.0/elasticsearch/transform/metadata_current/default.json'], esClient, savedObjectsClient diff --git a/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts b/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts index 5c05ed7532ac6..379bc8fa39bff 100644 --- a/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts +++ b/x-pack/plugins/fleet/server/services/fleet_server/saved_object_migrations.ts @@ -33,7 +33,7 @@ export async function runFleetServerMigration() { } function getInternalUserSOClient() { - const fakeRequest = ({ + const fakeRequest = { headers: {}, getBasePath: () => '', path: '/', @@ -46,7 +46,7 @@ function getInternalUserSOClient() { url: '/', }, }, - } as unknown) as KibanaRequest; + } as unknown as KibanaRequest; return appContextService.getInternalUserSOClient(fakeRequest); } @@ -74,9 +74,7 @@ async function migrateAgents() { for (const so of res.saved_objects) { try { - const { - attributes, - } = await appContextService + const { attributes } = await appContextService .getEncryptedSavedObjects() .getDecryptedAsInternalUser(AGENT_SAVED_OBJECT_TYPE, so.id); diff --git a/x-pack/plugins/fleet/server/services/package_policy.test.ts b/x-pack/plugins/fleet/server/services/package_policy.test.ts index 204650574e92a..aa70fc155fe74 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.test.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.test.ts @@ -117,7 +117,7 @@ describe('Package policy service', () => { describe('compilePackagePolicyInputs', () => { it('should work with config variables from the stream', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { type: 'logs', @@ -131,7 +131,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -180,7 +180,7 @@ describe('Package policy service', () => { it('should work with a two level dataset name', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { type: 'logs', @@ -194,7 +194,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -232,7 +232,7 @@ describe('Package policy service', () => { it('should work with config variables at the input level', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { dataset: 'package.dataset1', @@ -246,7 +246,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -295,7 +295,7 @@ describe('Package policy service', () => { it('should work with config variables at the package level', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { dataset: 'package.dataset1', @@ -309,7 +309,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, { hosts: { value: ['localhost'], @@ -363,14 +363,14 @@ describe('Package policy service', () => { it('should work with an input with a template and no streams', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [], policy_templates: [ { inputs: [{ type: 'log', template_path: 'some_template_path.yml' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -405,7 +405,7 @@ describe('Package policy service', () => { it('should work with an input with a template and streams', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { data_streams: [ { dataset: 'package.dataset1', @@ -424,7 +424,7 @@ describe('Package policy service', () => { inputs: [{ type: 'log', template_path: 'some_template_path.yml' }], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [ { @@ -510,13 +510,13 @@ describe('Package policy service', () => { it('should work with a package without input', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { policy_templates: [ { inputs: undefined, }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [] ); @@ -526,13 +526,13 @@ describe('Package policy service', () => { it('should work with a package with a empty inputs array', async () => { const inputs = await packagePolicyService.compilePackagePolicyInputs( - ({ + { policy_templates: [ { inputs: [], }, ], - } as unknown) as PackageInfo, + } as unknown as PackageInfo, {}, [] ); diff --git a/x-pack/plugins/fleet/server/services/preconfiguration.test.ts b/x-pack/plugins/fleet/server/services/preconfiguration.test.ts index d374553e1db83..86fdd2f0aa800 100644 --- a/x-pack/plugins/fleet/server/services/preconfiguration.test.ts +++ b/x-pack/plugins/fleet/server/services/preconfiguration.test.ts @@ -287,50 +287,46 @@ describe('policy preconfiguration', () => { const soClient = getPutPreconfiguredPackagesMock(); const esClient = elasticsearchServiceMock.createClusterClient().asInternalUser; - const { - policies: policiesA, - nonFatalErrors: nonFatalErrorsA, - } = await ensurePreconfiguredPackagesAndPolicies( - soClient, - esClient, - [ - { - name: 'Test policy', - namespace: 'default', - id: 'test-id', - package_policies: [], - }, - ] as PreconfiguredAgentPolicy[], - [], - mockDefaultOutput - ); + const { policies: policiesA, nonFatalErrors: nonFatalErrorsA } = + await ensurePreconfiguredPackagesAndPolicies( + soClient, + esClient, + [ + { + name: 'Test policy', + namespace: 'default', + id: 'test-id', + package_policies: [], + }, + ] as PreconfiguredAgentPolicy[], + [], + mockDefaultOutput + ); expect(policiesA.length).toEqual(1); expect(policiesA[0].id).toBe('mocked-test-id'); expect(nonFatalErrorsA.length).toBe(0); - const { - policies: policiesB, - nonFatalErrors: nonFatalErrorsB, - } = await ensurePreconfiguredPackagesAndPolicies( - soClient, - esClient, - [ - { - name: 'Test policy redo', - namespace: 'default', - id: 'test-id', - package_policies: [ - { - package: { name: 'some-uninstalled-package' }, - name: 'This package is not installed', - }, - ], - }, - ] as PreconfiguredAgentPolicy[], - [], - mockDefaultOutput - ); + const { policies: policiesB, nonFatalErrors: nonFatalErrorsB } = + await ensurePreconfiguredPackagesAndPolicies( + soClient, + esClient, + [ + { + name: 'Test policy redo', + namespace: 'default', + id: 'test-id', + package_policies: [ + { + package: { name: 'some-uninstalled-package' }, + name: 'This package is not installed', + }, + ], + }, + ] as PreconfiguredAgentPolicy[], + [], + mockDefaultOutput + ); expect(policiesB.length).toEqual(1); expect(policiesB[0].id).toBe('mocked-test-id'); @@ -352,26 +348,24 @@ describe('policy preconfiguration', () => { is_managed: true, } as PreconfiguredAgentPolicy); - const { - policies, - nonFatalErrors: nonFatalErrorsB, - } = await ensurePreconfiguredPackagesAndPolicies( - soClient, - esClient, - [ - { - name: 'Renamed Test policy', - description: 'Renamed Test policy description', - unenroll_timeout: 999, - namespace: 'default', - id: 'test-id', - is_managed: true, - package_policies: [], - }, - ] as PreconfiguredAgentPolicy[], - [], - mockDefaultOutput - ); + const { policies, nonFatalErrors: nonFatalErrorsB } = + await ensurePreconfiguredPackagesAndPolicies( + soClient, + esClient, + [ + { + name: 'Renamed Test policy', + description: 'Renamed Test policy description', + unenroll_timeout: 999, + namespace: 'default', + id: 'test-id', + is_managed: true, + package_policies: [], + }, + ] as PreconfiguredAgentPolicy[], + [], + mockDefaultOutput + ); expect(spyAgentPolicyServiceUpdate).toBeCalled(); expect(spyAgentPolicyServiceUpdate).toBeCalledWith( expect.anything(), // soClient @@ -400,16 +394,14 @@ describe('policy preconfiguration', () => { }; mockConfiguredPolicies.set('test-id', policy); - const { - policies, - nonFatalErrors: nonFatalErrorsB, - } = await ensurePreconfiguredPackagesAndPolicies( - soClient, - esClient, - [policy], - [], - mockDefaultOutput - ); + const { policies, nonFatalErrors: nonFatalErrorsB } = + await ensurePreconfiguredPackagesAndPolicies( + soClient, + esClient, + [policy], + [], + mockDefaultOutput + ); expect(spyAgentPolicyServiceUpdate).not.toBeCalled(); expect(policies.length).toEqual(1); expect(policies[0].id).toBe('test-id'); diff --git a/x-pack/plugins/global_search/public/plugin.ts b/x-pack/plugins/global_search/public/plugin.ts index b3a890d84f036..00f320d23b606 100644 --- a/x-pack/plugins/global_search/public/plugin.ts +++ b/x-pack/plugins/global_search/public/plugin.ts @@ -25,7 +25,8 @@ export class GlobalSearchPlugin GlobalSearchPluginStart, GlobalSearchPluginSetupDeps, GlobalSearchPluginStartDeps - > { + > +{ private readonly config: GlobalSearchClientConfigType; private licenseChecker?: ILicenseChecker; private readonly searchService = new SearchService(); diff --git a/x-pack/plugins/global_search/server/plugin.ts b/x-pack/plugins/global_search/server/plugin.ts index d7c06a92f70e0..688691d8941e2 100644 --- a/x-pack/plugins/global_search/server/plugin.ts +++ b/x-pack/plugins/global_search/server/plugin.ts @@ -30,7 +30,8 @@ export class GlobalSearchPlugin GlobalSearchPluginStart, GlobalSearchPluginSetupDeps, GlobalSearchPluginStartDeps - > { + > +{ private readonly config: GlobalSearchConfigType; private readonly searchService = new SearchService(); private searchServiceStart?: SearchServiceStart; diff --git a/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts b/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts index 6f495bfbd6433..cd093c8009a92 100644 --- a/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts +++ b/x-pack/plugins/global_search/server/routes/integration_tests/get_searchable_types.test.ts @@ -30,9 +30,10 @@ describe('GET /internal/global_search/searchable_types', () => { 'globalSearch' >(pluginId, 'globalSearch', () => globalSearchHandlerContext); - const router = httpSetup.createRouter< - ReturnType - >('/'); + const router = + httpSetup.createRouter>( + '/' + ); registerInternalSearchableTypesRoute(router); diff --git a/x-pack/plugins/global_search/server/services/context.ts b/x-pack/plugins/global_search/server/services/context.ts index 454b0324ab3c1..b0669f35b99b9 100644 --- a/x-pack/plugins/global_search/server/services/context.ts +++ b/x-pack/plugins/global_search/server/services/context.ts @@ -14,20 +14,20 @@ export type GlobalSearchContextFactory = (request: KibanaRequest) => GlobalSearc /** * {@link GlobalSearchProviderContext | context} factory */ -export const getContextFactory = (coreStart: CoreStart) => ( - request: KibanaRequest -): GlobalSearchProviderContext => { - const soClient = coreStart.savedObjects.getScopedClient(request); - return { - core: { - savedObjects: { - client: soClient, - typeRegistry: coreStart.savedObjects.getTypeRegistry(), +export const getContextFactory = + (coreStart: CoreStart) => + (request: KibanaRequest): GlobalSearchProviderContext => { + const soClient = coreStart.savedObjects.getScopedClient(request); + return { + core: { + savedObjects: { + client: soClient, + typeRegistry: coreStart.savedObjects.getTypeRegistry(), + }, + uiSettings: { + client: coreStart.uiSettings.asScopedToClient(soClient), + }, + capabilities: from(coreStart.capabilities.resolveCapabilities(request)), }, - uiSettings: { - client: coreStart.uiSettings.asScopedToClient(soClient), - }, - capabilities: from(coreStart.capabilities.resolveCapabilities(request)), - }, + }; }; -}; diff --git a/x-pack/plugins/global_search_providers/public/plugin.ts b/x-pack/plugins/global_search_providers/public/plugin.ts index 5fd47947d1b75..89e8e9f57a3de 100644 --- a/x-pack/plugins/global_search_providers/public/plugin.ts +++ b/x-pack/plugins/global_search_providers/public/plugin.ts @@ -14,7 +14,8 @@ export interface GlobalSearchProvidersPluginSetupDeps { } export class GlobalSearchProvidersPlugin - implements Plugin<{}, {}, GlobalSearchProvidersPluginSetupDeps, {}> { + implements Plugin<{}, {}, GlobalSearchProvidersPluginSetupDeps, {}> +{ setup( { getStartServices }: CoreSetup<{}, {}>, { globalSearch }: GlobalSearchProvidersPluginSetupDeps diff --git a/x-pack/plugins/global_search_providers/public/providers/application.test.ts b/x-pack/plugins/global_search_providers/public/providers/application.test.ts index a686f416292df..aa54f3a0e5ff2 100644 --- a/x-pack/plugins/global_search_providers/public/providers/application.test.ts +++ b/x-pack/plugins/global_search_providers/public/providers/application.test.ts @@ -246,9 +246,9 @@ describe('applicationResultProvider', () => { // test scheduler doesnt play well with promises. need to workaround by passing // an observable instead. Behavior with promise is asserted in previous tests of the suite - const applicationPromise = (hot('a', { + const applicationPromise = hot('a', { a: application, - }) as unknown) as Promise; + }) as unknown as Promise; const provider = createApplicationResultProvider(applicationPromise); @@ -271,9 +271,9 @@ describe('applicationResultProvider', () => { // test scheduler doesnt play well with promises. need to workaround by passing // an observable instead. Behavior with promise is asserted in previous tests of the suite - const applicationPromise = (hot('a', { + const applicationPromise = hot('a', { a: application, - }) as unknown) as Promise; + }) as unknown as Promise; const provider = createApplicationResultProvider(applicationPromise); diff --git a/x-pack/plugins/global_search_providers/server/plugin.ts b/x-pack/plugins/global_search_providers/server/plugin.ts index cf63389c45a34..dae346144bce3 100644 --- a/x-pack/plugins/global_search_providers/server/plugin.ts +++ b/x-pack/plugins/global_search_providers/server/plugin.ts @@ -14,7 +14,8 @@ export interface GlobalSearchProvidersPluginSetupDeps { } export class GlobalSearchProvidersPlugin - implements Plugin<{}, {}, GlobalSearchProvidersPluginSetupDeps, {}> { + implements Plugin<{}, {}, GlobalSearchProvidersPluginSetupDeps, {}> +{ setup( { getStartServices }: CoreSetup<{}, {}>, { globalSearch }: GlobalSearchProvidersPluginSetupDeps diff --git a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx index 1ae556a79edcb..8273d99f890c8 100644 --- a/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx +++ b/x-pack/plugins/graph/public/components/graph_visualization/graph_visualization.test.tsx @@ -101,7 +101,7 @@ describe('graph_visualization', () => { width: 2.2, }, ]; - const workspace = ({ + const workspace = { nodes, edges, selectNone: () => {}, @@ -110,7 +110,7 @@ describe('graph_visualization', () => { return !node.isSelected; }), getAllIntersections: jest.fn(), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; beforeEach(() => { jest.clearAllMocks(); @@ -120,7 +120,7 @@ describe('graph_visualization', () => { expect( shallow( {}} onSetControl={() => {}} onSetMergeCandidates={() => {}} diff --git a/x-pack/plugins/graph/public/components/inspect_panel.tsx b/x-pack/plugins/graph/public/components/inspect_panel.tsx index a254d54f616e4..5e5547ea341fb 100644 --- a/x-pack/plugins/graph/public/components/inspect_panel.tsx +++ b/x-pack/plugins/graph/public/components/inspect_panel.tsx @@ -49,11 +49,10 @@ export const InspectPanel = ({ const onRequestClick = () => setSelectedTabId('request'); const onResponseClick = () => setSelectedTabId('response'); - const editorContent = useMemo(() => (selectedTabId === 'request' ? lastRequest : lastResponse), [ - lastRequest, - lastResponse, - selectedTabId, - ]); + const editorContent = useMemo( + () => (selectedTabId === 'request' ? lastRequest : lastResponse), + [lastRequest, lastResponse, selectedTabId] + ); if (showInspect) { return ( diff --git a/x-pack/plugins/graph/public/components/search_bar.test.tsx b/x-pack/plugins/graph/public/components/search_bar.test.tsx index 1b76cde1a62fb..9237acb4741f1 100644 --- a/x-pack/plugins/graph/public/components/search_bar.test.tsx +++ b/x-pack/plugins/graph/public/components/search_bar.test.tsx @@ -77,7 +77,7 @@ describe('search_bar', () => { const defaultProps = { isLoading: false, indexPatternProvider: { - get: jest.fn(() => Promise.resolve(({ fields: [] } as unknown) as IndexPattern)), + get: jest.fn(() => Promise.resolve({ fields: [] } as unknown as IndexPattern)), }, confirmWipeWorkspace: (callback: () => void) => { callback(); @@ -169,9 +169,9 @@ describe('search_bar', () => { // pick the button component out of the tree because // it's part of a popover and thus not covered by enzyme - (instance - .find(QueryStringInput) - .prop('prepend') as ReactElement).props.children.props.onClick(); + ( + instance.find(QueryStringInput).prop('prepend') as ReactElement + ).props.children.props.onClick(); expect(openSourceModal).toHaveBeenCalled(); }); diff --git a/x-pack/plugins/graph/public/components/search_bar.tsx b/x-pack/plugins/graph/public/components/search_bar.tsx index fc7e3be3d0d37..57e9831d5a656 100644 --- a/x-pack/plugins/graph/public/components/search_bar.tsx +++ b/x-pack/plugins/graph/public/components/search_bar.tsx @@ -81,9 +81,10 @@ export function SearchBarComponent(props: SearchBarStateProps & SearchBarProps) } = props; const [query, setQuery] = useState({ language: 'kuery', query: urlQuery || '' }); - useEffect(() => setQuery((prev) => ({ language: prev.language, query: urlQuery || '' })), [ - urlQuery, - ]); + useEffect( + () => setQuery((prev) => ({ language: prev.language, query: urlQuery || '' })), + [urlQuery] + ); useEffect(() => { async function fetchPattern() { diff --git a/x-pack/plugins/graph/public/components/workspace_layout/workspace_top_nav_menu.tsx b/x-pack/plugins/graph/public/components/workspace_layout/workspace_top_nav_menu.tsx index 07e21287e5c16..dc7365672ffa2 100644 --- a/x-pack/plugins/graph/public/components/workspace_layout/workspace_top_nav_menu.tsx +++ b/x-pack/plugins/graph/public/components/workspace_layout/workspace_top_nav_menu.tsx @@ -136,12 +136,12 @@ export const WorkspaceTopNavMenu = (props: WorkspaceTopNavMenuProps) => { // since settings button will be disabled only if workspace was set const workspace = props.workspace as Workspace; - const settingsObservable = (asSyncedObservable(() => ({ + const settingsObservable = asSyncedObservable(() => ({ blocklistedNodes: workspace.blocklistedNodes, unblockNode: workspace.unblockNode, unblockAll: workspace.unblockAll, canEditDrillDownUrls: props.canEditDrillDownUrls, - })) as unknown) as AsObservable['observable']; + })) as unknown as AsObservable['observable']; props.coreStart.overlays.openFlyout( toMountPoint( diff --git a/x-pack/plugins/graph/public/helpers/kql_encoder.test.ts b/x-pack/plugins/graph/public/helpers/kql_encoder.test.ts index 4cf46e18c8fa7..8ef3cd44a63b7 100644 --- a/x-pack/plugins/graph/public/helpers/kql_encoder.test.ts +++ b/x-pack/plugins/graph/public/helpers/kql_encoder.test.ts @@ -12,7 +12,7 @@ describe('kql_encoder', () => { let workspaceMock: jest.Mocked; beforeEach(() => { - workspaceMock = ({ + workspaceMock = { returnUnpackedGroupeds: (nodes: []) => nodes, getSelectedOrAllNodes: jest.fn(() => [ { @@ -34,7 +34,7 @@ describe('kql_encoder', () => { }, }, ]), - } as unknown) as jest.Mocked; + } as unknown as jest.Mocked; }); it('should encode query as URI component', () => { diff --git a/x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx b/x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx index db80289d0d32d..cd0857f82ab6b 100644 --- a/x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx +++ b/x-pack/plugins/graph/public/helpers/use_workspace_loader.test.tsx @@ -33,13 +33,13 @@ jest.mock('react-router-dom', () => { }; }); -const mockSavedObjectsClient = ({ +const mockSavedObjectsClient = { resolve: jest.fn().mockResolvedValue({ saved_object: { id: 10, _version: '7.15.0', attributes: { wsState: '{}' } }, outcome: 'exactMatch', }), find: jest.fn().mockResolvedValue({ title: 'test' }), -} as unknown) as SavedObjectsClientCommon; +} as unknown as SavedObjectsClientCommon; async function setup(props: UseWorkspaceLoaderProps) { const returnVal = {}; @@ -66,7 +66,7 @@ describe('use_workspace_loader', () => { it('should not redirect if outcome is exactMatch', async () => { await act(async () => { - await setup((defaultProps as unknown) as UseWorkspaceLoaderProps); + await setup(defaultProps as unknown as UseWorkspaceLoaderProps); }); expect(defaultProps.spaces.ui.redirectLegacyUrl).not.toHaveBeenCalled(); expect(defaultProps.store.dispatch).toHaveBeenCalled(); @@ -85,7 +85,7 @@ describe('use_workspace_loader', () => { }, }; await act(async () => { - await setup((props as unknown) as UseWorkspaceLoaderProps); + await setup(props as unknown as UseWorkspaceLoaderProps); }); expect(props.spaces.ui.redirectLegacyUrl).toHaveBeenCalledWith( '#/workspace/aliasTargetId?query={}', diff --git a/x-pack/plugins/graph/public/plugin.ts b/x-pack/plugins/graph/public/plugin.ts index 1c44714a2c498..a1bc8a93f7f7a 100644 --- a/x-pack/plugins/graph/public/plugin.ts +++ b/x-pack/plugins/graph/public/plugin.ts @@ -49,7 +49,8 @@ export interface GraphPluginStartDependencies { } export class GraphPlugin - implements Plugin { + implements Plugin +{ private readonly appUpdater$ = new BehaviorSubject(() => ({})); constructor(private initializerContext: PluginInitializerContext) {} diff --git a/x-pack/plugins/graph/public/services/persistence/serialize.test.ts b/x-pack/plugins/graph/public/services/persistence/serialize.test.ts index 2466582bc7b25..ec52159ae10e2 100644 --- a/x-pack/plugins/graph/public/services/persistence/serialize.test.ts +++ b/x-pack/plugins/graph/public/services/persistence/serialize.test.ts @@ -159,7 +159,7 @@ describe('serialize', () => { }); it('should serialize given workspace', () => { - const savedWorkspace = ({} as unknown) as GraphWorkspaceSavedObject; + const savedWorkspace = {} as unknown as GraphWorkspaceSavedObject; appStateToSavedWorkspace(savedWorkspace, appState, true); @@ -281,7 +281,7 @@ describe('serialize', () => { }); it('should not save data if set to false', () => { - const savedWorkspace = ({} as unknown) as GraphWorkspaceSavedObject; + const savedWorkspace = {} as unknown as GraphWorkspaceSavedObject; appStateToSavedWorkspace(savedWorkspace, appState, false); diff --git a/x-pack/plugins/graph/public/state_management/helpers.ts b/x-pack/plugins/graph/public/state_management/helpers.ts index 098c1e029be8f..db853afc9f147 100644 --- a/x-pack/plugins/graph/public/state_management/helpers.ts +++ b/x-pack/plugins/graph/public/state_management/helpers.ts @@ -25,5 +25,7 @@ export type InferActionType = X extends ActionCreator ? T : never; * * @param actionCreators The action creators to create a unified matcher for */ -export const matchesOne = (...actionCreators: Array>) => (action: AnyAction) => - actionCreators.some((actionCreator) => actionCreator.match(action)); +export const matchesOne = + (...actionCreators: Array>) => + (action: AnyAction) => + actionCreators.some((actionCreator) => actionCreator.match(action)); diff --git a/x-pack/plugins/graph/public/state_management/mocks.ts b/x-pack/plugins/graph/public/state_management/mocks.ts index 189875d04b015..6f7b5dba2e4a1 100644 --- a/x-pack/plugins/graph/public/state_management/mocks.ts +++ b/x-pack/plugins/graph/public/state_management/mocks.ts @@ -40,48 +40,48 @@ export function createMockGraphStore({ mockedDepsOverwrites?: Partial>; initialStateOverwrites?: Partial; }): MockedGraphEnvironment { - const workspaceMock = ({ + const workspaceMock = { runLayout: jest.fn(), nodes: [], edges: [], options: {}, blocklistedNodes: [], - } as unknown) as Workspace; + } as unknown as Workspace; const mockedDeps: jest.Mocked = { basePath: '', addBasePath: jest.fn((url: string) => url), changeUrl: jest.fn(), - chrome: ({ + chrome: { setBreadcrumbs: jest.fn(), - } as unknown) as ChromeStart, + } as unknown as ChromeStart, createWorkspace: jest.fn(), getWorkspace: jest.fn(() => workspaceMock), indexPatternProvider: { get: jest.fn(() => - Promise.resolve(({ id: '123', title: 'test-pattern' } as unknown) as IndexPattern) + Promise.resolve({ id: '123', title: 'test-pattern' } as unknown as IndexPattern) ), }, I18nContext: jest .fn() .mockImplementation(({ children }: { children: React.ReactNode }) => children), - notifications: ({ + notifications: { toasts: { addDanger: jest.fn(), addSuccess: jest.fn(), }, - } as unknown) as NotificationsStart, + } as unknown as NotificationsStart, http: {} as HttpStart, notifyReact: jest.fn(), savePolicy: 'configAndData', showSaveModal: jest.fn(), - overlays: ({ + overlays: { openModal: jest.fn(), - } as unknown) as OverlayStart, - savedObjectsClient: ({ + } as unknown as OverlayStart, + savedObjectsClient: { find: jest.fn(), get: jest.fn(), - } as unknown) as SavedObjectsClientContract, + } as unknown as SavedObjectsClientContract, handleSearchQueryError: jest.fn(), ...mockedDepsOverwrites, }; diff --git a/x-pack/plugins/graph/public/state_management/url_templates.ts b/x-pack/plugins/graph/public/state_management/url_templates.ts index 01b1a9296b0b6..736270e53a797 100644 --- a/x-pack/plugins/graph/public/state_management/url_templates.ts +++ b/x-pack/plugins/graph/public/state_management/url_templates.ts @@ -23,9 +23,8 @@ import { matchesOne } from './helpers'; const actionCreator = actionCreatorFactory('x-pack/graph/urlTemplates'); export const loadTemplates = actionCreator('LOAD_TEMPLATES'); -export const saveTemplate = actionCreator<{ index: number; template: UrlTemplate }>( - 'SAVE_TEMPLATE' -); +export const saveTemplate = + actionCreator<{ index: number; template: UrlTemplate }>('SAVE_TEMPLATE'); export const removeTemplate = actionCreator('REMOVE_TEMPLATE'); export type UrlTemplatesState = UrlTemplate[]; diff --git a/x-pack/plugins/graph/server/sample_data/ecommerce.ts b/x-pack/plugins/graph/server/sample_data/ecommerce.ts index e8383ea542dbd..36e125864600d 100644 --- a/x-pack/plugins/graph/server/sample_data/ecommerce.ts +++ b/x-pack/plugins/graph/server/sample_data/ecommerce.ts @@ -335,8 +335,7 @@ const wsState: any = { ], urlTemplates: [ { - url: - '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3Aff959d40-b880-11e8-a6d9-e546fe2bba5f%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', + url: '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3Aff959d40-b880-11e8-a6d9-e546fe2bba5f%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', description: 'Raw documents', isDefault: true, encoderID: 'kql-loose', diff --git a/x-pack/plugins/graph/server/sample_data/flights.ts b/x-pack/plugins/graph/server/sample_data/flights.ts index d62b4e77e3251..61beacc3552f7 100644 --- a/x-pack/plugins/graph/server/sample_data/flights.ts +++ b/x-pack/plugins/graph/server/sample_data/flights.ts @@ -1589,8 +1589,7 @@ const wsState: any = { ], urlTemplates: [ { - url: - '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3Ad3d7af60-4c81-11e8-b3d7-01146121b73d%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', + url: '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3Ad3d7af60-4c81-11e8-b3d7-01146121b73d%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', description: 'Raw documents', isDefault: true, encoderID: 'kql-loose', diff --git a/x-pack/plugins/graph/server/sample_data/logs.ts b/x-pack/plugins/graph/server/sample_data/logs.ts index bd9b3a5c35097..d3d9c18a309e1 100644 --- a/x-pack/plugins/graph/server/sample_data/logs.ts +++ b/x-pack/plugins/graph/server/sample_data/logs.ts @@ -176,8 +176,7 @@ const wsState: any = { 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24', color: '#CE0060', field: 'agent.keyword', - term: - 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24', + term: 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.50 Safari/534.24', parent: null, size: 15, }, @@ -407,8 +406,7 @@ const wsState: any = { ], urlTemplates: [ { - url: - '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3A%2790943e30-9a47-11e8-b64d-95841ca0b247%27%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', + url: '/app/discover#/?_a=(columns%3A!(_source)%2Cindex%3A%2790943e30-9a47-11e8-b64d-95841ca0b247%27%2Cinterval%3Aauto%2Cquery%3A(language%3Akuery%2Cquery%3A{{gquery}})%2Csort%3A!(_score%2Cdesc))', description: 'Raw documents', isDefault: true, encoderID: 'kql-loose', diff --git a/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts b/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts index 7483e266a1ac9..1f2927436d4ae 100644 --- a/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts +++ b/x-pack/plugins/grokdebugger/server/routes/api/grokdebugger/register_grok_simulate_route.ts @@ -35,9 +35,10 @@ export function registerGrokSimulateRoute(framework: KibanaFramework) { async (requestContext, request, response) => { try { const grokdebuggerRequest = GrokdebuggerRequest.fromDownstreamJSON(request.body); - const simulateResponseFromES = await requestContext.core.elasticsearch.client.asCurrentUser.ingest.simulate( - { body: grokdebuggerRequest.upstreamJSON } - ); + const simulateResponseFromES = + await requestContext.core.elasticsearch.client.asCurrentUser.ingest.simulate({ + body: grokdebuggerRequest.upstreamJSON, + }); const grokdebuggerResponse = GrokdebuggerResponse.fromUpstreamJSON( simulateResponseFromES.body ); diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts index 90fff3a187355..f57f351ae0831 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/edit_policy/constants.ts @@ -181,7 +181,7 @@ export const POLICY_WITH_NODE_ROLE_ALLOCATION: PolicyFromES = { name: POLICY_NAME, }; -export const POLICY_WITH_KNOWN_AND_UNKNOWN_FIELDS = ({ +export const POLICY_WITH_KNOWN_AND_UNKNOWN_FIELDS = { version: 1, modified_date: Date.now().toString(), policy: { @@ -219,7 +219,7 @@ export const POLICY_WITH_KNOWN_AND_UNKNOWN_FIELDS = ({ name: POLICY_NAME, }, name: POLICY_NAME, -} as any) as PolicyFromES; +} as any as PolicyFromES; export const getGeneratedPolicies = (): PolicyFromES[] => { const policy = { diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts index 7acc6a3e2f26b..34d07d4a36ff9 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/errors_actions.ts @@ -17,17 +17,15 @@ const createWaitForValidationAction = (testBed: TestBed) => () => { component.update(); }; -const createExpectMessagesAction = (testBed: TestBed) => ( - expectedMessages: string[], - phase?: Phase -) => { - const { form } = testBed; - if (phase) { - expect(form.getErrorsMessages(`${phase}-phase`)).toEqual(expectedMessages); - } else { - expect(form.getErrorsMessages()).toEqual(expectedMessages); - } -}; +const createExpectMessagesAction = + (testBed: TestBed) => (expectedMessages: string[], phase?: Phase) => { + const { form } = testBed; + if (phase) { + expect(form.getErrorsMessages(`${phase}-phase`)).toEqual(expectedMessages); + } else { + expect(form.getErrorsMessages()).toEqual(expectedMessages); + } + }; export const createErrorsActions = (testBed: TestBed) => { const { exists } = testBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts index 400f3d2070e6a..f2a27aba9ec56 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/forcemerge_actions.ts @@ -11,15 +11,14 @@ import { Phase } from '../../../../common/types'; import { createFormToggleAction } from './form_toggle_action'; import { createFormSetValueAction } from './form_set_value_action'; -const createFormCheckboxAction = (testBed: TestBed, dataTestSubject: string) => async ( - checked: boolean -) => { - const { form, component } = testBed; - await act(async () => { - form.selectCheckBox(dataTestSubject, checked); - }); - component.update(); -}; +const createFormCheckboxAction = + (testBed: TestBed, dataTestSubject: string) => async (checked: boolean) => { + const { form, component } = testBed; + await act(async () => { + form.selectCheckBox(dataTestSubject, checked); + }); + component.update(); + }; export const createForceMergeActions = (testBed: TestBed, phase: Phase) => { const { exists } = testBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts index 643e0f23a9dea..b3510466b4b90 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/form_toggle_and_set_value_action.ts @@ -9,14 +9,11 @@ import { TestBed } from '@kbn/test/jest'; import { createFormToggleAction } from './form_toggle_action'; import { createFormSetValueAction } from './form_set_value_action'; -export const createFormToggleAndSetValueAction = ( - testBed: TestBed, - toggleSelector: string, - inputSelector: string -) => async (value: string) => { - const { exists } = testBed; - if (!exists(inputSelector)) { - await createFormToggleAction(testBed, toggleSelector)(); - } - await createFormSetValueAction(testBed, inputSelector)(value); -}; +export const createFormToggleAndSetValueAction = + (testBed: TestBed, toggleSelector: string, inputSelector: string) => async (value: string) => { + const { exists } = testBed; + if (!exists(inputSelector)) { + await createFormToggleAction(testBed, toggleSelector)(); + } + await createFormSetValueAction(testBed, inputSelector)(value); + }; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts index 798b74e40055f..93a1b959ec969 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts +++ b/x-pack/plugins/index_lifecycle_management/__jest__/client_integration/helpers/actions/rollover_actions.ts @@ -10,29 +10,27 @@ import { TestBed } from '@kbn/test/jest'; import { createFormToggleAction } from './form_toggle_action'; import { createFormSetValueAction } from './form_set_value_action'; -const createSetPrimaryShardSizeAction = (testBed: TestBed) => async ( - value: string, - units?: string -) => { - const { find, component } = testBed; +const createSetPrimaryShardSizeAction = + (testBed: TestBed) => async (value: string, units?: string) => { + const { find, component } = testBed; - await act(async () => { - find('hot-selectedMaxPrimaryShardSize').simulate('change', { target: { value } }); - }); - component.update(); - - if (units) { - act(() => { - find('hot-selectedMaxPrimaryShardSize.show-filters-button').simulate('click'); + await act(async () => { + find('hot-selectedMaxPrimaryShardSize').simulate('change', { target: { value } }); }); component.update(); - act(() => { - find(`hot-selectedMaxPrimaryShardSize.filter-option-${units}`).simulate('click'); - }); - component.update(); - } -}; + if (units) { + act(() => { + find('hot-selectedMaxPrimaryShardSize.show-filters-button').simulate('click'); + }); + component.update(); + + act(() => { + find(`hot-selectedMaxPrimaryShardSize.filter-option-${units}`).simulate('click'); + }); + component.update(); + } + }; const createSetMaxAgeAction = (testBed: TestBed) => async (value: string, units?: string) => { const { find, component } = testBed; diff --git a/x-pack/plugins/index_lifecycle_management/__jest__/policy_table.test.tsx b/x-pack/plugins/index_lifecycle_management/__jest__/policy_table.test.tsx index 820f8393d933d..cf25b1c335ae9 100644 --- a/x-pack/plugins/index_lifecycle_management/__jest__/policy_table.test.tsx +++ b/x-pack/plugins/index_lifecycle_management/__jest__/policy_table.test.tsx @@ -137,7 +137,7 @@ describe('policy table', () => { test('filters based on content of search input', () => { const rendered = mountWithIntl(component); const searchInput = rendered.find('.euiFieldSearch').first(); - ((searchInput.instance() as unknown) as HTMLInputElement).value = 'testy0'; + (searchInput.instance() as unknown as HTMLInputElement).value = 'testy0'; searchInput.simulate('keyup', { key: 'Enter', keyCode: 13, which: 13 }); rendered.update(); snapshot(getPolicyNames(rendered)); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/data_tier_allocation_field/components/data_tier_allocation.tsx b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/data_tier_allocation_field/components/data_tier_allocation.tsx index 1eeb32d84f677..6ca0324d8972d 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/data_tier_allocation_field/components/data_tier_allocation.tsx +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/data_tier_allocation_field/components/data_tier_allocation.tsx @@ -161,13 +161,8 @@ const getSelectOptions = (phase: PhaseWithAllocation, disableDataTierOption: boo ].filter(Boolean) as SelectOptions[]; export const DataTierAllocation: FunctionComponent = (props) => { - const { - phase, - hasNodeAttributes, - isCloudEnabled, - isUsingDeprecatedDataRoleConfig, - isLoading, - } = props; + const { phase, hasNodeAttributes, isCloudEnabled, isUsingDeprecatedDataRoleConfig, isLoading } = + props; /** * On Cloud we want to disable the data tier allocation option when we detect that we are not diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/min_age_field/min_age_field.tsx b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/min_age_field/min_age_field.tsx index ad92ef2d44479..2c42d76415dbc 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/min_age_field/min_age_field.tsx +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/phases/shared_fields/min_age_field/min_age_field.tsx @@ -86,9 +86,8 @@ export const MinAgeField: FunctionComponent = ({ phase }): React.ReactEle const { isUsingRollover } = useConfiguration(); const globalFields = useGlobalFields(); - const { setValue: setMillisecondValue } = globalFields[ - `${phase}MinAgeMilliSeconds` as 'coldMinAgeMilliSeconds' - ]; + const { setValue: setMillisecondValue } = + globalFields[`${phase}MinAgeMilliSeconds` as 'coldMinAgeMilliSeconds']; const [formData] = useFormData({ watch: [minAgeValuePath, minAgeUnitPath] }); const minAgeValue = get(formData, minAgeValuePath); const minAgeUnit = get(formData, minAgeUnitPath); @@ -153,9 +152,8 @@ export const MinAgeField: FunctionComponent = ({ phase }): React.ReactEle {(unitField) => { - const { isInvalid: isUnitFieldInvalid } = getFieldValidityAndErrorMessage( - unitField - ); + const { isInvalid: isUnitFieldInvalid } = + getFieldValidityAndErrorMessage(unitField); const icon = ( <> {/* This element is rendered for testing purposes only */} @@ -167,11 +165,10 @@ export const MinAgeField: FunctionComponent = ({ phase }): React.ReactEle /> ); - const selectAppendValue: Array< - string | React.ReactElement - > = isUsingRollover - ? [i18nTexts.minAgeUnitFieldSuffix, icon] - : [i18nTexts.minAgeUnitFieldSuffix]; + const selectAppendValue: Array = + isUsingRollover + ? [i18nTexts.minAgeUnitFieldSuffix, icon] + : [i18nTexts.minAgeUnitFieldSuffix]; return ( (fieldPath: string): boolean => - fieldPath.startsWith(`phases.${phase}`) || fieldPath.startsWith(`_meta.${phase}`); +const isXPhaseField = + (phase: keyof Phases) => + (fieldPath: string): boolean => + fieldPath.startsWith(`phases.${phase}`) || fieldPath.startsWith(`_meta.${phase}`); const isHotPhaseField = isXPhaseField('hot'); const isWarmPhaseField = isXPhaseField('warm'); diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/deserializer.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/deserializer.ts index ddb21dba90157..dc3714bdaf8da 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/deserializer.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/deserializer.ts @@ -14,133 +14,133 @@ import { getDefaultRepository } from '../lib'; import { FormInternal } from '../types'; import { CLOUD_DEFAULT_REPO } from '../constants'; -export const createDeserializer = (isCloudEnabled: boolean) => ( - policy: SerializedPolicy -): FormInternal => { - const { - phases: { hot, warm, cold, frozen, delete: deletePhase }, - } = policy; +export const createDeserializer = + (isCloudEnabled: boolean) => + (policy: SerializedPolicy): FormInternal => { + const { + phases: { hot, warm, cold, frozen, delete: deletePhase }, + } = policy; - let defaultRepository = getDefaultRepository([ - hot?.actions.searchable_snapshot, - cold?.actions.searchable_snapshot, - frozen?.actions.searchable_snapshot, - ]); + let defaultRepository = getDefaultRepository([ + hot?.actions.searchable_snapshot, + cold?.actions.searchable_snapshot, + frozen?.actions.searchable_snapshot, + ]); - if (!defaultRepository && isCloudEnabled) { - defaultRepository = CLOUD_DEFAULT_REPO; - } + if (!defaultRepository && isCloudEnabled) { + defaultRepository = CLOUD_DEFAULT_REPO; + } - const _meta: FormInternal['_meta'] = { - hot: { - isUsingDefaultRollover: isUsingDefaultRollover(policy), - customRollover: { - enabled: Boolean(hot?.actions?.rollover), + const _meta: FormInternal['_meta'] = { + hot: { + isUsingDefaultRollover: isUsingDefaultRollover(policy), + customRollover: { + enabled: Boolean(hot?.actions?.rollover), + }, + bestCompression: hot?.actions?.forcemerge?.index_codec === 'best_compression', + readonlyEnabled: Boolean(hot?.actions?.readonly), }, - bestCompression: hot?.actions?.forcemerge?.index_codec === 'best_compression', - readonlyEnabled: Boolean(hot?.actions?.readonly), - }, - warm: { - enabled: Boolean(warm), - warmPhaseOnRollover: warm === undefined ? true : Boolean(warm.min_age === '0ms'), - bestCompression: warm?.actions?.forcemerge?.index_codec === 'best_compression', - dataTierAllocationType: determineDataTierAllocationType(warm?.actions), - readonlyEnabled: Boolean(warm?.actions?.readonly), - minAgeToMilliSeconds: -1, - }, - cold: { - enabled: Boolean(cold), - dataTierAllocationType: determineDataTierAllocationType(cold?.actions), - freezeEnabled: Boolean(cold?.actions?.freeze), - readonlyEnabled: Boolean(cold?.actions?.readonly), - minAgeToMilliSeconds: -1, - }, - frozen: { - enabled: Boolean(frozen), - dataTierAllocationType: determineDataTierAllocationType(frozen?.actions), - freezeEnabled: Boolean(frozen?.actions?.freeze), - minAgeToMilliSeconds: -1, - }, - delete: { - enabled: Boolean(deletePhase), - minAgeToMilliSeconds: -1, - }, - searchableSnapshot: { - repository: defaultRepository, - }, - }; + warm: { + enabled: Boolean(warm), + warmPhaseOnRollover: warm === undefined ? true : Boolean(warm.min_age === '0ms'), + bestCompression: warm?.actions?.forcemerge?.index_codec === 'best_compression', + dataTierAllocationType: determineDataTierAllocationType(warm?.actions), + readonlyEnabled: Boolean(warm?.actions?.readonly), + minAgeToMilliSeconds: -1, + }, + cold: { + enabled: Boolean(cold), + dataTierAllocationType: determineDataTierAllocationType(cold?.actions), + freezeEnabled: Boolean(cold?.actions?.freeze), + readonlyEnabled: Boolean(cold?.actions?.readonly), + minAgeToMilliSeconds: -1, + }, + frozen: { + enabled: Boolean(frozen), + dataTierAllocationType: determineDataTierAllocationType(frozen?.actions), + freezeEnabled: Boolean(frozen?.actions?.freeze), + minAgeToMilliSeconds: -1, + }, + delete: { + enabled: Boolean(deletePhase), + minAgeToMilliSeconds: -1, + }, + searchableSnapshot: { + repository: defaultRepository, + }, + }; - return produce( - { - ...policy, - _meta, - }, - (draft: FormInternal) => { - if (draft.phases.hot?.actions?.rollover) { - if (draft.phases.hot.actions.rollover.max_size) { - const maxSize = splitSizeAndUnits(draft.phases.hot.actions.rollover.max_size); - draft.phases.hot.actions.rollover.max_size = maxSize.size; - draft._meta.hot.customRollover.maxStorageSizeUnit = maxSize.units; - } + return produce( + { + ...policy, + _meta, + }, + (draft: FormInternal) => { + if (draft.phases.hot?.actions?.rollover) { + if (draft.phases.hot.actions.rollover.max_size) { + const maxSize = splitSizeAndUnits(draft.phases.hot.actions.rollover.max_size); + draft.phases.hot.actions.rollover.max_size = maxSize.size; + draft._meta.hot.customRollover.maxStorageSizeUnit = maxSize.units; + } - if (draft.phases.hot.actions.rollover.max_primary_shard_size) { - const maxPrimaryShardSize = splitSizeAndUnits( - draft.phases.hot.actions.rollover.max_primary_shard_size - ); - draft.phases.hot.actions.rollover.max_primary_shard_size = maxPrimaryShardSize.size; - draft._meta.hot.customRollover.maxPrimaryShardSizeUnit = maxPrimaryShardSize.units; - } + if (draft.phases.hot.actions.rollover.max_primary_shard_size) { + const maxPrimaryShardSize = splitSizeAndUnits( + draft.phases.hot.actions.rollover.max_primary_shard_size + ); + draft.phases.hot.actions.rollover.max_primary_shard_size = maxPrimaryShardSize.size; + draft._meta.hot.customRollover.maxPrimaryShardSizeUnit = maxPrimaryShardSize.units; + } - if (draft.phases.hot.actions.rollover.max_age) { - const maxAge = splitSizeAndUnits(draft.phases.hot.actions.rollover.max_age); - draft.phases.hot.actions.rollover.max_age = maxAge.size; - draft._meta.hot.customRollover.maxAgeUnit = maxAge.units; + if (draft.phases.hot.actions.rollover.max_age) { + const maxAge = splitSizeAndUnits(draft.phases.hot.actions.rollover.max_age); + draft.phases.hot.actions.rollover.max_age = maxAge.size; + draft._meta.hot.customRollover.maxAgeUnit = maxAge.units; + } } - } - if (draft.phases.warm) { - if (draft.phases.warm.actions?.allocate?.require) { - Object.entries(draft.phases.warm.actions.allocate.require).forEach((entry) => { - draft._meta.warm.allocationNodeAttribute = entry.join(':'); - }); - } + if (draft.phases.warm) { + if (draft.phases.warm.actions?.allocate?.require) { + Object.entries(draft.phases.warm.actions.allocate.require).forEach((entry) => { + draft._meta.warm.allocationNodeAttribute = entry.join(':'); + }); + } - if (draft.phases.warm.min_age) { - const minAge = splitSizeAndUnits(draft.phases.warm.min_age); - draft.phases.warm.min_age = minAge.size; - draft._meta.warm.minAgeUnit = minAge.units; + if (draft.phases.warm.min_age) { + const minAge = splitSizeAndUnits(draft.phases.warm.min_age); + draft.phases.warm.min_age = minAge.size; + draft._meta.warm.minAgeUnit = minAge.units; + } } - } - if (draft.phases.cold) { - if (draft.phases.cold.actions?.allocate?.require) { - Object.entries(draft.phases.cold.actions.allocate.require).forEach((entry) => { - draft._meta.cold.allocationNodeAttribute = entry.join(':'); - }); - } + if (draft.phases.cold) { + if (draft.phases.cold.actions?.allocate?.require) { + Object.entries(draft.phases.cold.actions.allocate.require).forEach((entry) => { + draft._meta.cold.allocationNodeAttribute = entry.join(':'); + }); + } - if (draft.phases.cold.min_age) { - const minAge = splitSizeAndUnits(draft.phases.cold.min_age); - draft.phases.cold.min_age = minAge.size; - draft._meta.cold.minAgeUnit = minAge.units; + if (draft.phases.cold.min_age) { + const minAge = splitSizeAndUnits(draft.phases.cold.min_age); + draft.phases.cold.min_age = minAge.size; + draft._meta.cold.minAgeUnit = minAge.units; + } } - } - if (draft.phases.frozen) { - if (draft.phases.frozen.min_age) { - const minAge = splitSizeAndUnits(draft.phases.frozen.min_age); - draft.phases.frozen.min_age = minAge.size; - draft._meta.frozen.minAgeUnit = minAge.units; + if (draft.phases.frozen) { + if (draft.phases.frozen.min_age) { + const minAge = splitSizeAndUnits(draft.phases.frozen.min_age); + draft.phases.frozen.min_age = minAge.size; + draft._meta.frozen.minAgeUnit = minAge.units; + } } - } - if (draft.phases.delete) { - if (draft.phases.delete.min_age) { - const minAge = splitSizeAndUnits(draft.phases.delete.min_age); - draft.phases.delete.min_age = minAge.size; - draft._meta.delete.minAgeUnit = minAge.units; + if (draft.phases.delete) { + if (draft.phases.delete.min_age) { + const minAge = splitSizeAndUnits(draft.phases.delete.min_age); + draft.phases.delete.min_age = minAge.size; + draft._meta.delete.minAgeUnit = minAge.units; + } } } - } - ); -}; + ); + }; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/global_fields_context.tsx b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/global_fields_context.tsx index 94b804c1ce532..5834fe5b9ea77 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/global_fields_context.tsx +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/global_fields_context.tsx @@ -26,29 +26,27 @@ type GlobalFields = { const GlobalFieldsContext = createContext(null); -export const globalFields: Record< - keyof GlobalFields, - { path: string; config?: FieldConfig } -> = { - deleteEnabled: { - path: '_meta.delete.enabled', - }, - searchableSnapshotRepo: { - path: '_meta.searchableSnapshot.repository', - }, - warmMinAgeMilliSeconds: { - path: '_meta.warm.minAgeToMilliSeconds', - }, - coldMinAgeMilliSeconds: { - path: '_meta.cold.minAgeToMilliSeconds', - }, - frozenMinAgeMilliSeconds: { - path: '_meta.frozen.minAgeToMilliSeconds', - }, - deleteMinAgeMilliSeconds: { - path: '_meta.delete.minAgeToMilliSeconds', - }, -}; +export const globalFields: Record }> = + { + deleteEnabled: { + path: '_meta.delete.enabled', + }, + searchableSnapshotRepo: { + path: '_meta.searchableSnapshot.repository', + }, + warmMinAgeMilliSeconds: { + path: '_meta.warm.minAgeToMilliSeconds', + }, + coldMinAgeMilliSeconds: { + path: '_meta.cold.minAgeToMilliSeconds', + }, + frozenMinAgeMilliSeconds: { + path: '_meta.frozen.minAgeToMilliSeconds', + }, + deleteMinAgeMilliSeconds: { + path: '_meta.delete.minAgeToMilliSeconds', + }, + }; export const GlobalFieldsProvider: FunctionComponent = ({ children }) => { return ( diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/serializer/serializer.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/serializer/serializer.ts index 2a7d21cce03bc..cf81468dd2b48 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/serializer/serializer.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/serializer/serializer.ts @@ -16,312 +16,312 @@ import { FormInternal } from '../../types'; import { serializeMigrateAndAllocateActions } from './serialize_migrate_and_allocate_actions'; -export const createSerializer = (originalPolicy?: SerializedPolicy) => ( - data: FormInternal -): SerializedPolicy => { - const { _meta, ...updatedPolicy } = data; - - updatedPolicy.phases = { hot: { actions: {} }, ...updatedPolicy.phases }; - - return produce(originalPolicy ?? defaultPolicy, (draft) => { - // Copy over all updated fields - merge(draft, updatedPolicy); - - /** - * Important shared values for serialization - */ - const isUsingRollover = Boolean( - _meta.hot?.isUsingDefaultRollover || _meta.hot?.customRollover.enabled - ); - - // Next copy over all meta fields and delete any fields that have been removed - // by fields exposed in the form. It is very important that we do not delete - // data that the form does not control! E.g., unfollow action in hot phase. - - /** - * HOT PHASE SERIALIZATION - */ - if (draft.phases.hot) { - draft.phases.hot.min_age = draft.phases.hot.min_age ?? '0ms'; - } - - if (draft.phases.hot?.actions) { - const hotPhaseActions = draft.phases.hot.actions; +export const createSerializer = + (originalPolicy?: SerializedPolicy) => + (data: FormInternal): SerializedPolicy => { + const { _meta, ...updatedPolicy } = data; + + updatedPolicy.phases = { hot: { actions: {} }, ...updatedPolicy.phases }; + + return produce(originalPolicy ?? defaultPolicy, (draft) => { + // Copy over all updated fields + merge(draft, updatedPolicy); /** - * HOT PHASE ROLLOVER + * Important shared values for serialization */ - if (isUsingRollover) { - if (_meta.hot?.isUsingDefaultRollover) { - hotPhaseActions.rollover = cloneDeep(defaultRolloverAction); - } else { - // Rollover may not exist if editing an existing policy with initially no rollover configured - if (!hotPhaseActions.rollover) { - hotPhaseActions.rollover = {}; - } + const isUsingRollover = Boolean( + _meta.hot?.isUsingDefaultRollover || _meta.hot?.customRollover.enabled + ); - // We are using user-defined, custom rollover settings. - if (updatedPolicy.phases.hot!.actions.rollover?.max_age) { - hotPhaseActions.rollover.max_age = `${hotPhaseActions.rollover.max_age}${_meta.hot?.customRollover.maxAgeUnit}`; + // Next copy over all meta fields and delete any fields that have been removed + // by fields exposed in the form. It is very important that we do not delete + // data that the form does not control! E.g., unfollow action in hot phase. + + /** + * HOT PHASE SERIALIZATION + */ + if (draft.phases.hot) { + draft.phases.hot.min_age = draft.phases.hot.min_age ?? '0ms'; + } + + if (draft.phases.hot?.actions) { + const hotPhaseActions = draft.phases.hot.actions; + + /** + * HOT PHASE ROLLOVER + */ + if (isUsingRollover) { + if (_meta.hot?.isUsingDefaultRollover) { + hotPhaseActions.rollover = cloneDeep(defaultRolloverAction); } else { - delete hotPhaseActions.rollover.max_age; + // Rollover may not exist if editing an existing policy with initially no rollover configured + if (!hotPhaseActions.rollover) { + hotPhaseActions.rollover = {}; + } + + // We are using user-defined, custom rollover settings. + if (updatedPolicy.phases.hot!.actions.rollover?.max_age) { + hotPhaseActions.rollover.max_age = `${hotPhaseActions.rollover.max_age}${_meta.hot?.customRollover.maxAgeUnit}`; + } else { + delete hotPhaseActions.rollover.max_age; + } + + if (typeof updatedPolicy.phases.hot!.actions.rollover?.max_docs !== 'number') { + delete hotPhaseActions.rollover.max_docs; + } + + if (updatedPolicy.phases.hot!.actions.rollover?.max_primary_shard_size) { + hotPhaseActions.rollover.max_primary_shard_size = `${hotPhaseActions.rollover.max_primary_shard_size}${_meta.hot?.customRollover.maxPrimaryShardSizeUnit}`; + } else { + delete hotPhaseActions.rollover.max_primary_shard_size; + } + + if (updatedPolicy.phases.hot!.actions.rollover?.max_size) { + hotPhaseActions.rollover.max_size = `${hotPhaseActions.rollover.max_size}${_meta.hot?.customRollover.maxStorageSizeUnit}`; + } else { + delete hotPhaseActions.rollover.max_size; + } } - if (typeof updatedPolicy.phases.hot!.actions.rollover?.max_docs !== 'number') { - delete hotPhaseActions.rollover.max_docs; + /** + * HOT PHASE FORCEMERGE + */ + if (!updatedPolicy.phases.hot!.actions?.forcemerge) { + delete hotPhaseActions.forcemerge; + } else if (_meta.hot?.bestCompression) { + hotPhaseActions.forcemerge!.index_codec = 'best_compression'; + } else { + delete hotPhaseActions.forcemerge!.index_codec; } - if (updatedPolicy.phases.hot!.actions.rollover?.max_primary_shard_size) { - hotPhaseActions.rollover.max_primary_shard_size = `${hotPhaseActions.rollover.max_primary_shard_size}${_meta.hot?.customRollover.maxPrimaryShardSizeUnit}`; - } else { - delete hotPhaseActions.rollover.max_primary_shard_size; + if (_meta.hot?.bestCompression && hotPhaseActions.forcemerge) { + hotPhaseActions.forcemerge.index_codec = 'best_compression'; } - if (updatedPolicy.phases.hot!.actions.rollover?.max_size) { - hotPhaseActions.rollover.max_size = `${hotPhaseActions.rollover.max_size}${_meta.hot?.customRollover.maxStorageSizeUnit}`; + /** + * HOT PHASE READ-ONLY + */ + if (_meta.hot?.readonlyEnabled) { + hotPhaseActions.readonly = hotPhaseActions.readonly ?? {}; } else { - delete hotPhaseActions.rollover.max_size; + delete hotPhaseActions.readonly; } + } else { + delete hotPhaseActions.rollover; + delete hotPhaseActions.forcemerge; + delete hotPhaseActions.readonly; } /** - * HOT PHASE FORCEMERGE + * HOT PHASE SET PRIORITY */ - if (!updatedPolicy.phases.hot!.actions?.forcemerge) { - delete hotPhaseActions.forcemerge; - } else if (_meta.hot?.bestCompression) { - hotPhaseActions.forcemerge!.index_codec = 'best_compression'; - } else { - delete hotPhaseActions.forcemerge!.index_codec; + if (!updatedPolicy.phases.hot!.actions?.set_priority) { + delete hotPhaseActions.set_priority; } - if (_meta.hot?.bestCompression && hotPhaseActions.forcemerge) { - hotPhaseActions.forcemerge.index_codec = 'best_compression'; + /** + * HOT PHASE SHRINK + */ + if (!updatedPolicy.phases.hot?.actions?.shrink) { + delete hotPhaseActions.shrink; } /** - * HOT PHASE READ-ONLY + * HOT PHASE SEARCHABLE SNAPSHOT */ - if (_meta.hot?.readonlyEnabled) { - hotPhaseActions.readonly = hotPhaseActions.readonly ?? {}; + if (updatedPolicy.phases.hot!.actions?.searchable_snapshot) { + hotPhaseActions.searchable_snapshot = { + ...hotPhaseActions.searchable_snapshot, + snapshot_repository: _meta.searchableSnapshot.repository, + }; } else { - delete hotPhaseActions.readonly; + delete hotPhaseActions.searchable_snapshot; } - } else { - delete hotPhaseActions.rollover; - delete hotPhaseActions.forcemerge; - delete hotPhaseActions.readonly; } /** - * HOT PHASE SET PRIORITY + * WARM PHASE SERIALIZATION */ - if (!updatedPolicy.phases.hot!.actions?.set_priority) { - delete hotPhaseActions.set_priority; - } + if (_meta.warm.enabled) { + draft.phases.warm!.actions = draft.phases.warm?.actions ?? {}; + const warmPhase = draft.phases.warm!; - /** - * HOT PHASE SHRINK - */ - if (!updatedPolicy.phases.hot?.actions?.shrink) { - delete hotPhaseActions.shrink; - } + /** + * WARM PHASE MIN AGE + * + */ + if (updatedPolicy.phases.warm?.min_age) { + warmPhase.min_age = `${updatedPolicy.phases.warm!.min_age}${_meta.warm.minAgeUnit}`; + } - /** - * HOT PHASE SEARCHABLE SNAPSHOT - */ - if (updatedPolicy.phases.hot!.actions?.searchable_snapshot) { - hotPhaseActions.searchable_snapshot = { - ...hotPhaseActions.searchable_snapshot, - snapshot_repository: _meta.searchableSnapshot.repository, - }; - } else { - delete hotPhaseActions.searchable_snapshot; - } - } + /** + * WARM PHASE DATA ALLOCATION + */ + warmPhase.actions = serializeMigrateAndAllocateActions( + _meta.warm, + warmPhase.actions, + originalPolicy?.phases.warm?.actions, + updatedPolicy.phases.warm?.actions?.allocate?.number_of_replicas + ); - /** - * WARM PHASE SERIALIZATION - */ - if (_meta.warm.enabled) { - draft.phases.warm!.actions = draft.phases.warm?.actions ?? {}; - const warmPhase = draft.phases.warm!; + /** + * WARM PHASE FORCEMERGE + */ + if (!updatedPolicy.phases.warm?.actions?.forcemerge) { + delete warmPhase.actions.forcemerge; + } else if (_meta.warm.bestCompression) { + warmPhase.actions.forcemerge!.index_codec = 'best_compression'; + } else { + delete warmPhase.actions.forcemerge!.index_codec; + } - /** - * WARM PHASE MIN AGE - * - */ - if (updatedPolicy.phases.warm?.min_age) { - warmPhase.min_age = `${updatedPolicy.phases.warm!.min_age}${_meta.warm.minAgeUnit}`; - } + /** + * WARM PHASE READ ONLY + */ + if (_meta.warm.readonlyEnabled) { + warmPhase.actions.readonly = warmPhase.actions.readonly ?? {}; + } else { + delete warmPhase.actions.readonly; + } - /** - * WARM PHASE DATA ALLOCATION - */ - warmPhase.actions = serializeMigrateAndAllocateActions( - _meta.warm, - warmPhase.actions, - originalPolicy?.phases.warm?.actions, - updatedPolicy.phases.warm?.actions?.allocate?.number_of_replicas - ); + /** + * WARM PHASE SET PRIORITY + */ + if (!updatedPolicy.phases.warm?.actions?.set_priority) { + delete warmPhase.actions.set_priority; + } - /** - * WARM PHASE FORCEMERGE - */ - if (!updatedPolicy.phases.warm?.actions?.forcemerge) { - delete warmPhase.actions.forcemerge; - } else if (_meta.warm.bestCompression) { - warmPhase.actions.forcemerge!.index_codec = 'best_compression'; + /** + * WARM PHASE SHRINK + */ + if (!updatedPolicy.phases.warm?.actions?.shrink) { + delete warmPhase.actions.shrink; + } } else { - delete warmPhase.actions.forcemerge!.index_codec; + delete draft.phases.warm; } /** - * WARM PHASE READ ONLY + * COLD PHASE SERIALIZATION */ - if (_meta.warm.readonlyEnabled) { - warmPhase.actions.readonly = warmPhase.actions.readonly ?? {}; - } else { - delete warmPhase.actions.readonly; - } + if (_meta.cold.enabled) { + draft.phases.cold!.actions = draft.phases.cold?.actions ?? {}; + const coldPhase = draft.phases.cold!; - /** - * WARM PHASE SET PRIORITY - */ - if (!updatedPolicy.phases.warm?.actions?.set_priority) { - delete warmPhase.actions.set_priority; - } + /** + * COLD PHASE MIN AGE + */ + if (updatedPolicy.phases.cold?.min_age) { + coldPhase.min_age = `${updatedPolicy.phases.cold!.min_age}${_meta.cold.minAgeUnit}`; + } - /** - * WARM PHASE SHRINK - */ - if (!updatedPolicy.phases.warm?.actions?.shrink) { - delete warmPhase.actions.shrink; - } - } else { - delete draft.phases.warm; - } + /** + * COLD PHASE DATA ALLOCATION + */ + coldPhase.actions = serializeMigrateAndAllocateActions( + _meta.cold, + coldPhase.actions, + originalPolicy?.phases.cold?.actions, + updatedPolicy.phases.cold?.actions?.allocate?.number_of_replicas + ); - /** - * COLD PHASE SERIALIZATION - */ - if (_meta.cold.enabled) { - draft.phases.cold!.actions = draft.phases.cold?.actions ?? {}; - const coldPhase = draft.phases.cold!; + /** + * COLD PHASE FREEZE + */ + if (_meta.cold.freezeEnabled) { + coldPhase.actions.freeze = coldPhase.actions.freeze ?? {}; + } else { + delete coldPhase.actions.freeze; + } - /** - * COLD PHASE MIN AGE - */ - if (updatedPolicy.phases.cold?.min_age) { - coldPhase.min_age = `${updatedPolicy.phases.cold!.min_age}${_meta.cold.minAgeUnit}`; - } + /** + * COLD PHASE READ ONLY + */ + if (_meta.cold.readonlyEnabled) { + coldPhase.actions.readonly = coldPhase.actions.readonly ?? {}; + } else { + delete coldPhase.actions.readonly; + } - /** - * COLD PHASE DATA ALLOCATION - */ - coldPhase.actions = serializeMigrateAndAllocateActions( - _meta.cold, - coldPhase.actions, - originalPolicy?.phases.cold?.actions, - updatedPolicy.phases.cold?.actions?.allocate?.number_of_replicas - ); + /** + * COLD PHASE SET PRIORITY + */ + if (!updatedPolicy.phases.cold?.actions?.set_priority) { + delete coldPhase.actions.set_priority; + } - /** - * COLD PHASE FREEZE - */ - if (_meta.cold.freezeEnabled) { - coldPhase.actions.freeze = coldPhase.actions.freeze ?? {}; + /** + * COLD PHASE SEARCHABLE SNAPSHOT + */ + if (updatedPolicy.phases.cold?.actions?.searchable_snapshot) { + coldPhase.actions.searchable_snapshot = { + ...coldPhase.actions.searchable_snapshot, + snapshot_repository: _meta.searchableSnapshot.repository, + }; + } else { + delete coldPhase.actions.searchable_snapshot; + } } else { - delete coldPhase.actions.freeze; + delete draft.phases.cold; } /** - * COLD PHASE READ ONLY + * FROZEN PHASE SERIALIZATION */ - if (_meta.cold.readonlyEnabled) { - coldPhase.actions.readonly = coldPhase.actions.readonly ?? {}; - } else { - delete coldPhase.actions.readonly; - } + if (_meta.frozen?.enabled) { + draft.phases.frozen!.actions = draft.phases.frozen?.actions ?? {}; + const frozenPhase = draft.phases.frozen!; - /** - * COLD PHASE SET PRIORITY - */ - if (!updatedPolicy.phases.cold?.actions?.set_priority) { - delete coldPhase.actions.set_priority; - } + /** + * FROZEN PHASE MIN AGE + */ + if (updatedPolicy.phases.frozen?.min_age) { + frozenPhase.min_age = `${updatedPolicy.phases.frozen!.min_age}${_meta.frozen.minAgeUnit}`; + } - /** - * COLD PHASE SEARCHABLE SNAPSHOT - */ - if (updatedPolicy.phases.cold?.actions?.searchable_snapshot) { - coldPhase.actions.searchable_snapshot = { - ...coldPhase.actions.searchable_snapshot, - snapshot_repository: _meta.searchableSnapshot.repository, - }; + /** + * FROZEN PHASE SEARCHABLE SNAPSHOT + */ + if (updatedPolicy.phases.frozen?.actions?.searchable_snapshot) { + frozenPhase.actions.searchable_snapshot = { + ...frozenPhase.actions.searchable_snapshot, + snapshot_repository: _meta.searchableSnapshot.repository, + }; + } else { + delete frozenPhase.actions.searchable_snapshot; + } } else { - delete coldPhase.actions.searchable_snapshot; - } - } else { - delete draft.phases.cold; - } - - /** - * FROZEN PHASE SERIALIZATION - */ - if (_meta.frozen?.enabled) { - draft.phases.frozen!.actions = draft.phases.frozen?.actions ?? {}; - const frozenPhase = draft.phases.frozen!; - - /** - * FROZEN PHASE MIN AGE - */ - if (updatedPolicy.phases.frozen?.min_age) { - frozenPhase.min_age = `${updatedPolicy.phases.frozen!.min_age}${_meta.frozen.minAgeUnit}`; + delete draft.phases.frozen; } /** - * FROZEN PHASE SEARCHABLE SNAPSHOT + * DELETE PHASE SERIALIZATION */ - if (updatedPolicy.phases.frozen?.actions?.searchable_snapshot) { - frozenPhase.actions.searchable_snapshot = { - ...frozenPhase.actions.searchable_snapshot, - snapshot_repository: _meta.searchableSnapshot.repository, - }; - } else { - delete frozenPhase.actions.searchable_snapshot; - } - } else { - delete draft.phases.frozen; - } - - /** - * DELETE PHASE SERIALIZATION - */ - if (_meta.delete.enabled) { - const deletePhase = draft.phases.delete!; + if (_meta.delete.enabled) { + const deletePhase = draft.phases.delete!; - /** - * DELETE PHASE DELETE - */ - deletePhase.actions = deletePhase.actions ?? {}; - deletePhase.actions.delete = deletePhase.actions.delete ?? {}; + /** + * DELETE PHASE DELETE + */ + deletePhase.actions = deletePhase.actions ?? {}; + deletePhase.actions.delete = deletePhase.actions.delete ?? {}; - /** - * DELETE PHASE MIN AGE - */ - if (updatedPolicy.phases.delete?.min_age) { - deletePhase.min_age = `${updatedPolicy.phases.delete!.min_age}${_meta.delete.minAgeUnit}`; - } + /** + * DELETE PHASE MIN AGE + */ + if (updatedPolicy.phases.delete?.min_age) { + deletePhase.min_age = `${updatedPolicy.phases.delete!.min_age}${_meta.delete.minAgeUnit}`; + } - /** - * DELETE PHASE WAIT FOR SNAPSHOT - */ - if (!updatedPolicy.phases.delete?.actions?.wait_for_snapshot) { - delete deletePhase.actions.wait_for_snapshot; + /** + * DELETE PHASE WAIT FOR SNAPSHOT + */ + if (!updatedPolicy.phases.delete?.actions?.wait_for_snapshot) { + delete deletePhase.actions.wait_for_snapshot; + } + } else { + delete draft.phases.delete; } - } else { - delete draft.phases.delete; - } - }); -}; + }); + }; diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts index db43faf6cef17..efa6af4f61d0f 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/form/validations.ts @@ -164,110 +164,108 @@ export const createPolicyNameValidations = ({ * For example, the user can't define '5 days' for cold phase if the * warm phase is set to '10 days'. */ -export const minAgeGreaterThanPreviousPhase = (phase: PhaseWithTiming) => ({ - formData, -}: { - formData: Record; -}) => { - if (phase === 'warm') { - return; - } +export const minAgeGreaterThanPreviousPhase = + (phase: PhaseWithTiming) => + ({ formData }: { formData: Record }) => { + if (phase === 'warm') { + return; + } - const getValueFor = (_phase: PhaseWithTiming) => { - const milli = formData[`_meta.${_phase}.minAgeToMilliSeconds`]; + const getValueFor = (_phase: PhaseWithTiming) => { + const milli = formData[`_meta.${_phase}.minAgeToMilliSeconds`]; - const esFormat = - milli >= 0 - ? formData[`phases.${_phase}.min_age`] + formData[`_meta.${_phase}.minAgeUnit`] - : undefined; + const esFormat = + milli >= 0 + ? formData[`phases.${_phase}.min_age`] + formData[`_meta.${_phase}.minAgeUnit`] + : undefined; - return { - milli, - esFormat, + return { + milli, + esFormat, + }; }; - }; - const minAgeValues = { - warm: getValueFor('warm'), - cold: getValueFor('cold'), - frozen: getValueFor('frozen'), - delete: getValueFor('delete'), - }; + const minAgeValues = { + warm: getValueFor('warm'), + cold: getValueFor('cold'), + frozen: getValueFor('frozen'), + delete: getValueFor('delete'), + }; - const i18nErrors = { - greaterThanWarmPhase: i18n.translate( - 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanWarmPhaseError', - { - defaultMessage: 'Must be greater or equal than the warm phase value ({value})', - values: { - value: minAgeValues.warm.esFormat, - }, - } - ), - greaterThanColdPhase: i18n.translate( - 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanColdPhaseError', - { - defaultMessage: 'Must be greater or equal than the cold phase value ({value})', - values: { - value: minAgeValues.cold.esFormat, - }, - } - ), - greaterThanFrozenPhase: i18n.translate( - 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanFrozenPhaseError', - { - defaultMessage: 'Must be greater or equal than the frozen phase value ({value})', - values: { - value: minAgeValues.frozen.esFormat, - }, - } - ), - }; + const i18nErrors = { + greaterThanWarmPhase: i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanWarmPhaseError', + { + defaultMessage: 'Must be greater or equal than the warm phase value ({value})', + values: { + value: minAgeValues.warm.esFormat, + }, + } + ), + greaterThanColdPhase: i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanColdPhaseError', + { + defaultMessage: 'Must be greater or equal than the cold phase value ({value})', + values: { + value: minAgeValues.cold.esFormat, + }, + } + ), + greaterThanFrozenPhase: i18n.translate( + 'xpack.indexLifecycleMgmt.editPolicy.minAgeSmallerThanFrozenPhaseError', + { + defaultMessage: 'Must be greater or equal than the frozen phase value ({value})', + values: { + value: minAgeValues.frozen.esFormat, + }, + } + ), + }; - if (phase === 'cold') { - if (minAgeValues.warm.milli >= 0 && minAgeValues.cold.milli < minAgeValues.warm.milli) { - return { - message: i18nErrors.greaterThanWarmPhase, - }; + if (phase === 'cold') { + if (minAgeValues.warm.milli >= 0 && minAgeValues.cold.milli < minAgeValues.warm.milli) { + return { + message: i18nErrors.greaterThanWarmPhase, + }; + } + return; } - return; - } - if (phase === 'frozen') { - if (minAgeValues.cold.milli >= 0 && minAgeValues.frozen.milli < minAgeValues.cold.milli) { - return { - message: i18nErrors.greaterThanColdPhase, - }; - } else if ( - minAgeValues.warm.milli >= 0 && - minAgeValues.frozen.milli < minAgeValues.warm.milli - ) { - return { - message: i18nErrors.greaterThanWarmPhase, - }; + if (phase === 'frozen') { + if (minAgeValues.cold.milli >= 0 && minAgeValues.frozen.milli < minAgeValues.cold.milli) { + return { + message: i18nErrors.greaterThanColdPhase, + }; + } else if ( + minAgeValues.warm.milli >= 0 && + minAgeValues.frozen.milli < minAgeValues.warm.milli + ) { + return { + message: i18nErrors.greaterThanWarmPhase, + }; + } + return; } - return; - } - if (phase === 'delete') { - if (minAgeValues.frozen.milli >= 0 && minAgeValues.delete.milli < minAgeValues.frozen.milli) { - return { - message: i18nErrors.greaterThanFrozenPhase, - }; - } else if ( - minAgeValues.cold.milli >= 0 && - minAgeValues.delete.milli < minAgeValues.cold.milli - ) { - return { - message: i18nErrors.greaterThanColdPhase, - }; - } else if ( - minAgeValues.warm.milli >= 0 && - minAgeValues.delete.milli < minAgeValues.warm.milli - ) { - return { - message: i18nErrors.greaterThanWarmPhase, - }; + if (phase === 'delete') { + if (minAgeValues.frozen.milli >= 0 && minAgeValues.delete.milli < minAgeValues.frozen.milli) { + return { + message: i18nErrors.greaterThanFrozenPhase, + }; + } else if ( + minAgeValues.cold.milli >= 0 && + minAgeValues.delete.milli < minAgeValues.cold.milli + ) { + return { + message: i18nErrors.greaterThanColdPhase, + }; + } else if ( + minAgeValues.warm.milli >= 0 && + minAgeValues.delete.milli < minAgeValues.warm.milli + ) { + return { + message: i18nErrors.greaterThanWarmPhase, + }; + } } - } -}; + }; diff --git a/x-pack/plugins/index_lifecycle_management/public/plugin.tsx b/x-pack/plugins/index_lifecycle_management/public/plugin.tsx index 339d7a4d7db96..bc0981529c34f 100644 --- a/x-pack/plugins/index_lifecycle_management/public/plugin.tsx +++ b/x-pack/plugins/index_lifecycle_management/public/plugin.tsx @@ -20,7 +20,8 @@ import { ClientConfigType, SetupDependencies, StartDependencies } from './types' import { IlmLocatorDefinition } from './locator'; export class IndexLifecycleManagementPlugin - implements Plugin { + implements Plugin +{ constructor(private readonly initializerContext: PluginInitializerContext) {} private breadcrumbService = new BreadcrumbService(); diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/__jest__/fixtures.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/__jest__/fixtures.ts index fe8d685dc2e01..0ebed383e261a 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/__jest__/fixtures.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/__jest__/fixtures.ts @@ -127,8 +127,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -137,8 +136,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -354,8 +352,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -364,8 +361,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -580,8 +576,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -590,8 +585,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -806,8 +800,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -816,8 +809,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1032,8 +1024,7 @@ export const cloudNodeSettingsWithLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1042,8 +1033,7 @@ export const cloudNodeSettingsWithLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1269,8 +1259,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1279,8 +1268,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1496,8 +1484,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1506,8 +1493,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1722,8 +1708,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1732,8 +1717,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -1948,8 +1932,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -1958,8 +1941,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, @@ -2174,8 +2156,7 @@ export const cloudNodeSettingsWithoutLegacy = { principal: 'http://saml.elastic-cloud.com/attributes/principal', }, sp: { - acs: - 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', + acs: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/api/security/saml/callback', entity_id: 'ec:2628060457:916c269173df465f9826f4471799de42', logout: 'https://916c269173df465f9826f4471799de42.europe-west4.gcp.elastic-cloud.com:9243/logout', @@ -2184,8 +2165,7 @@ export const cloudNodeSettingsWithoutLegacy = { idp: { entity_id: 'urn:idp-cloud-elastic-co', metadata: { - path: - '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', + path: '/app/config/cloud-saml-metadata-916c269173df465f9826f4471799de42.xml', }, }, }, diff --git a/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/register_list_route.ts b/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/register_list_route.ts index accd8993abc62..314b206d6ea6b 100644 --- a/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/register_list_route.ts +++ b/x-pack/plugins/index_lifecycle_management/server/routes/api/nodes/register_list_route.ts @@ -88,15 +88,14 @@ export function registerListRoute({ { path: addBasePath('/nodes/list'), validate: false }, license.guardApiRoute(async (context, request, response) => { try { - const settingsResponse = await context.core.elasticsearch.client.asCurrentUser.transport.request( - { + const settingsResponse = + await context.core.elasticsearch.client.asCurrentUser.transport.request({ method: 'GET', path: '/_nodes/settings', querystring: { format: 'json', }, - } - ); + }); const body: ListNodesRouteResponse = convertSettingsIntoLists( settingsResponse.body as Settings, disallowedNodeAttributes diff --git a/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx index 9023a5ac53a98..7ce81fa47df97 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_management/__jest__/client_integration/helpers/setup_environment.tsx @@ -66,19 +66,19 @@ export const setupEnvironment = () => { }; }; -export const WithAppDependencies = (Comp: any, overridingDependencies: any = {}) => ( - props: any -) => { - const mergedDependencies = merge({}, appDependencies, overridingDependencies); - return ( - - - - - - - - - - ); -}; +export const WithAppDependencies = + (Comp: any, overridingDependencies: any = {}) => + (props: any) => { + const mergedDependencies = merge({}, appDependencies, overridingDependencies); + return ( + + + + + + + + + + ); + }; diff --git a/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts b/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts index 8e114b0596948..7c4d2573bdec6 100644 --- a/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts +++ b/x-pack/plugins/index_management/__jest__/client_integration/home/data_streams_tab.test.ts @@ -348,11 +348,8 @@ describe('Data Streams tab', () => { describe('when there are special characters', () => { beforeEach(async () => { - const { - setLoadIndicesResponse, - setLoadDataStreamsResponse, - setLoadDataStreamResponse, - } = httpRequestsMockHelpers; + const { setLoadIndicesResponse, setLoadDataStreamsResponse, setLoadDataStreamResponse } = + httpRequestsMockHelpers; setLoadIndicesResponse([ createDataStreamBackingIndex('data-stream-index', '%dataStream'), diff --git a/x-pack/plugins/index_management/common/lib/template_serialization.ts b/x-pack/plugins/index_management/common/lib/template_serialization.ts index 3e6698ac57136..ce49c32cd8271 100644 --- a/x-pack/plugins/index_management/common/lib/template_serialization.ts +++ b/x-pack/plugins/index_management/common/lib/template_serialization.ts @@ -16,15 +16,8 @@ import { const hasEntries = (data: object = {}) => Object.entries(data).length > 0; export function serializeTemplate(templateDeserialized: TemplateDeserialized): TemplateSerialized { - const { - version, - priority, - indexPatterns, - template, - composedOf, - dataStream, - _meta, - } = templateDeserialized; + const { version, priority, indexPatterns, template, composedOf, dataStream, _meta } = + templateDeserialized; return { version, @@ -86,10 +79,8 @@ export function deserializeTemplateList( cloudManagedTemplatePrefix?: string ): TemplateListItem[] { return indexTemplates.map(({ name, index_template: templateSerialized }) => { - const { - template: { mappings, settings, aliases } = {}, - ...deserializedTemplate - } = deserializeTemplate({ name, ...templateSerialized }, cloudManagedTemplatePrefix); + const { template: { mappings, settings, aliases } = {}, ...deserializedTemplate } = + deserializeTemplate({ name, ...templateSerialized }, cloudManagedTemplatePrefix); return { ...deserializedTemplate, @@ -150,10 +141,8 @@ export function deserializeLegacyTemplateList( cloudManagedTemplatePrefix?: string ): TemplateListItem[] { return Object.entries(indexTemplatesByName).map(([name, templateSerialized]) => { - const { - template: { mappings, settings, aliases } = {}, - ...deserializedTemplate - } = deserializeLegacyTemplate({ name, ...templateSerialized }, cloudManagedTemplatePrefix); + const { template: { mappings, settings, aliases } = {}, ...deserializedTemplate } = + deserializeLegacyTemplate({ name, ...templateSerialized }, cloudManagedTemplatePrefix); return { ...deserializedTemplate, diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx index ece377b0ee2cf..d532eaaba8923 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/__jest__/client_integration/helpers/setup_environment.tsx @@ -33,7 +33,7 @@ const appDependencies = { } as any; export const componentTemplatesDependencies = { - httpClient: (mockHttpClient as unknown) as HttpSetup, + httpClient: mockHttpClient as unknown as HttpSetup, apiBasePath: API_BASE_PATH, trackMetric: () => {}, docLinks: docLinksServiceMock.createStartContract(), @@ -51,15 +51,16 @@ export const setupEnvironment = () => { }; }; -export const WithAppDependencies = (Comp: any) => (props: any) => ( - - - - - - - - - / - -); +export const WithAppDependencies = (Comp: any) => (props: any) => + ( + + + + + + + + + / + + ); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx index 06a5e8b5c27dc..6dbf1b15174e9 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_details/component_template_details.tsx @@ -55,9 +55,11 @@ export const ComponentTemplateDetailsFlyoutContent: React.FunctionComponent('summary'); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx index 77668f7d55072..6ff7c5826459e 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_list/component_template_list.tsx @@ -42,10 +42,8 @@ export const ComponentTemplateList: React.FunctionComponent = ({ componentTemplateName, history, }) => { - const { - addContent: addContentToGlobalFlyout, - removeContent: removeContentFromGlobalFlyout, - } = useGlobalFlyout(); + const { addContent: addContentToGlobalFlyout, removeContent: removeContentFromGlobalFlyout } = + useGlobalFlyout(); const { api, trackMetric, documentation } = useComponentTemplatesContext(); const { data, isLoading, error, resendRequest } = api.useLoadComponentTemplates(); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx index a1e1cc5557660..41be138ea9fa5 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.tsx @@ -60,10 +60,8 @@ export const ComponentTemplatesSelector = ({ emptyPrompt: { text, showCreateButton } = {}, }: Props) => { const { data: components, isLoading, error } = useApi().useLoadComponentTemplates(); - const { - addContent: addContentToGlobalFlyout, - removeContent: removeContentFromGlobalFlyout, - } = useGlobalFlyout(); + const { addContent: addContentToGlobalFlyout, removeContent: removeContentFromGlobalFlyout } = + useGlobalFlyout(); const [selectedComponent, setSelectedComponent] = useState(null); const [componentsSelected, setComponentsSelected] = useState([]); const isInitialized = useRef(false); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_clone/component_template_clone.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_clone/component_template_clone.tsx index d19c500c3622a..1889da7c1336f 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_clone/component_template_clone.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_clone/component_template_clone.tsx @@ -24,9 +24,11 @@ export const ComponentTemplateClone: FunctionComponent { if (error && !isLoading) { diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/component_template_form.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/component_template_form.tsx index 8763bb8881ed7..8d5e61c81120f 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/component_template_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/component_template_form.tsx @@ -160,22 +160,21 @@ export const ComponentTemplateForm = ({ }; const buildComponentTemplateObject = useCallback( - (initialTemplate: ComponentTemplateDeserialized) => ( - wizardData: WizardContent - ): ComponentTemplateDeserialized => { - const outputComponentTemplate = { - ...initialTemplate, - name: wizardData.logistics.name, - version: wizardData.logistics.version, - _meta: wizardData.logistics._meta, - template: { - settings: wizardData.settings, - mappings: wizardData.mappings, - aliases: wizardData.aliases, - }, - }; - return cleanupComponentTemplateObject(outputComponentTemplate); - }, + (initialTemplate: ComponentTemplateDeserialized) => + (wizardData: WizardContent): ComponentTemplateDeserialized => { + const outputComponentTemplate = { + ...initialTemplate, + name: wizardData.logistics.name, + version: wizardData.logistics.version, + _meta: wizardData.logistics._meta, + template: { + settings: wizardData.settings, + mappings: wizardData.mappings, + aliases: wizardData.aliases, + }, + }; + return cleanupComponentTemplateObject(outputComponentTemplate); + }, [] ); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx index 94f5befab61c9..89b4e90741410 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_templates_context.tsx @@ -42,15 +42,8 @@ export const ComponentTemplatesProvider = ({ value: Props; children: React.ReactNode; }) => { - const { - httpClient, - apiBasePath, - trackMetric, - docLinks, - toasts, - setBreadcrumbs, - getUrlForApp, - } = value; + const { httpClient, apiBasePath, trackMetric, docLinks, toasts, setBreadcrumbs, getUrlForApp } = + value; const useRequest = getUseRequest(httpClient); const sendRequest = getSendRequest(httpClient); diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts b/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts index a7056e27b5cad..92847bbe5dc05 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts +++ b/x-pack/plugins/index_management/public/application/components/component_templates/lib/request.ts @@ -22,14 +22,14 @@ export type UseRequestHook = ( ) => UseRequestResponse; export type SendRequestHook = (config: SendRequestConfig) => Promise; -export const getUseRequest = (httpClient: HttpSetup): UseRequestHook => ( - config: UseRequestConfig -) => { - return _useRequest(httpClient, config); -}; +export const getUseRequest = + (httpClient: HttpSetup): UseRequestHook => + (config: UseRequestConfig) => { + return _useRequest(httpClient, config); + }; -export const getSendRequest = (httpClient: HttpSetup): SendRequestHook => ( - config: SendRequestConfig -) => { - return _sendRequest(httpClient, config); -}; +export const getSendRequest = + (httpClient: HttpSetup): SendRequestHook => + (config: SendRequestConfig) => { + return _sendRequest(httpClient, config); + }; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/setup_environment.tsx index efd1ec7062423..7055dcc74ce7b 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/__jest__/client_integration/helpers/setup_environment.tsx @@ -78,12 +78,13 @@ const defaultProps = { docLinks: docLinksServiceMock.createStartContract(), }; -export const WithAppDependencies = (Comp: any) => (props: any) => ( - - - - - - - -); +export const WithAppDependencies = (Comp: any) => (props: any) => + ( + + + + + + + + ); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx index 7b464a299c24b..a28531ed70953 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/document_fields.tsx @@ -22,10 +22,8 @@ const { useGlobalFlyout } = GlobalFlyout; export const DocumentFields = React.memo(() => { const { fields, search, documentFields } = useMappingsState(); const dispatch = useDispatch(); - const { - addContent: addContentToGlobalFlyout, - removeContent: removeContentFromGlobalFlyout, - } = useGlobalFlyout(); + const { addContent: addContentToGlobalFlyout, removeContent: removeContentFromGlobalFlyout } = + useGlobalFlyout(); const { editor: editorType } = documentFields; const isEditing = documentFields.status === 'editingField'; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx index bb6a5aae82f1a..5d5f0fc0b930c 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/analyzer_parameter.tsx @@ -33,9 +33,9 @@ interface Props { const ANALYZER_OPTIONS = PARAMETERS_OPTIONS.analyzer!; // token_count requires a value for "analyzer", therefore, we cannot not allow "index_default" -const ANALYZER_OPTIONS_WITHOUT_DEFAULT = (PARAMETERS_OPTIONS.analyzer as SuperSelectOption[]).filter( - ({ value }) => value !== INDEX_DEFAULT -); +const ANALYZER_OPTIONS_WITHOUT_DEFAULT = ( + PARAMETERS_OPTIONS.analyzer as SuperSelectOption[] +).filter(({ value }) => value !== INDEX_DEFAULT); const getCustomAnalyzers = (indexSettings: IndexSettings): SelectOption[] | undefined => { const settings: IndexSettingsInterface = {}.hasOwnProperty.call(indexSettings, 'index') diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx index 5ce48f63f0b94..aeb4debddcd65 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/field_parameters/path_parameter.tsx @@ -40,20 +40,20 @@ const getSuggestedFields = ( })) .sort((a, b) => (a.label > b.label ? 1 : a.label < b.label ? -1 : 0)); -const getDeserializer = (allFields: NormalizedFields['byId']): SerializerFunc => ( - value: string | object -): AliasOption[] => { - if (typeof value === 'string' && Boolean(value)) { - return [ - { - id: value, - label: allFields[value].path.join(' > '), - }, - ]; - } +const getDeserializer = + (allFields: NormalizedFields['byId']): SerializerFunc => + (value: string | object): AliasOption[] => { + if (typeof value === 'string' && Boolean(value)) { + return [ + { + id: value, + label: allFields[value].path.join(' > '), + }, + ]; + } - return []; -}; + return []; + }; interface Props { allFields: NormalizedFields['byId']; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx index 1a03dec48c97e..2a007e7741d4a 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/field_types/text_type.tsx @@ -74,13 +74,12 @@ const getDefaultToggleValue = (param: string, field: FieldType) => { }; export const TextType = React.memo(({ field }: Props) => { - const onIndexPrefixesChanage = (minField: FieldHook, maxField: FieldHook) => ([ - min, - max, - ]: any) => { - minField.setValue(min); - maxField.setValue(max); - }; + const onIndexPrefixesChanage = + (minField: FieldHook, maxField: FieldHook) => + ([min, max]: any) => { + minField.setValue(min); + maxField.setValue(max); + }; return ( <> diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx index 1f4e1d1475e5d..76284f925c3b1 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/fields_list_item.tsx @@ -131,12 +131,8 @@ function FieldListItemComponent( return null; } - const { - addMultiFieldButtonLabel, - addPropertyButtonLabel, - editButtonLabel, - deleteButtonLabel, - } = i18nTexts; + const { addMultiFieldButtonLabel, addPropertyButtonLabel, editButtonLabel, deleteButtonLabel } = + i18nTexts; return ( diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx index 7f6aea8878a77..2413df5e5d64d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/load_mappings/load_mappings_provider.test.tsx @@ -37,20 +37,22 @@ const setup = (props: any) => defaultProps: props, })(); -const openModalWithJsonContent = ({ component, find }: TestBed) => (json: any) => { - act(() => { - find('load-json-button').simulate('click'); - }); +const openModalWithJsonContent = + ({ component, find }: TestBed) => + (json: any) => { + act(() => { + find('load-json-button').simulate('click'); + }); - component.update(); + component.update(); - act(() => { - // Set the mappings to load - find('mockCodeEditor').simulate('change', { - jsonString: JSON.stringify(json), + act(() => { + // Set the mappings to load + find('mockCodeEditor').simulate('change', { + jsonString: JSON.stringify(json), + }); }); - }); -}; + }; describe('', () => { test('it should forward valid mapping definition', () => { diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/runtime_fields/runtime_fields_list.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/runtime_fields/runtime_fields_list.tsx index 387c53e3353fc..13cbd8e227328 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/runtime_fields/runtime_fields_list.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/runtime_fields/runtime_fields_list.tsx @@ -34,10 +34,8 @@ export const RuntimeFieldsList = () => { const dispatch = useDispatch(); - const { - addContent: addContentToGlobalFlyout, - removeContent: removeContentFromGlobalFlyout, - } = useGlobalFlyout(); + const { addContent: addContentToGlobalFlyout, removeContent: removeContentFromGlobalFlyout } = + useGlobalFlyout(); const { value: { docLinks }, diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts index 2abaeb45639bf..3eb2f8d6371d8 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/lib/mappings_validator.ts @@ -284,9 +284,8 @@ export const validateMappings = (mappings: any = {}): MappingsValidatorResponse const { properties, dynamic_templates: dynamicTemplates, ...mappingsConfiguration } = mappings; - const { value: parsedConfiguration, errors: configurationErrors } = validateMappingsConfiguration( - mappingsConfiguration - ); + const { value: parsedConfiguration, errors: configurationErrors } = + validateMappingsConfiguration(mappingsConfiguration); const { value: parsedProperties, errors: propertiesErrors } = validateProperties(properties); const errors = [...configurationErrors, ...propertiesErrors]; diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx index cd2740d78df3f..b188b15b0fb72 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/mappings_editor.tsx @@ -51,50 +51,48 @@ interface Props { } export const MappingsEditor = React.memo(({ onChange, value, docLinks, indexSettings }: Props) => { - const { - parsedDefaultValue, - multipleMappingsDeclared, - } = useMemo(() => { - const mappingsDefinition = extractMappingsDefinition(value); - - if (mappingsDefinition === null) { - return { multipleMappingsDeclared: true }; - } + const { parsedDefaultValue, multipleMappingsDeclared } = + useMemo(() => { + const mappingsDefinition = extractMappingsDefinition(value); + + if (mappingsDefinition === null) { + return { multipleMappingsDeclared: true }; + } - const { - _source, - _meta, - _routing, - dynamic, - properties, - runtime, - /* eslint-disable @typescript-eslint/naming-convention */ - numeric_detection, - date_detection, - dynamic_date_formats, - dynamic_templates, - /* eslint-enable @typescript-eslint/naming-convention */ - } = mappingsDefinition; - - const parsed = { - configuration: { + const { _source, _meta, _routing, dynamic, + properties, + runtime, + /* eslint-disable @typescript-eslint/naming-convention */ numeric_detection, date_detection, dynamic_date_formats, - }, - fields: properties, - templates: { dynamic_templates, - }, - runtime, - }; - - return { parsedDefaultValue: parsed, multipleMappingsDeclared: false }; - }, [value]); + /* eslint-enable @typescript-eslint/naming-convention */ + } = mappingsDefinition; + + const parsed = { + configuration: { + _source, + _meta, + _routing, + dynamic, + numeric_detection, + date_detection, + dynamic_date_formats, + }, + fields: properties, + templates: { + dynamic_templates, + }, + runtime, + }; + + return { parsedDefaultValue: parsed, multipleMappingsDeclared: false }; + }, [value]); /** * Hook that will listen to: diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx index e7ace1aff3101..2314f269e540d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/use_state_listener.tsx @@ -41,9 +41,10 @@ export const useMappingsStateListener = ({ onChange, value }: Args) => { const { fields: mappedFields, runtime: runtimeFields } = value ?? {}; const parsedFieldsDefaultValue = useMemo(() => normalize(mappedFields), [mappedFields]); - const parsedRuntimeFieldsDefaultValue = useMemo(() => normalizeRuntimeFields(runtimeFields), [ - runtimeFields, - ]); + const parsedRuntimeFieldsDefaultValue = useMemo( + () => normalizeRuntimeFields(runtimeFields), + [runtimeFields] + ); useEffect(() => { // If we are creating a new field, but haven't entered any name diff --git a/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx b/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx index 4ccd77d275a94..a0362b440cb0b 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/template_form.tsx @@ -196,22 +196,21 @@ export const TemplateForm = ({ }; const buildTemplateObject = useCallback( - (initialTemplate: TemplateDeserialized) => ( - wizardData: WizardContent - ): TemplateDeserialized => { - const outputTemplate = { - ...wizardData.logistics, - _kbnMeta: initialTemplate._kbnMeta, - composedOf: wizardData.components, - template: { - settings: wizardData.settings, - mappings: wizardData.mappings, - aliases: wizardData.aliases, - }, - }; - - return cleanupTemplateObject(outputTemplate); - }, + (initialTemplate: TemplateDeserialized) => + (wizardData: WizardContent): TemplateDeserialized => { + const outputTemplate = { + ...wizardData.logistics, + _kbnMeta: initialTemplate._kbnMeta, + composedOf: wizardData.components, + template: { + settings: wizardData.settings, + mappings: wizardData.mappings, + aliases: wizardData.aliases, + }, + }; + + return cleanupTemplateObject(outputTemplate); + }, [] ); diff --git a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx index 7bd7c163837d8..583d1fcb83ed4 100644 --- a/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx +++ b/x-pack/plugins/index_management/public/application/sections/home/data_stream_list/data_stream_list.tsx @@ -61,7 +61,12 @@ export const DataStreamList: React.FunctionComponent(false); const [saveError, setSaveError] = useState(null); - const { error: templateToCloneError, data: templateToClone, isLoading } = useLoadIndexTemplate( - decodedTemplateName, - isLegacy - ); + const { + error: templateToCloneError, + data: templateToClone, + isLoading, + } = useLoadIndexTemplate(decodedTemplateName, isLegacy); const onSave = async (template: TemplateDeserialized) => { setIsSaving(true); diff --git a/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js b/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js index 75dc762b8f894..179aa73b4f0a8 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/clear_cache_indices.js @@ -14,19 +14,21 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus, reloadIndices } from '../actions'; export const clearCacheIndicesStart = createAction('INDEX_MANAGEMENT_CLEAR_CACHE_INDICES_START'); -export const clearCacheIndices = ({ indexNames }) => async (dispatch) => { - dispatch(clearCacheIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.clearCacheIndicesAction.successMessage', { - defaultMessage: 'Successfully cleared cache: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const clearCacheIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(clearCacheIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.clearCacheIndicesAction.successMessage', { + defaultMessage: 'Successfully cleared cache: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/close_indices.js b/x-pack/plugins/index_management/public/application/store/actions/close_indices.js index 4ba2db666e009..1669d6b1b022f 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/close_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/close_indices.js @@ -12,19 +12,21 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus, reloadIndices } from '../actions'; export const closeIndicesStart = createAction('INDEX_MANAGEMENT_CLOSE_INDICES_START'); -export const closeIndices = ({ indexNames }) => async (dispatch) => { - dispatch(closeIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.closeIndicesAction.successfullyClosedIndicesMessage', { - defaultMessage: 'Successfully closed: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const closeIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(closeIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.closeIndicesAction.successfullyClosedIndicesMessage', { + defaultMessage: 'Successfully closed: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js b/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js index d886b35879d4f..307c359b0fe21 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/delete_indices.js @@ -12,18 +12,20 @@ import { notificationService } from '../../services/notification'; import { clearRowStatus } from '../actions'; export const deleteIndicesSuccess = createAction('INDEX_MANAGEMENT_DELETE_INDICES_SUCCESS'); -export const deleteIndices = ({ indexNames }) => async (dispatch) => { - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.deleteIndicesAction.successfullyDeletedIndicesMessage', { - defaultMessage: 'Successfully deleted: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); - dispatch(deleteIndicesSuccess({ indexNames })); -}; +export const deleteIndices = + ({ indexNames }) => + async (dispatch) => { + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.deleteIndicesAction.successfullyDeletedIndicesMessage', { + defaultMessage: 'Successfully deleted: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + dispatch(deleteIndicesSuccess({ indexNames })); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js b/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js index 0ebb36f68311f..4a82ced82eb83 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js +++ b/x-pack/plugins/index_management/public/application/store/actions/edit_index_settings.js @@ -10,27 +10,29 @@ import { loadIndexSettings as request } from '../../services'; import { notificationService } from '../../services/notification'; import { loadIndexDataSuccess } from './load_index_data'; -export const editIndexSettings = ({ indexName }) => async (dispatch) => { - let indexSettings; - try { - indexSettings = await request(indexName); - } catch (error) { - return notificationService.showDangerToast(error.message); - } - notificationService.showSuccessToast( - i18n.translate( - 'xpack.idxMgmt.editIndexSettingsAction.successfullySavedSettingsForIndicesMessage', - { - defaultMessage: 'Successfully saved settings for {indexName}', - values: { indexName }, - } - ) - ); - dispatch( - loadIndexDataSuccess({ - data: indexSettings, - panelType: 'editIndexSettings', - indexName, - }) - ); -}; +export const editIndexSettings = + ({ indexName }) => + async (dispatch) => { + let indexSettings; + try { + indexSettings = await request(indexName); + } catch (error) { + return notificationService.showDangerToast(error.message); + } + notificationService.showSuccessToast( + i18n.translate( + 'xpack.idxMgmt.editIndexSettingsAction.successfullySavedSettingsForIndicesMessage', + { + defaultMessage: 'Successfully saved settings for {indexName}', + values: { indexName }, + } + ) + ); + dispatch( + loadIndexDataSuccess({ + data: indexSettings, + panelType: 'editIndexSettings', + indexName, + }) + ); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/extension_action.js b/x-pack/plugins/index_management/public/application/store/actions/extension_action.js index 97937f67f9ae4..eda9d32d75fba 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/extension_action.js +++ b/x-pack/plugins/index_management/public/application/store/actions/extension_action.js @@ -9,15 +9,15 @@ import { reloadIndices } from '../actions'; import { notificationService } from '../../services/notification'; import { httpService } from '../../services/http'; -export const performExtensionAction = ({ requestMethod, indexNames, successMessage }) => async ( - dispatch -) => { - try { - await requestMethod(indexNames, httpService.httpClient); - } catch (error) { - notificationService.showDangerToast(error.message); - return; - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast(successMessage); -}; +export const performExtensionAction = + ({ requestMethod, indexNames, successMessage }) => + async (dispatch) => { + try { + await requestMethod(indexNames, httpService.httpClient); + } catch (error) { + notificationService.showDangerToast(error.message); + return; + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast(successMessage); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js b/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js index f3dae725947e1..364b87e9f2bb7 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/flush_indices.js @@ -13,19 +13,21 @@ import { notificationService } from '../../services/notification'; export const flushIndicesStart = createAction('INDEX_MANAGEMENT_FLUSH_INDICES_START'); -export const flushIndices = ({ indexNames }) => async (dispatch) => { - dispatch(flushIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.flushIndicesAction.successfullyFlushedIndicesMessage', { - defaultMessage: 'Successfully flushed: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const flushIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(flushIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.flushIndicesAction.successfullyFlushedIndicesMessage', { + defaultMessage: 'Successfully flushed: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js b/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js index 726e5a1fbed27..60f5da7d4925d 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/forcemerge_indices.js @@ -13,19 +13,24 @@ import { notificationService } from '../../services/notification'; export const forcemergeIndicesStart = createAction('INDEX_MANAGEMENT_FORCEMERGE_INDICES_START'); -export const forcemergeIndices = ({ indexNames, maxNumSegments }) => async (dispatch) => { - dispatch(forcemergeIndicesStart({ indexNames })); - try { - await request(indexNames, maxNumSegments); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.forceMergeIndicesAction.successfullyForceMergedIndicesMessage', { - defaultMessage: 'Successfully force merged: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const forcemergeIndices = + ({ indexNames, maxNumSegments }) => + async (dispatch) => { + dispatch(forcemergeIndicesStart({ indexNames })); + try { + await request(indexNames, maxNumSegments); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate( + 'xpack.idxMgmt.forceMergeIndicesAction.successfullyForceMergedIndicesMessage', + { + defaultMessage: 'Successfully force merged: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + } + ) + ); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js b/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js index f06239cc0d1b4..002b0c5f00c9d 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/freeze_indices.js @@ -13,19 +13,21 @@ import { notificationService } from '../../services/notification'; export const freezeIndicesStart = createAction('INDEX_MANAGEMENT_FREEZE_INDICES_START'); -export const freezeIndices = ({ indexNames }) => async (dispatch) => { - dispatch(freezeIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.freezeIndicesAction.successfullyFrozeIndicesMessage', { - defaultMessage: 'Successfully froze: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const freezeIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(freezeIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.freezeIndicesAction.successfullyFrozeIndicesMessage', { + defaultMessage: 'Successfully froze: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js b/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js index 0fc37fa7cc98b..18925d6d05e64 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js +++ b/x-pack/plugins/index_management/public/application/store/actions/load_index_data.js @@ -11,12 +11,14 @@ import { notificationService } from '../../services/notification'; export const loadIndexDataSuccess = createAction('INDEX_MANAGEMENT_LOAD_INDEX_DATA_SUCCESS'); -export const loadIndexData = ({ indexName, dataType }) => async (dispatch) => { - let data; - try { - data = await request(dataType, indexName); - } catch (error) { - notificationService.showDangerToast(error.message); - } - dispatch(loadIndexDataSuccess({ data, indexName })); -}; +export const loadIndexData = + ({ indexName, dataType }) => + async (dispatch) => { + let data; + try { + data = await request(dataType, indexName); + } catch (error) { + notificationService.showDangerToast(error.message); + } + dispatch(loadIndexDataSuccess({ data, indexName })); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/open_indices.js b/x-pack/plugins/index_management/public/application/store/actions/open_indices.js index 7c74f0ae870e9..73a4a3350b841 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/open_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/open_indices.js @@ -13,19 +13,21 @@ import { notificationService } from '../../services/notification'; export const openIndicesStart = createAction('INDEX_MANAGEMENT_OPEN_INDICES_START'); -export const openIndices = ({ indexNames }) => async (dispatch) => { - dispatch(openIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.openIndicesAction.successfullyOpenedIndicesMessage', { - defaultMessage: 'Successfully opened: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const openIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(openIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.openIndicesAction.successfullyOpenedIndicesMessage', { + defaultMessage: 'Successfully opened: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js b/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js index 0f1162bacc814..77944344c47c7 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/refresh_indices.js @@ -13,19 +13,21 @@ import { clearRowStatus, reloadIndices } from '../actions'; import { notificationService } from '../../services/notification'; export const refreshIndicesStart = createAction('INDEX_MANAGEMENT_REFRESH_INDICES_START'); -export const refreshIndices = ({ indexNames }) => async (dispatch) => { - dispatch(refreshIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.refreshIndicesAction.successfullyRefreshedIndicesMessage', { - defaultMessage: 'Successfully refreshed: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const refreshIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(refreshIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.refreshIndicesAction.successfullyRefreshedIndicesMessage', { + defaultMessage: 'Successfully refreshed: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js b/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js index 9b0220e33b175..96d38c48f240d 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js +++ b/x-pack/plugins/index_management/public/application/store/actions/unfreeze_indices.js @@ -13,19 +13,21 @@ import { notificationService } from '../../services/notification'; export const unfreezeIndicesStart = createAction('INDEX_MANAGEMENT_UNFREEZE_INDICES_START'); -export const unfreezeIndices = ({ indexNames }) => async (dispatch) => { - dispatch(unfreezeIndicesStart({ indexNames })); - try { - await request(indexNames); - } catch (error) { - notificationService.showDangerToast(error.message); - return dispatch(clearRowStatus({ indexNames })); - } - dispatch(reloadIndices(indexNames)); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.unfreezeIndicesAction.successfullyUnfrozeIndicesMessage', { - defaultMessage: 'Successfully unfroze: [{indexNames}]', - values: { indexNames: indexNames.join(', ') }, - }) - ); -}; +export const unfreezeIndices = + ({ indexNames }) => + async (dispatch) => { + dispatch(unfreezeIndicesStart({ indexNames })); + try { + await request(indexNames); + } catch (error) { + notificationService.showDangerToast(error.message); + return dispatch(clearRowStatus({ indexNames })); + } + dispatch(reloadIndices(indexNames)); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.unfreezeIndicesAction.successfullyUnfrozeIndicesMessage', { + defaultMessage: 'Successfully unfroze: [{indexNames}]', + values: { indexNames: indexNames.join(', ') }, + }) + ); + }; diff --git a/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js b/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js index 5d2fd5353fe09..bbb251634976e 100644 --- a/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js +++ b/x-pack/plugins/index_management/public/application/store/actions/update_index_settings.js @@ -18,24 +18,26 @@ export const updateIndexSettingsError = createAction( 'INDEX_MANAGEMENT_UPDATE_INDEX_SETTINGS_ERROR' ); -export const updateIndexSettings = ({ indexName, settings }) => async (dispatch) => { - if (Object.keys(settings).length !== 0) { - try { - const { error, message } = await request(indexName, settings); +export const updateIndexSettings = + ({ indexName, settings }) => + async (dispatch) => { + if (Object.keys(settings).length !== 0) { + try { + const { error, message } = await request(indexName, settings); - if (error) { - return dispatch(updateIndexSettingsError({ error: message })); + if (error) { + return dispatch(updateIndexSettingsError({ error: message })); + } + } catch (error) { + return dispatch(updateIndexSettingsError({ error: error.message })); } - } catch (error) { - return dispatch(updateIndexSettingsError({ error: error.message })); } - } - dispatch(updateIndexSettingsSuccess()); - dispatch(reloadIndices([indexName])); - notificationService.showSuccessToast( - i18n.translate('xpack.idxMgmt.updateIndexSettingsAction.settingsSuccessUpdateMessage', { - defaultMessage: 'Successfully updated settings for index {indexName}', - values: { indexName }, - }) - ); -}; + dispatch(updateIndexSettingsSuccess()); + dispatch(reloadIndices([indexName])); + notificationService.showSuccessToast( + i18n.translate('xpack.idxMgmt.updateIndexSettingsAction.settingsSuccessUpdateMessage', { + defaultMessage: 'Successfully updated settings for index {indexName}', + values: { indexName }, + }) + ); + }; diff --git a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts b/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts index fdbf0db89e689..2c5070ab846ad 100644 --- a/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts +++ b/x-pack/plugins/index_management/server/routes/api/component_templates/register_privileges_route.test.ts @@ -19,7 +19,7 @@ const httpService = httpServiceMock.createSetupContract(); const mockedIndexDataEnricher = new IndexDataEnricher(); const mockRouteContext = ({ hasPrivileges }: { hasPrivileges: unknown }): RequestHandlerContext => { - const routeContextMock = ({ + const routeContextMock = { core: { elasticsearch: { client: { @@ -31,7 +31,7 @@ const mockRouteContext = ({ hasPrivileges }: { hasPrivileges: unknown }): Reques }, }, }, - } as unknown) as RequestHandlerContext; + } as unknown as RequestHandlerContext; return routeContextMock; }; diff --git a/x-pack/plugins/infra/common/formatters/index.ts b/x-pack/plugins/infra/common/formatters/index.ts index a4aeee8084824..372df5b28ca1b 100644 --- a/x-pack/plugins/infra/common/formatters/index.ts +++ b/x-pack/plugins/infra/common/formatters/index.ts @@ -25,13 +25,13 @@ export const FORMATTERS = { highPercision: formatHighPercision, }; -export const createFormatter = (format: InventoryFormatterType, template: string = '{{value}}') => ( - val: string | number -) => { - if (val == null) { - return ''; - } - const fmtFn = FORMATTERS[format]; - const value = fmtFn(Number(val)); - return template.replace(/{{value}}/g, value); -}; +export const createFormatter = + (format: InventoryFormatterType, template: string = '{{value}}') => + (val: string | number) => { + if (val == null) { + return ''; + } + const fmtFn = FORMATTERS[format]; + const value = fmtFn(Number(val)); + return template.replace(/{{value}}/g, value); + }; diff --git a/x-pack/plugins/infra/common/http_api/log_sources/patch_log_source_configuration.ts b/x-pack/plugins/infra/common/http_api/log_sources/patch_log_source_configuration.ts index 30f53bc256cd8..a16f0651e7e5d 100644 --- a/x-pack/plugins/infra/common/http_api/log_sources/patch_log_source_configuration.ts +++ b/x-pack/plugins/infra/common/http_api/log_sources/patch_log_source_configuration.ts @@ -44,7 +44,8 @@ export type PatchLogSourceConfigurationRequestBody = rt.TypeOf< * response */ -export const patchLogSourceConfigurationSuccessResponsePayloadRT = getLogSourceConfigurationSuccessResponsePayloadRT; +export const patchLogSourceConfigurationSuccessResponsePayloadRT = + getLogSourceConfigurationSuccessResponsePayloadRT; export type PatchLogSourceConfigurationSuccessResponsePayload = rt.TypeOf< typeof patchLogSourceConfigurationSuccessResponsePayloadRT diff --git a/x-pack/plugins/infra/common/inventory_models/create_tsvb_model.ts b/x-pack/plugins/infra/common/inventory_models/create_tsvb_model.ts index 4280ef40a8249..5c9b3beb31c7c 100644 --- a/x-pack/plugins/infra/common/inventory_models/create_tsvb_model.ts +++ b/x-pack/plugins/infra/common/inventory_models/create_tsvb_model.ts @@ -7,19 +7,21 @@ import { TSVBMetricModelCreator, TSVBMetricModel, TSVBSeries, InventoryMetric } from './types'; -export const createTSVBModel = ( - id: InventoryMetric, - requires: string[], - series: TSVBSeries[], - interval = '>=300s', - dropLastBucket = true -): TSVBMetricModelCreator => (timeField, indexPattern): TSVBMetricModel => ({ - id, - requires, - drop_last_bucket: dropLastBucket, - index_pattern: indexPattern, - interval, - time_field: timeField, - type: 'timeseries', - series, -}); +export const createTSVBModel = + ( + id: InventoryMetric, + requires: string[], + series: TSVBSeries[], + interval = '>=300s', + dropLastBucket = true + ): TSVBMetricModelCreator => + (timeField, indexPattern): TSVBMetricModel => ({ + id, + requires, + drop_last_bucket: dropLastBucket, + index_pattern: indexPattern, + interval, + time_field: timeField, + type: 'timeseries', + series, + }); diff --git a/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx b/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx index 691ebec3c829c..b881396963d17 100644 --- a/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx +++ b/x-pack/plugins/infra/common/inventory_models/shared/components/metrics_and_groupby_toolbar_items.tsx @@ -34,9 +34,10 @@ export const MetricsAndGroupByToolbarItems = (props: Props) => { [props.metricTypes] ); - const groupByOptions = useMemo(() => props.groupByFields.map(toGroupByOpt), [ - props.groupByFields, - ]); + const groupByOptions = useMemo( + () => props.groupByFields.map(toGroupByOpt), + [props.groupByFields] + ); return ( <> diff --git a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts index ee831d9a98eb9..9c41a216c7f92 100644 --- a/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts +++ b/x-pack/plugins/infra/common/log_sources/resolved_log_source_configuration.ts @@ -106,9 +106,9 @@ const resolveKibanaIndexPatternReference = async ( const resolveRuntimeMappings = (indexPattern: IndexPattern): estypes.MappingRuntimeFields => { const { runtimeFields } = indexPattern.getComputedFields(); - const runtimeMappingsFromIndexPattern = (Object.entries(runtimeFields) as ObjectEntries< - typeof runtimeFields - >).reduce( + const runtimeMappingsFromIndexPattern = ( + Object.entries(runtimeFields) as ObjectEntries + ).reduce( (accumulatedMappings, [runtimeFieldName, runtimeFieldSpec]) => ({ ...accumulatedMappings, [runtimeFieldName]: { diff --git a/x-pack/plugins/infra/common/runtime_types.ts b/x-pack/plugins/infra/common/runtime_types.ts index 43c1e3f520556..06df361b3de42 100644 --- a/x-pack/plugins/infra/common/runtime_types.ts +++ b/x-pack/plugins/infra/common/runtime_types.ts @@ -45,21 +45,25 @@ export const throwErrors = (createError: ErrorFactory) => (errors: Errors) => { throw createError(formatErrors(errors)); }; -export const decodeOrThrow = ( - runtimeType: Type, - createError: ErrorFactory = createPlainError -) => (inputValue: InputValue) => - pipe(runtimeType.decode(inputValue), fold(throwErrors(createError), identity)); +export const decodeOrThrow = + ( + runtimeType: Type, + createError: ErrorFactory = createPlainError + ) => + (inputValue: InputValue) => + pipe(runtimeType.decode(inputValue), fold(throwErrors(createError), identity)); type ValdidationResult = ReturnType>; -export const createValidationFunction = ( - runtimeType: Type -): RouteValidationFunction => (inputValue, { badRequest, ok }) => - pipe( - runtimeType.decode(inputValue), - fold>( - (errors: Errors) => badRequest(formatErrors(errors)), - (result: DecodedValue) => ok(result) - ) - ); +export const createValidationFunction = + ( + runtimeType: Type + ): RouteValidationFunction => + (inputValue, { badRequest, ok }) => + pipe( + runtimeType.decode(inputValue), + fold>( + (errors: Errors) => badRequest(formatErrors(errors)), + (result: DecodedValue) => ok(result) + ) + ); diff --git a/x-pack/plugins/infra/common/time/time_key.ts b/x-pack/plugins/infra/common/time/time_key.ts index 0647c6dcab42a..42b14625d22a9 100644 --- a/x-pack/plugins/infra/common/time/time_key.ts +++ b/x-pack/plugins/infra/common/time/time_key.ts @@ -54,10 +54,10 @@ export function compareTimeKeys( return timeComparison; } -export const compareToTimeKey = ( - keyAccessor: (value: Value) => TimeKey, - compareValues?: Comparator -) => (value: Value, key: TimeKey) => compareTimeKeys(keyAccessor(value), key, compareValues); +export const compareToTimeKey = + (keyAccessor: (value: Value) => TimeKey, compareValues?: Comparator) => + (value: Value, key: TimeKey) => + compareTimeKeys(keyAccessor(value), key, compareValues); export const getIndexAtTimeKey = ( keyAccessor: (value: Value) => TimeKey, diff --git a/x-pack/plugins/infra/common/utility_types.ts b/x-pack/plugins/infra/common/utility_types.ts index 1f26309973f0d..49d60c31a71ef 100644 --- a/x-pack/plugins/infra/common/utility_types.ts +++ b/x-pack/plugins/infra/common/utility_types.ts @@ -12,10 +12,9 @@ export type Pick3 = T & - { - [prop in Prop]-?: NonNullable; - }; +export type MandatoryProperty = T & { + [prop in Prop]-?: NonNullable; +}; /** * Portions of below code are derived from https://github.com/tycho01/typical diff --git a/x-pack/plugins/infra/public/alerting/common/components/metrics_alert_dropdown.tsx b/x-pack/plugins/infra/public/alerting/common/components/metrics_alert_dropdown.tsx index 5cbd1909054af..b92144d37eaa1 100644 --- a/x-pack/plugins/infra/public/alerting/common/components/metrics_alert_dropdown.tsx +++ b/x-pack/plugins/infra/public/alerting/common/components/metrics_alert_dropdown.tsx @@ -26,9 +26,10 @@ export const MetricsAlertDropdown = () => { const [visibleFlyoutType, setVisibleFlyoutType] = useState(null); const uiCapabilities = useKibana().services.application?.capabilities; - const canCreateAlerts = useMemo(() => Boolean(uiCapabilities?.infrastructure?.save), [ - uiCapabilities, - ]); + const canCreateAlerts = useMemo( + () => Boolean(uiCapabilities?.infrastructure?.save), + [uiCapabilities] + ); const closeFlyout = useCallback(() => setVisibleFlyoutType(null), [setVisibleFlyoutType]); diff --git a/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx b/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx index 78005d9d87cf9..f72c9d4531424 100644 --- a/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx +++ b/x-pack/plugins/infra/public/alerting/inventory/components/expression.tsx @@ -119,9 +119,10 @@ export const Expressions: React.FC = (props) => { const [timeSize, setTimeSize] = useState(1); const [timeUnit, setTimeUnit] = useState('m'); - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern(), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern(), + [createDerivedIndexPattern] + ); const updateParams = useCallback( (id, e: InventoryMetricConditions) => { @@ -436,16 +437,8 @@ export const ExpressionRow: React.FC = (props) => { const [isExpanded, setRowState] = useState(true); const toggleRowState = useCallback(() => setRowState(!isExpanded), [isExpanded]); - const { - children, - setAlertParams, - expression, - errors, - expressionId, - remove, - canDelete, - fields, - } = props; + const { children, setAlertParams, expression, errors, expressionId, remove, canDelete, fields } = + props; const { metric, comparator = Comparator.GT, diff --git a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx index 4eb0f3e8645cf..2664a0d6aa2b0 100644 --- a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx +++ b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/editor.tsx @@ -159,175 +159,177 @@ export const SourceStatusWrapper: React.FC = ({ children }) => { ); }; -export const Editor: React.FC< - AlertTypeParamsExpressionProps -> = (props) => { - const { setAlertParams, alertParams, errors } = props; - const [hasSetDefaults, setHasSetDefaults] = useState(false); - const { sourceId, resolvedSourceConfiguration } = useLogSourceContext(); - - const { - criteria: criteriaErrors, - threshold: thresholdErrors, - timeSizeUnit: timeSizeUnitErrors, - timeWindowSize: timeWindowSizeErrors, - } = useMemo(() => decodeOrThrow(errorsRT)(errors), [errors]); - - const supportedFields = useMemo(() => { - if (resolvedSourceConfiguration?.fields) { - return resolvedSourceConfiguration.fields.filter((field) => { - return (field.type === 'string' || field.type === 'number') && field.searchable; - }); - } else { - return []; - } - }, [resolvedSourceConfiguration]); - - const groupByFields = useMemo(() => { - if (resolvedSourceConfiguration?.fields) { - return resolvedSourceConfiguration.fields.filter((field) => { - return field.type === 'string' && field.aggregatable; - }); - } else { - return []; - } - }, [resolvedSourceConfiguration]); - - const updateThreshold = useCallback( - (thresholdParams) => { - const nextThresholdParams = { ...alertParams.count, ...thresholdParams }; - setAlertParams('count', nextThresholdParams); - }, - [alertParams.count, setAlertParams] - ); - - const updateCriteria = useCallback( - (criteria: PartialCriteriaType) => { - setAlertParams('criteria', criteria); - }, - [setAlertParams] - ); - - const updateTimeSize = useCallback( - (ts: number | undefined) => { - setAlertParams('timeSize', ts); - }, - [setAlertParams] - ); - - const updateTimeUnit = useCallback( - (tu: string) => { - if (timeUnitRT.is(tu)) { - setAlertParams('timeUnit', tu); +export const Editor: React.FC> = + (props) => { + const { setAlertParams, alertParams, errors } = props; + const [hasSetDefaults, setHasSetDefaults] = useState(false); + const { sourceId, resolvedSourceConfiguration } = useLogSourceContext(); + + const { + criteria: criteriaErrors, + threshold: thresholdErrors, + timeSizeUnit: timeSizeUnitErrors, + timeWindowSize: timeWindowSizeErrors, + } = useMemo(() => decodeOrThrow(errorsRT)(errors), [errors]); + + const supportedFields = useMemo(() => { + if (resolvedSourceConfiguration?.fields) { + return resolvedSourceConfiguration.fields.filter((field) => { + return (field.type === 'string' || field.type === 'number') && field.searchable; + }); + } else { + return []; } - }, - [setAlertParams] - ); - - const updateGroupBy = useCallback( - (groups: string[]) => { - setAlertParams('groupBy', groups); - }, - [setAlertParams] - ); - - const defaultCountAlertParams = useMemo(() => createDefaultCountAlertParams(supportedFields), [ - supportedFields, - ]); - - const updateType = useCallback( - (type: ThresholdType) => { - const defaults = - type === 'count' ? defaultCountAlertParams : createDefaultRatioAlertParams(supportedFields); - // Reset properties that don't make sense switching from one context to the other - setAlertParams('count', defaults.count); - setAlertParams('criteria', defaults.criteria); - }, - [defaultCountAlertParams, setAlertParams, supportedFields] - ); + }, [resolvedSourceConfiguration]); + + const groupByFields = useMemo(() => { + if (resolvedSourceConfiguration?.fields) { + return resolvedSourceConfiguration.fields.filter((field) => { + return field.type === 'string' && field.aggregatable; + }); + } else { + return []; + } + }, [resolvedSourceConfiguration]); + + const updateThreshold = useCallback( + (thresholdParams) => { + const nextThresholdParams = { ...alertParams.count, ...thresholdParams }; + setAlertParams('count', nextThresholdParams); + }, + [alertParams.count, setAlertParams] + ); - useMount(() => { - const newAlertParams = { ...defaultCountAlertParams, ...alertParams }; - for (const [key, value] of Object.entries(newAlertParams) as ObjectEntries< - typeof newAlertParams - >) { - setAlertParams(key, value); - } - setHasSetDefaults(true); - }); + const updateCriteria = useCallback( + (criteria: PartialCriteriaType) => { + setAlertParams('criteria', criteria); + }, + [setAlertParams] + ); - const shouldShowGroupByOptimizationWarning = useMemo(() => { - const hasSetGroupBy = alertParams.groupBy && alertParams.groupBy.length > 0; - return ( - hasSetGroupBy && - alertParams.count && - !isOptimizableGroupedThreshold(alertParams.count.comparator, alertParams.count.value) + const updateTimeSize = useCallback( + (ts: number | undefined) => { + setAlertParams('timeSize', ts); + }, + [setAlertParams] ); - }, [alertParams]); - - // Wait until the alert param defaults have been set - if (!hasSetDefaults) return null; - - const criteriaComponent = alertParams.criteria ? ( - - ) : null; - return ( - <> - + const updateTimeUnit = useCallback( + (tu: string) => { + if (timeUnitRT.is(tu)) { + setAlertParams('timeUnit', tu); + } + }, + [setAlertParams] + ); - {alertParams.criteria && !isRatioAlert(alertParams.criteria) && criteriaComponent} + const updateGroupBy = useCallback( + (groups: string[]) => { + setAlertParams('groupBy', groups); + }, + [setAlertParams] + ); - + const defaultCountAlertParams = useMemo( + () => createDefaultCountAlertParams(supportedFields), + [supportedFields] + ); - + const updateType = useCallback( + (type: ThresholdType) => { + const defaults = + type === 'count' + ? defaultCountAlertParams + : createDefaultRatioAlertParams(supportedFields); + // Reset properties that don't make sense switching from one context to the other + setAlertParams('count', defaults.count); + setAlertParams('criteria', defaults.criteria); + }, + [defaultCountAlertParams, setAlertParams, supportedFields] + ); - { + const newAlertParams = { ...defaultCountAlertParams, ...alertParams }; + for (const [key, value] of Object.entries(newAlertParams) as ObjectEntries< + typeof newAlertParams + >) { + setAlertParams(key, value); + } + setHasSetDefaults(true); + }); + + const shouldShowGroupByOptimizationWarning = useMemo(() => { + const hasSetGroupBy = alertParams.groupBy && alertParams.groupBy.length > 0; + return ( + hasSetGroupBy && + alertParams.count && + !isOptimizableGroupedThreshold(alertParams.count.comparator, alertParams.count.value) + ); + }, [alertParams]); + + // Wait until the alert param defaults have been set + if (!hasSetDefaults) return null; + + const criteriaComponent = alertParams.criteria ? ( + + ) : null; - {alertParams.criteria && isRatioAlert(alertParams.criteria) && criteriaComponent} - - {shouldShowGroupByOptimizationWarning && ( - <> - - - {i18n.translate('xpack.infra.logs.alertFlyout.groupByOptimizationWarning', { - defaultMessage: - 'When setting a "group by" we highly recommend using the "{comparator}" comparator for your threshold. This can lead to significant performance improvements.', - values: { - comparator: Comparator.GT, - }, - })} - - - )} - - - - ); -}; + return ( + <> + + + {alertParams.criteria && !isRatioAlert(alertParams.criteria) && criteriaComponent} + + + + + + + + {alertParams.criteria && isRatioAlert(alertParams.criteria) && criteriaComponent} + + {shouldShowGroupByOptimizationWarning && ( + <> + + + {i18n.translate('xpack.infra.logs.alertFlyout.groupByOptimizationWarning', { + defaultMessage: + 'When setting a "group by" we highly recommend using the "{comparator}" comparator for your threshold. This can lead to significant performance improvements.', + values: { + comparator: Comparator.GT, + }, + })} + + + )} + + + + ); + }; // required for dynamic import // eslint-disable-next-line import/no-default-export diff --git a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/hooks/use_chart_preview_data.tsx b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/hooks/use_chart_preview_data.tsx index f97ad64adedd4..42f826d09aca8 100644 --- a/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/hooks/use_chart_preview_data.tsx +++ b/x-pack/plugins/infra/public/alerting/log_threshold/components/expression_editor/hooks/use_chart_preview_data.tsx @@ -49,9 +49,10 @@ export const useChartPreviewData = ({ sourceId, alertParams, buckets }: Options) [sourceId, http, alertParams, buckets] ); - const isLoading = useMemo(() => getChartPreviewDataRequest.state === 'pending', [ - getChartPreviewDataRequest.state, - ]); + const isLoading = useMemo( + () => getChartPreviewDataRequest.state === 'pending', + [getChartPreviewDataRequest.state] + ); return { chartPreviewData, diff --git a/x-pack/plugins/infra/public/alerting/metric_anomaly/components/expression.tsx b/x-pack/plugins/infra/public/alerting/metric_anomaly/components/expression.tsx index 9f5c47554ac56..5c821c89ad317 100644 --- a/x-pack/plugins/infra/public/alerting/metric_anomaly/components/expression.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_anomaly/components/expression.tsx @@ -66,9 +66,10 @@ export const Expression: React.FC = (props) => { toastWarning: notifications.toasts.addWarning, }); - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern(), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern(), + [createDerivedIndexPattern] + ); const [influencerFieldName, updateInfluencerFieldName] = useState( alertParams.influencerFilter?.fieldName ?? 'host.name' diff --git a/x-pack/plugins/infra/public/alerting/metric_anomaly/components/influencer_filter.tsx b/x-pack/plugins/infra/public/alerting/metric_anomaly/components/influencer_filter.tsx index 34a917a77dcf5..fa149ab12fd63 100644 --- a/x-pack/plugins/infra/public/alerting/metric_anomaly/components/influencer_filter.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_anomaly/components/influencer_filter.tsx @@ -35,9 +35,10 @@ export const InfluencerFilter = ({ onChangeFieldValue, derivedIndexPattern, }: Props) => { - const fieldNameOptions = useMemo(() => (nodeType === 'k8s' ? k8sFieldNames : hostFieldNames), [ - nodeType, - ]); + const fieldNameOptions = useMemo( + () => (nodeType === 'k8s' ? k8sFieldNames : hostFieldNames), + [nodeType] + ); // If initial props contain a fieldValue, assume it was passed in from loaded alertParams, // and enable the UI element @@ -52,9 +53,10 @@ export const InfluencerFilter = ({ [nodeType, onChangeFieldName] ); - const onSelectFieldName = useCallback((e) => onChangeFieldName(e.target.value), [ - onChangeFieldName, - ]); + const onSelectFieldName = useCallback( + (e) => onChangeFieldName(e.target.value), + [onChangeFieldName] + ); const onUpdateFieldValue = useCallback( (value) => { updateStoredFieldValue(value); @@ -79,32 +81,29 @@ export const InfluencerFilter = ({ [onUpdateFieldValue] ); - const affixFieldNameToQuery: CurryLoadSuggestionsType = (fn) => ( - expression, - cursorPosition, - maxSuggestions - ) => { - // Add the field name to the front of the passed-in query - const prefix = `${fieldName}:`; - // Trim whitespace to prevent AND/OR suggestions - const modifiedExpression = `${prefix}${expression}`.trim(); - // Move the cursor position forward by the length of the field name - const modifiedPosition = cursorPosition + prefix.length; - return fn(modifiedExpression, modifiedPosition, maxSuggestions, (suggestions) => - suggestions - .map((s) => ({ - ...s, - // Remove quotes from suggestions - text: s.text.replace(/\"/g, '').trim(), - // Offset the returned suggestions' cursor positions so that they can be autocompleted accurately - start: s.start - prefix.length, - end: s.end - prefix.length, - })) - // Removing quotes can lead to an already-selected suggestion still coming up in the autocomplete list, - // so filter these out - .filter((s) => !expression.startsWith(s.text)) - ); - }; + const affixFieldNameToQuery: CurryLoadSuggestionsType = + (fn) => (expression, cursorPosition, maxSuggestions) => { + // Add the field name to the front of the passed-in query + const prefix = `${fieldName}:`; + // Trim whitespace to prevent AND/OR suggestions + const modifiedExpression = `${prefix}${expression}`.trim(); + // Move the cursor position forward by the length of the field name + const modifiedPosition = cursorPosition + prefix.length; + return fn(modifiedExpression, modifiedPosition, maxSuggestions, (suggestions) => + suggestions + .map((s) => ({ + ...s, + // Remove quotes from suggestions + text: s.text.replace(/\"/g, '').trim(), + // Offset the returned suggestions' cursor positions so that they can be autocompleted accurately + start: s.start - prefix.length, + end: s.end - prefix.length, + })) + // Removing quotes can lead to an already-selected suggestion still coming up in the autocomplete list, + // so filter these out + .filter((s) => !expression.startsWith(s.text)) + ); + }; return ( = (props) => { const [timeSize, setTimeSize] = useState(1); const [timeUnit, setTimeUnit] = useState('m'); - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern(), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern(), + [createDerivedIndexPattern] + ); const options = useMemo(() => { if (metadata?.currentOptions?.metrics) { diff --git a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx index f6618603388d0..4dd191313261b 100644 --- a/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx +++ b/x-pack/plugins/infra/public/alerting/metric_threshold/components/expression_row.tsx @@ -74,16 +74,8 @@ const StyledHealth = euiStyled(EuiHealth)` export const ExpressionRow: React.FC = (props) => { const [isExpanded, setRowState] = useState(true); const toggleRowState = useCallback(() => setRowState(!isExpanded), [isExpanded]); - const { - children, - setAlertParams, - expression, - errors, - expressionId, - remove, - fields, - canDelete, - } = props; + const { children, setAlertParams, expression, errors, expressionId, remove, fields, canDelete } = + props; const { aggType = AGGREGATION_TYPES.MAX, metric, diff --git a/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx b/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx index fbb883b228088..0e3e2018c963b 100644 --- a/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx +++ b/x-pack/plugins/infra/public/components/autocomplete_field/autocomplete_field.tsx @@ -265,18 +265,17 @@ const withNextSuggestionSelected = ( : 0, }); -const withSuggestionAtIndexSelected = (suggestionIndex: number) => ( - state: AutocompleteFieldState, - props: AutocompleteFieldProps -): AutocompleteFieldState => ({ - ...state, - selectedIndex: - props.suggestions.length === 0 - ? null - : suggestionIndex >= 0 && suggestionIndex < props.suggestions.length - ? suggestionIndex - : 0, -}); +const withSuggestionAtIndexSelected = + (suggestionIndex: number) => + (state: AutocompleteFieldState, props: AutocompleteFieldProps): AutocompleteFieldState => ({ + ...state, + selectedIndex: + props.suggestions.length === 0 + ? null + : suggestionIndex >= 0 && suggestionIndex < props.suggestions.length + ? suggestionIndex + : 0, + }); const withSuggestionsVisible = (state: AutocompleteFieldState) => ({ ...state, diff --git a/x-pack/plugins/infra/public/components/basic_table/row_expansion_button.tsx b/x-pack/plugins/infra/public/components/basic_table/row_expansion_button.tsx index 76e7280acd080..7b046e9f2d252 100644 --- a/x-pack/plugins/infra/public/components/basic_table/row_expansion_button.tsx +++ b/x-pack/plugins/infra/public/components/basic_table/row_expansion_button.tsx @@ -20,12 +20,10 @@ export const RowExpansionButton = ({ onCollapse: (item: Item) => void; onExpand: (item: Item) => void; }) => { - const handleClick = useCallback(() => (isExpanded ? onCollapse(item) : onExpand(item)), [ - isExpanded, - item, - onCollapse, - onExpand, - ]); + const handleClick = useCallback( + () => (isExpanded ? onCollapse(item) : onExpand(item)), + [isExpanded, item, onCollapse, onExpand] + ); return ( getFormattedTime(time, dateFormat, fallbackFormat), [ - time, - dateFormat, - fallbackFormat, - ]); + const formattedTime = useMemo( + () => getFormattedTime(time, dateFormat, fallbackFormat), + [time, dateFormat, fallbackFormat] + ); return formattedTime; }; diff --git a/x-pack/plugins/infra/public/components/log_stream/log_stream_embeddable_factory.ts b/x-pack/plugins/infra/public/components/log_stream/log_stream_embeddable_factory.ts index 1c7e8ceb28fb4..15500dacf12d9 100644 --- a/x-pack/plugins/infra/public/components/log_stream/log_stream_embeddable_factory.ts +++ b/x-pack/plugins/infra/public/components/log_stream/log_stream_embeddable_factory.ts @@ -19,7 +19,8 @@ import { } from './log_stream_embeddable'; export class LogStreamEmbeddableFactoryDefinition - implements EmbeddableFactoryDefinition { + implements EmbeddableFactoryDefinition +{ public readonly type = LOG_STREAM_EMBEDDABLE; constructor(private getStartServices: StartServicesAccessor) {} diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx index 969838284f1aa..0ccd208cf24bd 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx @@ -23,14 +23,10 @@ export const LogAnalysisModuleList: React.FC<{ onViewModuleSetup: (module: ModuleId) => void; }> = ({ onViewModuleSetup }) => { const { hasLogAnalysisSetupCapabilities } = useLogAnalysisCapabilitiesContext(); - const { - setupStatus: logEntryRateSetupStatus, - jobIds: logEntryRateJobIds, - } = useLogEntryRateModuleContext(); - const { - setupStatus: logEntryCategoriesSetupStatus, - jobIds: logEntryCategoriesJobIds, - } = useLogEntryCategoriesModuleContext(); + const { setupStatus: logEntryRateSetupStatus, jobIds: logEntryRateJobIds } = + useLogEntryRateModuleContext(); + const { setupStatus: logEntryCategoriesSetupStatus, jobIds: logEntryCategoriesJobIds } = + useLogEntryCategoriesModuleContext(); const viewLogEntryRateSetupFlyout = useCallback(() => { onViewModuleSetup('logs_ui_analysis'); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx index 4a744eafaf5f9..77ebb9084dbe3 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx @@ -26,12 +26,8 @@ const FLYOUT_HEADING_ID = 'logAnalysisSetupFlyoutHeading'; export const LogAnalysisSetupFlyout: React.FC<{ allowedModules?: ModuleId[]; }> = ({ allowedModules = moduleIds }) => { - const { - closeFlyout, - flyoutView, - showModuleList, - showModuleSetup, - } = useLogAnalysisSetupFlyoutStateContext(); + const { closeFlyout, flyoutView, showModuleList, showModuleSetup } = + useLogAnalysisSetupFlyoutStateContext(); if (flyoutView.view === 'hidden') { return null; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts index 4f73781a07d77..8167b50ab6021 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts @@ -42,7 +42,5 @@ export const useLogAnalysisSetupFlyoutState = ({ }; }; -export const [ - LogAnalysisSetupFlyoutStateProvider, - useLogAnalysisSetupFlyoutStateContext, -] = createContainer(useLogAnalysisSetupFlyoutState); +export const [LogAnalysisSetupFlyoutStateProvider, useLogAnalysisSetupFlyoutStateContext] = + createContainer(useLogAnalysisSetupFlyoutState); diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx index 5ba2ddf736059..c871011d0f01a 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_row.tsx @@ -80,10 +80,10 @@ export const LogEntryRow = memo( const setItemIsHovered = useCallback(() => setIsHovered(true), []); const setItemIsNotHovered = useCallback(() => setIsHovered(false), []); - const openFlyout = useCallback(() => openFlyoutWithItem?.(logEntry.id), [ - openFlyoutWithItem, - logEntry.id, - ]); + const openFlyout = useCallback( + () => openFlyoutWithItem?.(logEntry.id), + [openFlyoutWithItem, logEntry.id] + ); const handleOpenViewLogInContext = useCallback(() => { openViewLogInContext?.(logEntry); diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx index 56c6698935b3e..d1330bdb44b33 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/text_styles.tsx @@ -77,11 +77,12 @@ export const useMeasuredCharacterDimensions = (scale: TextScale) => { }, []); const CharacterDimensionsProbe = useMemo( - () => () => ( - - X - - ), + () => () => + ( + + X + + ), [measureElement, scale] ); diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx index 123455ecab2c8..7e13f8b4131fe 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/vertical_scroll_panel.tsx @@ -300,5 +300,6 @@ const getVisibleChildren = ( }; }; -const getChildIndexBefore = bisector<[any, Rect], number>(([key, rect]) => rect.top + rect.height) - .left; +const getChildIndexBefore = bisector<[any, Rect], number>( + ([key, rect]) => rect.top + rect.height +).left; diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx index 26a2e19671da3..db519b4c795eb 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_capabilities.tsx @@ -17,9 +17,8 @@ import { useKibanaContextForPlugin } from '../../../hooks/use_kibana'; export const useLogAnalysisCapabilities = () => { const { services } = useKibanaContextForPlugin(); - const [mlCapabilities, setMlCapabilities] = useState( - initialMlCapabilities - ); + const [mlCapabilities, setMlCapabilities] = + useState(initialMlCapabilities); const [fetchMlCapabilitiesRequest, fetchMlCapabilities] = useTrackedPromise( { @@ -40,9 +39,10 @@ export const useLogAnalysisCapabilities = () => { fetchMlCapabilities(); }, [fetchMlCapabilities]); - const isLoading = useMemo(() => fetchMlCapabilitiesRequest.state === 'pending', [ - fetchMlCapabilitiesRequest.state, - ]); + const isLoading = useMemo( + () => fetchMlCapabilitiesRequest.state === 'pending', + [fetchMlCapabilitiesRequest.state] + ); const hasLogAnalysisSetupCapabilities = mlCapabilities.capabilities.canCreateJob; const hasLogAnalysisReadCapabilities = mlCapabilities.capabilities.canGetJobs; diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx index a9ea7e6d6e39a..d844b7439710c 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx @@ -127,9 +127,10 @@ export const useLogAnalysisModule = ({ [spaceId, sourceId] ); - const isCleaningUp = useMemo(() => cleanUpModuleRequest.state === 'pending', [ - cleanUpModuleRequest.state, - ]); + const isCleaningUp = useMemo( + () => cleanUpModuleRequest.state === 'pending', + [cleanUpModuleRequest.state] + ); const cleanUpAndSetUpModule = useCallback( ( @@ -154,11 +155,10 @@ export const useLogAnalysisModule = ({ dispatchModuleStatus({ type: 'viewedResults' }); }, [dispatchModuleStatus]); - const jobIds = useMemo(() => moduleDescriptor.getJobIds(spaceId, sourceId), [ - moduleDescriptor, - spaceId, - sourceId, - ]); + const jobIds = useMemo( + () => moduleDescriptor.getJobIds(spaceId, sourceId), + [moduleDescriptor, spaceId, sourceId] + ); return { cleanUpAndSetUpModule, diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts index ae58fb91b8881..057580679210a 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_configuration.ts @@ -27,33 +27,35 @@ export const useLogAnalysisModuleConfiguration = ({ }; }; -export const isJobConfigurationOutdated = ( - { bucketSpan }: ModuleDescriptor, - currentSourceConfiguration: ModuleSourceConfiguration -) => (jobSummary: JobSummary): boolean => { - if ( - !jobSummary.fullJob || - !jobSummary.fullJob.custom_settings || - !jobSummary.fullJob.datafeed_config - ) { - return false; - } +export const isJobConfigurationOutdated = + ( + { bucketSpan }: ModuleDescriptor, + currentSourceConfiguration: ModuleSourceConfiguration + ) => + (jobSummary: JobSummary): boolean => { + if ( + !jobSummary.fullJob || + !jobSummary.fullJob.custom_settings || + !jobSummary.fullJob.datafeed_config + ) { + return false; + } - const jobConfiguration = jobSummary.fullJob.custom_settings.logs_source_config; - const datafeedRuntimeMappings = jobSummary.fullJob.datafeed_config.runtime_mappings ?? {}; + const jobConfiguration = jobSummary.fullJob.custom_settings.logs_source_config; + const datafeedRuntimeMappings = jobSummary.fullJob.datafeed_config.runtime_mappings ?? {}; - return !( - jobConfiguration && - jobConfiguration.bucketSpan === bucketSpan && - jobConfiguration.indexPattern && - isSubset( - new Set(jobConfiguration.indexPattern.split(',')), - new Set(currentSourceConfiguration.indices) - ) && - jobConfiguration.timestampField === currentSourceConfiguration.timestampField && - equal(datafeedRuntimeMappings, currentSourceConfiguration.runtimeMappings) - ); -}; + return !( + jobConfiguration && + jobConfiguration.bucketSpan === bucketSpan && + jobConfiguration.indexPattern && + isSubset( + new Set(jobConfiguration.indexPattern.split(',')), + new Set(currentSourceConfiguration.indices) + ) && + jobConfiguration.timestampField === currentSourceConfiguration.timestampField && + equal(datafeedRuntimeMappings, currentSourceConfiguration.runtimeMappings) + ); + }; const isSubset = (subset: Set, superset: Set) => { return Array.from(subset).every((subsetElement) => superset.has(subsetElement)); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx index c3117c9326d1e..03522fd9ce6e5 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx @@ -63,151 +63,152 @@ const createInitialState = ({ setupStatus: { type: 'initializing' }, }); -const createStatusReducer = (jobTypes: JobType[]) => ( - state: StatusReducerState, - action: StatusReducerAction -): StatusReducerState => { - switch (action.type) { - case 'startedSetup': { - return { - ...state, - jobStatus: jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: 'initializing', - }), - {} as Record - ), - setupStatus: { type: 'pending' }, - }; - } - case 'finishedSetup': { - const { datafeedSetupResults, jobSetupResults, jobSummaries, spaceId, sourceId } = action; - const nextJobStatus = jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: - hasSuccessfullyCreatedJob(getJobId(spaceId, sourceId, jobType))(jobSetupResults) && - hasSuccessfullyStartedDatafeed(getDatafeedId(spaceId, sourceId, jobType))( - datafeedSetupResults - ) - ? 'started' - : 'failed', - }), - {} as Record - ); - const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( - (jobState) => jobState === 'started' - ) - ? { type: 'succeeded' } - : { - type: 'failed', - reasons: [ - ...Object.values(datafeedSetupResults) - .filter(hasError) - .map((datafeed) => datafeed.error.error?.reason), - ...Object.values(jobSetupResults) - .filter(hasError) - .map((job) => job.error.error?.reason), - ], - }; - - return { - ...state, - jobStatus: nextJobStatus, - jobSummaries, - setupStatus: nextSetupStatus, - }; - } - case 'failedSetup': { - return { - ...state, - jobStatus: jobTypes.reduce( +const createStatusReducer = + (jobTypes: JobType[]) => + ( + state: StatusReducerState, + action: StatusReducerAction + ): StatusReducerState => { + switch (action.type) { + case 'startedSetup': { + return { + ...state, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'initializing', + }), + {} as Record + ), + setupStatus: { type: 'pending' }, + }; + } + case 'finishedSetup': { + const { datafeedSetupResults, jobSetupResults, jobSummaries, spaceId, sourceId } = action; + const nextJobStatus = jobTypes.reduce( (accumulatedJobStatus, jobType) => ({ ...accumulatedJobStatus, - [jobType]: 'failed', + [jobType]: + hasSuccessfullyCreatedJob(getJobId(spaceId, sourceId, jobType))(jobSetupResults) && + hasSuccessfullyStartedDatafeed(getDatafeedId(spaceId, sourceId, jobType))( + datafeedSetupResults + ) + ? 'started' + : 'failed', }), {} as Record - ), - setupStatus: { type: 'failed', reasons: ['unknown'] }, - }; - } - case 'fetchingJobStatuses': { - return { - ...state, - setupStatus: - state.setupStatus.type === 'unknown' ? { type: 'initializing' } : state.setupStatus, - }; - } - case 'fetchedJobStatuses': { - const { payload: jobSummaries, spaceId, sourceId } = action; - const { setupStatus } = state; + ); + const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( + (jobState) => jobState === 'started' + ) + ? { type: 'succeeded' } + : { + type: 'failed', + reasons: [ + ...Object.values(datafeedSetupResults) + .filter(hasError) + .map((datafeed) => datafeed.error.error?.reason), + ...Object.values(jobSetupResults) + .filter(hasError) + .map((job) => job.error.error?.reason), + ], + }; - const nextJobStatus = jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: getJobStatus(getJobId(spaceId, sourceId, jobType))(jobSummaries), - }), - {} as Record - ); - const nextSetupStatus = getSetupStatus(nextJobStatus)(setupStatus); + return { + ...state, + jobStatus: nextJobStatus, + jobSummaries, + setupStatus: nextSetupStatus, + }; + } + case 'failedSetup': { + return { + ...state, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'failed', + }), + {} as Record + ), + setupStatus: { type: 'failed', reasons: ['unknown'] }, + }; + } + case 'fetchingJobStatuses': { + return { + ...state, + setupStatus: + state.setupStatus.type === 'unknown' ? { type: 'initializing' } : state.setupStatus, + }; + } + case 'fetchedJobStatuses': { + const { payload: jobSummaries, spaceId, sourceId } = action; + const { setupStatus } = state; - return { - ...state, - jobSummaries, - jobStatus: nextJobStatus, - setupStatus: nextSetupStatus, - }; - } - case 'failedFetchingJobStatuses': { - return { - ...state, - setupStatus: { type: 'unknown' }, - jobStatus: jobTypes.reduce( + const nextJobStatus = jobTypes.reduce( (accumulatedJobStatus, jobType) => ({ ...accumulatedJobStatus, - [jobType]: 'unknown', + [jobType]: getJobStatus(getJobId(spaceId, sourceId, jobType))(jobSummaries), }), {} as Record - ), - }; - } - case 'viewedResults': { - return { - ...state, - setupStatus: { type: 'skipped', newlyCreated: true }, - }; - } - default: { - return state; + ); + const nextSetupStatus = getSetupStatus(nextJobStatus)(setupStatus); + + return { + ...state, + jobSummaries, + jobStatus: nextJobStatus, + setupStatus: nextSetupStatus, + }; + } + case 'failedFetchingJobStatuses': { + return { + ...state, + setupStatus: { type: 'unknown' }, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'unknown', + }), + {} as Record + ), + }; + } + case 'viewedResults': { + return { + ...state, + setupStatus: { type: 'skipped', newlyCreated: true }, + }; + } + default: { + return state; + } } - } -}; + }; -const hasSuccessfullyCreatedJob = (jobId: string) => ( - jobSetupResponses: SetupMlModuleResponsePayload['jobs'] -) => - jobSetupResponses.filter( - (jobSetupResponse) => - jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error - ).length > 0; +const hasSuccessfullyCreatedJob = + (jobId: string) => (jobSetupResponses: SetupMlModuleResponsePayload['jobs']) => + jobSetupResponses.filter( + (jobSetupResponse) => + jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error + ).length > 0; -const hasSuccessfullyStartedDatafeed = (datafeedId: string) => ( - datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds'] -) => - datafeedSetupResponses.filter( - (datafeedSetupResponse) => - datafeedSetupResponse.id === datafeedId && - datafeedSetupResponse.success && - datafeedSetupResponse.started && - !datafeedSetupResponse.error - ).length > 0; +const hasSuccessfullyStartedDatafeed = + (datafeedId: string) => (datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds']) => + datafeedSetupResponses.filter( + (datafeedSetupResponse) => + datafeedSetupResponse.id === datafeedId && + datafeedSetupResponse.success && + datafeedSetupResponse.started && + !datafeedSetupResponse.error + ).length > 0; -const getJobStatus = (jobId: string) => (jobSummaries: FetchJobStatusResponsePayload): JobStatus => - jobSummaries - .filter((jobSummary) => jobSummary.id === jobId) - .map( - (jobSummary): JobStatus => { +const getJobStatus = + (jobId: string) => + (jobSummaries: FetchJobStatusResponsePayload): JobStatus => + jobSummaries + .filter((jobSummary) => jobSummary.id === jobId) + .map((jobSummary): JobStatus => { if (jobSummary.jobState === 'failed' || jobSummary.datafeedState === '') { return 'failed'; } else if ( @@ -230,27 +231,26 @@ const getJobStatus = (jobId: string) => (jobSummaries: FetchJobStatusResponsePay } return 'unknown'; + })[0] || 'missing'; + +const getSetupStatus = + (everyJobStatus: Record) => + (previousSetupStatus: SetupStatus): SetupStatus => + Object.entries(everyJobStatus).reduce((setupStatus, [, jobStatus]) => { + if (jobStatus === 'missing') { + return { type: 'required' }; + } else if (setupStatus.type === 'required' || setupStatus.type === 'succeeded') { + return setupStatus; + } else if (setupStatus.type === 'skipped' || isJobStatusWithResults(jobStatus)) { + return { + type: 'skipped', + // preserve newlyCreated status + newlyCreated: setupStatus.type === 'skipped' && setupStatus.newlyCreated, + }; } - )[0] || 'missing'; -const getSetupStatus = (everyJobStatus: Record) => ( - previousSetupStatus: SetupStatus -): SetupStatus => - Object.entries(everyJobStatus).reduce((setupStatus, [, jobStatus]) => { - if (jobStatus === 'missing') { - return { type: 'required' }; - } else if (setupStatus.type === 'required' || setupStatus.type === 'succeeded') { return setupStatus; - } else if (setupStatus.type === 'skipped' || isJobStatusWithResults(jobStatus)) { - return { - type: 'skipped', - // preserve newlyCreated status - newlyCreated: setupStatus.type === 'skipped' && setupStatus.newlyCreated, - }; - } - - return setupStatus; - }, previousSetupStatus); + }, previousSetupStatus); const hasError = ( value: Value diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx index 86e8e75dc3d41..99d4ab4becee5 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx @@ -86,7 +86,5 @@ export const useLogEntryCategoriesModule = ({ }; }; -export const [ - LogEntryCategoriesModuleProvider, - useLogEntryCategoriesModuleContext, -] = createContainer(useLogEntryCategoriesModule); +export const [LogEntryCategoriesModuleProvider, useLogEntryCategoriesModuleContext] = + createContainer(useLogEntryCategoriesModule); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx index 0df5d9b446dbe..f3e8f7e777597 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx @@ -80,6 +80,5 @@ export const useLogEntryRateModule = ({ }; }; -export const [LogEntryRateModuleProvider, useLogEntryRateModuleContext] = createContainer( - useLogEntryRateModule -); +export const [LogEntryRateModuleProvider, useLogEntryRateModuleContext] = + createContainer(useLogEntryRateModule); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx index cc1ef39de32cc..603747c2d2c2b 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx @@ -56,6 +56,5 @@ export const useLogEntryRateSetup = () => { }; }; -export const [LogEntryRateSetupProvider, useLogEntryRateSetupContext] = createContainer( - useLogEntryRateSetup -); +export const [LogEntryRateSetupProvider, useLogEntryRateSetupContext] = + createContainer(useLogEntryRateSetup); diff --git a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_highlights.tsx b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_highlights.tsx index f7f6f156f78e8..dab4abff3bed4 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_highlights.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_highlights.tsx @@ -39,20 +39,17 @@ export const useLogHighlightsState = ({ const throttledStartTimestamp = useThrottle(startTimestamp, FETCH_THROTTLE_INTERVAL); const throttledEndTimestamp = useThrottle(endTimestamp, FETCH_THROTTLE_INTERVAL); - const { - logEntryHighlights, - logEntryHighlightsById, - loadLogEntryHighlightsRequest, - } = useLogEntryHighlights( - sourceId, - sourceVersion, - throttledStartTimestamp, - throttledEndTimestamp, - centerCursor, - size, - filterQuery, - highlightTerms - ); + const { logEntryHighlights, logEntryHighlightsById, loadLogEntryHighlightsRequest } = + useLogEntryHighlights( + sourceId, + sourceVersion, + throttledStartTimestamp, + throttledEndTimestamp, + centerCursor, + size, + filterQuery, + highlightTerms + ); const { logSummaryHighlights, loadLogSummaryHighlightsRequest } = useLogSummaryHighlights( sourceId, diff --git a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts index 7a36fe6aae28c..59abb716f6cb3 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_highlights/log_summary_highlights.ts @@ -56,9 +56,10 @@ export const useLogSummaryHighlights = ( [sourceId, startTimestamp, endTimestamp, bucketSize, filterQuery, highlightTerms] ); - const debouncedLoadSummaryHighlights = useMemo(() => debounce(loadLogSummaryHighlights, 275), [ - loadLogSummaryHighlights, - ]); + const debouncedLoadSummaryHighlights = useMemo( + () => debounce(loadLogSummaryHighlights, 275), + [loadLogSummaryHighlights] + ); useEffect(() => { setLogSummaryHighlights([]); diff --git a/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts b/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts index bda1085d44612..6021c728d32af 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_source/log_source.mock.ts @@ -11,56 +11,56 @@ type CreateUseLogSource = (sourceConfiguration?: { sourceId?: string }) => typeo const defaultSourceId = 'default'; -export const createUninitializedUseLogSourceMock: CreateUseLogSource = ({ - sourceId = defaultSourceId, -} = {}) => () => ({ - derivedIndexPattern: { - fields: [], - title: 'unknown', - }, - hasFailedLoading: false, - hasFailedLoadingSource: false, - hasFailedLoadingSourceStatus: false, - hasFailedResolvingSource: false, - initialize: jest.fn(), - isLoading: false, - isLoadingSourceConfiguration: false, - isLoadingSourceStatus: false, - isResolvingSourceConfiguration: false, - isUninitialized: true, - loadSource: jest.fn(), - loadSourceConfiguration: jest.fn(), - latestLoadSourceFailures: [], - resolveSourceFailureMessage: undefined, - loadSourceStatus: jest.fn(), - sourceConfiguration: undefined, - sourceId, - sourceStatus: undefined, - updateSource: jest.fn(), - resolvedSourceConfiguration: undefined, - loadResolveLogSourceConfiguration: jest.fn(), -}); +export const createUninitializedUseLogSourceMock: CreateUseLogSource = + ({ sourceId = defaultSourceId } = {}) => + () => ({ + derivedIndexPattern: { + fields: [], + title: 'unknown', + }, + hasFailedLoading: false, + hasFailedLoadingSource: false, + hasFailedLoadingSourceStatus: false, + hasFailedResolvingSource: false, + initialize: jest.fn(), + isLoading: false, + isLoadingSourceConfiguration: false, + isLoadingSourceStatus: false, + isResolvingSourceConfiguration: false, + isUninitialized: true, + loadSource: jest.fn(), + loadSourceConfiguration: jest.fn(), + latestLoadSourceFailures: [], + resolveSourceFailureMessage: undefined, + loadSourceStatus: jest.fn(), + sourceConfiguration: undefined, + sourceId, + sourceStatus: undefined, + updateSource: jest.fn(), + resolvedSourceConfiguration: undefined, + loadResolveLogSourceConfiguration: jest.fn(), + }); -export const createLoadingUseLogSourceMock: CreateUseLogSource = ({ - sourceId = defaultSourceId, -} = {}) => (args) => ({ - ...createUninitializedUseLogSourceMock({ sourceId })(args), - isLoading: true, - isLoadingSourceConfiguration: true, - isLoadingSourceStatus: true, - isResolvingSourceConfiguration: true, -}); +export const createLoadingUseLogSourceMock: CreateUseLogSource = + ({ sourceId = defaultSourceId } = {}) => + (args) => ({ + ...createUninitializedUseLogSourceMock({ sourceId })(args), + isLoading: true, + isLoadingSourceConfiguration: true, + isLoadingSourceStatus: true, + isResolvingSourceConfiguration: true, + }); -export const createLoadedUseLogSourceMock: CreateUseLogSource = ({ - sourceId = defaultSourceId, -} = {}) => (args) => ({ - ...createUninitializedUseLogSourceMock({ sourceId })(args), - sourceConfiguration: createBasicSourceConfiguration(sourceId), - sourceStatus: { - logIndexFields: [], - logIndexStatus: 'available', - }, -}); +export const createLoadedUseLogSourceMock: CreateUseLogSource = + ({ sourceId = defaultSourceId } = {}) => + (args) => ({ + ...createUninitializedUseLogSourceMock({ sourceId })(args), + sourceConfiguration: createBasicSourceConfiguration(sourceId), + sourceStatus: { + logIndexFields: [], + logIndexStatus: 'available', + }, + }); export const createBasicSourceConfiguration = (sourceId: string): LogSourceConfiguration => ({ id: sourceId, diff --git a/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_after.ts b/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_after.ts index e41bc07dfd364..ea2162cb96e36 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_after.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_after.ts @@ -88,13 +88,8 @@ export const useLogEntriesAfterResponse = flattenLogEntriesAfterSearchResponse ); - const { - cancelRequest, - isRequestRunning, - isResponsePartial, - loaded, - total, - } = useDataSearchResponseState(logEntriesAfterSearchResponse$); + const { cancelRequest, isRequestRunning, isResponsePartial, loaded, total } = + useDataSearchResponseState(logEntriesAfterSearchResponse$); return { cancelRequest, diff --git a/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_before.ts b/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_before.ts index c9a7dab168200..7d99b3069d973 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_before.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_stream/use_fetch_log_entries_before.ts @@ -44,34 +44,32 @@ export const useLogEntriesBeforeRequest = ({ sourceId: string; startTimestamp: number; }) => { - const { - search: fetchLogEntriesBefore, - requests$: logEntriesBeforeSearchRequests$, - } = useDataSearch({ - getRequest: useCallback( - (cursor: LogEntryBeforeCursor['before'], params: { size: number; extendTo?: number }) => { - return !!sourceId - ? { - request: { - params: logEntriesSearchRequestParamsRT.encode({ - before: cursor, - columns: columnOverrides, - endTimestamp, - highlightPhrase, - query: query as JsonObject, - size: params.size, - sourceId, - startTimestamp: params.extendTo ?? startTimestamp, - }), - }, - options: { strategy: LOG_ENTRIES_SEARCH_STRATEGY }, - } - : null; - }, - [columnOverrides, endTimestamp, highlightPhrase, query, sourceId, startTimestamp] - ), - parseResponses: parseLogEntriesBeforeSearchResponses, - }); + const { search: fetchLogEntriesBefore, requests$: logEntriesBeforeSearchRequests$ } = + useDataSearch({ + getRequest: useCallback( + (cursor: LogEntryBeforeCursor['before'], params: { size: number; extendTo?: number }) => { + return !!sourceId + ? { + request: { + params: logEntriesSearchRequestParamsRT.encode({ + before: cursor, + columns: columnOverrides, + endTimestamp, + highlightPhrase, + query: query as JsonObject, + size: params.size, + sourceId, + startTimestamp: params.extendTo ?? startTimestamp, + }), + }, + options: { strategy: LOG_ENTRIES_SEARCH_STRATEGY }, + } + : null; + }, + [columnOverrides, endTimestamp, highlightPhrase, query, sourceId, startTimestamp] + ), + parseResponses: parseLogEntriesBeforeSearchResponses, + }); return { fetchLogEntriesBefore, @@ -89,13 +87,8 @@ export const useLogEntriesBeforeResponse = { ] ); - const isUninitialized = useMemo(() => loadSourceRequest.state === 'uninitialized', [ - loadSourceRequest.state, - ]); + const isUninitialized = useMemo( + () => loadSourceRequest.state === 'uninitialized', + [loadSourceRequest.state] + ); const sourceExists = useMemo(() => (source ? !!source.version : undefined), [source]); diff --git a/x-pack/plugins/infra/public/containers/metrics_source/use_source_via_http.ts b/x-pack/plugins/infra/public/containers/metrics_source/use_source_via_http.ts index 2947f8fb09847..c7da5afd8dcd6 100644 --- a/x-pack/plugins/infra/public/containers/metrics_source/use_source_via_http.ts +++ b/x-pack/plugins/infra/public/containers/metrics_source/use_source_via_http.ts @@ -47,19 +47,15 @@ export const useSourceViaHttp = ({ sourceId = 'default', fetch, toastWarning }: ); }; - const { - error, - loading, - response, - makeRequest, - } = useHTTPRequest( - `/api/metrics/source/${sourceId}`, - 'GET', - null, - decodeResponse, - fetch, - toastWarning - ); + const { error, loading, response, makeRequest } = + useHTTPRequest( + `/api/metrics/source/${sourceId}`, + 'GET', + null, + decodeResponse, + fetch, + toastWarning + ); useEffect(() => { (async () => { diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx b/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx index 661ce8f8a253c..7b9fe25cc3fa1 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_capabilities.tsx @@ -20,9 +20,8 @@ import { useKibanaContextForPlugin } from '../../hooks/use_kibana'; export const useInfraMLCapabilities = () => { const { services } = useKibanaContextForPlugin(); - const [mlCapabilities, setMlCapabilities] = useState( - initialMlCapabilities - ); + const [mlCapabilities, setMlCapabilities] = + useState(initialMlCapabilities); const [fetchMlCapabilitiesRequest, fetchMlCapabilities] = useTrackedPromise( { @@ -46,9 +45,10 @@ export const useInfraMLCapabilities = () => { fetchMlCapabilities(); }, [fetchMlCapabilities]); - const isLoading = useMemo(() => fetchMlCapabilitiesRequest.state === 'pending', [ - fetchMlCapabilitiesRequest.state, - ]); + const isLoading = useMemo( + () => fetchMlCapabilitiesRequest.state === 'pending', + [fetchMlCapabilitiesRequest.state] + ); const hasInfraMLSetupCapabilities = mlCapabilities.capabilities.canCreateJob; const hasInfraMLReadCapabilities = mlCapabilities.capabilities.canGetJobs; @@ -63,9 +63,8 @@ export const useInfraMLCapabilities = () => { }; }; -export const [InfraMLCapabilitiesProvider, useInfraMLCapabilitiesContext] = createContainer( - useInfraMLCapabilities -); +export const [InfraMLCapabilitiesProvider, useInfraMLCapabilitiesContext] = + createContainer(useInfraMLCapabilities); const initialMlCapabilities = { capabilities: { diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx b/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx index b55ae65e58e91..198a99f394850 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module.tsx @@ -104,9 +104,10 @@ export const useInfraMLModule = ({ [spaceId, sourceId] ); - const isCleaningUp = useMemo(() => cleanUpModuleRequest.state === 'pending', [ - cleanUpModuleRequest.state, - ]); + const isCleaningUp = useMemo( + () => cleanUpModuleRequest.state === 'pending', + [cleanUpModuleRequest.state] + ); const cleanUpAndSetUpModule = useCallback( ( @@ -132,11 +133,10 @@ export const useInfraMLModule = ({ dispatchModuleStatus({ type: 'viewedResults' }); }, [dispatchModuleStatus]); - const jobIds = useMemo(() => moduleDescriptor.getJobIds(spaceId, sourceId), [ - moduleDescriptor, - spaceId, - sourceId, - ]); + const jobIds = useMemo( + () => moduleDescriptor.getJobIds(spaceId, sourceId), + [moduleDescriptor, spaceId, sourceId] + ); return { cleanUpAndSetUpModule, diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts index 3f8ebb835211d..4c876c1705364 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_configuration.ts @@ -26,27 +26,29 @@ export const useInfraMLModuleConfiguration = ({ }; }; -export const isJobConfigurationOutdated = ( - { bucketSpan }: ModuleDescriptor, - currentSourceConfiguration: ModuleSourceConfiguration -) => (jobSummary: JobSummary): boolean => { - if (!jobSummary.fullJob || !jobSummary.fullJob.custom_settings) { - return false; - } +export const isJobConfigurationOutdated = + ( + { bucketSpan }: ModuleDescriptor, + currentSourceConfiguration: ModuleSourceConfiguration + ) => + (jobSummary: JobSummary): boolean => { + if (!jobSummary.fullJob || !jobSummary.fullJob.custom_settings) { + return false; + } - const jobConfiguration = jobSummary.fullJob.custom_settings.metrics_source_config; + const jobConfiguration = jobSummary.fullJob.custom_settings.metrics_source_config; - return !( - jobConfiguration && - jobConfiguration.bucketSpan === bucketSpan && - jobConfiguration.indexPattern && - isSubset( - new Set(jobConfiguration.indexPattern.split(',')), - new Set(currentSourceConfiguration.indices) - ) && - jobConfiguration.timestampField === currentSourceConfiguration.timestampField - ); -}; + return !( + jobConfiguration && + jobConfiguration.bucketSpan === bucketSpan && + jobConfiguration.indexPattern && + isSubset( + new Set(jobConfiguration.indexPattern.split(',')), + new Set(currentSourceConfiguration.indices) + ) && + jobConfiguration.timestampField === currentSourceConfiguration.timestampField + ); + }; const isSubset = (subset: Set, superset: Set) => { return Array.from(subset).every((subsetElement) => superset.has(subsetElement)); diff --git a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_status.tsx b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_status.tsx index 4ebad85ef0fe7..9bbd7720e168f 100644 --- a/x-pack/plugins/infra/public/containers/ml/infra_ml_module_status.tsx +++ b/x-pack/plugins/infra/public/containers/ml/infra_ml_module_status.tsx @@ -63,153 +63,152 @@ const createInitialState = ({ setupStatus: { type: 'initializing' }, }); -const createStatusReducer = (jobTypes: JobType[]) => ( - state: StatusReducerState, - action: StatusReducerAction -): StatusReducerState => { - switch (action.type) { - case 'startedSetup': { - return { - ...state, - jobStatus: jobTypes.reduce( +const createStatusReducer = + (jobTypes: JobType[]) => + ( + state: StatusReducerState, + action: StatusReducerAction + ): StatusReducerState => { + switch (action.type) { + case 'startedSetup': { + return { + ...state, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'initializing', + }), + {} as Record + ), + setupStatus: { type: 'pending' }, + }; + } + case 'finishedSetup': { + const { datafeedSetupResults, jobSetupResults, jobSummaries, spaceId, sourceId } = action; + const nextJobStatus = jobTypes.reduce( (accumulatedJobStatus, jobType) => ({ ...accumulatedJobStatus, - [jobType]: 'initializing', + [jobType]: + hasSuccessfullyCreatedJob(getJobId(spaceId, sourceId, jobType))(jobSetupResults) && + hasSuccessfullyStartedDatafeed(getDatafeedId(spaceId, sourceId, jobType))( + datafeedSetupResults + ) + ? 'started' + : 'failed', }), {} as Record - ), - setupStatus: { type: 'pending' }, - }; - } - case 'finishedSetup': { - const { datafeedSetupResults, jobSetupResults, jobSummaries, spaceId, sourceId } = action; - const nextJobStatus = jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: - hasSuccessfullyCreatedJob(getJobId(spaceId, sourceId, jobType))(jobSetupResults) && - hasSuccessfullyStartedDatafeed(getDatafeedId(spaceId, sourceId, jobType))( - datafeedSetupResults - ) - ? 'started' - : 'failed', - }), - {} as Record - ); - const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( - (jobState) => jobState === 'started' - ) - ? { type: 'succeeded' } - : { - type: 'failed', - reasons: [ - ...Object.values(datafeedSetupResults) - .filter(hasError) - .map((datafeed) => datafeed.error.msg), - ...Object.values(jobSetupResults) - .filter(hasError) - .map((job) => job.error.msg), - ], - }; + ); + const nextSetupStatus: SetupStatus = Object.values(nextJobStatus).every( + (jobState) => jobState === 'started' + ) + ? { type: 'succeeded' } + : { + type: 'failed', + reasons: [ + ...Object.values(datafeedSetupResults) + .filter(hasError) + .map((datafeed) => datafeed.error.msg), + ...Object.values(jobSetupResults) + .filter(hasError) + .map((job) => job.error.msg), + ], + }; - return { - ...state, - jobStatus: nextJobStatus, - jobSummaries, - setupStatus: nextSetupStatus, - }; - } - case 'failedSetup': { - return { - ...state, - jobStatus: jobTypes.reduce( + return { + ...state, + jobStatus: nextJobStatus, + jobSummaries, + setupStatus: nextSetupStatus, + }; + } + case 'failedSetup': { + return { + ...state, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'failed', + }), + {} as Record + ), + setupStatus: { type: 'failed', reasons: ['unknown'] }, + }; + } + case 'fetchingJobStatuses': { + return { + ...state, + setupStatus: + state.setupStatus.type === 'unknown' ? { type: 'initializing' } : state.setupStatus, + }; + } + case 'fetchedJobStatuses': { + const { payload: jobSummaries, spaceId, sourceId } = action; + const { setupStatus } = state; + const nextJobStatus = jobTypes.reduce( (accumulatedJobStatus, jobType) => ({ ...accumulatedJobStatus, - [jobType]: 'failed', + [jobType]: getJobStatus(getJobId(spaceId, sourceId, jobType))(jobSummaries), }), {} as Record - ), - setupStatus: { type: 'failed', reasons: ['unknown'] }, - }; - } - case 'fetchingJobStatuses': { - return { - ...state, - setupStatus: - state.setupStatus.type === 'unknown' ? { type: 'initializing' } : state.setupStatus, - }; - } - case 'fetchedJobStatuses': { - const { payload: jobSummaries, spaceId, sourceId } = action; - const { setupStatus } = state; - const nextJobStatus = jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: getJobStatus(getJobId(spaceId, sourceId, jobType))(jobSummaries), - }), - {} as Record - ); - const nextSetupStatus = getSetupStatus(nextJobStatus)(setupStatus); + ); + const nextSetupStatus = getSetupStatus(nextJobStatus)(setupStatus); - return { - ...state, - jobSummaries, - jobStatus: nextJobStatus, - setupStatus: nextSetupStatus, - }; - } - case 'failedFetchingJobStatuses': { - return { - ...state, - setupStatus: { type: 'unknown' }, - jobStatus: jobTypes.reduce( - (accumulatedJobStatus, jobType) => ({ - ...accumulatedJobStatus, - [jobType]: 'unknown', - }), - {} as Record - ), - }; - } - case 'viewedResults': { - return { - ...state, - setupStatus: { type: 'skipped', newlyCreated: true }, - }; - } - default: { - return state; + return { + ...state, + jobSummaries, + jobStatus: nextJobStatus, + setupStatus: nextSetupStatus, + }; + } + case 'failedFetchingJobStatuses': { + return { + ...state, + setupStatus: { type: 'unknown' }, + jobStatus: jobTypes.reduce( + (accumulatedJobStatus, jobType) => ({ + ...accumulatedJobStatus, + [jobType]: 'unknown', + }), + {} as Record + ), + }; + } + case 'viewedResults': { + return { + ...state, + setupStatus: { type: 'skipped', newlyCreated: true }, + }; + } + default: { + return state; + } } - } -}; + }; -const hasSuccessfullyCreatedJob = (jobId: string) => ( - jobSetupResponses: SetupMlModuleResponsePayload['jobs'] -) => - jobSetupResponses.filter( - (jobSetupResponse) => - jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error - ).length > 0; +const hasSuccessfullyCreatedJob = + (jobId: string) => (jobSetupResponses: SetupMlModuleResponsePayload['jobs']) => + jobSetupResponses.filter( + (jobSetupResponse) => + jobSetupResponse.id === jobId && jobSetupResponse.success && !jobSetupResponse.error + ).length > 0; -const hasSuccessfullyStartedDatafeed = (datafeedId: string) => ( - datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds'] -) => - datafeedSetupResponses.filter( - (datafeedSetupResponse) => - datafeedSetupResponse.id === datafeedId && - datafeedSetupResponse.success && - datafeedSetupResponse.started && - !datafeedSetupResponse.error - ).length > 0; +const hasSuccessfullyStartedDatafeed = + (datafeedId: string) => (datafeedSetupResponses: SetupMlModuleResponsePayload['datafeeds']) => + datafeedSetupResponses.filter( + (datafeedSetupResponse) => + datafeedSetupResponse.id === datafeedId && + datafeedSetupResponse.success && + datafeedSetupResponse.started && + !datafeedSetupResponse.error + ).length > 0; -const getJobStatus = (jobId: string) => ( - jobSummaries: FetchJobStatusResponsePayload -): JobStatus => { - return ( - jobSummaries - .filter((jobSummary) => jobSummary.id === jobId) - .map( - (jobSummary): JobStatus => { +const getJobStatus = + (jobId: string) => + (jobSummaries: FetchJobStatusResponsePayload): JobStatus => { + return ( + jobSummaries + .filter((jobSummary) => jobSummary.id === jobId) + .map((jobSummary): JobStatus => { if (jobSummary.jobState === 'failed' || jobSummary.datafeedState === '') { return 'failed'; } else if ( @@ -232,33 +231,32 @@ const getJobStatus = (jobId: string) => ( } return 'unknown'; + })[0] || 'missing' + ); + }; + +const getSetupStatus = + (everyJobStatus: Record) => + (previousSetupStatus: SetupStatus): SetupStatus => { + return Object.entries(everyJobStatus).reduce( + (setupStatus, [, jobStatus]) => { + if (jobStatus === 'missing') { + return { type: 'required' }; + } else if (setupStatus.type === 'required' || setupStatus.type === 'succeeded') { + return setupStatus; + } else if (setupStatus.type === 'skipped' || isJobStatusWithResults(jobStatus)) { + return { + type: 'skipped', + // preserve newlyCreated status + newlyCreated: setupStatus.type === 'skipped' && setupStatus.newlyCreated, + }; } - )[0] || 'missing' - ); -}; -const getSetupStatus = (everyJobStatus: Record) => ( - previousSetupStatus: SetupStatus -): SetupStatus => { - return Object.entries(everyJobStatus).reduce( - (setupStatus, [, jobStatus]) => { - if (jobStatus === 'missing') { - return { type: 'required' }; - } else if (setupStatus.type === 'required' || setupStatus.type === 'succeeded') { return setupStatus; - } else if (setupStatus.type === 'skipped' || isJobStatusWithResults(jobStatus)) { - return { - type: 'skipped', - // preserve newlyCreated status - newlyCreated: setupStatus.type === 'skipped' && setupStatus.newlyCreated, - }; - } - - return setupStatus; - }, - previousSetupStatus - ); -}; + }, + previousSetupStatus + ); + }; const hasError = ( value: Value diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx index 2697a4223fc18..f892ab62ee3d8 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_hosts/module.tsx @@ -76,6 +76,5 @@ export const useMetricHostsModule = ({ }; }; -export const [MetricHostsModuleProvider, useMetricHostsModuleContext] = createContainer( - useMetricHostsModule -); +export const [MetricHostsModuleProvider, useMetricHostsModuleContext] = + createContainer(useMetricHostsModule); diff --git a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx index 98edbca2166b8..eadc374434817 100644 --- a/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx +++ b/x-pack/plugins/infra/public/containers/ml/modules/metrics_k8s/module.tsx @@ -76,6 +76,5 @@ export const useMetricK8sModule = ({ }; }; -export const [MetricK8sModuleProvider, useMetricK8sModuleContext] = createContainer( - useMetricK8sModule -); +export const [MetricK8sModuleProvider, useMetricK8sModuleContext] = + createContainer(useMetricK8sModule); diff --git a/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx b/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx index c54a2a69a994c..44792019a5f9c 100644 --- a/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx +++ b/x-pack/plugins/infra/public/containers/saved_view/saved_view.tsx @@ -62,9 +62,13 @@ export const useSavedView = (props: Props) => { } = useContext(Source.Context); const { viewType, defaultViewState } = props; type ViewState = typeof defaultViewState; - const { data, loading, find, error: errorOnFind, hasView } = useFindSavedObject< - SavedViewSavedObject - >(viewType); + const { + data, + loading, + find, + error: errorOnFind, + hasView, + } = useFindSavedObject>(viewType); const [urlState, setUrlState] = useUrlState({ defaultState: DEFAULT_SAVED_VIEW_STATE, decodeUrlState, @@ -75,12 +79,18 @@ export const useSavedView = (props: Props) => { const [shouldLoadDefault] = useState(props.shouldLoadDefault); const [currentView, setCurrentView] = useState | null>(null); const [loadingDefaultView, setLoadingDefaultView] = useState(null); - const { create, error: errorOnCreate, data: createdViewData, createdId } = useCreateSavedObject( - viewType - ); - const { update, error: errorOnUpdate, data: updatedViewData, updatedId } = useUpdateSavedObject( - viewType - ); + const { + create, + error: errorOnCreate, + data: createdViewData, + createdId, + } = useCreateSavedObject(viewType); + const { + update, + error: errorOnUpdate, + data: updatedViewData, + updatedId, + } = useUpdateSavedObject(viewType); const { deleteObject, deletedId } = useDeleteSavedObject(viewType); const { getObject, data: currentViewSavedObject } = useGetSavedObject(viewType); const [createError, setCreateError] = useState(null); diff --git a/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx b/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx index 1a759950f640d..f50c629d521e5 100644 --- a/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx +++ b/x-pack/plugins/infra/public/containers/with_kuery_autocompletion.tsx @@ -61,9 +61,8 @@ class WithKueryAutocompletionComponent extends React.Component< ) => { const { indexPattern } = this.props; const language = 'kuery'; - const hasQuerySuggestions = this.props.kibana.services.data?.autocomplete.hasQuerySuggestions( - language - ); + const hasQuerySuggestions = + this.props.kibana.services.data?.autocomplete.hasQuerySuggestions(language); if (!hasQuerySuggestions) { return; diff --git a/x-pack/plugins/infra/public/hooks/use_kibana.ts b/x-pack/plugins/infra/public/hooks/use_kibana.ts index 207e08589cde9..1d21f352a9ea4 100644 --- a/x-pack/plugins/infra/public/hooks/use_kibana.ts +++ b/x-pack/plugins/infra/public/hooks/use_kibana.ts @@ -21,4 +21,5 @@ export const createKibanaContextForPlugin = (core: CoreStart, pluginsStart: Infr ...pluginsStart, }); -export const useKibanaContextForPlugin = useKibana as () => KibanaReactContextValue; +export const useKibanaContextForPlugin = + useKibana as () => KibanaReactContextValue; diff --git a/x-pack/plugins/infra/public/metrics_overview_fetchers.ts b/x-pack/plugins/infra/public/metrics_overview_fetchers.ts index 4f5b73d685591..57017d25ecc64 100644 --- a/x-pack/plugins/infra/public/metrics_overview_fetchers.ts +++ b/x-pack/plugins/infra/public/metrics_overview_fetchers.ts @@ -17,44 +17,43 @@ import { FetchDataParams, MetricsFetchDataResponse } from '../../observability/p import { TopNodesRequest, TopNodesResponse } from '../common/http_api/overview_api'; import { InfraClientCoreSetup } from './types'; -export const createMetricsHasData = ( - getStartServices: InfraClientCoreSetup['getStartServices'] -) => async () => { - const [coreServices] = await getStartServices(); - const { http } = coreServices; - const results = await http.get<{ hasData: boolean }>('/api/metrics/source/default/hasData'); - return results.hasData; -}; +export const createMetricsHasData = + (getStartServices: InfraClientCoreSetup['getStartServices']) => async () => { + const [coreServices] = await getStartServices(); + const { http } = coreServices; + const results = await http.get<{ hasData: boolean }>('/api/metrics/source/default/hasData'); + return results.hasData; + }; -export const createMetricsFetchData = ( - getStartServices: InfraClientCoreSetup['getStartServices'] -) => async ({ absoluteTime, bucketSize }: FetchDataParams): Promise => { - const [coreServices] = await getStartServices(); - const { http } = coreServices; +export const createMetricsFetchData = + (getStartServices: InfraClientCoreSetup['getStartServices']) => + async ({ absoluteTime, bucketSize }: FetchDataParams): Promise => { + const [coreServices] = await getStartServices(); + const { http } = coreServices; - const makeRequest = async (overrides: Partial = {}) => { - const { start, end } = absoluteTime; + const makeRequest = async (overrides: Partial = {}) => { + const { start, end } = absoluteTime; - const overviewRequest: TopNodesRequest = { - sourceId: 'default', - bucketSize, - size: 5, - timerange: { - from: start, - to: end, - }, - ...overrides, - }; - const results = await http.post('/api/metrics/overview/top', { - body: JSON.stringify(overviewRequest), - }); - return { - appLink: `/app/metrics/inventory?waffleTime=(currentTime:${end},isAutoReloading:!f)`, - series: results.series, - sort: async (by: string, direction: string) => - makeRequest({ sort: by, sortDirection: direction }), + const overviewRequest: TopNodesRequest = { + sourceId: 'default', + bucketSize, + size: 5, + timerange: { + from: start, + to: end, + }, + ...overrides, + }; + const results = await http.post('/api/metrics/overview/top', { + body: JSON.stringify(overviewRequest), + }); + return { + appLink: `/app/metrics/inventory?waffleTime=(currentTime:${end},isAutoReloading:!f)`, + series: results.series, + sort: async (by: string, direction: string) => + makeRequest({ sort: by, sortDirection: direction }), + }; }; - }; - return await makeRequest(); -}; + return await makeRequest(); + }; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx index bfdbe03526164..a8d98ea843c96 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx @@ -40,9 +40,10 @@ export const LogEntryCategoriesPageContent = () => { const { fetchJobStatus, setupStatus, jobStatus } = useLogEntryCategoriesModuleContext(); const { showModuleSetup } = useLogAnalysisSetupFlyoutStateContext(); - const showCategoriesModuleSetup = useCallback(() => showModuleSetup('logs_ui_categories'), [ - showModuleSetup, - ]); + const showCategoriesModuleSetup = useCallback( + () => showModuleSetup('logs_ui_categories'), + [showModuleSetup] + ); useEffect(() => { if (hasLogAnalysisReadCapabilities) { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx index 7098f457117d3..bf6fe978ddae2 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx @@ -40,240 +40,241 @@ interface LogEntryCategoriesResultsContentProps { pageTitle: string; } -export const LogEntryCategoriesResultsContent: React.FunctionComponent = ({ - onOpenSetup, - pageTitle, -}) => { - useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_results' }); - useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_results', delay: 15000 }); +export const LogEntryCategoriesResultsContent: React.FunctionComponent = + ({ onOpenSetup, pageTitle }) => { + useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_results' }); + useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_results', delay: 15000 }); - const { - services: { ml, http }, - } = useKibanaContextForPlugin(); + const { + services: { ml, http }, + } = useKibanaContextForPlugin(); - const { hasLogAnalysisSetupCapabilities } = useLogAnalysisCapabilitiesContext(); + const { hasLogAnalysisSetupCapabilities } = useLogAnalysisCapabilitiesContext(); - const { - fetchJobStatus, - fetchModuleDefinition, - moduleDescriptor, - setupStatus, - hasOutdatedJobConfigurations, - hasOutdatedJobDefinitions, - hasStoppedJobs, - jobIds, - categoryQualityWarnings, - sourceConfiguration: { sourceId }, - } = useLogEntryCategoriesModuleContext(); + const { + fetchJobStatus, + fetchModuleDefinition, + moduleDescriptor, + setupStatus, + hasOutdatedJobConfigurations, + hasOutdatedJobDefinitions, + hasStoppedJobs, + jobIds, + categoryQualityWarnings, + sourceConfiguration: { sourceId }, + } = useLogEntryCategoriesModuleContext(); - const { - timeRange: selectedTimeRange, - setTimeRange: setSelectedTimeRange, - autoRefresh, - setAutoRefresh, - } = useLogEntryCategoriesResultsUrlState(); + const { + timeRange: selectedTimeRange, + setTimeRange: setSelectedTimeRange, + autoRefresh, + setAutoRefresh, + } = useLogEntryCategoriesResultsUrlState(); - const [categoryQueryTimeRange, setCategoryQueryTimeRange] = useState<{ - lastChangedTime: number; - timeRange: TimeRange; - }>(() => ({ - lastChangedTime: Date.now(), - timeRange: stringToNumericTimeRange(selectedTimeRange), - })); + const [categoryQueryTimeRange, setCategoryQueryTimeRange] = useState<{ + lastChangedTime: number; + timeRange: TimeRange; + }>(() => ({ + lastChangedTime: Date.now(), + timeRange: stringToNumericTimeRange(selectedTimeRange), + })); - const [categoryQueryDatasets, setCategoryQueryDatasets] = useState([]); + const [categoryQueryDatasets, setCategoryQueryDatasets] = useState([]); - const { services } = useKibana<{}>(); + const { services } = useKibana<{}>(); - const showLoadDataErrorNotification = useCallback( - (error: Error) => { - services.notifications?.toasts.addError(error, { - title: loadDataErrorTitle, - }); - }, - [services.notifications] - ); + const showLoadDataErrorNotification = useCallback( + (error: Error) => { + services.notifications?.toasts.addError(error, { + title: loadDataErrorTitle, + }); + }, + [services.notifications] + ); - const { - getLogEntryCategoryDatasets, - getTopLogEntryCategories, - isLoadingLogEntryCategoryDatasets, - isLoadingTopLogEntryCategories, - logEntryCategoryDatasets, - topLogEntryCategories, - sortOptions, - changeSortOptions, - } = useLogEntryCategoriesResults({ - categoriesCount: 25, - endTime: categoryQueryTimeRange.timeRange.endTime, - filteredDatasets: categoryQueryDatasets, - onGetTopLogEntryCategoriesError: showLoadDataErrorNotification, - sourceId, - startTime: categoryQueryTimeRange.timeRange.startTime, - }); + const { + getLogEntryCategoryDatasets, + getTopLogEntryCategories, + isLoadingLogEntryCategoryDatasets, + isLoadingTopLogEntryCategories, + logEntryCategoryDatasets, + topLogEntryCategories, + sortOptions, + changeSortOptions, + } = useLogEntryCategoriesResults({ + categoriesCount: 25, + endTime: categoryQueryTimeRange.timeRange.endTime, + filteredDatasets: categoryQueryDatasets, + onGetTopLogEntryCategoriesError: showLoadDataErrorNotification, + sourceId, + startTime: categoryQueryTimeRange.timeRange.startTime, + }); - const handleQueryTimeRangeChange = useCallback( - ({ start: startTime, end: endTime }: { start: string; end: string }) => { - setCategoryQueryTimeRange((previousQueryParameters) => ({ - ...previousQueryParameters, - timeRange: stringToNumericTimeRange({ startTime, endTime }), - lastChangedTime: Date.now(), - })); - }, - [setCategoryQueryTimeRange] - ); + const handleQueryTimeRangeChange = useCallback( + ({ start: startTime, end: endTime }: { start: string; end: string }) => { + setCategoryQueryTimeRange((previousQueryParameters) => ({ + ...previousQueryParameters, + timeRange: stringToNumericTimeRange({ startTime, endTime }), + lastChangedTime: Date.now(), + })); + }, + [setCategoryQueryTimeRange] + ); - const handleSelectedTimeRangeChange = useCallback( - (selectedTime: { start: string; end: string; isInvalid: boolean }) => { - if (selectedTime.isInvalid) { - return; - } - setSelectedTimeRange({ - startTime: selectedTime.start, - endTime: selectedTime.end, - }); - handleQueryTimeRangeChange(selectedTime); - }, - [setSelectedTimeRange, handleQueryTimeRangeChange] - ); + const handleSelectedTimeRangeChange = useCallback( + (selectedTime: { start: string; end: string; isInvalid: boolean }) => { + if (selectedTime.isInvalid) { + return; + } + setSelectedTimeRange({ + startTime: selectedTime.start, + endTime: selectedTime.end, + }); + handleQueryTimeRangeChange(selectedTime); + }, + [setSelectedTimeRange, handleQueryTimeRangeChange] + ); - const handleAutoRefreshChange = useCallback( - ({ isPaused, refreshInterval: interval }: { isPaused: boolean; refreshInterval: number }) => { - setAutoRefresh({ - isPaused, - interval, - }); - }, - [setAutoRefresh] - ); + const handleAutoRefreshChange = useCallback( + ({ isPaused, refreshInterval: interval }: { isPaused: boolean; refreshInterval: number }) => { + setAutoRefresh({ + isPaused, + interval, + }); + }, + [setAutoRefresh] + ); - const hasResults = useMemo(() => topLogEntryCategories.length > 0, [ - topLogEntryCategories.length, - ]); + const hasResults = useMemo( + () => topLogEntryCategories.length > 0, + [topLogEntryCategories.length] + ); - const isFirstUse = useMemo( - () => - ((setupStatus.type === 'skipped' && !!setupStatus.newlyCreated) || - setupStatus.type === 'succeeded') && - !hasResults, - [hasResults, setupStatus] - ); + const isFirstUse = useMemo( + () => + ((setupStatus.type === 'skipped' && !!setupStatus.newlyCreated) || + setupStatus.type === 'succeeded') && + !hasResults, + [hasResults, setupStatus] + ); - useEffect(() => { - getTopLogEntryCategories(); - }, [ - getTopLogEntryCategories, - categoryQueryDatasets, - categoryQueryTimeRange.lastChangedTime, - sortOptions, - ]); + useEffect(() => { + getTopLogEntryCategories(); + }, [ + getTopLogEntryCategories, + categoryQueryDatasets, + categoryQueryTimeRange.lastChangedTime, + sortOptions, + ]); - useEffect(() => { - getLogEntryCategoryDatasets(); - }, [getLogEntryCategoryDatasets, categoryQueryTimeRange.lastChangedTime]); + useEffect(() => { + getLogEntryCategoryDatasets(); + }, [getLogEntryCategoryDatasets, categoryQueryTimeRange.lastChangedTime]); - useEffect(() => { - fetchModuleDefinition(); - }, [fetchModuleDefinition]); + useEffect(() => { + fetchModuleDefinition(); + }, [fetchModuleDefinition]); - useInterval(() => { - fetchJobStatus(); - }, JOB_STATUS_POLLING_INTERVAL); + useInterval(() => { + fetchJobStatus(); + }, JOB_STATUS_POLLING_INTERVAL); - useInterval( - () => { - handleQueryTimeRangeChange({ - start: selectedTimeRange.startTime, - end: selectedTimeRange.endTime, - }); - }, - autoRefresh.isPaused ? null : autoRefresh.interval - ); + useInterval( + () => { + handleQueryTimeRangeChange({ + start: selectedTimeRange.startTime, + end: selectedTimeRange.endTime, + }); + }, + autoRefresh.isPaused ? null : autoRefresh.interval + ); - const analyzeInMlLink = useMlHref(ml, http.basePath.get(), { - page: ML_PAGES.ANOMALY_EXPLORER, - pageState: { - jobIds: [jobIds['log-entry-categories-count']], - timeRange: { - from: moment(categoryQueryTimeRange.timeRange.startTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), - to: moment(categoryQueryTimeRange.timeRange.endTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), - mode: 'absolute', + const analyzeInMlLink = useMlHref(ml, http.basePath.get(), { + page: ML_PAGES.ANOMALY_EXPLORER, + pageState: { + jobIds: [jobIds['log-entry-categories-count']], + timeRange: { + from: moment(categoryQueryTimeRange.timeRange.startTime).format( + 'YYYY-MM-DDTHH:mm:ss.SSSZ' + ), + to: moment(categoryQueryTimeRange.timeRange.endTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), + mode: 'absolute', + }, }, - }, - }); + }); - return ( - - , - , - ], - }} + return ( + - - - - - - - - - - - - - - - - - - - - - - ); -}; + , + , + ], + }} + > + + + + + + + + + + + + + + + + + + + + + + ); + }; const stringToNumericTimeRange = (timeRange: StringTimeRange): TimeRange => ({ startTime: moment( diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_setup_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_setup_content.tsx index 18adfaad03ef8..c012d97dd1fc0 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_setup_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_setup_content.tsx @@ -14,41 +14,40 @@ interface LogEntryCategoriesSetupContentProps { onOpenSetup: () => void; } -export const LogEntryCategoriesSetupContent: React.FunctionComponent = ({ - onOpenSetup, -}) => { - useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_setup' }); - useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_setup', delay: 15000 }); +export const LogEntryCategoriesSetupContent: React.FunctionComponent = + ({ onOpenSetup }) => { + useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_setup' }); + useTrackPageview({ app: 'infra_logs', path: 'log_entry_categories_setup', delay: 15000 }); - return ( - - - - } - body={ - -

+ return ( + -

-
- } - actions={ - - - - } - /> - ); -}; + + } + body={ + +

+ +

+
+ } + actions={ + + + + } + /> + ); + }; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts index 73779af8752ee..b4cfb301e0402 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_results.ts @@ -18,7 +18,8 @@ import { callGetLogEntryCategoryDatasetsAPI } from './service_calls/get_log_entr import { useKibanaContextForPlugin } from '../../../hooks/use_kibana'; type TopLogEntryCategories = GetLogEntryCategoriesSuccessResponsePayload['data']['categories']; -type LogEntryCategoryDatasets = GetLogEntryCategoryDatasetsSuccessResponsePayload['data']['datasets']; +type LogEntryCategoryDatasets = + GetLogEntryCategoryDatasetsSuccessResponsePayload['data']['datasets']; export type SortOptions = CategoriesSort; export type ChangeSortOptions = (sortOptions: CategoriesSort) => void; @@ -46,10 +47,8 @@ export const useLogEntryCategoriesResults = ({ }); const { services } = useKibanaContextForPlugin(); const [topLogEntryCategories, setTopLogEntryCategories] = useState([]); - const [ - logEntryCategoryDatasets, - setLogEntryCategoryDatasets, - ] = useState([]); + const [logEntryCategoryDatasets, setLogEntryCategoryDatasets] = + useState([]); const [getTopLogEntryCategoriesRequest, getTopLogEntryCategories] = useTrackedPromise( { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx index 2d833c87c1e25..2aac520dbc28a 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx @@ -161,12 +161,14 @@ export const LogEntryRateResultsContent: React.FunctionComponent<{ const { showModuleList, showModuleSetup } = useLogAnalysisSetupFlyoutStateContext(); - const showLogEntryRateSetup = useCallback(() => showModuleSetup('logs_ui_analysis'), [ - showModuleSetup, - ]); - const showLogEntryCategoriesSetup = useCallback(() => showModuleSetup('logs_ui_categories'), [ - showModuleSetup, - ]); + const showLogEntryRateSetup = useCallback( + () => showModuleSetup('logs_ui_analysis'), + [showModuleSetup] + ); + const showLogEntryCategoriesSetup = useCallback( + () => showModuleSetup('logs_ui_categories'), + [showModuleSetup] + ); const hasAnomalyResults = logEntryAnomalies.length > 0; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_anomalies_results.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_anomalies_results.ts index 3cb0c4c89927c..80123bb10e550 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_anomalies_results.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_anomalies_results.ts @@ -27,7 +27,8 @@ export type FetchPreviousPage = () => void; export type ChangeSortOptions = (sortOptions: AnomaliesSort) => void; export type ChangePaginationOptions = (paginationOptions: PaginationOptions) => void; export type LogEntryAnomalies = LogEntryAnomaly[]; -type LogEntryAnomaliesDatasets = GetLogEntryAnomaliesDatasetsSuccessResponsePayload['data']['datasets']; +type LogEntryAnomaliesDatasets = + GetLogEntryAnomaliesDatasetsSuccessResponsePayload['data']['datasets']; interface PaginationCursors { previousPageCursor: PaginationCursor; nextPageCursor: PaginationCursor; @@ -285,10 +286,8 @@ export const useLogEntryAnomaliesResults = ({ ); // Anomalies datasets - const [ - logEntryAnomaliesDatasets, - setLogEntryAnomaliesDatasets, - ] = useState([]); + const [logEntryAnomaliesDatasets, setLogEntryAnomaliesDatasets] = + useState([]); const [getLogEntryAnomaliesDatasetsRequest, getLogEntryAnomaliesDatasets] = useTrackedPromise( { @@ -315,9 +314,10 @@ export const useLogEntryAnomaliesResults = ({ [endTime, sourceId, startTime] ); - const isLoadingDatasets = useMemo(() => getLogEntryAnomaliesDatasetsRequest.state === 'pending', [ - getLogEntryAnomaliesDatasetsRequest.state, - ]); + const isLoadingDatasets = useMemo( + () => getLogEntryAnomaliesDatasetsRequest.state === 'pending', + [getLogEntryAnomaliesDatasetsRequest.state] + ); const hasFailedLoadingDatasets = useMemo( () => getLogEntryAnomaliesDatasetsRequest.state === 'rejected', diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_examples.ts b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_examples.ts index 34d14de4aa941..8f6269c46c3df 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_examples.ts +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_examples.ts @@ -53,9 +53,10 @@ export const useLogEntryExamples = ({ [dataset, endTime, exampleCount, sourceId, startTime] ); - const isLoadingLogEntryExamples = useMemo(() => getLogEntryExamplesRequest.state === 'pending', [ - getLogEntryExamplesRequest.state, - ]); + const isLoadingLogEntryExamples = useMemo( + () => getLogEntryExamplesRequest.state === 'pending', + [getLogEntryExamplesRequest.state] + ); const hasFailedLoadingLogEntryExamples = useMemo( () => getLogEntryExamplesRequest.state === 'rejected', diff --git a/x-pack/plugins/infra/public/pages/logs/settings/fields_configuration_panel.tsx b/x-pack/plugins/infra/public/pages/logs/settings/fields_configuration_panel.tsx index 3f8922b1871c9..d21b0b0588dea 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/fields_configuration_panel.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/fields_configuration_panel.tsx @@ -118,18 +118,20 @@ export const FieldsConfigurationPanel = ({ defaultMessage="Timestamp" /> } - {...useMemo(() => getFormRowProps(timestampFieldFormElement), [ - timestampFieldFormElement, - ])} + {...useMemo( + () => getFormRowProps(timestampFieldFormElement), + [timestampFieldFormElement] + )} > getStringInputFieldProps(timestampFieldFormElement), [ - timestampFieldFormElement, - ])} + {...useMemo( + () => getStringInputFieldProps(timestampFieldFormElement), + [timestampFieldFormElement] + )} />
@@ -166,18 +168,20 @@ export const FieldsConfigurationPanel = ({ defaultMessage="Tiebreaker" /> } - {...useMemo(() => getFormRowProps(tiebreakerFieldFormElement), [ - tiebreakerFieldFormElement, - ])} + {...useMemo( + () => getFormRowProps(tiebreakerFieldFormElement), + [tiebreakerFieldFormElement] + )} > getStringInputFieldProps(tiebreakerFieldFormElement), [ - tiebreakerFieldFormElement, - ])} + {...useMemo( + () => getStringInputFieldProps(tiebreakerFieldFormElement), + [tiebreakerFieldFormElement] + )} /> diff --git a/x-pack/plugins/infra/public/pages/logs/settings/form_elements.tsx b/x-pack/plugins/infra/public/pages/logs/settings/form_elements.tsx index 90504a691cb95..8058a10bcd269 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/form_elements.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/form_elements.tsx @@ -141,10 +141,10 @@ export const useCompositeFormElement = ({ } }, [childFormElementEntries]); - const validity = useMemo(() => getCombinedValidity(formValidity, childFormElementsValidity), [ - formValidity, - childFormElementsValidity, - ]); + const validity = useMemo( + () => getCombinedValidity(formValidity, childFormElementsValidity), + [formValidity, childFormElementsValidity] + ); const resetValue = useCallback(() => { childFormElementEntries.forEach(([, formElement]) => formElement.resetValue()); @@ -180,10 +180,10 @@ const useValidity = ( value: Value, validate?: (value: Value) => Promise ) => { - const validationState = useAsync(() => validate?.(value) ?? Promise.resolve([]), [ - validate, - value, - ]); + const validationState = useAsync( + () => validate?.(value) ?? Promise.resolve([]), + [validate, value] + ); const validity = useMemo>(() => { if (validationState.loading) { @@ -236,8 +236,9 @@ export const getCombinedValidity = ( } }; -export const isFormElementForType = ( - isValue: (value: any) => value is Value -) => ( - formElement: FormElement -): formElement is FormElement => isValue(formElement.value); +export const isFormElementForType = + (isValue: (value: any) => value is Value) => + ( + formElement: FormElement + ): formElement is FormElement => + isValue(formElement.value); diff --git a/x-pack/plugins/infra/public/pages/logs/settings/form_field_props.tsx b/x-pack/plugins/infra/public/pages/logs/settings/form_field_props.tsx index 4a3927157b136..81711f7464da8 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/form_field_props.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/form_field_props.tsx @@ -19,17 +19,19 @@ export const getFormRowProps = (formElement: FormElement( - decodeInputValue: (value: string) => Value, - encodeInputValue: (value: Value) => string -) => (formElement: FormElement) => ({ - isInvalid: formElement.validity.validity === 'invalid', - onChange: (evt: React.ChangeEvent) => { - const newValue = evt.currentTarget.value; - formElement.updateValue(() => decodeInputValue(newValue)); - }, - value: encodeInputValue(formElement.value), -}); +export const getInputFieldProps = + ( + decodeInputValue: (value: string) => Value, + encodeInputValue: (value: Value) => string + ) => + (formElement: FormElement) => ({ + isInvalid: formElement.validity.validity === 'invalid', + onChange: (evt: React.ChangeEvent) => { + const newValue = evt.currentTarget.value; + formElement.updateValue(() => decodeInputValue(newValue)); + }, + value: encodeInputValue(formElement.value), + }); export const getStringInputFieldProps = getInputFieldProps( (value) => `${value}`, diff --git a/x-pack/plugins/infra/public/pages/logs/settings/index_pattern_configuration_panel.tsx b/x-pack/plugins/infra/public/pages/logs/settings/index_pattern_configuration_panel.tsx index a16f15505bc30..7e466ee2a6ae9 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/index_pattern_configuration_panel.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/index_pattern_configuration_panel.tsx @@ -79,10 +79,10 @@ export const IndexPatternConfigurationPanel: React.FC<{ defaultMessage="Log index pattern" /> } - {...useMemo(() => (isLoading ? {} : getFormRowProps(indexPatternFormElement)), [ - isLoading, - indexPatternFormElement, - ])} + {...useMemo( + () => (isLoading ? {} : getFormRowProps(indexPatternFormElement)), + [isLoading, indexPatternFormElement] + )} > void; }> = ({ logColumnConfiguration, dragHandleProps, onRemove }) => { - const removeColumn = useCallback(() => onRemove(logColumnConfiguration), [ - logColumnConfiguration, - onRemove, - ]); + const removeColumn = useCallback( + () => onRemove(logColumnConfiguration), + [logColumnConfiguration, onRemove] + ); return ( <> diff --git a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_form_state.tsx b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_form_state.tsx index 67e790a98f518..ac390a5bcfb8b 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_form_state.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_form_state.tsx @@ -28,19 +28,16 @@ export const useLogSourceConfigurationFormState = ( ) ); - const { - fieldsFormElement, - tiebreakerFieldFormElement, - timestampFieldFormElement, - } = useFieldsFormElement( - useMemo( - () => ({ - tiebreakerField: configuration?.fields?.tiebreaker ?? '_doc', - timestampField: configuration?.fields?.timestamp ?? '@timestamp', - }), - [configuration] - ) - ); + const { fieldsFormElement, tiebreakerFieldFormElement, timestampFieldFormElement } = + useFieldsFormElement( + useMemo( + () => ({ + tiebreakerField: configuration?.fields?.tiebreaker ?? '_doc', + timestampField: configuration?.fields?.timestamp ?? '@timestamp', + }), + [configuration] + ) + ); const logColumnsFormElement = useLogColumnsFormElement( useMemo(() => configuration?.logColumns ?? [], [configuration]) diff --git a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx index 51355cab1fba5..883c321db9ae6 100644 --- a/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx +++ b/x-pack/plugins/infra/public/pages/logs/settings/source_configuration_settings.tsx @@ -76,10 +76,10 @@ export const LogsSettingsPage = () => { sourceConfigurationFormElement.resetValue(); }, [updateSource, sourceConfigurationFormElement, formState]); - const isWriteable = useMemo(() => shouldAllowEdit && source && source.origin !== 'internal', [ - shouldAllowEdit, - source, - ]); + const isWriteable = useMemo( + () => shouldAllowEdit && source && source.origin !== 'internal', + [shouldAllowEdit, source] + ); if ((isLoading || isUninitialized) && !resolvedSourceConfiguration) { return ; diff --git a/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx b/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx index 6d7f9fb09676a..015476687d468 100644 --- a/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx +++ b/x-pack/plugins/infra/public/pages/logs/stream/page_toolbar.tsx @@ -27,12 +27,8 @@ export const LogsToolbar = () => { const { availableTextScales, setTextScale, setTextWrap, textScale, textWrap } = useContext( LogViewConfiguration.Context ); - const { - filterQueryDraft, - isFilterQueryDraftValid, - applyLogFilterQuery, - setLogFilterQueryDraft, - } = useContext(LogFilterState.Context); + const { filterQueryDraft, isFilterQueryDraftValid, applyLogFilterQuery, setLogFilterQueryDraft } = + useContext(LogFilterState.Context); const { setSurroundingLogsId } = useContext(LogFlyout.Context); const { diff --git a/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx b/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx index 5537ef9541f89..da507fac5272c 100644 --- a/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx +++ b/x-pack/plugins/infra/public/pages/logs/stream/page_view_log_in_context.tsx @@ -25,10 +25,8 @@ import { LogStream } from '../../../components/log_stream'; const MODAL_MARGIN = 25; export const PageViewLogInContext: React.FC = () => { - const [ - { contextEntry, startTimestamp, endTimestamp, sourceId }, - { setContextEntry }, - ] = useContext(ViewLogInContext.Context); + const [{ contextEntry, startTimestamp, endTimestamp, sourceId }, { setContextEntry }] = + useContext(ViewLogInContext.Context); const closeModal = useCallback(() => setContextEntry(undefined), [setContextEntry]); const { width: vw, height: vh } = useViewportDimensions(); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomalies_table/anomalies_table.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomalies_table/anomalies_table.tsx index 98f3c82818dd2..05227dd1ed5e4 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomalies_table/anomalies_table.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/anomalies_table/anomalies_table.tsx @@ -268,16 +268,14 @@ export const AnomaliesTable = (props: Props) => { fetchPreviousPage: k8sPreviousPage, isLoadingMetricsK8sAnomalies: k8sLoading, } = useMetricsK8sAnomaliesResults(anomalyParams); - const page = useMemo(() => (jobType === 'hosts' ? hostPage : k8sPage), [ - jobType, - hostPage, - k8sPage, - ]); - const isLoading = useMemo(() => (jobType === 'hosts' ? hostLoading : k8sLoading), [ - jobType, - hostLoading, - k8sLoading, - ]); + const page = useMemo( + () => (jobType === 'hosts' ? hostPage : k8sPage), + [jobType, hostPage, k8sPage] + ); + const isLoading = useMemo( + () => (jobType === 'hosts' ? hostLoading : k8sLoading), + [jobType, hostLoading, k8sLoading] + ); const fetchNextPage = useMemo( () => (jobType === 'hosts' ? hostFetchNextPage : k8sFetchNextPage), [jobType, hostFetchNextPage, k8sFetchNextPage] diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx index 993ae1d9d7571..a16aff903776e 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/flyout_home.tsx @@ -48,11 +48,8 @@ export const FlyoutHome = (props: Props) => { setupStatus: k8sSetupStatus, jobSummaries: k8sJobSummaries, } = useMetricK8sModuleContext(); - const { - hasInfraMLCapabilities, - hasInfraMLReadCapabilities, - hasInfraMLSetupCapabilities, - } = useInfraMLCapabilitiesContext(); + const { hasInfraMLCapabilities, hasInfraMLReadCapabilities, hasInfraMLSetupCapabilities } = + useInfraMLCapabilitiesContext(); const createHosts = useCallback(() => { goToSetup('hosts'); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx index f6d739078002e..fd75aa3bec7a6 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/ml/anomaly_detection/job_setup_screen.tsx @@ -80,9 +80,10 @@ export const JobSetupScreen = (props: Props) => { } }, [props.jobType, k.jobSummaries, h.jobSummaries]); - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern(), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern(), + [createDerivedIndexPattern] + ); const updateStart = useCallback((date: Moment) => { setStartDate(date); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx index e2803629afd51..f4c9f9b804135 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/overlay.tsx @@ -50,9 +50,10 @@ export const NodeContextPopover = ({ const inventoryModel = findInventoryModel(nodeType); const nodeDetailFrom = currentTime - inventoryModel.metrics.defaultTimeRangeInSeconds * 1000; const uiCapabilities = useKibana().services.application?.capabilities; - const canCreateAlerts = useMemo(() => Boolean(uiCapabilities?.infrastructure?.save), [ - uiCapabilities, - ]); + const canCreateAlerts = useMemo( + () => Boolean(uiCapabilities?.infrastructure?.save), + [uiCapabilities] + ); const tabs = useMemo(() => { return tabConfigs.map((m) => { diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx index b554cb8024211..fbb8bd469c1e1 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/metrics/metrics.tsx @@ -72,9 +72,10 @@ const TabComponent = (props: TabProps) => { const { sourceId, createDerivedIndexPattern } = useSourceContext(); const { nodeType, accountId, region, customMetrics } = useWaffleOptionsContext(); const { currentTime, options, node } = props; - const derivedIndexPattern = useMemo(() => createDerivedIndexPattern('metrics'), [ - createDerivedIndexPattern, - ]); + const derivedIndexPattern = useMemo( + () => createDerivedIndexPattern('metrics'), + [createDerivedIndexPattern] + ); let filter = options.fields ? `${findInventoryFields(nodeType, options.fields).id}: "${node.id}"` : ''; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx index df3b37c0aa386..c227a31edc4ab 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/node_details/tabs/processes/index.tsx @@ -46,13 +46,12 @@ const TabComponent = ({ currentTime, node, nodeType, options }: TabProps) => { return { [field]: node.name }; }, [options, node, nodeType]); - const { loading, error, response, makeRequest: reload } = useProcessList( - hostTerm, - timefield, - currentTime, - sortBy, - parseSearchString(searchFilter) - ); + const { + loading, + error, + response, + makeRequest: reload, + } = useProcessList(hostTerm, timefield, currentTime, sortBy, parseSearchString(searchFilter)); const debouncedSearchOnChange = useMemo( () => debounce<(queryText: string) => void>((queryText) => setSearchFilter(queryText), 500), diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx index dd1023e7f0185..65c3136cb48a6 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/timeline/timeline.tsx @@ -81,12 +81,10 @@ export const Timeline: React.FC = ({ interval, yAxisFormatter, isVisible defaultPaginationOptions: { pageSize: 100 }, }; - const { metricsHostsAnomalies, getMetricsHostsAnomalies } = useMetricsHostsAnomaliesResults( - anomalyParams - ); - const { metricsK8sAnomalies, getMetricsK8sAnomalies } = useMetricsK8sAnomaliesResults( - anomalyParams - ); + const { metricsHostsAnomalies, getMetricsHostsAnomalies } = + useMetricsHostsAnomaliesResults(anomalyParams); + const { metricsK8sAnomalies, getMetricsK8sAnomalies } = + useMetricsK8sAnomaliesResults(anomalyParams); const getAnomalies = useMemo(() => { if (nodeType === 'host') { diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx index 2d3ff0beb2525..062349fa3ec6c 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/gradient_legend.tsx @@ -21,20 +21,19 @@ interface Props { formatter: InfraFormatter; } -const createTickRender = (bounds: InfraWaffleMapBounds, formatter: InfraFormatter) => ( - rule: InfraWaffleMapGradientRule, - index: number -) => { - const value = rule.value === 0 ? bounds.min : bounds.max * rule.value; - const style = { left: `${rule.value * 100}%` }; - const label = formatter(value); - return ( - - - {label} - - ); -}; +const createTickRender = + (bounds: InfraWaffleMapBounds, formatter: InfraFormatter) => + (rule: InfraWaffleMapGradientRule, index: number) => { + const value = rule.value === 0 ? bounds.min : bounds.max * rule.value; + const style = { left: `${rule.value * 100}%` }; + const label = formatter(value); + return ( + + + {label} + + ); + }; export const GradientLegend: React.FC = ({ legend, bounds, formatter }) => { const maxValue = legend.rules.reduce((acc, rule) => { diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_time_controls.tsx b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_time_controls.tsx index 765ae9d131ba6..39150a98c2e89 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_time_controls.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/components/waffle/waffle_time_controls.tsx @@ -17,13 +17,8 @@ interface Props { } export const WaffleTimeControls = withTheme(({ theme }: Props) => { - const { - currentTime, - isAutoReloading, - startAutoReload, - stopAutoReload, - jumpToTime, - } = useWaffleTimeContext(); + const { currentTime, isAutoReloading, startAutoReload, stopAutoReload, jumpToTime } = + useWaffleTimeContext(); const currentMoment = moment(currentTime); diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_metrics_k8s_anomalies.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_metrics_k8s_anomalies.ts index 384cefa691d96..986c4dfa2f8e8 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_metrics_k8s_anomalies.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_metrics_k8s_anomalies.ts @@ -315,16 +315,8 @@ export const callGetMetricsK8sAnomaliesAPI = async ( requestArgs: RequestArgs, fetch: HttpHandler ) => { - const { - sourceId, - anomalyThreshold, - startTime, - endTime, - metric, - query, - sort, - pagination, - } = requestArgs; + const { sourceId, anomalyThreshold, startTime, endTime, metric, query, sort, pagination } = + requestArgs; const response = await fetch(INFA_ML_GET_METRICS_K8S_ANOMALIES_PATH, { method: 'POST', body: JSON.stringify( diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_timeline.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_timeline.ts index b210379910c3f..53ff7e318e1f8 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_timeline.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_timeline.ts @@ -77,9 +77,10 @@ export function useTimeline( const displayInterval = useMemo(() => getDisplayInterval(interval), [interval]); - const timeLengthResult = useMemo(() => getTimeLengthFromInterval(displayInterval), [ - displayInterval, - ]); + const timeLengthResult = useMemo( + () => getTimeLengthFromInterval(displayInterval), + [displayInterval] + ); const { timeLength, intervalInSeconds } = timeLengthResult; const endTime = currentTime + intervalInSeconds * 1000; diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts index 90cf96330e758..67bc13251de20 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.ts @@ -66,9 +66,10 @@ export const useWaffleFilters = () => { setFilterQueryDraft(filterQuery.expression); }, []); - const isFilterQueryDraftValid = useMemo(() => validateKuery(filterQueryDraft), [ - filterQueryDraft, - ]); + const isFilterQueryDraftValid = useMemo( + () => validateKuery(filterQueryDraft), + [filterQueryDraft] + ); const { inventoryPrefill } = useAlertPrefillContext(); const prefillContext = useMemo(() => inventoryPrefill, [inventoryPrefill]); // For Jest compatibility diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts index 0d8114af3d05c..06b6138404a68 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts @@ -56,8 +56,7 @@ describe('useWaffleOptions', () => { customMetrics: [ { type: 'custom', - id: - "i don't want to bother to copy and paste an actual uuid so instead i'm going to smash my keyboard skjdghsjodkyjheurvjnsgn", + id: "i don't want to bother to copy and paste an actual uuid so instead i'm going to smash my keyboard skjdghsjodkyjheurvjnsgn", aggregation: 'avg', field: 'hey.system.are.you.good', }, diff --git a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_inventory_metric_formatter.ts b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_inventory_metric_formatter.ts index b6ba48290010d..ca09762442d20 100644 --- a/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_inventory_metric_formatter.ts +++ b/x-pack/plugins/infra/public/pages/metrics/inventory_view/lib/create_inventory_metric_formatter.ts @@ -78,17 +78,16 @@ const METRIC_FORMATTERS: MetricFormatters = { }, }; -export const createInventoryMetricFormatter = (metric: SnapshotMetricInput) => ( - val: string | number -) => { - if (SnapshotCustomMetricInputRT.is(metric)) { - const formatter = createFormatterForMetric(metric); +export const createInventoryMetricFormatter = + (metric: SnapshotMetricInput) => (val: string | number) => { + if (SnapshotCustomMetricInputRT.is(metric)) { + const formatter = createFormatterForMetric(metric); + return formatter(val); + } + const metricFormatter = get(METRIC_FORMATTERS, metric.type, METRIC_FORMATTERS.count); + if (val == null) { + return ''; + } + const formatter = createFormatter(metricFormatter.formatter, metricFormatter.template); return formatter(val); - } - const metricFormatter = get(METRIC_FORMATTERS, metric.type, METRIC_FORMATTERS.count); - if (val == null) { - return ''; - } - const formatter = createFormatter(metricFormatter.formatter, metricFormatter.template); - return formatter(val); -}; + }; diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/gauges_section_vis.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/gauges_section_vis.tsx index a4faa3d6c4755..709357719763b 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/gauges_section_vis.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/gauges_section_vis.tsx @@ -23,23 +23,25 @@ import { InventoryFormatterType } from '../../../../../common/inventory_models/t import { SeriesOverrides, VisSectionProps } from '../types'; import { getChartName } from './helpers'; -const getFormatter = ( - defaultFormatter: InventoryFormatterType = 'number', - defaultFormatterTemplate: string = '{{value}}', - seriesOverrides: SeriesOverrides = {}, - seriesId: string -) => (val: ReactText) => { - if (val == null) { - return ''; - } - const formatter = get(seriesOverrides, [seriesId, 'formatter'], defaultFormatter); - const formatterTemplate = get( - seriesOverrides, - [seriesId, 'formatterTemplate'], - defaultFormatterTemplate - ); - return createFormatter(formatter, formatterTemplate)(val); -}; +const getFormatter = + ( + defaultFormatter: InventoryFormatterType = 'number', + defaultFormatterTemplate: string = '{{value}}', + seriesOverrides: SeriesOverrides = {}, + seriesId: string + ) => + (val: ReactText) => { + if (val == null) { + return ''; + } + const formatter = get(seriesOverrides, [seriesId, 'formatter'], defaultFormatter); + const formatterTemplate = get( + seriesOverrides, + [seriesId, 'formatterTemplate'], + defaultFormatterTemplate + ); + return createFormatter(formatter, formatterTemplate)(val); + }; export const GaugesSectionVis = ({ id, diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/helpers.ts b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/helpers.ts index a0a795a760b58..0602e8a39b03b 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/helpers.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/components/helpers.ts @@ -23,10 +23,10 @@ import { /** * Returns a formatter */ -export const getFormatter = ( - formatter: InventoryFormatterType = 'number', - template: string = '{{value}}' -) => (val: ReactText) => (val != null ? createFormatter(formatter, template)(val) : ''); +export const getFormatter = + (formatter: InventoryFormatterType = 'number', template: string = '{{value}}') => + (val: ReactText) => + val != null ? createFormatter(formatter, template)(val) : ''; /** * Does a series have more then two points? diff --git a/x-pack/plugins/infra/public/pages/metrics/metric_detail/page_providers.tsx b/x-pack/plugins/infra/public/pages/metrics/metric_detail/page_providers.tsx index c4e1b6bf8ef16..6f44d49ddce90 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metric_detail/page_providers.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metric_detail/page_providers.tsx @@ -10,14 +10,15 @@ import React from 'react'; import { Source } from '../../../containers/metrics_source'; import { MetricsTimeProvider } from './hooks/use_metrics_time'; -export const withMetricPageProviders = (Component: React.ComponentType) => ( - props: T -) => ( - - - - - - - -); +export const withMetricPageProviders = + (Component: React.ComponentType) => + (props: T) => + ( + + + + + + + + ); diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts index a7ed8763d1c72..a9e65bc30a3c6 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.test.ts @@ -22,7 +22,7 @@ import { MetricsExplorerOptions } from '../../hooks/use_metrics_explorer_options jest.mock('uuid'); const mockedUuid = uuid as jest.Mocked; -mockedUuid.v1.mockReturnValue(('test-id' as unknown) as OutputBuffer); +mockedUuid.v1.mockReturnValue('test-id' as unknown as OutputBuffer); const series = { id: 'example-01', rows: [], columns: [] }; describe('createTSVBLink()', () => { @@ -32,8 +32,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -50,8 +49,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:bytes,id:test-id,label:'rate(system.network.out.bytes)',line_width:2,metrics:!((field:system.network.out.bytes,id:test-id,type:max),(field:test-id,id:test-id,type:derivative,unit:'1s'),(field:test-id,id:test-id,type:positive_only)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}}/s)),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:bytes,id:test-id,label:'rate(system.network.out.bytes)',line_width:2,metrics:!((field:system.network.out.bytes,id:test-id,type:max),(field:test-id,id:test-id,type:derivative,unit:'1s'),(field:test-id,id:test-id,type:positive_only)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}}/s)),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -64,8 +62,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-10m,to:now))', type: 'metrics', }, @@ -82,8 +79,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -101,8 +97,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'system.network.name:lo* and host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'my-beats-*',filter:(language:kuery,query:'system.network.name:lo* and host.name : \"example-01\"'),id:test-id,index_pattern:'my-beats-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -116,8 +111,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -131,8 +125,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0.5,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0.5,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -150,8 +143,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0.5,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:stacked,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metricbeat-*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metricbeat-*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0.5,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:stacked,value_template:{{value}})),show_grid:1,show_legend:1,time_field:'@timestamp',type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, @@ -169,8 +161,7 @@ describe('createTSVBLink()', () => { app: 'visualize', hash: '/create', search: { - _a: - "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metric*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metric*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", + _a: "(filters:!(),linked:!f,query:(language:kuery,query:''),uiState:(),vis:(aggs:!(),params:(axis_formatter:number,axis_min:0,axis_position:left,axis_scale:normal,default_index_pattern:'metric*',filter:(language:kuery,query:'host.name : \"example-01\"'),id:test-id,index_pattern:'metric*',interval:auto,series:!((axis_position:right,chart_type:line,color:#6092C0,fill:0,formatter:percent,id:test-id,label:'avg(system.cpu.user.pct)',line_width:2,metrics:!((field:system.cpu.user.pct,id:test-id,type:avg)),point_size:0,separate_axis:0,split_mode:everything,stacked:none,value_template:{{value}})),show_grid:1,show_legend:1,time_field:time,type:timeseries),title:example-01,type:metrics))", _g: '(refreshInterval:(pause:!t,value:0),time:(from:now-1h,to:now))', type: 'metrics', }, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts index 1a549041823ec..84d87ee4ad1b7 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts @@ -84,27 +84,26 @@ export const metricsExplorerMetricToTSVBMetric = (metric: MetricsExplorerOptions } }; -const mapMetricToSeries = (chartOptions: MetricsExplorerChartOptions) => ( - metric: MetricsExplorerOptionsMetric -) => { - const format = metricToFormat(metric); - return { - label: createMetricLabel(metric), - axis_position: 'right', - chart_type: 'line', - color: (metric.color && colorTransformer(metric.color)) || colorTransformer(Color.color0), - fill: chartOptions.type === MetricsExplorerChartType.area ? 0.5 : 0, - formatter: format === InfraFormatterType.bits ? InfraFormatterType.bytes : format, - value_template: 'rate' === metric.aggregation ? '{{value}}/s' : '{{value}}', - id: uuid.v1(), - line_width: 2, - metrics: metricsExplorerMetricToTSVBMetric(metric), - point_size: 0, - separate_axis: 0, - split_mode: 'everything', - stacked: chartOptions.stack ? 'stacked' : 'none', +const mapMetricToSeries = + (chartOptions: MetricsExplorerChartOptions) => (metric: MetricsExplorerOptionsMetric) => { + const format = metricToFormat(metric); + return { + label: createMetricLabel(metric), + axis_position: 'right', + chart_type: 'line', + color: (metric.color && colorTransformer(metric.color)) || colorTransformer(Color.color0), + fill: chartOptions.type === MetricsExplorerChartType.area ? 0.5 : 0, + formatter: format === InfraFormatterType.bits ? InfraFormatterType.bytes : format, + value_template: 'rate' === metric.aggregation ? '{{value}}/s' : '{{value}}', + id: uuid.v1(), + line_width: 2, + metrics: metricsExplorerMetricToTSVBMetric(metric), + point_size: 0, + separate_axis: 0, + split_mode: 'everything', + stacked: chartOptions.stack ? 'stacked' : 'none', + }; }; -}; export const createFilterFromOptions = ( options: MetricsExplorerOptions, diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/kuery_bar.tsx b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/kuery_bar.tsx index e22c6fa661181..cf201c9a57f7c 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/kuery_bar.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/kuery_bar.tsx @@ -99,5 +99,7 @@ export const MetricsExplorerKueryBar = ({ ); }; -const defaultCurryLoadSuggestions: CurryLoadSuggestionsType = (loadSuggestions) => (...args) => - loadSuggestions(...args); +const defaultCurryLoadSuggestions: CurryLoadSuggestionsType = + (loadSuggestions) => + (...args) => + loadSuggestions(...args); diff --git a/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_form_state.tsx b/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_form_state.tsx index 37da4bd1aa1bd..909bf294e4098 100644 --- a/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_form_state.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_form_state.tsx @@ -32,21 +32,24 @@ export const useSourceConfigurationFormState = ( ), }); - const errors = useMemo(() => [...indicesConfigurationFormState.errors], [ - indicesConfigurationFormState.errors, - ]); + const errors = useMemo( + () => [...indicesConfigurationFormState.errors], + [indicesConfigurationFormState.errors] + ); const resetForm = useCallback(() => { indicesConfigurationFormState.resetForm(); }, [indicesConfigurationFormState]); - const isFormDirty = useMemo(() => indicesConfigurationFormState.isFormDirty, [ - indicesConfigurationFormState.isFormDirty, - ]); + const isFormDirty = useMemo( + () => indicesConfigurationFormState.isFormDirty, + [indicesConfigurationFormState.isFormDirty] + ); - const isFormValid = useMemo(() => indicesConfigurationFormState.isFormValid, [ - indicesConfigurationFormState.isFormValid, - ]); + const isFormValid = useMemo( + () => indicesConfigurationFormState.isFormValid, + [indicesConfigurationFormState.isFormValid] + ); const formState = useMemo( () => ({ diff --git a/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_settings.tsx b/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_settings.tsx index 62577b949bdba..0adf4ed6b5b45 100644 --- a/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_settings.tsx +++ b/x-pack/plugins/infra/public/pages/metrics/settings/source_configuration_settings.tsx @@ -76,10 +76,10 @@ export const SourceConfigurationSettings = ({ formStateChanges, ]); - const isWriteable = useMemo(() => shouldAllowEdit && source && source.origin !== 'internal', [ - shouldAllowEdit, - source, - ]); + const isWriteable = useMemo( + () => shouldAllowEdit && source && source.origin !== 'internal', + [shouldAllowEdit, source] + ); const { hasInfraMLCapabilities } = useInfraMLCapabilitiesContext(); diff --git a/x-pack/plugins/infra/public/plugin.ts b/x-pack/plugins/infra/public/plugin.ts index 76e3e777e6378..712b7c01b9f0a 100644 --- a/x-pack/plugins/infra/public/plugin.ts +++ b/x-pack/plugins/infra/public/plugin.ts @@ -59,33 +59,39 @@ export class Plugin implements InfraClientPluginClass { /** !! Need to be kept in sync with the deepLinks in x-pack/plugins/infra/public/plugin.ts */ pluginsSetup.observability.navigation.registerSections( from(core.getStartServices()).pipe( - map(([{ application: { capabilities } }]) => [ - ...(capabilities.logs.show - ? [ - { - label: 'Logs', - sortKey: 200, - entries: [ - { label: 'Stream', app: 'logs', path: '/stream' }, - { label: 'Anomalies', app: 'logs', path: '/anomalies' }, - { label: 'Categories', app: 'logs', path: '/log-categories' }, - ], - }, - ] - : []), - ...(capabilities.infrastructure.show - ? [ - { - label: 'Metrics', - sortKey: 300, - entries: [ - { label: 'Inventory', app: 'metrics', path: '/inventory' }, - { label: 'Metrics Explorer', app: 'metrics', path: '/explorer' }, - ], - }, - ] - : []), - ]) + map( + ([ + { + application: { capabilities }, + }, + ]) => [ + ...(capabilities.logs.show + ? [ + { + label: 'Logs', + sortKey: 200, + entries: [ + { label: 'Stream', app: 'logs', path: '/stream' }, + { label: 'Anomalies', app: 'logs', path: '/anomalies' }, + { label: 'Categories', app: 'logs', path: '/log-categories' }, + ], + }, + ] + : []), + ...(capabilities.infrastructure.show + ? [ + { + label: 'Metrics', + sortKey: 300, + entries: [ + { label: 'Inventory', app: 'metrics', path: '/inventory' }, + { label: 'Metrics Explorer', app: 'metrics', path: '/explorer' }, + ], + }, + ] + : []), + ] + ) ) ); diff --git a/x-pack/plugins/infra/public/utils/data_search/normalize_data_search_responses.ts b/x-pack/plugins/infra/public/utils/data_search/normalize_data_search_responses.ts index 4c329110ae46e..71975af168f9f 100644 --- a/x-pack/plugins/infra/public/utils/data_search/normalize_data_search_responses.ts +++ b/x-pack/plugins/infra/public/utils/data_search/normalize_data_search_responses.ts @@ -12,9 +12,10 @@ import { AbortError } from '../../../../../../src/plugins/kibana_utils/public'; import { SearchStrategyError } from '../../../common/search_strategies/common/errors'; import { ParsedKibanaSearchResponse } from './types'; -export type RawResponseParser = ( - rawResponse: RawResponse -) => { data: Response; errors?: SearchStrategyError[] }; +export type RawResponseParser = (rawResponse: RawResponse) => { + data: Response; + errors?: SearchStrategyError[]; +}; /** * An operator factory that normalizes each {@link IKibanaSearchResponse} by @@ -30,49 +31,51 @@ export type RawResponseParser = ( * @return An operator that adds parsing and error handling transformations to * each response payload using the arguments given above. */ -export const normalizeDataSearchResponses = ( - initialResponse: InitialResponse, - parseRawResponse: RawResponseParser -) => ( - response$: Observable> -): Observable> => - response$.pipe( - map((response) => { - const { data, errors = [] } = parseRawResponse(response.rawResponse); - return { - data, - errors, - isPartial: response.isPartial ?? false, - isRunning: response.isRunning ?? false, - loaded: response.loaded, - total: response.total, - }; - }), - startWith({ - data: initialResponse, - errors: [], - isPartial: true, - isRunning: true, - loaded: 0, - total: undefined, - }), - catchError((error) => - of({ +export const normalizeDataSearchResponses = + ( + initialResponse: InitialResponse, + parseRawResponse: RawResponseParser + ) => + ( + response$: Observable> + ): Observable> => + response$.pipe( + map((response) => { + const { data, errors = [] } = parseRawResponse(response.rawResponse); + return { + data, + errors, + isPartial: response.isPartial ?? false, + isRunning: response.isRunning ?? false, + loaded: response.loaded, + total: response.total, + }; + }), + startWith({ data: initialResponse, - errors: [ - error instanceof AbortError - ? { - type: 'aborted' as const, - } - : { - type: 'generic' as const, - message: `${error.message ?? error}`, - }, - ], + errors: [], isPartial: true, - isRunning: false, + isRunning: true, loaded: 0, total: undefined, - }) - ) - ); + }), + catchError((error) => + of({ + data: initialResponse, + errors: [ + error instanceof AbortError + ? { + type: 'aborted' as const, + } + : { + type: 'generic' as const, + message: `${error.message ?? error}`, + }, + ], + isPartial: true, + isRunning: false, + loaded: 0, + total: undefined, + }) + ) + ); diff --git a/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx b/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx index 1ed912b0e01f6..71c49ef75023e 100644 --- a/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx +++ b/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx @@ -107,9 +107,8 @@ describe('useLatestPartialDataSearchResponse hook', () => { }), }; - const requests$ = of, string>>( - firstRequest - ); + const requests$ = + of, string>>(firstRequest); const { unmount } = renderHook(() => useLatestPartialDataSearchResponse(requests$)); diff --git a/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.ts b/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.ts index 741136b513116..2cafceaad3cb5 100644 --- a/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.ts +++ b/x-pack/plugins/infra/public/utils/data_search/use_latest_partial_data_search_response.ts @@ -16,9 +16,8 @@ import { useDataSearchResponseState } from './use_data_search_response_state'; export const useLatestPartialDataSearchResponse = ( requests$: Observable> ) => { - const latestResponse$: Observable< - ParsedDataSearchResponseDescriptor - > = useOperator(requests$, flattenLatestDataSearchResponse); + const latestResponse$: Observable> = + useOperator(requests$, flattenLatestDataSearchResponse); const { cancelRequest, diff --git a/x-pack/plugins/infra/public/utils/loading_state/loading_progress.ts b/x-pack/plugins/infra/public/utils/loading_state/loading_progress.ts index 5ddc5761f03c3..4670883ec2a77 100644 --- a/x-pack/plugins/infra/public/utils/loading_state/loading_progress.ts +++ b/x-pack/plugins/infra/public/utils/loading_state/loading_progress.ts @@ -25,17 +25,19 @@ export const isRunningLoadingProgress =

( loadingProgress: LoadingProgress

): loadingProgress is RunningLoadingProgress

=> loadingProgress.progress === 'running'; -export const createIdleProgressReducer = () => ( - state: LoadingProgress -): IdleLoadingProgress => ({ - progress: 'idle', -}); +export const createIdleProgressReducer = + () => + (state: LoadingProgress): IdleLoadingProgress => ({ + progress: 'idle', + }); -export const createRunningProgressReducer = () => ( - state: LoadingProgress, - parameters: Parameters -): RunningLoadingProgress => ({ - parameters, - progress: 'running', - time: Date.now(), -}); +export const createRunningProgressReducer = + () => + ( + state: LoadingProgress, + parameters: Parameters + ): RunningLoadingProgress => ({ + parameters, + progress: 'running', + time: Date.now(), + }); diff --git a/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts b/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts index 683de7aeedc11..09411f6c6fce8 100644 --- a/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts +++ b/x-pack/plugins/infra/public/utils/loading_state/loading_result.ts @@ -64,12 +64,15 @@ export const createSuccessResult = ( time: Date.now(), }); -export const createSuccessResultReducer = ( - isExhausted: (params: Parameters, result: Payload) => boolean -) => ( - state: LoadingResult, - { params, result }: { params: Parameters; result: Payload } -): SuccessLoadingResult => createSuccessResult(params, isExhausted(params, result)); +export const createSuccessResultReducer = + ( + isExhausted: (params: Parameters, result: Payload) => boolean + ) => + ( + state: LoadingResult, + { params, result }: { params: Parameters; result: Payload } + ): SuccessLoadingResult => + createSuccessResult(params, isExhausted(params, result)); export const createFailureResult = ( parameters: Parameters, @@ -81,9 +84,12 @@ export const createFailureResult = ( time: Date.now(), }); -export const createFailureResultReducer = ( - convertErrorToString: (error: ErrorPayload) => string = (error) => `${error}` -) => ( - state: LoadingResult, - { params, error }: { params: Parameters; error: ErrorPayload } -): FailureLoadingResult => createFailureResult(params, convertErrorToString(error)); +export const createFailureResultReducer = + ( + convertErrorToString: (error: ErrorPayload) => string = (error) => `${error}` + ) => + ( + state: LoadingResult, + { params, error }: { params: Parameters; error: ErrorPayload } + ): FailureLoadingResult => + createFailureResult(params, convertErrorToString(error)); diff --git a/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts b/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts index 8d51f54e3f55a..6dfb400567717 100644 --- a/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts +++ b/x-pack/plugins/infra/public/utils/logs_overview_fetches.test.ts @@ -21,9 +21,10 @@ const mockedCallFetchLogSourceStatusAPI = callFetchLogSourceStatusAPI as jest.Mo >; jest.mock('../containers/logs/log_source/api/fetch_log_source_configuration'); -const mockedCallFetchLogSourceConfigurationAPI = callFetchLogSourceConfigurationAPI as jest.MockedFunction< - typeof callFetchLogSourceConfigurationAPI ->; +const mockedCallFetchLogSourceConfigurationAPI = + callFetchLogSourceConfigurationAPI as jest.MockedFunction< + typeof callFetchLogSourceConfigurationAPI + >; const DEFAULT_PARAMS = { absoluteTime: { start: 1593430680000, end: 1593430800000 }, diff --git a/x-pack/plugins/infra/public/utils/styles.ts b/x-pack/plugins/infra/public/utils/styles.ts index db979a9ac68ee..bd0ba2099d95c 100644 --- a/x-pack/plugins/infra/public/utils/styles.ts +++ b/x-pack/plugins/infra/public/utils/styles.ts @@ -19,9 +19,7 @@ const asPropReader = (reader: string | string[] | PropReader) => ) => get(props, reader as Prop, defaultValue); export const switchProp = Object.assign( - (propName: string | string[] | PropReader, options: Map | object) => ( - props: object - ) => { + (propName: string | string[] | PropReader, options: Map | object) => (props: object) => { const propValue = asPropReader(propName)(props, switchProp.default); if (typeof propValue === 'undefined') { return; @@ -33,11 +31,10 @@ export const switchProp = Object.assign( } ); -export const ifProp = ( - propName: string | string[] | PropReader, - pass: Pass, - fail: Fail -) => (props: object) => (asPropReader(propName)(props) ? pass : fail); +export const ifProp = + (propName: string | string[] | PropReader, pass: Pass, fail: Fail) => + (props: object) => + asPropReader(propName)(props) ? pass : fail; export const tintOrShade = ( textColor: string, diff --git a/x-pack/plugins/infra/public/utils/typed_redux.ts b/x-pack/plugins/infra/public/utils/typed_redux.ts index 04b3190c0146b..cd02539e719bb 100644 --- a/x-pack/plugins/infra/public/utils/typed_redux.ts +++ b/x-pack/plugins/infra/public/utils/typed_redux.ts @@ -23,15 +23,13 @@ export type GlobalSelectors = { >; }; -export const globalizeSelector = < - GlobalState, - LocalSelector extends Selector, - LocalState = any, - Value = any ->( - globalizer: Selector, - selector: LocalSelector -): Selector => (globalState: GlobalState) => selector(globalizer(globalState)); +export const globalizeSelector = + , LocalState = any, Value = any>( + globalizer: Selector, + selector: LocalSelector + ): Selector => + (globalState: GlobalState) => + selector(globalizer(globalState)); export const globalizeSelectors = < GlobalState, @@ -63,9 +61,9 @@ type PlainActionCreator = WrappedActionCreator extends () ? (payload: A) => R : never; -export const bindPlainActionCreators = ( - actionCreators: WrappedActionCreators -) => (dispatch: Dispatch) => - (bindActionCreators(actionCreators, dispatch) as unknown) as { - [P in keyof WrappedActionCreators]: PlainActionCreator; - }; +export const bindPlainActionCreators = + (actionCreators: WrappedActionCreators) => + (dispatch: Dispatch) => + bindActionCreators(actionCreators, dispatch) as unknown as { + [P in keyof WrappedActionCreators]: PlainActionCreator; + }; diff --git a/x-pack/plugins/infra/public/utils/url_state.tsx b/x-pack/plugins/infra/public/utils/url_state.tsx index 0e6c38e893ca8..8148463ab3fe3 100644 --- a/x-pack/plugins/infra/public/utils/url_state.tsx +++ b/x-pack/plugins/infra/public/utils/url_state.tsx @@ -152,20 +152,19 @@ export const getParamFromQueryString = (queryString: string, key: string): strin return Array.isArray(queryParam) ? queryParam[0] : queryParam; }; -export const replaceStateKeyInQueryString = ( - stateKey: string, - urlState: UrlState | undefined -) => (queryString: string) => { - const previousQueryValues = parse(queryString, { sort: false }); - const newValue = - typeof urlState === 'undefined' - ? previousQueryValues - : { - ...previousQueryValues, - [stateKey]: encodeRisonUrlState(urlState), - }; - return stringify(url.encodeQuery(newValue), { sort: false, encode: false }); -}; +export const replaceStateKeyInQueryString = + (stateKey: string, urlState: UrlState | undefined) => + (queryString: string) => { + const previousQueryValues = parse(queryString, { sort: false }); + const newValue = + typeof urlState === 'undefined' + ? previousQueryValues + : { + ...previousQueryValues, + [stateKey]: encodeRisonUrlState(urlState), + }; + return stringify(url.encodeQuery(newValue), { sort: false, encode: false }); + }; const replaceQueryStringInLocation = (location: Location, queryString: string): Location => { if (queryString === getQueryStringFromLocation(location)) { diff --git a/x-pack/plugins/infra/public/utils/use_observable.ts b/x-pack/plugins/infra/public/utils/use_observable.ts index 345d57e6fa5f6..87d182c94ac05 100644 --- a/x-pack/plugins/infra/public/utils/use_observable.ts +++ b/x-pack/plugins/infra/public/utils/use_observable.ts @@ -95,17 +95,19 @@ export const useOperator = ( ); }; -export const tapUnsubscribe = (onUnsubscribe: () => void) => (source$: Observable) => { - return new Observable((subscriber) => { - const subscription = source$.subscribe({ - next: (value) => subscriber.next(value), - error: (error) => subscriber.error(error), - complete: () => subscriber.complete(), +export const tapUnsubscribe = + (onUnsubscribe: () => void) => + (source$: Observable) => { + return new Observable((subscriber) => { + const subscription = source$.subscribe({ + next: (value) => subscriber.next(value), + error: (error) => subscriber.error(error), + complete: () => subscriber.complete(), + }); + + return () => { + onUnsubscribe(); + subscription.unsubscribe(); + }; }); - - return () => { - onUnsubscribe(); - subscription.unsubscribe(); - }; - }); -}; + }; diff --git a/x-pack/plugins/infra/public/utils/use_tracked_promise.ts b/x-pack/plugins/infra/public/utils/use_tracked_promise.ts index 1b0c290bd6511..4380db2dcb4c4 100644 --- a/x-pack/plugins/infra/public/utils/use_tracked_promise.ts +++ b/x-pack/plugins/infra/public/utils/use_tracked_promise.ts @@ -113,109 +113,110 @@ export const useTrackedPromise = ( }); const execute = useMemo( - () => (...args: Arguments) => { - let rejectCancellationPromise!: (value: any) => void; - const cancellationPromise = new Promise((_, reject) => { - rejectCancellationPromise = reject; - }); - - // remember the list of prior pending promises for cancellation - const previousPendingPromises = pendingPromises.current; - - const cancelPreviousPendingPromises = () => { - previousPendingPromises.forEach((promise) => promise.cancel()); - }; - - const newPromise = createPromise(...args); - const newCancelablePromise = Promise.race([newPromise, cancellationPromise]); - - // track this new state - setPromiseState({ - state: 'pending', - promise: newCancelablePromise, - }); - - if (cancelPreviousOn === 'creation') { - cancelPreviousPendingPromises(); - } - - const newPendingPromise: CancelablePromise = { - cancel: () => { - rejectCancellationPromise(new CanceledPromiseError()); - }, - cancelSilently: () => { - rejectCancellationPromise(new SilentCanceledPromiseError()); - }, - promise: newCancelablePromise.then( - (value) => { - setPromiseState((previousPromiseState) => - previousPromiseState.state === 'pending' && - previousPromiseState.promise === newCancelablePromise - ? { - state: 'resolved', - promise: newPendingPromise.promise, - value, - } - : previousPromiseState - ); - - if (['settlement', 'resolution'].includes(cancelPreviousOn)) { - cancelPreviousPendingPromises(); - } - - // remove itself from the list of pending promises - pendingPromises.current = pendingPromises.current.filter( - (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise - ); - - if (onResolve && shouldTriggerOrThrow()) { - onResolve(value); - } - - return value; + () => + (...args: Arguments) => { + let rejectCancellationPromise!: (value: any) => void; + const cancellationPromise = new Promise((_, reject) => { + rejectCancellationPromise = reject; + }); + + // remember the list of prior pending promises for cancellation + const previousPendingPromises = pendingPromises.current; + + const cancelPreviousPendingPromises = () => { + previousPendingPromises.forEach((promise) => promise.cancel()); + }; + + const newPromise = createPromise(...args); + const newCancelablePromise = Promise.race([newPromise, cancellationPromise]); + + // track this new state + setPromiseState({ + state: 'pending', + promise: newCancelablePromise, + }); + + if (cancelPreviousOn === 'creation') { + cancelPreviousPendingPromises(); + } + + const newPendingPromise: CancelablePromise = { + cancel: () => { + rejectCancellationPromise(new CanceledPromiseError()); }, - (value) => { - if (!(value instanceof SilentCanceledPromiseError)) { + cancelSilently: () => { + rejectCancellationPromise(new SilentCanceledPromiseError()); + }, + promise: newCancelablePromise.then( + (value) => { setPromiseState((previousPromiseState) => previousPromiseState.state === 'pending' && previousPromiseState.promise === newCancelablePromise ? { - state: 'rejected', - promise: newCancelablePromise, + state: 'resolved', + promise: newPendingPromise.promise, value, } : previousPromiseState ); - } - if (['settlement', 'rejection'].includes(cancelPreviousOn)) { - cancelPreviousPendingPromises(); - } + if (['settlement', 'resolution'].includes(cancelPreviousOn)) { + cancelPreviousPendingPromises(); + } - // remove itself from the list of pending promises - pendingPromises.current = pendingPromises.current.filter( - (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise - ); + // remove itself from the list of pending promises + pendingPromises.current = pendingPromises.current.filter( + (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise + ); - if (shouldTriggerOrThrow()) { - if (onReject) { - onReject(value); + if (onResolve && shouldTriggerOrThrow()) { + onResolve(value); } - throw value; + return value; + }, + (value) => { + if (!(value instanceof SilentCanceledPromiseError)) { + setPromiseState((previousPromiseState) => + previousPromiseState.state === 'pending' && + previousPromiseState.promise === newCancelablePromise + ? { + state: 'rejected', + promise: newCancelablePromise, + value, + } + : previousPromiseState + ); + } + + if (['settlement', 'rejection'].includes(cancelPreviousOn)) { + cancelPreviousPendingPromises(); + } + + // remove itself from the list of pending promises + pendingPromises.current = pendingPromises.current.filter( + (pendingPromise) => pendingPromise.promise !== newPendingPromise.promise + ); + + if (shouldTriggerOrThrow()) { + if (onReject) { + onReject(value); + } + + throw value; + } } - } - ), - }; + ), + }; - // add the new promise to the list of pending promises - pendingPromises.current = [...pendingPromises.current, newPendingPromise]; + // add the new promise to the list of pending promises + pendingPromises.current = [...pendingPromises.current, newPendingPromise]; - // silence "unhandled rejection" warnings - newPendingPromise.promise.catch(noOp); + // silence "unhandled rejection" warnings + newPendingPromise.promise.catch(noOp); - return newPendingPromise.promise; - }, + return newPendingPromise.promise; + }, // the dependencies are managed by the caller // eslint-disable-next-line react-hooks/exhaustive-deps dependencies diff --git a/x-pack/plugins/infra/public/utils/use_url_state.ts b/x-pack/plugins/infra/public/utils/use_url_state.ts index 970b3a20b2951..eef82438ff017 100644 --- a/x-pack/plugins/infra/public/utils/use_url_state.ts +++ b/x-pack/plugins/infra/public/utils/use_url_state.ts @@ -105,21 +105,20 @@ const getParamFromQueryString = (queryString: string, key: string) => { return Array.isArray(queryParam) ? queryParam[0] : queryParam; }; -export const replaceStateKeyInQueryString = ( - stateKey: string, - urlState: UrlState | undefined -) => (queryString: string) => { - const previousQueryValues = parse(queryString, { sort: false }); - const newValue = - typeof urlState === 'undefined' - ? previousQueryValues - : { - ...previousQueryValues, - [stateKey]: encodeRisonUrlState(urlState), - }; - - return stringify(url.encodeQuery(newValue), { sort: false, encode: false }); -}; +export const replaceStateKeyInQueryString = + (stateKey: string, urlState: UrlState | undefined) => + (queryString: string) => { + const previousQueryValues = parse(queryString, { sort: false }); + const newValue = + typeof urlState === 'undefined' + ? previousQueryValues + : { + ...previousQueryValues, + [stateKey]: encodeRisonUrlState(urlState), + }; + + return stringify(url.encodeQuery(newValue), { sort: false, encode: false }); + }; const replaceQueryStringInLocation = (location: Location, queryString: string): Location => { if (queryString === getQueryStringFromLocation(location)) { diff --git a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts index 4ad2fa656f9b2..ab98de7901a3d 100644 --- a/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/log_entries/kibana_log_entries_adapter.ts @@ -268,9 +268,7 @@ const createFilterClauses = ( const createQueryFilterClauses = (filterQuery: LogEntryQuery | undefined) => filterQuery ? [filterQuery] : []; -function processCursor( - cursor: LogEntriesParams['cursor'] -): { +function processCursor(cursor: LogEntriesParams['cursor']): { sortDirection: 'asc' | 'desc'; searchAfterClause: { search_after?: readonly [number, number] }; } { diff --git a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts index 079d39c080bf5..0aa305a580ffa 100644 --- a/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts +++ b/x-pack/plugins/infra/server/lib/adapters/source_status/elasticsearch_source_status_adapter.ts @@ -76,11 +76,11 @@ export class InfraElasticsearchSourceStatusAdapter implements InfraSourceStatusA } } -const withDefaultIfNotFound = (defaultValue: DefaultValue) => ( - error: any -): DefaultValue => { - if (error && error.status === 404) { - return defaultValue; - } - throw error; -}; +const withDefaultIfNotFound = + (defaultValue: DefaultValue) => + (error: any): DefaultValue => { + if (error && error.status === 404) { + return defaultValue; + } + throw error; + }; diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts index ddfc575438faa..bbbb0e917d518 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts @@ -70,13 +70,8 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = InventoryMetricThresholdAlertInstanceContext, InventoryMetricThresholdAllowedActionGroups >(async ({ services, params }) => { - const { - criteria, - filterQuery, - sourceId, - nodeType, - alertOnNoData, - } = params as InventoryMetricThresholdParams; + const { criteria, filterQuery, sourceId, nodeType, alertOnNoData } = + params as InventoryMetricThresholdParams; if (criteria.length === 0) throw new Error('Cannot execute an alert with 0 conditions'); const { alertWithLifecycle, savedObjectsClient } = services; const alertInstanceFactory: InventoryMetricThresholdAlertInstanceFactory = (id, reason) => @@ -185,7 +180,7 @@ export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) = * TODO: We're lying to the compiler here as explicitly calling `scheduleActions` on * the RecoveredActionGroup isn't allowed */ - (actionGroupId as unknown) as InventoryMetricThresholdAllowedActionGroups, + actionGroupId as unknown as InventoryMetricThresholdAllowedActionGroups, { group: item, alertState: stateToAlertMessage[nextState], diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_anomaly/metric_anomaly_executor.ts b/x-pack/plugins/infra/server/lib/alerting/metric_anomaly/metric_anomaly_executor.ts index 2282a7ff255d1..f7dbe95b4161c 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_anomaly/metric_anomaly_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_anomaly/metric_anomaly_executor.ts @@ -25,80 +25,79 @@ import { KibanaRequest } from '../../../../../../../src/core/server'; import { InfraBackendLibs } from '../../infra_types'; import { evaluateCondition } from './evaluate_condition'; -export const createMetricAnomalyExecutor = (libs: InfraBackendLibs, ml?: MlPluginSetup) => async ({ - services, - params, - startedAt, -}: AlertExecutorOptions< - /** - * TODO: Remove this use of `any` by utilizing a proper type - */ - Record, - Record, - AlertInstanceState, - AlertInstanceContext, - MetricAnomalyAllowedActionGroups ->) => { - if (!ml) { - return; - } - const request = {} as KibanaRequest; - const mlSystem = ml.mlSystemProvider(request, services.savedObjectsClient); - const mlAnomalyDetectors = ml.anomalyDetectorsProvider(request, services.savedObjectsClient); +export const createMetricAnomalyExecutor = + (libs: InfraBackendLibs, ml?: MlPluginSetup) => + async ({ + services, + params, + startedAt, + }: AlertExecutorOptions< + /** + * TODO: Remove this use of `any` by utilizing a proper type + */ + Record, + Record, + AlertInstanceState, + AlertInstanceContext, + MetricAnomalyAllowedActionGroups + >) => { + if (!ml) { + return; + } + const request = {} as KibanaRequest; + const mlSystem = ml.mlSystemProvider(request, services.savedObjectsClient); + const mlAnomalyDetectors = ml.anomalyDetectorsProvider(request, services.savedObjectsClient); - const { - metric, - alertInterval, - influencerFilter, - sourceId, - spaceId, - nodeType, - threshold, - } = params as MetricAnomalyParams; + const { metric, alertInterval, influencerFilter, sourceId, spaceId, nodeType, threshold } = + params as MetricAnomalyParams; - const bucketInterval = getIntervalInSeconds('15m') * 1000; - const alertIntervalInMs = getIntervalInSeconds(alertInterval ?? '1m') * 1000; + const bucketInterval = getIntervalInSeconds('15m') * 1000; + const alertIntervalInMs = getIntervalInSeconds(alertInterval ?? '1m') * 1000; - const endTime = startedAt.getTime(); - // Anomalies are bucketed at :00, :15, :30, :45 minutes every hour - const previousBucketStartTime = endTime - (endTime % bucketInterval); + const endTime = startedAt.getTime(); + // Anomalies are bucketed at :00, :15, :30, :45 minutes every hour + const previousBucketStartTime = endTime - (endTime % bucketInterval); - // If the alert interval is less than 15m, make sure that it actually queries an anomaly bucket - const startTime = Math.min(endTime - alertIntervalInMs, previousBucketStartTime); + // If the alert interval is less than 15m, make sure that it actually queries an anomaly bucket + const startTime = Math.min(endTime - alertIntervalInMs, previousBucketStartTime); - const { data } = await evaluateCondition({ - sourceId: sourceId ?? 'default', - spaceId: spaceId ?? 'default', - mlSystem, - mlAnomalyDetectors, - startTime, - endTime, - metric, - threshold, - nodeType, - influencerFilter, - }); + const { data } = await evaluateCondition({ + sourceId: sourceId ?? 'default', + spaceId: spaceId ?? 'default', + mlSystem, + mlAnomalyDetectors, + startTime, + endTime, + metric, + threshold, + nodeType, + influencerFilter, + }); - const shouldAlertFire = data.length > 0; + const shouldAlertFire = data.length > 0; - if (shouldAlertFire) { - const { startTime: anomalyStartTime, anomalyScore, actual, typical, influencers } = first( - data as MappedAnomalyHit[] - )!; - const alertInstance = services.alertInstanceFactory(`${nodeType}-${metric}`); + if (shouldAlertFire) { + const { + startTime: anomalyStartTime, + anomalyScore, + actual, + typical, + influencers, + } = first(data as MappedAnomalyHit[])!; + const alertInstance = services.alertInstanceFactory(`${nodeType}-${metric}`); - alertInstance.scheduleActions(FIRED_ACTIONS_ID, { - alertState: stateToAlertMessage[AlertStates.ALERT], - timestamp: moment(anomalyStartTime).toISOString(), - anomalyScore, - actual, - typical, - metric: metricNameMap[metric], - summary: generateSummaryMessage(actual, typical), - influencers: influencers.join(', '), - }); - } -}; + alertInstance.scheduleActions(FIRED_ACTIONS_ID, { + alertState: stateToAlertMessage[AlertStates.ALERT], + timestamp: moment(anomalyStartTime).toISOString(), + anomalyScore, + actual, + typical, + metric: metricNameMap[metric], + summary: generateSummaryMessage(actual, typical), + influencers: influencers.join(', '), + }); + } + }; export const FIRED_ACTIONS_ID = 'metrics.anomaly.fired'; export const FIRED_ACTIONS: ActionGroup = { diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts index a099b83fdb423..c7c1eb5454d1d 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts @@ -195,7 +195,7 @@ const getMetric: ( return { [UNGROUPED_FACTORY_KEY]: getValuesFromAggregations( - (result.aggregations! as unknown) as Aggregation, + result.aggregations! as unknown as Aggregation, aggType, dropPartialBucketsOptions, calculatedTimerange, @@ -225,16 +225,18 @@ interface DropPartialBucketOptions { bucketSizeInMillis: number; } -const dropPartialBuckets = ({ from, to, bucketSizeInMillis }: DropPartialBucketOptions) => ( - row: { - key: string; - value: number | null; - } | null -) => { - if (row == null) return null; - const timestamp = new Date(row.key).valueOf(); - return timestamp >= from && timestamp + bucketSizeInMillis <= to; -}; +const dropPartialBuckets = + ({ from, to, bucketSizeInMillis }: DropPartialBucketOptions) => + ( + row: { + key: string; + value: number | null; + } | null + ) => { + if (row == null) return null; + const timestamp = new Date(row.key).valueOf(); + return timestamp >= from && timestamp + bucketSizeInMillis <= to; + }; const getValuesFromAggregations = ( aggregations: Aggregation | undefined, diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts index 259318b6c93a1..9c99ad6bf49e2 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts @@ -207,14 +207,8 @@ const formatAlertResult = ( } & AlertResult, useWarningThreshold?: boolean ) => { - const { - metric, - currentValue, - threshold, - comparator, - warningThreshold, - warningComparator, - } = alertResult; + const { metric, currentValue, threshold, comparator, warningThreshold, warningComparator } = + alertResult; const noDataValue = i18n.translate( 'xpack.infra.metrics.alerting.threshold.noDataFormattedValue', { diff --git a/x-pack/plugins/infra/server/lib/create_search_client.ts b/x-pack/plugins/infra/server/lib/create_search_client.ts index afe16801dd2a2..6688ae1af1afc 100644 --- a/x-pack/plugins/infra/server/lib/create_search_client.ts +++ b/x-pack/plugins/infra/server/lib/create_search_client.ts @@ -9,10 +9,9 @@ import type { InfraPluginRequestHandlerContext } from '../types'; import { CallWithRequestParams, InfraDatabaseSearchResponse } from './adapters/framework'; import { KibanaFramework } from './adapters/framework/kibana_framework_adapter'; -export const createSearchClient = ( - requestContext: InfraPluginRequestHandlerContext, - framework: KibanaFramework -) => ( - opts: CallWithRequestParams -): Promise> => - framework.callWithRequest(requestContext, 'search', opts); +export const createSearchClient = + (requestContext: InfraPluginRequestHandlerContext, framework: KibanaFramework) => + ( + opts: CallWithRequestParams + ): Promise> => + framework.callWithRequest(requestContext, 'search', opts); diff --git a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts index f6be310d79ed2..16209e5e4b684 100644 --- a/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts +++ b/x-pack/plugins/infra/server/lib/domains/log_entries_domain/log_entries_domain.ts @@ -166,28 +166,26 @@ export class InfraLogEntriesDomain { id: doc.id, index: doc.index, cursor: doc.cursor, - columns: columnDefinitions.map( - (column): LogColumn => { - if ('timestampColumn' in column) { - return { - columnId: column.timestampColumn.id, - timestamp: doc.cursor.time, - }; - } else if ('messageColumn' in column) { - return { - columnId: column.messageColumn.id, - message: messageFormattingRules.format(doc.fields, doc.highlights), - }; - } else { - return { - columnId: column.fieldColumn.id, - field: column.fieldColumn.field, - value: doc.fields[column.fieldColumn.field] ?? [], - highlights: doc.highlights[column.fieldColumn.field] ?? [], - }; - } + columns: columnDefinitions.map((column): LogColumn => { + if ('timestampColumn' in column) { + return { + columnId: column.timestampColumn.id, + timestamp: doc.cursor.time, + }; + } else if ('messageColumn' in column) { + return { + columnId: column.messageColumn.id, + message: messageFormattingRules.format(doc.fields, doc.highlights), + }; + } else { + return { + columnId: column.fieldColumn.id, + field: column.fieldColumn.field, + value: doc.fields[column.fieldColumn.field] ?? [], + highlights: doc.highlights[column.fieldColumn.field] ?? [], + }; } - ), + }), context: getContextFromDoc(doc), }; }); diff --git a/x-pack/plugins/infra/server/lib/host_details/process_list.ts b/x-pack/plugins/infra/server/lib/host_details/process_list.ts index e51e06af83f94..a9125c73fe5d0 100644 --- a/x-pack/plugins/infra/server/lib/host_details/process_list.ts +++ b/x-pack/plugins/infra/server/lib/host_details/process_list.ts @@ -129,8 +129,8 @@ export const getProcessList = async ( let summary: { [p: string]: number } = {}; if (result.aggregations!.summaryEvent.summary.hits.hits.length) { - summary = result.aggregations!.summaryEvent.summary.hits.hits[0]._source.system.process - .summary; + summary = + result.aggregations!.summaryEvent.summary.hits.hits[0]._source.system.process.summary; } return { diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts index 7739f39cb5624..7023f7007763c 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_analysis.ts @@ -244,15 +244,14 @@ async function fetchTopLogEntryCategories( const topLogEntryCategories = topLogEntryCategoriesResponse.aggregations?.terms_category_id.buckets.map( (topCategoryBucket) => { - const maximumAnomalyScoresByDataset = topCategoryBucket.filter_record.terms_dataset.buckets.reduce< - Record - >( - (accumulatedMaximumAnomalyScores, datasetFromRecord) => ({ - ...accumulatedMaximumAnomalyScores, - [datasetFromRecord.key]: datasetFromRecord.maximum_record_score.value ?? 0, - }), - {} - ); + const maximumAnomalyScoresByDataset = + topCategoryBucket.filter_record.terms_dataset.buckets.reduce>( + (accumulatedMaximumAnomalyScores, datasetFromRecord) => ({ + ...accumulatedMaximumAnomalyScores, + [datasetFromRecord.key]: datasetFromRecord.maximum_record_score.value ?? 0, + }), + {} + ); return { categoryId: parseCategoryId(topCategoryBucket.key), diff --git a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_datasets_stats.ts b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_datasets_stats.ts index 7c92a81e1a896..8c3f739339152 100644 --- a/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_datasets_stats.ts +++ b/x-pack/plugins/infra/server/lib/log_analysis/log_entry_categories_datasets_stats.ts @@ -34,16 +34,17 @@ export async function getLatestLogEntriesCategoriesDatasetsStats( let afterLatestBatchKey: CompositeDatasetKey | undefined; while (true) { - const latestLogEntryCategoriesDatasetsStatsResponse = await context.infra.mlSystem.mlAnomalySearch( - createLatestLogEntryCategoriesDatasetsStatsQuery( - jobIds, - startTime, - endTime, - COMPOSITE_AGGREGATION_BATCH_SIZE, - afterLatestBatchKey - ), - jobIds - ); + const latestLogEntryCategoriesDatasetsStatsResponse = + await context.infra.mlSystem.mlAnomalySearch( + createLatestLogEntryCategoriesDatasetsStatsQuery( + jobIds, + startTime, + endTime, + COMPOSITE_AGGREGATION_BATCH_SIZE, + afterLatestBatchKey + ), + jobIds + ); const { after_key: afterKey, buckets: latestBatchBuckets = [] } = decodeOrThrow(latestLogEntryCategoriesDatasetsStatsResponseRT)( diff --git a/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.ts b/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.ts index f6761f72fabb9..82bd99896839f 100644 --- a/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.ts +++ b/x-pack/plugins/infra/server/lib/metrics/lib/convert_histogram_buckets_to_timeseries.ts @@ -64,9 +64,9 @@ const getValue = (valueObject: ValueObjectType) => { return null; }; -const dropOutOfBoundsBuckets = (from: number, to: number, bucketSizeInMillis: number) => ( - row: MetricsAPIRow -) => row.timestamp >= from && row.timestamp + bucketSizeInMillis <= to; +const dropOutOfBoundsBuckets = + (from: number, to: number, bucketSizeInMillis: number) => (row: MetricsAPIRow) => + row.timestamp >= from && row.timestamp + bucketSizeInMillis <= to; const convertBucketsToRows = ( options: MetricsAPIRequest, diff --git a/x-pack/plugins/infra/server/lib/sources/saved_object_references.test.ts b/x-pack/plugins/infra/server/lib/sources/saved_object_references.test.ts index 7d31f7342b05b..9f6f9cd284c67 100644 --- a/x-pack/plugins/infra/server/lib/sources/saved_object_references.test.ts +++ b/x-pack/plugins/infra/server/lib/sources/saved_object_references.test.ts @@ -17,8 +17,14 @@ describe('extractSavedObjectReferences function', () => { sourceConfigurationWithIndexPatternReference ); - expect(references).toMatchObject([{ id: 'INDEX_PATTERN_ID' }]); + expect(references).toMatchObject([ + { id: 'INDEX_PATTERN_ID' }, + { id: 'INVENTORY_DEFAULT_VIEW' }, + { id: 'METRICS_EXPLORER_DEFAULT_VIEW' }, + ]); expect(attributes).toHaveProperty(['logIndices', 'indexPatternId'], references[0].name); + expect(attributes).toHaveProperty(['inventoryDefaultView'], references[1].name); + expect(attributes).toHaveProperty(['metricsExplorerDefaultView'], references[2].name); }); it('ignores log index name references', () => { @@ -26,7 +32,29 @@ describe('extractSavedObjectReferences function', () => { sourceConfigurationWithIndexNameReference ); - expect(references).toHaveLength(0); + expect(references).toHaveLength(2); + expect(attributes).toHaveProperty(['logIndices', 'indexName'], 'INDEX_NAME'); + }); + + it('ignores default inventory view', () => { + const { attributes, references } = extractSavedObjectReferences({ + ...sourceConfigurationWithIndexNameReference, + inventoryDefaultView: '0', + }); + + expect(references).toHaveLength(1); + expect(references).toMatchObject([{ id: 'METRICS_EXPLORER_DEFAULT_VIEW' }]); + expect(attributes).toHaveProperty(['logIndices', 'indexName'], 'INDEX_NAME'); + }); + + it('ignores default metrics explorer view', () => { + const { attributes, references } = extractSavedObjectReferences({ + ...sourceConfigurationWithIndexNameReference, + metricsExplorerDefaultView: '0', + }); + + expect(references).toHaveLength(1); + expect(references).toMatchObject([{ id: 'INVENTORY_DEFAULT_VIEW' }]); expect(attributes).toHaveProperty(['logIndices', 'indexName'], 'INDEX_NAME'); }); }); diff --git a/x-pack/plugins/infra/server/lib/sources/saved_object_references.ts b/x-pack/plugins/infra/server/lib/sources/saved_object_references.ts index 31f36380cc23e..9ad8c9951d4f3 100644 --- a/x-pack/plugins/infra/server/lib/sources/saved_object_references.ts +++ b/x-pack/plugins/infra/server/lib/sources/saved_object_references.ts @@ -27,9 +27,11 @@ interface SavedObjectAttributesWithReferences { export const extractSavedObjectReferences = ( sourceConfiguration: InfraSourceConfiguration ): SavedObjectAttributesWithReferences => - [extractLogIndicesSavedObjectReferences].reduce< - SavedObjectAttributesWithReferences - >( + [ + extractLogIndicesSavedObjectReferences, + extractInventorySavedViewReferences, + extractMetricsExplorerSavedViewReferences, + ].reduce>( ({ attributes: accumulatedAttributes, references: accumulatedReferences }, extract) => { const { attributes, references } = extract(accumulatedAttributes); return { @@ -52,7 +54,11 @@ export const resolveSavedObjectReferences = ( attributes: InfraSavedSourceConfiguration, references: SavedObjectReference[] ): InfraSavedSourceConfiguration => - [resolveLogIndicesSavedObjectReferences].reduce( + [ + resolveLogIndicesSavedObjectReferences, + resolveInventoryViewSavedObjectReferences, + resolveMetricsExplorerSavedObjectReferences, + ].reduce( (accumulatedAttributes, resolve) => resolve(accumulatedAttributes, references), attributes ); @@ -85,6 +91,58 @@ const extractLogIndicesSavedObjectReferences = ( } }; +const extractInventorySavedViewReferences = ( + sourceConfiguration: InfraSourceConfiguration +): SavedObjectAttributesWithReferences => { + const { inventoryDefaultView } = sourceConfiguration; + if (inventoryDefaultView && inventoryDefaultView !== '0') { + const inventoryDefaultViewReference: SavedObjectReference = { + id: inventoryDefaultView, + type: 'inventory-view', + name: 'inventory-saved-view-0', + }; + const attributes: InfraSourceConfiguration = { + ...sourceConfiguration, + inventoryDefaultView: inventoryDefaultViewReference.name, + }; + return { + attributes, + references: [inventoryDefaultViewReference], + }; + } else { + return { + attributes: sourceConfiguration, + references: [], + }; + } +}; + +const extractMetricsExplorerSavedViewReferences = ( + sourceConfiguration: InfraSourceConfiguration +): SavedObjectAttributesWithReferences => { + const { metricsExplorerDefaultView } = sourceConfiguration; + if (metricsExplorerDefaultView && metricsExplorerDefaultView !== '0') { + const metricsExplorerDefaultViewReference: SavedObjectReference = { + id: metricsExplorerDefaultView, + type: 'metrics-explorer-view', + name: 'metrics-explorer-saved-view-0', + }; + const attributes: InfraSourceConfiguration = { + ...sourceConfiguration, + metricsExplorerDefaultView: metricsExplorerDefaultViewReference.name, + }; + return { + attributes, + references: [metricsExplorerDefaultViewReference], + }; + } else { + return { + attributes: sourceConfiguration, + references: [], + }; + } +}; + const resolveLogIndicesSavedObjectReferences = ( attributes: InfraSavedSourceConfiguration, references: SavedObjectReference[] @@ -111,3 +169,51 @@ const resolveLogIndicesSavedObjectReferences = ( return attributes; } }; + +const resolveInventoryViewSavedObjectReferences = ( + attributes: InfraSavedSourceConfiguration, + references: SavedObjectReference[] +): InfraSavedSourceConfiguration => { + if (attributes.inventoryDefaultView && attributes.inventoryDefaultView !== '0') { + const inventoryViewReference = references.find( + (reference) => reference.name === 'inventory-saved-view-0' + ); + + if (inventoryViewReference == null) { + throw new SavedObjectReferenceResolutionError( + 'Failed to resolve Inventory default view "inventory-saved-view-0".' + ); + } + + return { + ...attributes, + inventoryDefaultView: inventoryViewReference.id, + }; + } else { + return attributes; + } +}; + +const resolveMetricsExplorerSavedObjectReferences = ( + attributes: InfraSavedSourceConfiguration, + references: SavedObjectReference[] +): InfraSavedSourceConfiguration => { + if (attributes.metricsExplorerDefaultView && attributes.metricsExplorerDefaultView !== '0') { + const metricsExplorerViewReference = references.find( + (reference) => reference.name === 'metrics-explorer-saved-view-0' + ); + + if (metricsExplorerViewReference == null) { + throw new SavedObjectReferenceResolutionError( + 'Failed to resolve Metrics Explorer default view "metrics-explorer-saved-view-0".' + ); + } + + return { + ...attributes, + metricsExplorerDefaultView: metricsExplorerViewReference.id, + }; + } else { + return attributes; + } +}; diff --git a/x-pack/plugins/infra/server/lib/sources/sources.ts b/x-pack/plugins/infra/server/lib/sources/sources.ts index 7dc47388bd1da..45da4546ad3b8 100644 --- a/x-pack/plugins/infra/server/lib/sources/sources.ts +++ b/x-pack/plugins/infra/server/lib/sources/sources.ts @@ -205,11 +205,12 @@ export class InfraSources { } private async getStaticDefaultSourceConfiguration() { - const staticSourceConfiguration: SourceConfigurationConfigFileProperties['sources']['default'] = pipe( - sourceConfigurationConfigFilePropertiesRT.decode(this.libs.config), - map(({ sources: { default: defaultConfiguration } }) => defaultConfiguration), - fold(constant({}), identity) - ); + const staticSourceConfiguration: SourceConfigurationConfigFileProperties['sources']['default'] = + pipe( + sourceConfigurationConfigFilePropertiesRT.decode(this.libs.config), + map(({ sources: { default: defaultConfiguration } }) => defaultConfiguration), + fold(constant({}), identity) + ); // NOTE: Legacy logAlias needs converting to a logIndices reference until we can remove // config file sources in 8.0.0. diff --git a/x-pack/plugins/infra/server/routes/metadata/index.ts b/x-pack/plugins/infra/server/routes/metadata/index.ts index cc8888e9bd09d..39021ba51c9d9 100644 --- a/x-pack/plugins/infra/server/routes/metadata/index.ts +++ b/x-pack/plugins/infra/server/routes/metadata/index.ts @@ -92,7 +92,9 @@ export const initMetadataRoute = (libs: InfraBackendLibs) => { ); }; -const nameToFeature = (source: string) => (name: string): InfraMetadataFeature => ({ - name, - source, -}); +const nameToFeature = + (source: string) => + (name: string): InfraMetadataFeature => ({ + name, + source, + }); diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/transform_series.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/transform_series.ts index 3de020c2ad327..6b876887bd568 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/transform_series.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/transform_series.ts @@ -7,19 +7,21 @@ import { MetricsAPISeries, MetricsExplorerSeries } from '../../../../common/http_api'; -export const transformSeries = (hasGroupBy: boolean) => ( - series: MetricsAPISeries -): MetricsExplorerSeries => { - const id = series.keys?.join(' / ') ?? series.id; - return { - ...series, - id, - rows: series.rows.map((row) => { - if (hasGroupBy) { - return { ...row, groupBy: id }; - } - return row; - }), - columns: hasGroupBy ? [...series.columns, { name: 'groupBy', type: 'string' }] : series.columns, +export const transformSeries = + (hasGroupBy: boolean) => + (series: MetricsAPISeries): MetricsExplorerSeries => { + const id = series.keys?.join(' / ') ?? series.id; + return { + ...series, + id, + rows: series.rows.map((row) => { + if (hasGroupBy) { + return { ...row, groupBy: id }; + } + return row; + }), + columns: hasGroupBy + ? [...series.columns, { name: 'groupBy', type: 'string' }] + : series.columns, + }; }; -}; diff --git a/x-pack/plugins/infra/server/routes/snapshot/lib/query_all_data.ts b/x-pack/plugins/infra/server/routes/snapshot/lib/query_all_data.ts index ff0e9b6ce57f1..b92fbab90af93 100644 --- a/x-pack/plugins/infra/server/routes/snapshot/lib/query_all_data.ts +++ b/x-pack/plugins/infra/server/routes/snapshot/lib/query_all_data.ts @@ -9,25 +9,23 @@ import { MetricsAPIRequest, MetricsAPIResponse } from '../../../../common/http_a import { ESSearchClient } from '../../../lib/metrics/types'; import { query } from '../../../lib/metrics'; -const handleResponse = ( - client: ESSearchClient, - options: MetricsAPIRequest, - previousResponse?: MetricsAPIResponse -) => async (resp: MetricsAPIResponse): Promise => { - const combinedResponse = previousResponse - ? { - ...previousResponse, - series: [...previousResponse.series, ...resp.series], - info: resp.info, - } - : resp; - if (resp.info.afterKey) { - return query(client, { ...options, afterKey: resp.info.afterKey }).then( - handleResponse(client, options, combinedResponse) - ); - } - return combinedResponse; -}; +const handleResponse = + (client: ESSearchClient, options: MetricsAPIRequest, previousResponse?: MetricsAPIResponse) => + async (resp: MetricsAPIResponse): Promise => { + const combinedResponse = previousResponse + ? { + ...previousResponse, + series: [...previousResponse.series, ...resp.series], + info: resp.info, + } + : resp; + if (resp.info.afterKey) { + return query(client, { ...options, afterKey: resp.info.afterKey }).then( + handleResponse(client, options, combinedResponse) + ); + } + return combinedResponse; + }; export const queryAllData = (client: ESSearchClient, options: MetricsAPIRequest) => { return query(client, options).then(handleResponse(client, options)); diff --git a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts index c47a1c163f9ec..651758d9cd976 100644 --- a/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts +++ b/x-pack/plugins/infra/server/services/log_entries/log_entries_search_strategy.ts @@ -197,17 +197,18 @@ const { asyncInitialRequestRT, asyncRecoveredRequestRT, asyncRequestRT } = creat logEntriesSearchRequestParamsRT ); -const getLogEntryFromHit = ( - columnDefinitions: LogSourceColumnConfiguration[], - messageFormattingRules: CompiledLogMessageFormattingRule -) => (hit: LogEntryHit): LogEntry => { - const cursor = getLogEntryCursorFromHit(hit); - return { - id: hit._id, - index: hit._index, - cursor, - columns: columnDefinitions.map( - (column): LogColumn => { +const getLogEntryFromHit = + ( + columnDefinitions: LogSourceColumnConfiguration[], + messageFormattingRules: CompiledLogMessageFormattingRule + ) => + (hit: LogEntryHit): LogEntry => { + const cursor = getLogEntryCursorFromHit(hit); + return { + id: hit._id, + index: hit._index, + cursor, + columns: columnDefinitions.map((column): LogColumn => { if ('timestampColumn' in column) { return { columnId: column.timestampColumn.id, @@ -226,11 +227,10 @@ const getLogEntryFromHit = ( highlights: hit.highlight?.[column.fieldColumn.field] ?? [], }; } - } - ), - context: getContextFromHit(hit), + }), + context: getContextFromHit(hit), + }; }; -}; const pickRequestCursor = ( params: LogEntriesSearchRequestParams diff --git a/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts b/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts index 0c320c7b8ec1b..6d41f17a6bb5e 100644 --- a/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts +++ b/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts @@ -8,18 +8,20 @@ import { set } from '@elastic/safer-lodash-set'; import { InfraDatabaseSearchResponse } from '../lib/adapters/framework'; -export const createAfterKeyHandler = ( - optionsAfterKeyPath: string | string[], - afterKeySelector: (input: InfraDatabaseSearchResponse) => any -) => ( - options: Options, - response: InfraDatabaseSearchResponse -): Options => { - if (!response.aggregations) { - return options; - } - const newOptions = { ...options }; - const afterKey = afterKeySelector(response); - set(newOptions, optionsAfterKeyPath, afterKey); - return newOptions; -}; +export const createAfterKeyHandler = + ( + optionsAfterKeyPath: string | string[], + afterKeySelector: (input: InfraDatabaseSearchResponse) => any + ) => + ( + options: Options, + response: InfraDatabaseSearchResponse + ): Options => { + if (!response.aggregations) { + return options; + } + const newOptions = { ...options }; + const afterKey = afterKeySelector(response); + set(newOptions, optionsAfterKeyPath, afterKey); + return newOptions; + }; diff --git a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx index abd8efb730ef5..7ba5e44cddf61 100644 --- a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx @@ -52,7 +52,7 @@ const appServices = { export const setupEnvironment = () => { uiMetricService.setup(usageCollectionPluginMock.createSetupContract()); - apiService.setup((mockHttpClient as unknown) as HttpSetup, uiMetricService); + apiService.setup(mockHttpClient as unknown as HttpSetup, uiMetricService); documentationService.setup(docLinksServiceMock.createStartContract()); breadcrumbService.setup(() => {}); @@ -64,8 +64,9 @@ export const setupEnvironment = () => { }; }; -export const WithAppDependencies = (Comp: any) => (props: any) => ( - - - -); +export const WithAppDependencies = (Comp: any) => (props: any) => + ( + + + + ); diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/pipeline_processors_editor.test.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/pipeline_processors_editor.test.tsx index 5b02927ab873c..c5daa1db2ac07 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/pipeline_processors_editor.test.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/__jest__/pipeline_processors_editor.test.tsx @@ -297,21 +297,25 @@ describe('Pipeline Editor', () => { none: 'No description', }; - const createAssertForProcessor = (processorIndex: string) => ({ - description, - descriptionVisible, - }: { - description: string; - descriptionVisible: boolean; - }) => { - expect(find(`processors>${processorIndex}.inlineTextInputNonEditableText`).text()).toBe( - description - ); - expect( - (find(`processors>${processorIndex}.pipelineProcessorItemDescriptionContainer`).props() - .className as string).includes('--displayNone') - ).toBe(!descriptionVisible); - }; + const createAssertForProcessor = + (processorIndex: string) => + ({ + description, + descriptionVisible, + }: { + description: string; + descriptionVisible: boolean; + }) => { + expect(find(`processors>${processorIndex}.inlineTextInputNonEditableText`).text()).toBe( + description + ); + expect( + ( + find(`processors>${processorIndex}.pipelineProcessorItemDescriptionContainer`).props() + .className as string + ).includes('--displayNone') + ).toBe(!descriptionVisible); + }; const assertScriptProcessor = createAssertForProcessor('0'); const assertSetProcessor = createAssertForProcessor('2'); diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/field_components/drag_and_drop_text_list.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/field_components/drag_and_drop_text_list.tsx index 03bdc2ceb9579..7a0ea533b0d68 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/field_components/drag_and_drop_text_list.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/field_components/drag_and_drop_text_list.tsx @@ -152,9 +152,8 @@ function DragAndDropTextListComponent({ readDefaultValueOnForm={!item.isNew} > {(field) => { - const { isInvalid, errorMessage } = getFieldValidityAndErrorMessage( - field - ); + const { isInvalid, errorMessage } = + getFieldValidityAndErrorMessage(field); return ( diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/network_direction.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/network_direction.tsx index 22f2226d80b10..ab8744ee01ab8 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/network_direction.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/network_direction.tsx @@ -86,9 +86,7 @@ const fieldsConfig: FieldsConfig = { }, }; -const getInternalNetworkConfig: ( - toggleCustom: () => void -) => Record< +const getInternalNetworkConfig: (toggleCustom: () => void) => Record< keyof InternalNetworkFields, { path: string; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/set.tsx b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/set.tsx index 16d89fcbfb119..6bbda366826f7 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/set.tsx +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/set.tsx @@ -97,9 +97,7 @@ const fieldsConfig: FieldsConfig = { }; // Required fields config -const getValueConfig: ( - toggleCustom: () => void -) => Record< +const getValueConfig: (toggleCustom: () => void) => Record< keyof ValueToggleFields, { path: string; diff --git a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/shared.ts b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/shared.ts index 9a45f7f0017c6..a14944a33a8ce 100644 --- a/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/shared.ts +++ b/x-pack/plugins/ingest_pipelines/public/application/components/pipeline_editor/components/processor_form/processors/shared.ts @@ -81,7 +81,7 @@ export const from = { return undefined; }, optionalArrayOfStrings: (v: string[]) => (v.length ? v : undefined), - undefinedIfValue: (value: unknown) => (v: boolean) => (v === value ? undefined : v), + undefinedIfValue: (value: unknown) => (v: boolean) => v === value ? undefined : v, emptyStringToUndefined: (v: unknown) => (v === '' ? undefined : v), /** * Useful when serializing user input from a