Skip to content
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

refactor: [M3-8232] - Query Key Factory for Firewalls #10568

Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@linode/manager": Tech Stories
---

Query Key Factory for Firewalls ([#10568](https://github.com/linode/manager/pull/10568))
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const AddNodebalancerDrawer = (props: Props) => {
const isRestrictedUser = Boolean(profile?.restricted);
const queryClient = useQueryClient();

const { data, error, isLoading } = useAllFirewallsQuery();
const { data, error, isLoading } = useAllFirewallsQuery(open);

const firewall = data?.find((firewall) => firewall.id === Number(id));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { ActionsPanel } from 'src/components/ActionsPanel/ActionsPanel';
import { ConfirmationDialog } from 'src/components/ConfirmationDialog/ConfirmationDialog';
import { Typography } from 'src/components/Typography';
import { useRemoveFirewallDeviceMutation } from 'src/queries/firewalls';
import { queryKey as firewallQueryKey } from 'src/queries/firewalls';
import { queryKey as linodesQueryKey } from 'src/queries/linodes/linodes';
import { queryKey as nodebalancersQueryKey } from 'src/queries/nodebalancers';

Expand Down Expand Up @@ -59,8 +58,6 @@ export const RemoveDeviceDialog = React.memo((props: Props) => {
'firewalls',
]);

queryClient.invalidateQueries([firewallQueryKey]);

onClose();
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
/* eslint-disable jsx-a11y/anchor-is-valid */
import { Linode } from '@linode/api-v4';
import {
CreateFirewallPayload,
Firewall,
FirewallDeviceEntityType,
} from '@linode/api-v4/lib/firewalls';
import { NodeBalancer } from '@linode/api-v4/lib/nodebalancers';
import { CreateFirewallSchema } from '@linode/validation/lib/firewalls.schema';
import { useQueryClient } from '@tanstack/react-query';
import { useFormik } from 'formik';
Expand All @@ -27,11 +20,7 @@ import { FIREWALL_LIMITS_CONSIDERATIONS_LINK } from 'src/constants';
import { LinodeSelect } from 'src/features/Linodes/LinodeSelect/LinodeSelect';
import { NodeBalancerSelect } from 'src/features/NodeBalancers/NodeBalancerSelect';
import { useAccountManagement } from 'src/hooks/useAccountManagement';
import {
queryKey as firewallQueryKey,
useAllFirewallsQuery,
useCreateFirewall,
} from 'src/queries/firewalls';
import { useAllFirewallsQuery, useCreateFirewall } from 'src/queries/firewalls';
import { queryKey as linodesQueryKey } from 'src/queries/linodes/linodes';
import { queryKey as nodebalancersQueryKey } from 'src/queries/nodebalancers';
import { useGrants } from 'src/queries/profile/profile';
Expand All @@ -49,6 +38,13 @@ import {
NODEBALANCER_CREATE_FLOW_TEXT,
} from './constants';

import type {
CreateFirewallPayload,
Firewall,
FirewallDeviceEntityType,
Linode,
NodeBalancer,
} from '@linode/api-v4';
import type { LinodeCreateType } from 'src/features/Linodes/LinodesCreate/types';

export const READ_ONLY_DEVICES_HIDDEN_MESSAGE =
Expand Down Expand Up @@ -81,7 +77,7 @@ export const CreateFirewallDrawer = React.memo(
const { _hasGrant, _isRestrictedUser } = useAccountManagement();
const { data: grants } = useGrants();
const { mutateAsync } = useCreateFirewall();
const { data } = useAllFirewallsQuery();
const { data } = useAllFirewallsQuery(open);

const { enqueueSnackbar } = useSnackbar();
const queryClient = useQueryClient();
Expand Down Expand Up @@ -132,7 +128,6 @@ export const CreateFirewallDrawer = React.memo(
mutateAsync(payload)
.then((response) => {
setSubmitting(false);
queryClient.invalidateQueries([firewallQueryKey]);
enqueueSnackbar(`Firewall ${payload.label} successfully created`, {
variant: 'success',
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,46 +5,37 @@ import * as React from 'react';
import { ActionsPanel } from 'src/components/ActionsPanel/ActionsPanel';
import { ConfirmationDialog } from 'src/components/ConfirmationDialog/ConfirmationDialog';
import { useDeleteFirewall, useMutateFirewall } from 'src/queries/firewalls';
import { queryKey as firewallQueryKey } from 'src/queries/firewalls';
import { useAllFirewallDevicesQuery } from 'src/queries/firewalls';
import { queryKey as linodesQueryKey } from 'src/queries/linodes/linodes';
import { queryKey as nodebalancersQueryKey } from 'src/queries/nodebalancers';
import { capitalize } from 'src/utilities/capitalize';

import type { Firewall } from '@linode/api-v4';

export type Mode = 'delete' | 'disable' | 'enable';

interface Props {
mode: Mode;
onClose: () => void;
open: boolean;
selectedFirewallId: number;
selectedFirewallLabel: string;
selectedFirewall: Firewall;
}

export const FirewallDialog = React.memo((props: Props) => {
const { enqueueSnackbar } = useSnackbar();
const queryClient = useQueryClient();

const {
mode,
onClose,
open,
selectedFirewallId,
selectedFirewallLabel: label,
} = props;

const { data: devices } = useAllFirewallDevicesQuery(selectedFirewallId);
const { mode, onClose, open, selectedFirewall } = props;

const {
error: updateError,
isLoading: isUpdating,
mutateAsync: updateFirewall,
} = useMutateFirewall(selectedFirewallId);
} = useMutateFirewall(selectedFirewall.id);
const {
error: deleteError,
isLoading: isDeleting,
mutateAsync: deleteFirewall,
} = useDeleteFirewall(selectedFirewallId);
} = useDeleteFirewall(selectedFirewall.id);

const requestMap = {
delete: () => deleteFirewall(),
Expand All @@ -66,23 +57,24 @@ export const FirewallDialog = React.memo((props: Props) => {

const onSubmit = async () => {
await requestMap[mode]();

// Invalidate Firewalls assigned to NodeBalancers and Linodes when Firewall is enabled, disabled, or deleted.
// eslint-disable-next-line no-unused-expressions
devices?.forEach((device) => {
const deviceType = device.entity.type;
for (const entity of selectedFirewall.entities) {
queryClient.invalidateQueries([
deviceType === 'linode' ? linodesQueryKey : nodebalancersQueryKey,
deviceType,
device.entity.id,
entity.type === 'linode' ? linodesQueryKey : nodebalancersQueryKey,
entity.type,
entity.id,
'firewalls',
]);
});
if (mode === 'delete') {
queryClient.invalidateQueries([firewallQueryKey]);
}
enqueueSnackbar(`Firewall ${label} successfully ${mode}d`, {
variant: 'success',
});

enqueueSnackbar(
`Firewall ${selectedFirewall.label} successfully ${mode}d`,
{
variant: 'success',
}
);

onClose();
};

Expand All @@ -101,7 +93,7 @@ export const FirewallDialog = React.memo((props: Props) => {
error={errorMap[mode]?.[0].reason}
onClose={onClose}
open={open}
title={`${capitalize(mode)} Firewall ${label}?`}
title={`${capitalize(mode)} Firewall ${selectedFirewall.label}?`}
>
Are you sure you want to {mode} this firewall?
</ConfirmationDialog>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ import { useFirewallsQuery } from 'src/queries/firewalls';
import { getAPIErrorOrDefault } from 'src/utilities/errorUtils';

import { CreateFirewallDrawer } from './CreateFirewallDrawer';
import { ActionHandlers as FirewallHandlers } from './FirewallActionMenu';
import { FirewallDialog, Mode } from './FirewallDialog';
import { FirewallDialog } from './FirewallDialog';
import { FirewallLandingEmptyState } from './FirewallLandingEmptyState';
import { FirewallRow } from './FirewallRow';

import type { ActionHandlers as FirewallHandlers } from './FirewallActionMenu';
import type { Mode } from './FirewallDialog';

const preferenceKey = 'firewalls';

const FirewallLanding = () => {
Expand Down Expand Up @@ -175,13 +177,12 @@ const FirewallLanding = () => {
onClose={onCloseCreateDrawer}
open={isCreateFirewallDrawerOpen}
/>
{selectedFirewallId && (
{selectedFirewall && (
<FirewallDialog
mode={dialogMode}
onClose={() => setIsModalOpen(false)}
open={isModalOpen}
selectedFirewallId={selectedFirewallId}
selectedFirewallLabel={selectedFirewall?.label ?? ''}
selectedFirewall={selectedFirewall}
/>
)}
</React.Fragment>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,21 +68,21 @@ describe('FirewallRow', () => {
describe('getDeviceLinks', () => {
it('should return a single Link if one Device is attached', () => {
const device = firewallDeviceFactory.build();
const links = getDeviceLinks([device]);
const links = getDeviceLinks([device.entity]);
const { getByText } = renderWithTheme(links);
expect(getByText(device.entity.label));
});

it('should render up to three comma-separated links', () => {
const devices = firewallDeviceFactory.buildList(3);
const links = getDeviceLinks(devices);
const links = getDeviceLinks(devices.map((device) => device.entity));
const { queryAllByTestId } = renderWithTheme(links);
expect(queryAllByTestId('firewall-row-link')).toHaveLength(3);
});

it('should render "plus N more" text for any devices over three', () => {
const devices = firewallDeviceFactory.buildList(13);
const links = getDeviceLinks(devices);
const links = getDeviceLinks(devices.map((device) => device.entity));
const { getByText, queryAllByTestId } = renderWithTheme(links);
expect(queryAllByTestId('firewall-row-link')).toHaveLength(3);
expect(getByText(/10 more/));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
import { Firewall, FirewallDevice } from '@linode/api-v4/lib/firewalls';
import { APIError } from '@linode/api-v4/lib/types';
import React from 'react';
import { Link } from 'react-router-dom';

import { Hidden } from 'src/components/Hidden';
import { StatusIcon } from 'src/components/StatusIcon/StatusIcon';
import { TableCell } from 'src/components/TableCell';
import { TableRow } from 'src/components/TableRow';
import { useAllFirewallDevicesQuery } from 'src/queries/firewalls';
import { capitalize } from 'src/utilities/capitalize';

import { ActionHandlers, FirewallActionMenu } from './FirewallActionMenu';
import { FirewallActionMenu } from './FirewallActionMenu';

import type { ActionHandlers } from './FirewallActionMenu';
import type { Firewall, FirewallDeviceEntity } from '@linode/api-v4';

export interface FirewallRowProps extends Firewall, ActionHandlers {}

export const FirewallRow = React.memo((props: FirewallRowProps) => {
const { id, label, rules, status, ...actionHandlers } = props;

const { data: devices, error, isLoading } = useAllFirewallDevicesQuery(id);
const { entities, id, label, rules, status, ...actionHandlers } = props;

const count = getCountOfRules(rules);

Expand All @@ -34,9 +32,7 @@ export const FirewallRow = React.memo((props: FirewallRowProps) => {
</TableCell>
<Hidden smDown>
<TableCell>{getRuleString(count)}</TableCell>
<TableCell>
{getDevicesCellString(devices ?? [], isLoading, error ?? undefined)}
</TableCell>
<TableCell>{getDevicesCellString(entities)}</TableCell>
</Hidden>
<TableCell sx={{ textAlign: 'end', whiteSpace: 'nowrap' }}>
<FirewallActionMenu
Expand Down Expand Up @@ -79,45 +75,32 @@ export const getCountOfRules = (rules: Firewall['rules']): [number, number] => {
return [(rules.inbound || []).length, (rules.outbound || []).length];
};

const getDevicesCellString = (
data: FirewallDevice[],
loading: boolean,
error?: APIError[]
): JSX.Element | string => {
if (loading) {
return 'Loading...';
}

if (error) {
return 'Error retrieving Linodes';
}

if (data.length === 0) {
const getDevicesCellString = (entities: FirewallDeviceEntity[]) => {
if (entities.length === 0) {
return 'None assigned';
}

return getDeviceLinks(data);
return getDeviceLinks(entities);
};

export const getDeviceLinks = (data: FirewallDevice[]): JSX.Element => {
const firstThree = data.slice(0, 3);
export const getDeviceLinks = (entities: FirewallDeviceEntity[]) => {
const firstThree = entities.slice(0, 3);

return (
<>
{firstThree.map((thisDevice, idx) => (
<>
{firstThree.map((entity, idx) => (
<React.Fragment key={entity.url}>
{idx > 0 && ', '}
<Link
className="link secondaryLink"
data-testid="firewall-row-link"
key={thisDevice.id}
to={`/${thisDevice.entity.type}s/${thisDevice.entity.id}`}
to={`/${entity.type}s/${entity.id}`}
>
{thisDevice.entity.label}
{entity.label}
</Link>
</>
</React.Fragment>
))}
{data.length > 3 && <span>, plus {data.length - 3} more.</span>}
{entities.length > 3 && <span>, plus {entities.length - 3} more.</span>}
</>
);
};
Loading
Loading