This is an automated email from the ASF dual-hosted git repository.
lizhimins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-dashboard.git
The following commit(s) were added to refs/heads/master by this push:
new c187d3a22 feat(litetopic): delete Lite parent topics with
cascade-aware confirmations (#7364)
c187d3a22 is described below
commit c187d3a22f3992f8cd131797f7ceab3724a3f296
Author: wizcraft_kris <[email protected]>
AuthorDate: Fri Nov 27 11:52:08 2026 +0800
feat(litetopic): delete Lite parent topics with cascade-aware confirmations
(#7364)
---
web/src/i18n/translations.ts | 60 +++++++++
.../pages/instance/__tests__/TopicPage.test.tsx | 123 +++++++++++++++++
web/src/pages/instance/topic.tsx | 118 +++++++++++++----
web/src/pages/studio/LiteTopic.tsx | 145 +++++++++++++++++++++
web/src/pages/studio/__tests__/LiteTopic.test.tsx | 142 +++++++++++++++++++-
5 files changed, 555 insertions(+), 33 deletions(-)
diff --git a/web/src/i18n/translations.ts b/web/src/i18n/translations.ts
index e62cc971f..6b367d28d 100644
--- a/web/src/i18n/translations.ts
+++ b/web/src/i18n/translations.ts
@@ -2442,6 +2442,36 @@ const translations: Record<string, Record<Lang, string>>
= {
zh: '确定要删除 Topic「{name}」吗?此操作不可撤销。',
en: 'Are you sure to delete Topic "{name}"? This cannot be undone.',
},
+ 'topic.deleteConfirmTitle': { zh: '确认删除', en: 'Confirm Deletion' },
+ 'topic.deleteSuccess': {
+ zh: 'Topic「{name}」已删除',
+ en: 'Topic "{name}" deleted',
+ },
+ 'topic.deleteFailed': {
+ zh: '删除 Topic 失败,请稍后重试',
+ en: 'Failed to delete the topic. Please try again later.',
+ },
+ 'topic.batchDeleteConfirmTitle': { zh: '确认批量删除', en: 'Confirm Batch
Deletion' },
+ 'topic.batchDeleteContent': {
+ zh: '确定要删除选中的 {count} 个 Topic 吗?此操作不可撤销。',
+ en: 'Delete the {count} selected topics? This cannot be undone.',
+ },
+ 'topic.batchDeleteSuccess': {
+ zh: '已删除 {count} 个 Topic',
+ en: 'Deleted {count} topics',
+ },
+ 'topic.batchDeletePartial': {
+ zh: '已删除 {deleted} 个 Topic,{failed} 个删除失败',
+ en: 'Deleted {deleted} topics, {failed} failed to delete',
+ },
+ 'topic.batchDeleteFailCount': {
+ zh: '{count} 个 Topic 删除失败,请稍后重试',
+ en: '{count} topics failed to delete. Please try again later.',
+ },
+ 'topic.batchDeleteFailed': {
+ zh: '批量删除 Topic 失败,请稍后重试',
+ en: 'Batch topic deletion failed. Please try again later.',
+ },
'topic.allTypes': { zh: '全部类型', en: 'All Types' },
'topic.normal': { zh: '普通', en: 'Normal' },
'topic.fifo': { zh: '顺序', en: 'FIFO' },
@@ -3152,6 +3182,26 @@ const translations: Record<string, Record<Lang, string>>
= {
'messages; range 1-43200 (30 days). Adjust it later from the LiteTopic
page, where Extend TTL ' +
'takes milliseconds (60000 ms = 1 minute)',
},
+ 'topic.liteDeleteWarning': {
+ zh: '「{name}」是 Lite 父主题,删除会在 Broker 上级联删除它的全部子 Lite 会话。',
+ en:
+ '"{name}" is a Lite parent topic; deleting it cascades to all of its
child Lite ' +
+ 'sessions on the broker.',
+ },
+ 'topic.liteDeleteCounts': {
+ zh: '子 Lite 会话 {topicCount} 个,绑定消费组 {consumerCount} 个。',
+ en: '{topicCount} child Lite sessions, {consumerCount} bound consumer
groups.',
+ },
+ 'topic.liteDeleteGroupNote': {
+ zh: '绑定消费组不会被删除。',
+ en: 'Bound consumer groups are not deleted.',
+ },
+ 'topic.liteDeleteBatchWarning': {
+ zh: '选中项包含 {count} 个 Lite 父主题,删除会在 Broker 上级联删除它们的全部子 Lite 会话。',
+ en:
+ 'The selection includes {count} Lite parent topics; deleting them
cascades to all of ' +
+ 'their child Lite sessions on the broker.',
+ },
'topic.remarkPlaceholder': {
zh: '可选,描述 Topic 用途',
en: 'Optional, describe the topic purpose',
@@ -4090,6 +4140,16 @@ const translations: Record<string, Record<Lang, string>>
= {
zh: '请选择 Topic 所属的实例',
en: 'Select the instance that owns the topic',
},
+ 'liteTopic.deleteParent': { zh: '删除', en: 'Delete' },
+ 'liteTopic.deleteModalTitle': { zh: '删除 Lite 父主题', en: 'Delete Lite Parent'
},
+ 'liteTopic.deleteSuccess': {
+ zh: 'Lite 父主题「{name}」已删除',
+ en: 'Lite parent "{name}" deleted',
+ },
+ 'liteTopic.deleteFailed': {
+ zh: '删除 Lite 父主题失败,请稍后重试',
+ en: 'Failed to delete the Lite parent topic',
+ },
'liteTopic.sessionStatus': { zh: '会话状态', en: 'Session Status' },
'liteTopic.creationCount': { zh: '创建数量', en: 'Creation Count' },
'liteTopic.liteTopics': { zh: 'LiteTopic 列表', en: 'LiteTopics' },
diff --git a/web/src/pages/instance/__tests__/TopicPage.test.tsx
b/web/src/pages/instance/__tests__/TopicPage.test.tsx
index 55b72b4ec..e65e62b90 100644
--- a/web/src/pages/instance/__tests__/TopicPage.test.tsx
+++ b/web/src/pages/instance/__tests__/TopicPage.test.tsx
@@ -48,6 +48,12 @@ const instanceServiceMocks = vi.hoisted(() => ({
vi.mock('../../../services/topicService', () => topicServiceMocks);
+const liteTopicApiMocks = vi.hoisted(() => ({
+ queryLiteTopicList: vi.fn(),
+}));
+
+vi.mock('../../../api/liteTopic', () => liteTopicApiMocks);
+
const mockTopicsList = (items: Topic[]) =>
topicServiceMocks.listTopicsPage.mockResolvedValue({
items,
@@ -1834,4 +1840,121 @@ describe('TopicPage', () => {
await screen.findByText(/当前列表中的 1 个 Topic 在 Broker 上均有路由/),
).toBeInTheDocument();
});
+
+ it('shows the Lite child-session blast radius before deleting a Lite
parent', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ liteTopicApiMocks.queryLiteTopicList
+ .mockReset()
+ .mockResolvedValue([
+ { namespace: 'default', topicPattern: 'topic-01', topicCount: 12,
consumerCount: 3 },
+ ]);
+ mockTopicsList([{ ...buildTopics(1)[0], type: 'LITE' }]);
+ topicServiceMocks.deleteTopic.mockResolvedValue(undefined);
+ renderWithProviders();
+
+ const row = await screen.findByRole('row', { name: /topic-01/ });
+ await user.click(within(row).getByRole('button', { name: /删除/ }));
+
+ // A Lite parent delete cascades to its child Lite sessions on the broker,
so the
+ // confirm dialog has to say how many sessions and bound consumer groups
ride along.
+ await screen.findByText(/是 Lite 父主题/);
+
expect(liteTopicApiMocks.queryLiteTopicList).toHaveBeenCalledWith('topic-01');
+ expect(screen.getByText(/级联删除/)).toBeInTheDocument();
+ expect(screen.getByText(/子 Lite 会话 12 个/)).toBeInTheDocument();
+ expect(screen.getByText(/绑定消费组 3 个/)).toBeInTheDocument();
+ expect(screen.getByText(/绑定消费组不会被删除/)).toBeInTheDocument();
+
+ const dialog = screen.getByText(/是 Lite 父主题/).closest('.ant-modal') as
HTMLElement;
+ await user.click(within(dialog).getByRole('button', { name: /删\s*除/ }));
+ await waitFor(() =>
+ expect(topicServiceMocks.deleteTopic).toHaveBeenCalledWith('topic-01',
'instance-proxy-1'),
+ );
+ });
+
+ it('keeps the plain delete confirm for non-Lite topics', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ liteTopicApiMocks.queryLiteTopicList.mockReset().mockResolvedValue([]);
+ mockTopicsList(buildTopics(1));
+ topicServiceMocks.deleteTopic.mockResolvedValue(undefined);
+ renderWithProviders();
+
+ const row = await screen.findByRole('row', { name: /topic-01/ });
+ await user.click(within(row).getByRole('button', { name: /删除/ }));
+
+ // Nothing cascades on a normal topic, so the dialog must not borrow the
Lite
+ // warning - and must not pay for a Lite summary lookup it will not show.
+ expect(await screen.findByText(/确定要删除
Topic「topic-01」/)).toBeInTheDocument();
+ expect(liteTopicApiMocks.queryLiteTopicList).not.toHaveBeenCalled();
+ expect(screen.queryByText(/是 Lite 父主题/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/级联删除/)).not.toBeInTheDocument();
+ });
+
+ it('warns about Lite parents in the batch delete confirm', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ liteTopicApiMocks.queryLiteTopicList.mockReset().mockResolvedValue([]);
+ const [normalTopic, firstLite, secondLite] = buildTopics(3);
+ mockTopicsList([normalTopic, { ...firstLite, type: 'LITE' }, {
...secondLite, type: 'LITE' }]);
+ renderWithProviders();
+
+ expect(await screen.findByText('topic-01')).toBeInTheDocument();
+ await user.click(
+ within(screen.getByText('topic-02').closest('tr') as
HTMLElement).getByRole('checkbox'),
+ );
+ await user.click(
+ within(screen.getByText('topic-03').closest('tr') as
HTMLElement).getByRole('checkbox'),
+ );
+ await user.click(screen.getByRole('button', { name: /删除 \(2\)$/ }));
+
+ // Batch deleting Lite parents cascades just like the single delete, so the
+ // confirm dialog has to surface it before the rows are gone.
+ expect(await screen.findByText(/包含 2 个 Lite 父主题/)).toBeInTheDocument();
+ expect(screen.getByText(/级联删除/)).toBeInTheDocument();
+ expect(screen.getByText(/绑定消费组不会被删除/)).toBeInTheDocument();
+ });
+
+ it('keeps the Lite cascade warning for a selected parent that fell out of
the current page', async () => {
+ // The batch delete submits every selected name, but a reload (create,
import or a
+ // single delete) reshuffles the server-paginated rows and can push a
selected Lite
+ // parent off the page while its name stays selected. The warning has to
count it
+ // from what was checked, not from the rows that happen to be visible now.
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ liteTopicApiMocks.queryLiteTopicList.mockReset().mockResolvedValue([]);
+ const [normalTopic, liteParent] = buildTopics(2);
+ const liteRow = { ...liteParent, type: 'LITE' };
+ const replacement = buildTopics(3)[2];
+ let call = 0;
+ topicServiceMocks.listTopicsPage.mockImplementation(async () => {
+ call += 1;
+ return call === 1
+ ? { items: [normalTopic, liteRow], total: 2, page: 1, size: 20 }
+ : // The reload after the single delete returns a page without the
selected
+ // parent, as a name that shifted to another page would.
+ { items: [replacement], total: 1, page: 1, size: 20 };
+ });
+ topicServiceMocks.deleteTopic.mockResolvedValue(undefined);
+ renderWithProviders();
+
+ expect(await screen.findByText('topic-02')).toBeInTheDocument();
+ await user.click(
+ within(screen.getByText('topic-02').closest('tr') as
HTMLElement).getByRole('checkbox'),
+ );
+ expect(screen.getByRole('button', { name: /删除 \(1\)$/
})).toBeInTheDocument();
+
+ const normalRow = screen.getByText('topic-01').closest('tr') as
HTMLElement;
+ await user.click(within(normalRow).getByRole('button', { name: /删除/ }));
+ const dialog = (await screen.findByText(/确定要删除 Topic「topic-01」/)).closest(
+ '.ant-modal',
+ ) as HTMLElement;
+ await user.click(within(dialog).getByRole('button', { name: /删\s*除/ }));
+
+ await waitFor(() =>
+ expect(topicServiceMocks.deleteTopic).toHaveBeenCalledWith('topic-01',
'instance-proxy-1'),
+ );
+ await waitFor(() =>
expect(screen.queryByText('topic-02')).not.toBeInTheDocument());
+ expect(screen.getByRole('button', { name: /删除 \(1\)$/
})).toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: /删除 \(1\)$/ }));
+ expect(await screen.findByText(/包含 1 个 Lite 父主题/)).toBeInTheDocument();
+ expect(screen.getByText(/绑定消费组不会被删除/)).toBeInTheDocument();
+ });
});
diff --git a/web/src/pages/instance/topic.tsx b/web/src/pages/instance/topic.tsx
index 82c54e8ba..378a7105e 100644
--- a/web/src/pages/instance/topic.tsx
+++ b/web/src/pages/instance/topic.tsx
@@ -78,6 +78,7 @@ import {
} from '../../services/topicService';
import { useInstanceFilter } from '../../hooks/useInstanceFilter';
import type { Instance } from '../../api/instance';
+import { queryLiteTopicList, type LiteTopicItem } from '../../api/liteTopic';
import {
parseCsvTable,
RESOURCE_NAME_MAX_LENGTH,
@@ -325,6 +326,12 @@ const TopicPageContent = ({
{},
);
const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
+ // Type of every row this page has shown, keyed by name. The batch delete
submits every
+ // selected name, and a reload (create, import, single delete) reshuffles the
+ // server-paginated rows: a selected row can leave the page while its name
stays
+ // selected. The Lite cascade warning has to count those too, so remember
the type
+ // where it was seen instead of re-deriving it from the rows visible right
now.
+ const topicTypesByName = useRef(new Map<string, string>());
const [searchText, setSearchText] = useState('');
const [typeFilter, setTypeFilter] = useState('');
const [mixedTypeEnabled, setMixedTypeEnabled] = useState(false);
@@ -500,6 +507,10 @@ const TopicPageContent = ({
[topics, selectedInstanceId, searchText, typeFilter],
);
+ useEffect(() => {
+ for (const topic of topics) topicTypesByName.current.set(topic.name,
topic.type);
+ }, [topics]);
+
const maxTablePage = Math.max(1, Math.ceil(totalTopics / tablePageSize));
const currentTablePage = Math.min(tablePage, maxTablePage);
@@ -711,26 +722,59 @@ const TopicPageContent = ({
sendForm.setFieldsValue({ topic: topic.name, tag: '', key: '', body: '',
properties: [] });
setSendModalOpen(true);
} else if (key === 'delete') {
- modal.confirm({
- title: '确认删除',
- content: `确定要删除 Topic「${topic.name}」吗?此操作不可撤销。`,
- okText: '删除',
- okType: 'danger',
- cancelText: '取消',
- onOk: async () => {
- try {
- await deleteTopic(topic.name, selectedInstanceId || undefined);
- // Drop the deleted row from the selection: a checked row that
disappears would
- // otherwise keep the batch delete armed with a name that no
longer exists, and its
- // failure path re-seeds that same selection - leaving nothing to
uncheck.
- setSelectedRowKeys((previous) => previous.filter((key) => key !==
topic.name));
- await reloadTopicPage();
- message.success(`Topic「${topic.name}」已删除`);
- } catch {
- message.error('删除 Topic 失败,请稍后重试');
- }
- },
- });
+ const openDeleteConfirm = (liteSummary: LiteTopicItem | undefined) => {
+ modal.confirm({
+ title: t('topic.deleteConfirmTitle'),
+ content: (
+ <div>
+ <div>{t('topic.deleteContent', { name: topic.name })}</div>
+ {topic.type === 'LITE' && (
+ <>
+ <div>{t('topic.liteDeleteWarning', { name: topic.name
})}</div>
+ {liteSummary?.topicCount != null &&
liteSummary?.consumerCount != null && (
+ <div>
+ {t('topic.liteDeleteCounts', {
+ topicCount: liteSummary.topicCount,
+ consumerCount: liteSummary.consumerCount,
+ })}
+ </div>
+ )}
+ <div>{t('topic.liteDeleteGroupNote')}</div>
+ </>
+ )}
+ </div>
+ ),
+ okText: t('common.delete'),
+ okType: 'danger',
+ cancelText: t('common.cancel'),
+ onOk: async () => {
+ try {
+ await deleteTopic(topic.name, selectedInstanceId || undefined);
+ // Drop the deleted row from the selection: a checked row that
disappears would
+ // otherwise keep the batch delete armed with a name that no
longer exists, and its
+ // failure path re-seeds that same selection - leaving nothing
to uncheck.
+ setSelectedRowKeys((previous) => previous.filter((key) => key
!== topic.name));
+ await reloadTopicPage();
+ message.success(t('topic.deleteSuccess', { name: topic.name }));
+ } catch {
+ message.error(t('topic.deleteFailed'));
+ }
+ },
+ });
+ };
+ if (topic.type === 'LITE') {
+ // Deleting a Lite parent cascades to its child Lite sessions on the
broker, so
+ // surface the blast radius first. The lookup is a fuzzy pattern query
- only a
+ // row whose pattern is exactly this parent counts - and a failed
lookup must not
+ // block the delete, just leave the counts out.
+ queryLiteTopicList(topic.name)
+ .then((items) =>
+ openDeleteConfirm(items.find((item) => item.topicPattern ===
topic.name)),
+ )
+ .catch(() => openDeleteConfirm(undefined));
+ } else {
+ openDeleteConfirm(undefined);
+ }
}
};
@@ -1373,12 +1417,27 @@ const TopicPageContent = ({
danger
icon={<DeleteOutlined />}
onClick={() => {
+ // Count from what was checked, not from the visible rows: the
delete below
+ // submits every selected name, and a selected row may have
left the page.
+ const liteParentCount = selectedRowKeys.filter(
+ (key) => topicTypesByName.current.get(String(key)) ===
'LITE',
+ ).length;
Modal.confirm({
- title: '确认批量删除',
- content: `确定要删除选中的 ${selectedRowKeys.length} 个 Topic
吗?此操作不可撤销。`,
- okText: '删除',
+ title: t('topic.batchDeleteConfirmTitle'),
+ content: (
+ <div>
+ <div>{t('topic.batchDeleteContent', { count:
selectedRowKeys.length })}</div>
+ {liteParentCount > 0 && (
+ <>
+ <div>{t('topic.liteDeleteBatchWarning', { count:
liteParentCount })}</div>
+ <div>{t('topic.liteDeleteGroupNote')}</div>
+ </>
+ )}
+ </div>
+ ),
+ okText: t('common.delete'),
okType: 'danger',
- cancelText: '取消',
+ cancelText: t('common.cancel'),
onOk: async () => {
try {
const names = selectedRowKeys.map(String);
@@ -1390,16 +1449,19 @@ const TopicPageContent = ({
setSelectedRowKeys(failed);
if (failed.length === 0) {
- message.success(`已删除 ${deleted.length} 个 Topic`);
+ message.success(t('topic.batchDeleteSuccess', { count:
deleted.length }));
} else if (deleted.length > 0) {
message.warning(
- `已删除 ${deleted.length} 个 Topic,${failed.length}
个删除失败`,
+ t('topic.batchDeletePartial', {
+ deleted: deleted.length,
+ failed: failed.length,
+ }),
);
} else {
- message.error(`${failed.length} 个 Topic 删除失败,请稍后重试`);
+ message.error(t('topic.batchDeleteFailCount', { count:
failed.length }));
}
} catch {
- message.error('批量删除 Topic 失败,请稍后重试');
+ message.error(t('topic.batchDeleteFailed'));
}
},
});
diff --git a/web/src/pages/studio/LiteTopic.tsx
b/web/src/pages/studio/LiteTopic.tsx
index 67ddd66b4..bbdf47825 100644
--- a/web/src/pages/studio/LiteTopic.tsx
+++ b/web/src/pages/studio/LiteTopic.tsx
@@ -43,6 +43,7 @@ import {
ClockCounterClockwise,
Eye,
PencilSimple,
+ Trash,
Gauge,
Info,
DownloadSimple,
@@ -63,7 +64,9 @@ import {
type LiteTopicSession,
} from '../../api/liteTopic';
import { listInstances, supportsApacheRuntime, type Instance } from
'../../api/instance';
+import { deleteTopic } from '../../services/topicService';
import { buildCsv, downloadCsv, localExportDateStamp, type CsvColumn } from
'../../utils/download';
+import { tableScrollX } from '../../utils/table';
const formatDuration = (ms: number | undefined | null): string => {
if (ms == null) return '-';
@@ -180,12 +183,21 @@ const LiteTopicPage: React.FC = () => {
const [ttlInstanceOptions, setTtlInstanceOptions] = useState<Instance[]>([]);
const [ttlInstancesLoading, setTtlInstancesLoading] = useState(false);
+ // Delete Lite parent modal
+ const [deleteModalOpen, setDeleteModalOpen] = useState(false);
+ const [deleteTarget, setDeleteTarget] = useState<LiteTopicItem | null>(null);
+ const [deleteInstanceId, setDeleteInstanceId] = useState('');
+ const [deleteLoading, setDeleteLoading] = useState(false);
+ const [deleteInstanceOptions, setDeleteInstanceOptions] =
useState<Instance[]>([]);
+ const [deleteInstancesLoading, setDeleteInstancesLoading] = useState(false);
+
const mountedRef = useRef(false);
const bootstrapRequestId = useRef(0);
const displayRequestId = useRef(0);
const displayQueryRef = useRef<{ pattern?: string; namespace?: string }>({});
const sessionRequestId = useRef(0);
const ttlInstanceRequestId = useRef(0);
+ const deleteInstanceRequestId = useRef(0);
useEffect(() => {
messageRef.current = message;
@@ -405,6 +417,72 @@ const LiteTopicPage: React.FC = () => {
}
};
+ const handleOpenDelete = (record: LiteTopicItem) => {
+ const requestId = ++deleteInstanceRequestId.current;
+ setDeleteTarget(record);
+ // The cascade warning must not trust the counts from the last list
refresh: look the
+ // parent up again the moment the dialog opens, mirroring the topic page
single delete.
+ // A failed lookup keeps the row counts and never blocks the delete.
+ queryLiteTopicList(record.topicPattern)
+ .then((items) => {
+ const fresh = items.find((item) => item.topicPattern ===
record.topicPattern);
+ if (!fresh) return;
+ setDeleteTarget((current) =>
+ current?.topicPattern === record.topicPattern
+ ? {
+ ...current,
+ topicCount: fresh.topicCount ?? current.topicCount,
+ consumerCount: fresh.consumerCount ?? current.consumerCount,
+ }
+ : current,
+ );
+ })
+ .catch(() => undefined);
+ setDeleteInstanceId('');
+ setDeleteModalOpen(true);
+ setDeleteInstanceOptions([]);
+ // The delete is ownership-checked against the owning instance, so the
modal needs
+ // the Apache-vendor instance list; auto-select when only one candidate
exists.
+ setDeleteInstancesLoading(true);
+ listInstances()
+ .then((instances) => {
+ if (requestId !== deleteInstanceRequestId.current) return;
+ const candidates = instances.filter(supportsApacheRuntime);
+ setDeleteInstanceOptions(candidates);
+ setDeleteInstanceId((current) =>
+ current === '' && candidates.length === 1 ?
String(candidates[0].name) : current,
+ );
+ })
+ .catch(() => {
+ if (requestId === deleteInstanceRequestId.current)
setDeleteInstanceOptions([]);
+ })
+ .finally(() => {
+ if (requestId === deleteInstanceRequestId.current)
setDeleteInstancesLoading(false);
+ });
+ };
+
+ const closeDelete = () => {
+ ++deleteInstanceRequestId.current;
+ setDeleteModalOpen(false);
+ setDeleteInstancesLoading(false);
+ };
+
+ const handleDeleteParent = async () => {
+ const target = deleteTarget;
+ if (!target?.topicPattern || !deleteInstanceId) return;
+ setDeleteLoading(true);
+ try {
+ await deleteTopic(target.topicPattern, deleteInstanceId);
+ message.success(t('liteTopic.deleteSuccess', { name: target.topicPattern
}));
+ closeDelete();
+ void fetchData(patternFilter || undefined, namespaceFilter || undefined);
+ } catch {
+ message.error(t('liteTopic.deleteFailed'));
+ } finally {
+ setDeleteLoading(false);
+ }
+ };
+
const getTTLStatusTag = (status: string | undefined) => {
const map: Record<string, { color: string; label: string }> = {
ACTIVE: { color: 'success', label: t('liteTopic.active') },
@@ -457,6 +535,7 @@ const LiteTopicPage: React.FC = () => {
title: t('liteTopic.namespace'),
dataIndex: 'namespace',
key: 'namespace',
+ width: 110,
render: (text: string) => text || '-',
ellipsis: true,
},
@@ -464,6 +543,7 @@ const LiteTopicPage: React.FC = () => {
title: t('liteTopic.pattern'),
dataIndex: 'topicPattern',
key: 'topicPattern',
+ width: 160,
render: (text: string) => <span style={{ fontWeight: 500, color:
'#1677ff' }}>{text}</span>,
ellipsis: true,
},
@@ -471,6 +551,7 @@ const LiteTopicPage: React.FC = () => {
title: t('liteTopic.topicCount'),
dataIndex: 'topicCount',
key: 'topicCount',
+ width: 110,
render: (val: number) => <span style={{ fontWeight: 500 }}>{val ??
'-'}</span>,
sorter: (a, b) => (a.topicCount || 0) - (b.topicCount || 0),
},
@@ -478,6 +559,7 @@ const LiteTopicPage: React.FC = () => {
title: t('liteTopic.consumers'),
dataIndex: 'consumerCount',
key: 'consumerCount',
+ width: 110,
render: (val: number) => <span style={{ fontWeight: 500 }}>{val ??
'-'}</span>,
sorter: (a, b) => (a.consumerCount || 0) - (b.consumerCount || 0),
},
@@ -485,6 +567,7 @@ const LiteTopicPage: React.FC = () => {
title: t('liteTopic.backlog'),
dataIndex: 'totalBacklog',
key: 'totalBacklog',
+ width: 110,
render: (val: number) => {
const num = val ?? 0;
const color = num > 10000 ? '#ff4d4f' : num > 0 ? '#fa8c16' :
'#52c41a';
@@ -496,6 +579,7 @@ const LiteTopicPage: React.FC = () => {
title: t('liteTopic.avgTtl'),
dataIndex: 'averageTTL',
key: 'averageTTL',
+ width: 110,
render: (val: number) => formatDuration(val),
sorter: (a, b, sortOrder?: 'ascend' | 'descend' | null) =>
unmeasuredSortKey(a.averageTTL, sortOrder) -
unmeasuredSortKey(b.averageTTL, sortOrder),
@@ -504,12 +588,14 @@ const LiteTopicPage: React.FC = () => {
title: t('liteTopic.status'),
dataIndex: 'ttlStatus',
key: 'ttlStatus',
+ width: 90,
render: (status: string) => getTTLStatusTag(status),
},
{
title: t('liteTopic.lastActive'),
dataIndex: 'lastActiveTime',
key: 'lastActiveTime',
+ width: 150,
render: (val: number) => formatTime(val),
sorter: (a, b, sortOrder?: 'ascend' | 'descend' | null) =>
unmeasuredSortKey(a.lastActiveTime, sortOrder) -
@@ -518,6 +604,7 @@ const LiteTopicPage: React.FC = () => {
{
title: t('liteTopic.actions'),
key: 'action',
+ width: 290,
render: (_: unknown, record: LiteTopicItem) => (
<Space size="small">
<Button
@@ -544,6 +631,18 @@ const LiteTopicPage: React.FC = () => {
{t('liteTopic.viewSessions')}
</Button>
)}
+ <Button
+ type="link"
+ size="small"
+ danger
+ icon={<Trash size={14} />}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleOpenDelete(record);
+ }}
+ >
+ {t('liteTopic.deleteParent')}
+ </Button>
</Space>
),
},
@@ -958,6 +1057,7 @@ const LiteTopicPage: React.FC = () => {
<Card variant="borderless" style={{ borderRadius: 8 }}>
<Table
columns={columns}
+ scroll={{ x: tableScrollX(columns) }}
dataSource={filteredTopicList}
rowKey={(record) => JSON.stringify([record.namespace,
record.topicPattern])}
loading={loading}
@@ -1063,6 +1163,51 @@ const LiteTopicPage: React.FC = () => {
</Form.Item>
</Form>
</Modal>
+
+ {/* Delete Lite parent Modal */}
+ <Modal
+ title={t('liteTopic.deleteModalTitle')}
+ open={deleteModalOpen}
+ onOk={handleDeleteParent}
+ onCancel={closeDelete}
+ confirmLoading={deleteLoading}
+ okText={t('liteTopic.deleteParent')}
+ okButtonProps={{ danger: true }}
+ cancelText={t('common.cancel')}
+ destroyOnHidden
+ >
+ <Form layout="vertical" style={{ marginTop: 16 }}>
+ <div style={{ marginBottom: 16 }}>
+ <div>{t('topic.liteDeleteWarning', { name:
deleteTarget?.topicPattern || '' })}</div>
+ {deleteTarget?.topicCount != null && deleteTarget?.consumerCount
!= null && (
+ <div>
+ {t('topic.liteDeleteCounts', {
+ topicCount: deleteTarget.topicCount,
+ consumerCount: deleteTarget.consumerCount,
+ })}
+ </div>
+ )}
+ <div>{t('topic.liteDeleteGroupNote')}</div>
+ </div>
+ <Form.Item
+ label={t('liteTopic.instance')}
+ required
+ validateStatus={deleteInstanceId ? '' : 'error'}
+ help={deleteInstanceId ? undefined :
t('liteTopic.instanceRequired')}
+ >
+ <Select
+ value={deleteInstanceId || undefined}
+ onChange={(val) => setDeleteInstanceId(val)}
+ loading={deleteInstancesLoading}
+ placeholder={t('liteTopic.instancePlaceholder')}
+ options={deleteInstanceOptions.map((instance) => ({
+ value: String(instance.name),
+ label: instance.name,
+ }))}
+ />
+ </Form.Item>
+ </Form>
+ </Modal>
</div>
);
};
diff --git a/web/src/pages/studio/__tests__/LiteTopic.test.tsx
b/web/src/pages/studio/__tests__/LiteTopic.test.tsx
index 77d4cf05b..eb840d496 100644
--- a/web/src/pages/studio/__tests__/LiteTopic.test.tsx
+++ b/web/src/pages/studio/__tests__/LiteTopic.test.tsx
@@ -16,7 +16,7 @@
*/
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
-import { act, render, screen, waitFor } from '@testing-library/react';
+import { act, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { App } from 'antd';
@@ -36,6 +36,10 @@ const apiMocks = vi.hoisted(() => ({
vi.mock('../../../api/liteTopic', () => apiMocks);
+const topicServiceMocks = vi.hoisted(() => ({ deleteTopic: vi.fn() }));
+
+vi.mock('../../../services/topicService', () => topicServiceMocks);
+
const instanceApiMocks = vi.hoisted(() => ({ listInstances: vi.fn() }));
vi.mock('../../../api/instance', async () => {
@@ -287,19 +291,21 @@ describe('LiteTopic Page', () => {
const indexOf = (pattern: string) => rowOrder().findIndex((text) =>
text.includes(pattern));
// Ascending: a value the column renders as '-' must not sort as a zero
TTL, which would
- // place that pattern as if it had expired before every measurable one.
- await user.click(screen.getByText('平均 TTL'));
+ // place that pattern as if it had expired before every measurable one.
The click goes
+ // through the columnheader role: with scroll.x the table keeps an
aria-hidden measure row
+ // that clones each header cell, so a plain text query would match twice.
+ await user.click(screen.getByRole('columnheader', { name: '平均 TTL' }));
await waitFor(() =>
expect(indexOf('aaa-unmeasured-*')).toBeGreaterThan(indexOf('zzz-measured-*')),
);
// The unset value stays last in the descending direction too instead of
swapping to the top.
- await user.click(screen.getByText('平均 TTL'));
+ await user.click(screen.getByRole('columnheader', { name: '平均 TTL' }));
await waitFor(() =>
expect(indexOf('aaa-unmeasured-*')).toBeGreaterThan(indexOf('zzz-measured-*')),
);
- await user.click(screen.getByText('最后活跃'));
+ await user.click(screen.getByRole('columnheader', { name: '最后活跃' }));
await waitFor(() =>
expect(indexOf('aaa-unmeasured-*')).toBeGreaterThan(indexOf('zzz-measured-*')),
);
@@ -884,4 +890,130 @@ describe('LiteTopic Page', () => {
expect(screen.queryByText('90 / 100')).not.toBeInTheDocument();
expect(await screen.findByText('获取配额信息失败')).toBeInTheDocument();
});
+
+ it('shows the child-session blast radius before deleting a Lite parent',
async () => {
+ // Deleting the parent cascades to every child Lite session on the broker,
so the
+ // confirm dialog has to show the row's counts before the parent is gone.
+ apiMocks.queryLiteTopicList.mockResolvedValue([
+ {
+ namespace: 'default',
+ topicPattern: 'order-*',
+ topicCount: 5,
+ consumerCount: 2,
+ sessionIds: ['session-1'],
+ },
+ ]);
+ const user = userEvent.setup();
+ renderPage();
+
+ await screen.findByText('order-*');
+ await user.click(await screen.findByRole('button', { name: /删\s*除/ }));
+
+ expect(await screen.findByText(/级联删除/)).toBeInTheDocument();
+ expect(screen.getByText(/子 Lite 会话 5 个/)).toBeInTheDocument();
+ expect(screen.getByText(/绑定消费组 2 个/)).toBeInTheDocument();
+ expect(screen.getByText(/绑定消费组不会被删除/)).toBeInTheDocument();
+ });
+
+ it('refreshes the blast-radius counts when the delete dialog opens', async
() => {
+ // The dialog must not trust the counts from the last list refresh - a
stale pair
+ // would misstate what the cascade is about to delete. Mirror the topic
page single
+ // delete: look the parent up again the moment the dialog opens.
+ apiMocks.queryLiteTopicList.mockImplementation(async (pattern?: string) =>
[
+ {
+ namespace: 'default',
+ topicPattern: 'order-*',
+ topicCount: pattern ? 7 : 5,
+ consumerCount: pattern ? 3 : 2,
+ sessionIds: ['session-1'],
+ },
+ ]);
+ const user = userEvent.setup();
+ renderPage();
+
+ await screen.findByText('order-*');
+ await user.click(await screen.findByRole('button', { name: /删\s*除/ }));
+
+ expect(await screen.findByText(/子 Lite 会话 7 个/)).toBeInTheDocument();
+ expect(screen.getByText(/绑定消费组 3 个/)).toBeInTheDocument();
+ expect(screen.queryByText(/子 Lite 会话 5 个/)).not.toBeInTheDocument();
+ });
+
+ it('keeps the row counts in the delete dialog when the refresh lookup
fails', async () => {
+ // A failed refresh must not block the delete or blank the blast radius:
the row
+ // counts are still the best numbers available.
+ instanceApiMocks.listInstances.mockResolvedValue([
+ { id: 1, name: 'apache-main', vendor: 'APACHE' },
+ ] as unknown as Instance[]);
+ apiMocks.queryLiteTopicList.mockImplementation(async (pattern?: string) =>
{
+ if (pattern) throw new Error('lite list unavailable');
+ return [
+ {
+ namespace: 'default',
+ topicPattern: 'order-*',
+ topicCount: 5,
+ consumerCount: 2,
+ sessionIds: ['session-1'],
+ },
+ ];
+ });
+ topicServiceMocks.deleteTopic.mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ renderPage();
+
+ await screen.findByText('order-*');
+ await user.click(await screen.findByRole('button', { name: /删\s*除/ }));
+
+ expect(await screen.findByText(/子 Lite 会话 5 个/)).toBeInTheDocument();
+ expect(screen.getByText(/绑定消费组 2 个/)).toBeInTheDocument();
+ const dialog = (await screen.findByText('删除 Lite 父主题')).closest(
+ '.ant-modal',
+ ) as HTMLElement;
+ await user.click(within(dialog).getByRole('button', { name: /删\s*除/ }));
+ await waitFor(() =>
+ expect(topicServiceMocks.deleteTopic).toHaveBeenCalledWith('order-*',
'apache-main'),
+ );
+ });
+
+ it('sends the owning instance id when deleting a Lite parent', async () => {
+ // The delete is ownership-checked against the owning instance; mirror the
+ // Extend-TTL modal: only Apache-vendor instances are candidates, and a
sole
+ // candidate is auto-selected.
+ instanceApiMocks.listInstances.mockResolvedValue([
+ { id: 1, name: 'apache-main', vendor: 'APACHE' },
+ { id: 2, name: 'cloud-1', vendor: 'ALIYUN' },
+ ] as unknown as Instance[]);
+ apiMocks.queryLiteTopicList.mockResolvedValue([
+ {
+ namespace: 'default',
+ topicPattern: 'order-*',
+ topicCount: 5,
+ consumerCount: 2,
+ sessionIds: ['session-1'],
+ },
+ ]);
+ topicServiceMocks.deleteTopic.mockResolvedValue(undefined);
+ const user = userEvent.setup();
+ renderPage();
+
+ await screen.findByText('order-*');
+ await user.click(await screen.findByRole('button', { name: /删\s*除/ }));
+
+ await waitFor(() => {
+ expect(topicServiceMocks.deleteTopic).not.toHaveBeenCalled();
+ const selected = document.querySelector('.ant-modal
.ant-select-selection-item');
+ expect(selected?.textContent).toBe('apache-main');
+ });
+
+ const dialog = (await screen.findByText('删除 Lite 父主题')).closest(
+ '.ant-modal',
+ ) as HTMLElement;
+ await user.click(within(dialog).getByRole('button', { name: /删\s*除/ }));
+
+ await waitFor(() => {
+ expect(topicServiceMocks.deleteTopic).toHaveBeenCalledWith('order-*',
'apache-main');
+ });
+ // The list reloads once after the parent is deleted.
+ await waitFor(() =>
expect(apiMocks.queryLiteTopicList.mock.calls.length).toBeGreaterThan(1));
+ });
});