[8.12] [Transform] Fix retention policy field name not setting by default correctly in Transform creation wizard (#172609) (#173617)

# Backport

This will backport the following commits from `main` to `8.12`:
- [[Transform] Fix retention policy field name not setting by default
correctly in Transform creation wizard
(#172609)](https://github.com/elastic/kibana/pull/172609)

<!--- Backport version: 8.9.7 -->

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

<!--BACKPORT [{"author":{"name":"Quynh Nguyen
(Quinn)","email":"43350163+qn895@users.noreply.github.com"},"sourceCommit":{"committedDate":"2023-12-19T12:17:38Z","message":"[Transform]
Fix retention policy field name not setting by default correctly in
Transform creation wizard (#172609)\n\n## Summary\r\n\r\nThis PR fixes
https://github.com/elastic/kibana/issues/167207 where\r\ntransform
retention policy not setting the first time field as default,\r\nwhich
causes an error on
creation\r\n\r\nBefore:\r\n\r\n\r\n3db01069-36e2-4d9c-8059-d328e80da901\r\n\r\nIt
also disables the retention policy field if there's no
time/date\r\nfields in the transform's destination index
mappings.\r\n\r\n\r\n\r\n9d68296c-11e3-4685-bb53-6e68200f4225\r\n\r\n**This
PR also fixes the Edit Transform flyout to disable the
policy\r\nretention field when the destination mappings do not contain
any date\r\nfields.**\r\n\r\nFor transforms with no date fields in
destination
index:\r\n\r\n\r\nb4cecd6b-3ba6-4878-ae96-02d2607daebe\r\n\r\nFor
transforms with date fields in destination
index:\r\n\r\n\r\nc1007460-18c4-4016-a321-5bc60102af36\r\n\r\n\r\n\r\n\r\n\r\n\r\n###
Checklist\r\n\r\nDelete any items that are not applicable to this
PR.\r\n\r\n- [ ] Any text added follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n-
[
]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials\r\n- [ ] [Unit
or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n- [ ] [Flaky
Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\r\nused on any tests changed\r\n- [ ] Any UI touched in this PR is
usable by keyboard only (learn more\r\nabout [keyboard
accessibility](https://webaim.org/techniques/keyboard/))\r\n- [ ] Any UI
touched in this PR does not create any new axe failures\r\n(run axe in
browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))\r\n-
[ ] If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n-
[ ] This renders correctly on smaller devices using a
responsive\r\nlayout. (You can test this [in
your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))\r\n-
[ ] This was checked for
[cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)\r\n\r\n\r\n###
Risk Matrix\r\n\r\nDelete this section if it is not applicable to this
PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other
developers to\r\nidentify risks that should be tested prior to the
change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider
some of the following examples\r\nand how they may potentially impact
the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes
|\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n|
Multiple Spaces&mdash;unexpected behavior in non-default Kibana
Space.\r\n| Low | High | Integration tests will verify that all features
are still\r\nsupported in non-default Kibana Space and when user
switches between\r\nspaces. |\r\n| Multiple nodes&mdash;Elasticsearch
polling might have race conditions\r\nwhen multiple Kibana nodes are
polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so
executing them multiple times will not result\r\nin logical error, but
will degrade performance. To test for this case we\r\nadd plenty of unit
tests around this logic and document manual testing\r\nprocedure. |\r\n|
Code should gracefully handle cases when feature X or plugin Y
are\r\ndisabled. | Medium | High | Unit tests will verify that any
feature flag\r\nor plugin combination still results in our service
operational. |\r\n| [See more potential
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
|\r\n\r\n\r\n### For maintainers\r\n\r\n- [ ] This was checked for
breaking API changes and was
[labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n---------\r\n\r\nCo-authored-by:
Dima Arnautov
<dmitrii.arnautov@elastic.co>","sha":"bf8dba2d1610cba05664adc78a8c1f565abda990","branchLabelMapping":{"^v8.13.0$":"main","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:fix",":ml","Feature:Transforms","v8.12.0","v8.13.0"],"number":172609,"url":"https://github.com/elastic/kibana/pull/172609","mergeCommit":{"message":"[Transform]
Fix retention policy field name not setting by default correctly in
Transform creation wizard (#172609)\n\n## Summary\r\n\r\nThis PR fixes
https://github.com/elastic/kibana/issues/167207 where\r\ntransform
retention policy not setting the first time field as default,\r\nwhich
causes an error on
creation\r\n\r\nBefore:\r\n\r\n\r\n3db01069-36e2-4d9c-8059-d328e80da901\r\n\r\nIt
also disables the retention policy field if there's no
time/date\r\nfields in the transform's destination index
mappings.\r\n\r\n\r\n\r\n9d68296c-11e3-4685-bb53-6e68200f4225\r\n\r\n**This
PR also fixes the Edit Transform flyout to disable the
policy\r\nretention field when the destination mappings do not contain
any date\r\nfields.**\r\n\r\nFor transforms with no date fields in
destination
index:\r\n\r\n\r\nb4cecd6b-3ba6-4878-ae96-02d2607daebe\r\n\r\nFor
transforms with date fields in destination
index:\r\n\r\n\r\nc1007460-18c4-4016-a321-5bc60102af36\r\n\r\n\r\n\r\n\r\n\r\n\r\n###
Checklist\r\n\r\nDelete any items that are not applicable to this
PR.\r\n\r\n- [ ] Any text added follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n-
[
]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials\r\n- [ ] [Unit
or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n- [ ] [Flaky
Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\r\nused on any tests changed\r\n- [ ] Any UI touched in this PR is
usable by keyboard only (learn more\r\nabout [keyboard
accessibility](https://webaim.org/techniques/keyboard/))\r\n- [ ] Any UI
touched in this PR does not create any new axe failures\r\n(run axe in
browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))\r\n-
[ ] If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n-
[ ] This renders correctly on smaller devices using a
responsive\r\nlayout. (You can test this [in
your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))\r\n-
[ ] This was checked for
[cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)\r\n\r\n\r\n###
Risk Matrix\r\n\r\nDelete this section if it is not applicable to this
PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other
developers to\r\nidentify risks that should be tested prior to the
change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider
some of the following examples\r\nand how they may potentially impact
the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes
|\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n|
Multiple Spaces&mdash;unexpected behavior in non-default Kibana
Space.\r\n| Low | High | Integration tests will verify that all features
are still\r\nsupported in non-default Kibana Space and when user
switches between\r\nspaces. |\r\n| Multiple nodes&mdash;Elasticsearch
polling might have race conditions\r\nwhen multiple Kibana nodes are
polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so
executing them multiple times will not result\r\nin logical error, but
will degrade performance. To test for this case we\r\nadd plenty of unit
tests around this logic and document manual testing\r\nprocedure. |\r\n|
Code should gracefully handle cases when feature X or plugin Y
are\r\ndisabled. | Medium | High | Unit tests will verify that any
feature flag\r\nor plugin combination still results in our service
operational. |\r\n| [See more potential
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
|\r\n\r\n\r\n### For maintainers\r\n\r\n- [ ] This was checked for
breaking API changes and was
[labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n---------\r\n\r\nCo-authored-by:
Dima Arnautov
<dmitrii.arnautov@elastic.co>","sha":"bf8dba2d1610cba05664adc78a8c1f565abda990"}},"sourceBranch":"main","suggestedTargetBranches":["8.12"],"targetPullRequestStates":[{"branch":"8.12","label":"v8.12.0","labelRegex":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"main","label":"v8.13.0","labelRegex":"^v8.13.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/172609","number":172609,"mergeCommit":{"message":"[Transform]
Fix retention policy field name not setting by default correctly in
Transform creation wizard (#172609)\n\n## Summary\r\n\r\nThis PR fixes
https://github.com/elastic/kibana/issues/167207 where\r\ntransform
retention policy not setting the first time field as default,\r\nwhich
causes an error on
creation\r\n\r\nBefore:\r\n\r\n\r\n3db01069-36e2-4d9c-8059-d328e80da901\r\n\r\nIt
also disables the retention policy field if there's no
time/date\r\nfields in the transform's destination index
mappings.\r\n\r\n\r\n\r\n9d68296c-11e3-4685-bb53-6e68200f4225\r\n\r\n**This
PR also fixes the Edit Transform flyout to disable the
policy\r\nretention field when the destination mappings do not contain
any date\r\nfields.**\r\n\r\nFor transforms with no date fields in
destination
index:\r\n\r\n\r\nb4cecd6b-3ba6-4878-ae96-02d2607daebe\r\n\r\nFor
transforms with date fields in destination
index:\r\n\r\n\r\nc1007460-18c4-4016-a321-5bc60102af36\r\n\r\n\r\n\r\n\r\n\r\n\r\n###
Checklist\r\n\r\nDelete any items that are not applicable to this
PR.\r\n\r\n- [ ] Any text added follows [EUI's
writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\r\nsentence case text and includes
[i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)\r\n-
[
]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas
added for features that require explanation or tutorials\r\n- [ ] [Unit
or
functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere
updated or added to match the most common scenarios\r\n- [ ] [Flaky
Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\r\nused on any tests changed\r\n- [ ] Any UI touched in this PR is
usable by keyboard only (learn more\r\nabout [keyboard
accessibility](https://webaim.org/techniques/keyboard/))\r\n- [ ] Any UI
touched in this PR does not create any new axe failures\r\n(run axe in
browser:\r\n[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),\r\n[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))\r\n-
[ ] If a plugin configuration key changed, check if it needs to
be\r\nallowlisted in the cloud and added to the
[docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n-
[ ] This renders correctly on smaller devices using a
responsive\r\nlayout. (You can test this [in
your\r\nbrowser](https://www.browserstack.com/guide/responsive-testing-on-local-server))\r\n-
[ ] This was checked for
[cross-browser\r\ncompatibility](https://www.elastic.co/support/matrix#matrix_browsers)\r\n\r\n\r\n###
Risk Matrix\r\n\r\nDelete this section if it is not applicable to this
PR.\r\n\r\nBefore closing this PR, invite QA, stakeholders, and other
developers to\r\nidentify risks that should be tested prior to the
change/feature\r\nrelease.\r\n\r\nWhen forming the risk matrix, consider
some of the following examples\r\nand how they may potentially impact
the change:\r\n\r\n| Risk | Probability | Severity | Mitigation/Notes
|\r\n\r\n|---------------------------|-------------|----------|-------------------------|\r\n|
Multiple Spaces&mdash;unexpected behavior in non-default Kibana
Space.\r\n| Low | High | Integration tests will verify that all features
are still\r\nsupported in non-default Kibana Space and when user
switches between\r\nspaces. |\r\n| Multiple nodes&mdash;Elasticsearch
polling might have race conditions\r\nwhen multiple Kibana nodes are
polling for the same tasks. | High | Low\r\n| Tasks are idempotent, so
executing them multiple times will not result\r\nin logical error, but
will degrade performance. To test for this case we\r\nadd plenty of unit
tests around this logic and document manual testing\r\nprocedure. |\r\n|
Code should gracefully handle cases when feature X or plugin Y
are\r\ndisabled. | Medium | High | Unit tests will verify that any
feature flag\r\nor plugin combination still results in our service
operational. |\r\n| [See more potential
risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
|\r\n\r\n\r\n### For maintainers\r\n\r\n- [ ] This was checked for
breaking API changes and was
[labeled\r\nappropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n---------\r\n\r\nCo-authored-by:
Dima Arnautov
<dmitrii.arnautov@elastic.co>","sha":"bf8dba2d1610cba05664adc78a8c1f565abda990"}}]}]
BACKPORT-->

Co-authored-by: Quynh Nguyen (Quinn) <43350163+qn895@users.noreply.github.com>
This commit is contained in:
Kibana Machine 2023-12-19 08:55:02 -05:00 committed by GitHub
parent 7e6ab21b0a
commit d36413a10c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 149 additions and 97 deletions

View file

@ -271,7 +271,9 @@ export const getCreateTransformRequestBody = (
}
: {}),
// conditionally add retention policy settings
...(transformDetailsState.isRetentionPolicyEnabled
...(transformDetailsState.isRetentionPolicyEnabled &&
transformDetailsState.retentionPolicyDateField !== '' &&
transformDetailsState.retentionPolicyMaxAge !== ''
? {
retention_policy: {
time: {

View file

@ -106,9 +106,38 @@ export const StepDetailsForm: FC<StepDetailsFormProps> = React.memo(
const [createDataView, setCreateDataView] = useState(
canCreateDataView === false ? false : defaults.createDataView
);
const [dataViewAvailableTimeFields, setDataViewAvailableTimeFields] = useState<string[]>([]);
const [dataViewTimeField, setDataViewTimeField] = useState<string | undefined>();
const previewRequest = useMemo(() => {
const { searchQuery, previewRequest: partialPreviewRequest } = stepDefineState;
const transformConfigQuery = getTransformConfigQuery(searchQuery);
return getPreviewTransformRequestBody(
searchItems.dataView,
transformConfigQuery,
partialPreviewRequest,
stepDefineState.runtimeMappings
);
}, [searchItems.dataView, stepDefineState]);
const { error: transformsPreviewError, data: transformPreview } =
useGetTransformsPreview(previewRequest);
const destIndexAvailableTimeFields = useMemo<string[]>(() => {
if (!transformPreview) return [];
const properties = transformPreview.generated_dest_index.mappings.properties;
const timeFields: string[] = Object.keys(properties).filter(
(col) => properties[col].type === 'date'
);
return timeFields;
}, [transformPreview]);
useEffect(
function resetDataViewTimeField() {
setDataViewTimeField(destIndexAvailableTimeFields[0]);
},
[destIndexAvailableTimeFields]
);
const onTimeFieldChanged = React.useCallback(
(e: React.ChangeEvent<HTMLSelectElement>) => {
const value = e.target.value;
@ -118,11 +147,11 @@ export const StepDetailsForm: FC<StepDetailsFormProps> = React.memo(
}
// Find the time field based on the selected value
// this is to account for undefined when user chooses not to use a date field
const timeField = dataViewAvailableTimeFields.find((col) => col === value);
const timeField = destIndexAvailableTimeFields.find((col) => col === value);
setDataViewTimeField(timeField);
},
[setDataViewTimeField, dataViewAvailableTimeFields]
[setDataViewTimeField, destIndexAvailableTimeFields]
);
const {
@ -146,31 +175,6 @@ export const StepDetailsForm: FC<StepDetailsFormProps> = React.memo(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [transformsError]);
const previewRequest = useMemo(() => {
const { searchQuery, previewRequest: partialPreviewRequest } = stepDefineState;
const transformConfigQuery = getTransformConfigQuery(searchQuery);
return getPreviewTransformRequestBody(
searchItems.dataView,
transformConfigQuery,
partialPreviewRequest,
stepDefineState.runtimeMappings
);
}, [searchItems.dataView, stepDefineState]);
const { error: transformsPreviewError, data: transformPreview } =
useGetTransformsPreview(previewRequest);
useEffect(() => {
if (transformPreview) {
const properties = transformPreview.generated_dest_index.mappings.properties;
const timeFields: string[] = Object.keys(properties).filter(
(col) => properties[col].type === 'date'
);
setDataViewAvailableTimeFields(timeFields);
setDataViewTimeField(timeFields[0]);
}
}, [transformPreview]);
useEffect(() => {
if (transformsPreviewError !== null) {
toastNotifications.addDanger({
@ -242,24 +246,24 @@ export const StepDetailsForm: FC<StepDetailsFormProps> = React.memo(
}
}, [dataViewTitlesError]);
const dateFieldNames = searchItems.dataView.fields
const sourceIndexDateFieldNames = searchItems.dataView.fields
.filter((f) => f.type === KBN_FIELD_TYPES.DATE)
.map((f) => f.name)
.sort();
// Continuous Mode
const isContinuousModeAvailable = dateFieldNames.length > 0;
const isContinuousModeAvailable = sourceIndexDateFieldNames.length > 0;
const [isContinuousModeEnabled, setContinuousModeEnabled] = useState(
defaults.isContinuousModeEnabled
);
const [continuousModeDateField, setContinuousModeDateField] = useState(
isContinuousModeAvailable ? dateFieldNames[0] : ''
isContinuousModeAvailable ? sourceIndexDateFieldNames[0] : ''
);
const [continuousModeDelay, setContinuousModeDelay] = useState(defaults.continuousModeDelay);
const isContinuousModeDelayValid = continuousModeDelayValidator(continuousModeDelay);
// Retention Policy
const isRetentionPolicyAvailable = dateFieldNames.length > 0;
const isRetentionPolicyAvailable = destIndexAvailableTimeFields.length > 0;
const [isRetentionPolicyEnabled, setRetentionPolicyEnabled] = useState(
defaults.isRetentionPolicyEnabled
);
@ -272,15 +276,27 @@ export const StepDetailsForm: FC<StepDetailsFormProps> = React.memo(
const retentionPolicyMaxAgeEmpty = retentionPolicyMaxAge === '';
const isRetentionPolicyMaxAgeValid = retentionPolicyMaxAgeValidator(retentionPolicyMaxAge);
// Reset retention policy settings when the user disables the whole option
useEffect(() => {
// Reset retention policy settings when the user disables the whole option
if (!isRetentionPolicyEnabled) {
setRetentionPolicyDateField(
isRetentionPolicyAvailable ? dataViewAvailableTimeFields[0] : ''
isRetentionPolicyAvailable ? destIndexAvailableTimeFields[0] : ''
);
setRetentionPolicyMaxAge('');
}
}, [isRetentionPolicyEnabled]);
// When retention policy is first enabled, pick a default option
if (
isRetentionPolicyAvailable &&
isRetentionPolicyEnabled &&
retentionPolicyDateField === ''
) {
// If a time field '@timestamp' exists, prioritize that
const prioritizeTimestamp = destIndexAvailableTimeFields.find((d) => d === '@timestamp');
// else pick the first available option
setRetentionPolicyDateField(prioritizeTimestamp ?? destIndexAvailableTimeFields[0]);
}
}, [isRetentionPolicyEnabled, isRetentionPolicyAvailable, destIndexAvailableTimeFields]);
const transformIdExists = transformIds.some((id) => transformId === id);
const transformIdEmpty = transformId === '';
@ -537,7 +553,7 @@ export const StepDetailsForm: FC<StepDetailsFormProps> = React.memo(
createDataView={createDataView}
dataViewTitleExists={dataViewTitleExists}
setCreateDataView={setCreateDataView}
dataViewAvailableTimeFields={dataViewAvailableTimeFields}
dataViewAvailableTimeFields={destIndexAvailableTimeFields}
dataViewTimeField={dataViewTimeField}
onTimeFieldChanged={onTimeFieldChanged}
/>
@ -582,7 +598,7 @@ export const StepDetailsForm: FC<StepDetailsFormProps> = React.memo(
)}
>
<EuiSelect
options={dateFieldNames.map((text: string) => ({ text, value: text }))}
options={sourceIndexDateFieldNames.map((text: string) => ({ text, value: text }))}
value={continuousModeDateField}
onChange={(e) => setContinuousModeDateField(e.target.value)}
data-test-subj="transformContinuousDateFieldSelect"
@ -652,7 +668,7 @@ export const StepDetailsForm: FC<StepDetailsFormProps> = React.memo(
data-test-subj="transformRetentionPolicySwitch"
/>
</EuiFormRow>
{isRetentionPolicyEnabled && (
{isRetentionPolicyEnabled && isRetentionPolicyAvailable && (
<>
<EuiFormRow
label={i18n.translate(
@ -670,7 +686,7 @@ export const StepDetailsForm: FC<StepDetailsFormProps> = React.memo(
)}
>
<EuiSelect
options={dataViewAvailableTimeFields.map((text: string) => ({ text }))}
options={destIndexAvailableTimeFields.map((text: string) => ({ text }))}
value={retentionPolicyDateField}
onChange={(e) => setRetentionPolicyDateField(e.target.value)}
data-test-subj="transformRetentionPolicyDateFieldSelect"

View file

@ -5,80 +5,108 @@
* 2.0.
*/
import React, { useEffect, useMemo, useState, type FC } from 'react';
import React, { useEffect, useMemo, type FC } from 'react';
import { i18n } from '@kbn/i18n';
import { EuiFormRow, EuiSelect, EuiSpacer, EuiSwitch } from '@elastic/eui';
import { KBN_FIELD_TYPES } from '@kbn/field-types';
import { useAppDependencies } from '../../../../app_dependencies';
import { toMountPoint } from '@kbn/react-kibana-mount';
import { useAppDependencies, useToastNotifications } from '../../../../app_dependencies';
import { ToastNotificationText } from '../../../../components';
import { isLatestTransform, isPivotTransform } from '../../../../../../common/types/transform';
import { useGetTransformsPreview } from '../../../../hooks';
import { EditTransformFlyoutFormTextInput } from './edit_transform_flyout_form_text_input';
import { useEditTransformFlyout } from './use_edit_transform_flyout';
import { getErrorMessage } from '../../../../../../common/utils/errors';
export const EditTransformRetentionPolicy: FC = () => {
const appDeps = useAppDependencies();
const dataViewsClient = appDeps.data.dataViews;
const { i18n: i18nStart, theme } = useAppDependencies();
const toastNotifications = useToastNotifications();
const dataViewId = useEditTransformFlyout('dataViewId');
const formSections = useEditTransformFlyout('stateFormSection');
const retentionPolicyField = useEditTransformFlyout('retentionPolicyField');
const { formField, formSection } = useEditTransformFlyout('actions');
const requestConfig = useEditTransformFlyout('config');
const [dateFieldNames, setDateFieldNames] = useState<string[]>([]);
const previewRequest = useMemo(() => {
return {
source: requestConfig.source,
...(isPivotTransform(requestConfig) ? { pivot: requestConfig.pivot } : {}),
...(isLatestTransform(requestConfig) ? { latest: requestConfig.latest } : {}),
};
}, [requestConfig]);
useEffect(
function getDateFields() {
let unmounted = false;
if (dataViewId !== undefined) {
dataViewsClient.get(dataViewId).then((dataView) => {
if (dataView) {
const dateTimeFields = dataView.fields
.filter((f) => f.type === KBN_FIELD_TYPES.DATE)
.map((f) => f.name)
.sort();
if (!unmounted) {
setDateFieldNames(dateTimeFields);
}
}
});
return () => {
unmounted = true;
};
}
},
[dataViewId, dataViewsClient]
);
const { error: transformsPreviewError, data: transformPreview } =
useGetTransformsPreview(previewRequest);
const isRetentionPolicyAvailable = dateFieldNames.length > 0;
const destIndexAvailableTimeFields = useMemo<string[]>(() => {
if (transformPreview?.generated_dest_index) {
const properties = transformPreview.generated_dest_index.mappings.properties;
const timeFields: string[] = Object.keys(properties).filter(
(col) => properties[col].type === 'date'
);
return timeFields;
}
return [];
}, [transformPreview]);
useEffect(() => {
if (transformsPreviewError !== null) {
toastNotifications.addDanger({
title: i18n.translate('xpack.transform.transformList.errorGettingTransformPreview', {
defaultMessage: 'An error occurred fetching the transform preview',
}),
text: toMountPoint(
<ToastNotificationText text={getErrorMessage(transformsPreviewError)} />,
{ theme, i18n: i18nStart }
),
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [transformsPreviewError]);
const isRetentionPolicyAvailable = destIndexAvailableTimeFields.length > 0;
const retentionDateFieldOptions = useMemo(() => {
return Array.isArray(dateFieldNames)
? dateFieldNames.map((text: string) => ({ text, value: text }))
return Array.isArray(destIndexAvailableTimeFields)
? destIndexAvailableTimeFields.map((text: string) => ({ text, value: text }))
: [];
}, [dateFieldNames]);
}, [destIndexAvailableTimeFields]);
return (
<>
<EuiSwitch
name="transformEditRetentionPolicySwitch"
label={i18n.translate(
'xpack.transform.transformList.editFlyoutFormRetentionPolicySwitchLabel',
{
defaultMessage: 'Retention policy',
}
)}
checked={formSections.retentionPolicy.enabled}
onChange={(e) =>
formSection({
section: 'retentionPolicy',
enabled: e.target.checked,
})
<EuiFormRow
helpText={
isRetentionPolicyAvailable === false
? i18n.translate('xpack.transform.transformList.editFlyoutFormEetentionPolicyError', {
defaultMessage:
'Retention policy settings are not available for indices without date fields.',
})
: ''
}
disabled={!isRetentionPolicyAvailable}
data-test-subj="transformEditRetentionPolicySwitch"
/>
>
<EuiSwitch
name="transformEditRetentionPolicySwitch"
label={i18n.translate(
'xpack.transform.transformList.editFlyoutFormRetentionPolicySwitchLabel',
{
defaultMessage: 'Retention policy',
}
)}
checked={formSections.retentionPolicy.enabled}
onChange={(e) =>
formSection({
section: 'retentionPolicy',
enabled: e.target.checked,
})
}
disabled={!isRetentionPolicyAvailable}
data-test-subj="transformEditRetentionPolicySwitch"
/>
</EuiFormRow>
{formSections.retentionPolicy.enabled && (
<div data-test-subj="transformEditRetentionPolicyContent">
<EuiSpacer size="m" />

View file

@ -59,6 +59,7 @@ export default function ({ getService }: FtrProviderContext) {
transformDocsPerSecond: '1000',
transformFrequency: '10m',
resetRetentionPolicy: false,
retentionPolicyAvailable: false,
transformRetentionPolicyField: 'order_date',
transformRetentionPolicyMaxAge: '1d',
numFailureRetries: '0',
@ -84,6 +85,7 @@ export default function ({ getService }: FtrProviderContext) {
transformDocsPerSecond: '1000',
transformFrequency: '10m',
resetRetentionPolicy: true,
retentionPolicyAvailable: true,
numFailureRetries: '7',
expected: {
messageText: 'updated transform.',
@ -172,15 +174,19 @@ export default function ({ getService }: FtrProviderContext) {
);
await transform.testExecution.logTestStep('should update the transform retention policy');
await transform.editFlyout.clickTransformEditRetentionPolicySettings(
!testData.resetRetentionPolicy
);
await transform.editFlyout.assertTransformEditFlyoutRetentionPolicySwitchEnabled(
testData.retentionPolicyAvailable
);
if (
!testData.resetRetentionPolicy &&
testData.retentionPolicyAvailable &&
testData?.transformRetentionPolicyField &&
testData?.transformRetentionPolicyMaxAge
) {
await transform.editFlyout.clickTransformEditRetentionPolicySettings(
!testData.resetRetentionPolicy
);
await transform.editFlyout.assertTransformEditFlyoutRetentionPolicyFieldSelectEnabled(
true
);
@ -242,7 +248,7 @@ export default function ({ getService }: FtrProviderContext) {
await transform.table.assertTransformExpandedRowJson(
'retention_policy',
!testData.resetRetentionPolicy
testData.retentionPolicyAvailable
);
await transform.table.assertTransformExpandedRowJson('updated description');
await transform.table.assertTransformExpandedRowMessages(testData.expected.messageText);

View file

@ -158,7 +158,7 @@ export default function ({ getService }: FtrProviderContext) {
await transform.testExecution.logTestStep(
'should have the retention policy switch enabled'
);
await transform.editFlyout.assertTransformEditFlyoutRetentionPolicySwitchEnabled(true);
await transform.editFlyout.assertTransformEditFlyoutRetentionPolicySwitchEnabled(false);
await transform.testExecution.logTestStep(
'should have the advanced settings inputs enabled'