Skip to content

feat(rules): implement Rule editing and copying #1620

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@
"TIMEZONE": "Timezone",
"TO": "To",
"UNKNOWN_ERROR": "Unknown error",
"UPDATE": "Update",
"UPDATING": "Updating",
"USER_SUBMITTED": "User-submitted",
"VIEW": "View",
"VIEW_MORE": "View more",
Expand Down
17 changes: 17 additions & 0 deletions src/app/CreateRecording/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,27 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { TemplateType } from '@app/Shared/Services/api.types';
import { EventTemplateIdentifier } from './types';

export const RecordingNamePattern = /^[\w_]+$/;

export const DurationPattern = /^[1-9][0-9]*$/;

export const isRecordingNameValid = (name: string) => RecordingNamePattern.test(name);

export const isDurationValid = (duration: number) => DurationPattern.test(`${duration}`);

export const templateFromEventSpecifier = (eventSpecifier: string): EventTemplateIdentifier | undefined => {
const regex = /^template=([a-zA-Z0-9]+)(?:,type=([a-zA-Z0-9]+))?$/im;
if (eventSpecifier && regex.test(eventSpecifier)) {
const parts = regex.exec(eventSpecifier);
if (parts) {
return {
name: parts[1],
type: parts[2] as TemplateType,
};
}
}
return undefined;
};
4 changes: 2 additions & 2 deletions src/app/Recordings/ActiveRecordingsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import { ServiceContext } from '@app/Shared/Services/Services';
import { useDayjs } from '@app/utils/hooks/useDayjs';
import { useSort } from '@app/utils/hooks/useSort';
import { useSubscriptions } from '@app/utils/hooks/useSubscriptions';
import { formatBytes, formatDuration, LABEL_TEXT_MAXWIDTH, sortResources, TableColumn } from '@app/utils/utils';
import { formatBytes, formatDuration, LABEL_TEXT_MAXWIDTH, sortResources, TableColumn, toPath } from '@app/utils/utils';
import { useCryostatTranslation } from '@i18n/i18nextUtil';
import {
Button,
Expand Down Expand Up @@ -190,7 +190,7 @@ export const ActiveRecordingsTable: React.FC<ActiveRecordingsTableProps> = (prop
);

const handleCreateRecording = React.useCallback(() => {
navigate('create', { relative: 'path' });
navigate(toPath('/recordings/create'), { relative: 'path' });
}, [navigate]);

const handleEditLabels = React.useCallback(() => {
Expand Down
71 changes: 66 additions & 5 deletions src/app/Rules/CreateRule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import { BreadcrumbPage } from '@app/BreadcrumbPage/BreadcrumbPage';
import { BreadcrumbTrail } from '@app/BreadcrumbPage/types';
import { EventTemplateIdentifier } from '@app/CreateRecording/types';
import { templateFromEventSpecifier } from '@app/CreateRecording/utils';
import { MatchExpressionHint } from '@app/Shared/Components/MatchExpression/MatchExpressionHint';
import { MatchExpressionVisualizer } from '@app/Shared/Components/MatchExpression/MatchExpressionVisualizer';
import { SelectTemplateSelectorForm } from '@app/Shared/Components/SelectTemplateSelectorForm';
Expand Down Expand Up @@ -58,7 +59,7 @@ import { HelpIcon } from '@patternfly/react-icons';
import _ from 'lodash';
import * as React from 'react';
import { Trans } from 'react-i18next';
import { useNavigate } from 'react-router-dom-v5-compat';
import { useLocation, useNavigate } from 'react-router-dom-v5-compat';
import { combineLatest, forkJoin, iif, of, Subject } from 'rxjs';
import { catchError, debounceTime, map, switchMap, tap } from 'rxjs/operators';
import { RuleFormData } from './types';
Expand All @@ -70,11 +71,13 @@ export const CreateRuleForm: React.FC<CreateRuleFormProps> = (_props) => {
const context = React.useContext(ServiceContext);
const notifications = React.useContext(NotificationsContext);
const navigate = useNavigate();
const location = useLocation();
const { t } = useCryostatTranslation();
// Do not use useSearchExpression for display. This causes the cursor to jump to the end due to async updates.
const matchExprService = useMatchExpressionSvc();
const addSubscription = useSubscriptions();
const [autoanalyze, setAutoanalyze] = React.useState(true);
const [isExistingEdit, setExistingEdit] = React.useState(false);

const [formData, setFormData] = React.useState<RuleFormData>({
name: '',
Expand All @@ -100,6 +103,10 @@ export const CreateRuleForm: React.FC<CreateRuleFormProps> = (_props) => {

const matchedTargetsRef = React.useRef(new Subject<Target[]>());

React.useEffect(() => {
setExistingEdit(location?.state?.edit ?? false);
}, [location, setExistingEdit]);

const eventSpecifierString = React.useMemo(() => {
let str = '';
const { template } = formData;
Expand Down Expand Up @@ -157,6 +164,50 @@ export const CreateRuleForm: React.FC<CreateRuleFormProps> = (_props) => {
[setFormData, matchExprService],
);

React.useEffect(() => {
const prefilled: Partial<RuleFormData> = location.state || {};
const eventSpecifier = location?.state?.eventSpecifier;
const maxAgeSeconds = location?.state?.maxAgeSeconds;
const maxSizeBytes = location?.state?.maxSizeBytes;
const archivalPeriodSeconds = location?.state?.archivalPeriodSeconds;
let {
name,
enabled,
description,
matchExpression,
maxAge,
maxAgeUnit,
maxSize,
maxSizeUnit,
archivalPeriod,
archivalPeriodUnit,
initialDelay,
initialDelayUnit,
preservedArchives,
} = prefilled;
setFormData((old) => ({
...old,
enabled: enabled ?? true,
name: name ?? '',
description: description ?? '',
matchExpression: matchExpression ?? '',
template: templateFromEventSpecifier(eventSpecifier),
maxAge: maxAgeSeconds ?? maxAge ?? 0,
maxAgeUnit: maxAgeSeconds ? 1 : (maxAgeUnit ?? 1),
maxSize: maxSizeBytes ?? maxSize ?? 0,
maxSizeUnit: maxSizeBytes ? 1 : (maxSizeUnit ?? 1),
archivalPeriod: archivalPeriodSeconds ?? archivalPeriod ?? 0,
archivalPeriodUnit: archivalPeriodSeconds ? 1 : (archivalPeriodUnit ?? 1),
initialDelay: initialDelay ?? 0,
initialDelayUnit: initialDelayUnit ?? 1,
preservedArchives: preservedArchives ?? 0,
}));
handleNameChange(null, name ?? '');
if (matchExpression) {
handleMatchExpressionChange(null, matchExpression);
}
}, [location, setFormData, handleNameChange, handleMatchExpressionChange]);

const handleTemplateChange = React.useCallback(
(template: EventTemplateIdentifier) => setFormData((old) => ({ ...old, template })),
[setFormData],
Expand Down Expand Up @@ -269,14 +320,24 @@ export const CreateRuleForm: React.FC<CreateRuleFormProps> = (_props) => {
};
setLoading(true);
addSubscription(
context.api.createRule(rule).subscribe((success) => {
(isExistingEdit ? context.api.updateRule(rule, true) : context.api.createRule(rule)).subscribe((success) => {
setLoading(false);
if (success) {
exitForm();
}
}),
);
}, [setLoading, addSubscription, exitForm, context.api, notifications, formData, autoanalyze, eventSpecifierString]);
}, [
setLoading,
addSubscription,
exitForm,
context.api,
notifications,
formData,
autoanalyze,
eventSpecifierString,
isExistingEdit,
]);

React.useEffect(() => {
const matchedTargets = matchedTargetsRef.current;
Expand Down Expand Up @@ -360,7 +421,7 @@ export const CreateRuleForm: React.FC<CreateRuleFormProps> = (_props) => {
<FormGroup label={t('NAME')} isRequired fieldId="rule-name" data-quickstart-id="rule-name">
<TextInput
value={formData.name}
isDisabled={loading}
isDisabled={isExistingEdit || loading}
isRequired
type="text"
id="rule-name"
Expand Down Expand Up @@ -667,7 +728,7 @@ export const CreateRuleForm: React.FC<CreateRuleFormProps> = (_props) => {
data-quickstart-id="rule-create-btn"
{...createButtonLoadingProps}
>
{t(loading ? 'CREATING' : 'CREATE')}
{t(isExistingEdit ? (loading ? 'UPDATING' : 'UPDATE') : loading ? 'CREATING' : 'CREATE')}
</Button>
<Button variant="secondary" onClick={exitForm} isAriaDisabled={loading}>
{t('CANCEL')}
Expand Down
36 changes: 35 additions & 1 deletion src/app/Rules/Rules.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,32 @@ export const RulesTable: React.FC<RulesTableProps> = () => {
[addSubscription, context.api],
);

const handleEditButton = React.useCallback(
(rule: Rule) => {
navigate('create', {
relative: 'path',
state: {
...rule,
edit: true,
},
});
},
[navigate],
);

const handleCopyButton = React.useCallback(
(rule: Rule) => {
navigate('create', {
relative: 'path',
state: {
...rule,
name: `${rule.name}_copy`,
},
});
},
[navigate],
);

const handleDeleteButton = React.useCallback(
(rule: Rule) => {
if (context.settings.deletionDialogsEnabledFor(DeleteOrDisableWarningType.DeleteAutomatedRules)) {
Expand Down Expand Up @@ -295,6 +321,14 @@ export const RulesTable: React.FC<RulesTableProps> = () => {
const actionResolver = React.useCallback(
(rule: Rule): IAction[] => {
return [
{
title: t('EDIT'),
onClick: () => handleEditButton(rule),
},
{
title: t('COPY'),
onClick: () => handleCopyButton(rule),
},
{
title: t('DOWNLOAD'),
onClick: () => context.api.downloadRule(rule.name),
Expand All @@ -309,7 +343,7 @@ export const RulesTable: React.FC<RulesTableProps> = () => {
},
];
},
[context.api, handleDeleteButton, t],
[context.api, handleEditButton, handleDeleteButton, handleCopyButton, t],
);

const handleUploadModalClose = React.useCallback(() => {
Expand Down
6 changes: 5 additions & 1 deletion src/app/Rules/RulesUploadModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,11 @@ export const RuleUploadModal: React.FC<RuleUploadModalProps> = ({ onClose, ...pr
parseRule(fileUpload.file, t).pipe(
first(),
concatMap((rule) =>
context.api.uploadRule(rule, getProgressUpdateCallback(fileUpload.file.name), fileUpload.abortSignal),
context.api.uploadRule(
{ ...rule, id: undefined, enabled: false },
getProgressUpdateCallback(fileUpload.file.name),
fileUpload.abortSignal,
),
),
tap({
next: (_) => {
Expand Down
1 change: 1 addition & 0 deletions src/app/Shared/Services/api.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ export interface EventProbe {
// Rule resources
// ======================================
export interface Rule {
id?: number;
name: string;
description: string;
matchExpression: string;
Expand Down
30 changes: 29 additions & 1 deletion src/test/Rules/Rules.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ jest
.mockReturnValueOnce(of())
.mockReturnValueOnce(of())

.mockReturnValueOnce(of()) // open view to edit rules
.mockReturnValueOnce(of())
.mockReturnValueOnce(of())

.mockReturnValueOnce(of()) // opens upload modal
.mockReturnValueOnce(of())
.mockReturnValueOnce(of())
Expand Down Expand Up @@ -128,6 +132,26 @@ describe('<Rules />', () => {
expect(router.state.location.pathname).toEqual('/rules/create');
});

it('opens create rule view when Edit is clicked', async () => {
const { user, router } = render({
routerConfigs: {
routes: [
{
path: '/rules',
element: <RulesTable />,
},
],
},
});

await act(async () => {
await user.click(screen.getByLabelText('Kebab toggle'));
await user.click(await screen.findByText('Edit'));
});

expect(router.state.location.pathname).toEqual('/rules/create');
});

it('opens upload modal when upload icon is clicked', async () => {
const { user } = render({
routerConfigs: {
Expand Down Expand Up @@ -382,7 +406,11 @@ describe('<Rules />', () => {
await user.click(submitButton);

expect(uploadSpy).toHaveBeenCalled();
expect(uploadSpy).toHaveBeenCalledWith(mockRule, expect.any(Function), expect.any(Subject));
expect(uploadSpy).toHaveBeenCalledWith(
{ ...mockRule, id: undefined, enabled: false },
expect.any(Function),
expect.any(Subject),
);

expect(within(modal).queryByText('Submit')).not.toBeInTheDocument();
expect(within(modal).queryByText('Cancel')).not.toBeInTheDocument();
Expand Down
Loading