mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-11-16 14:54:23 +08:00
perf(nodes): paginate node lists and fetch details directly (#54)
* perf(nodes): paginate node lists and fetch details directly * fix(nodes): preserve Unicode search and page transition state * fix(nodes): validate search using the UTF-8 byte limit
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Field,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { NodeStatus } from '@/lib/services/openflare';
|
||||
|
||||
export function NodeListControls({
|
||||
search,
|
||||
searchTooLong,
|
||||
onSearchChange,
|
||||
status,
|
||||
onStatusChange,
|
||||
page,
|
||||
pageSize,
|
||||
onPageSizeChange,
|
||||
total,
|
||||
totalPages,
|
||||
loading,
|
||||
hasData,
|
||||
onPageChange,
|
||||
}: {
|
||||
search: string;
|
||||
searchTooLong: boolean;
|
||||
onSearchChange: (value: string) => void;
|
||||
status: NodeStatus | '';
|
||||
onStatusChange: (value: NodeStatus | '') => void;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
onPageSizeChange: (value: number) => void;
|
||||
total: number;
|
||||
totalPages: number;
|
||||
loading: boolean;
|
||||
hasData: boolean;
|
||||
onPageChange: (value: number) => void;
|
||||
}) {
|
||||
const t = useTranslations('nodes');
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
<FieldGroup className='flex flex-wrap gap-3 sm:flex-row'>
|
||||
<Field className='flex-1' data-invalid={searchTooLong || undefined}>
|
||||
<FieldLabel htmlFor='node-search'>
|
||||
{t('pagination.search')}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id='node-search'
|
||||
value={search}
|
||||
onChange={(event) => onSearchChange(event.target.value)}
|
||||
placeholder={t('pagination.searchPlaceholder')}
|
||||
maxLength={256}
|
||||
aria-invalid={searchTooLong || undefined}
|
||||
aria-describedby={searchTooLong ? 'node-search-error' : undefined}
|
||||
/>
|
||||
{searchTooLong && (
|
||||
<FieldError id='node-search-error'>
|
||||
{t('pagination.searchTooLong')}
|
||||
</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
<Field className='sm:w-44'>
|
||||
<FieldLabel htmlFor='node-status'>{t('table.status')}</FieldLabel>
|
||||
<Select
|
||||
value={status || 'all'}
|
||||
onValueChange={(value) =>
|
||||
onStatusChange(value === 'all' ? '' : (value as NodeStatus))
|
||||
}
|
||||
>
|
||||
<SelectTrigger id='node-status'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value='all'>
|
||||
{t('pagination.allStatuses')}
|
||||
</SelectItem>
|
||||
{(['pending', 'online', 'offline'] as const).map((value) => (
|
||||
<SelectItem key={value} value={value}>
|
||||
{t(`status.${value}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field className='sm:w-32'>
|
||||
<FieldLabel htmlFor='node-page-size'>
|
||||
{t('pagination.pageSize')}
|
||||
</FieldLabel>
|
||||
<Select
|
||||
value={String(pageSize)}
|
||||
onValueChange={(value) => onPageSizeChange(Number(value))}
|
||||
>
|
||||
<SelectTrigger id='node-page-size'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{[20, 50, 100].map((value) => (
|
||||
<SelectItem key={value} value={String(value)}>
|
||||
{value}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<div className='flex flex-wrap items-center justify-between gap-3'>
|
||||
{hasData && (
|
||||
<p className='text-sm text-muted-foreground' aria-live='polite'>
|
||||
{t('pagination.summary', { page, totalPages, total })}
|
||||
</p>
|
||||
)}
|
||||
<nav aria-label={t('pagination.navigation')} className='flex gap-2'>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
disabled={!hasData || loading || page <= 1}
|
||||
onClick={() => onPageChange(page - 1)}
|
||||
>
|
||||
{t('pagination.previous')}
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
disabled={!hasData || loading || page >= totalPages}
|
||||
onClick={() => onPageChange(page + 1)}
|
||||
>
|
||||
{t('pagination.next')}
|
||||
</Button>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -37,15 +37,20 @@ export function NodesTable({
|
||||
deletingId,
|
||||
onEdit,
|
||||
onDelete,
|
||||
actionsDisabled = false,
|
||||
}: {
|
||||
nodes: NodeItem[];
|
||||
deletingId: number | null;
|
||||
actionsDisabled?: boolean;
|
||||
onEdit: (node: NodeItem) => void;
|
||||
onDelete: (node: NodeItem) => void;
|
||||
}) {
|
||||
const t = useTranslations('nodes');
|
||||
return (
|
||||
<div className='border border-dashed rounded-lg overflow-hidden'>
|
||||
<div
|
||||
className='border border-dashed rounded-lg overflow-hidden'
|
||||
aria-busy={actionsDisabled}
|
||||
>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className='border-dashed hover:bg-transparent'>
|
||||
@@ -144,16 +149,22 @@ export function NodesTable({
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 text-xs'
|
||||
asChild
|
||||
asChild={!actionsDisabled}
|
||||
disabled={actionsDisabled}
|
||||
>
|
||||
<Link href={`/nodes/detail?id=${node.id}`}>
|
||||
{t('detail')}
|
||||
</Link>
|
||||
{actionsDisabled ? (
|
||||
t('detail')
|
||||
) : (
|
||||
<Link href={`/nodes/detail?id=${node.id}`}>
|
||||
{t('detail')}
|
||||
</Link>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 text-xs'
|
||||
disabled={actionsDisabled}
|
||||
onClick={() => onEdit(node)}
|
||||
>
|
||||
<Pencil className='size-3 mr-1' />
|
||||
@@ -163,7 +174,7 @@ export function NodesTable({
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 text-xs text-destructive hover:text-destructive'
|
||||
disabled={deletingId === node.id}
|
||||
disabled={actionsDisabled || deletingId === node.id}
|
||||
onClick={() => onDelete(node)}
|
||||
>
|
||||
<Trash2 className='size-3 mr-1' />
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useMemo } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ArrowLeft, Server } from 'lucide-react';
|
||||
@@ -25,20 +24,20 @@ export function NodeDetailPageClient() {
|
||||
const searchParams = useSearchParams();
|
||||
const nodeId = searchParams.get('id')?.trim() ?? '';
|
||||
|
||||
const validNodeId =
|
||||
Number.isSafeInteger(Number(nodeId)) && Number(nodeId) > 0;
|
||||
const nodesQuery = useQuery({
|
||||
queryKey: nodesQueryKey,
|
||||
queryFn: () => NodeService.listNodes(),
|
||||
refetchInterval: 5000,
|
||||
queryKey: [...nodesQueryKey, 'detail', nodeId],
|
||||
queryFn: () => NodeService.getNode(Number(nodeId)),
|
||||
enabled: validNodeId,
|
||||
refetchInterval: (query) =>
|
||||
query.state.status === 'error' ? false : 15000,
|
||||
refetchIntervalInBackground: false,
|
||||
});
|
||||
|
||||
const node = useMemo(() => {
|
||||
if (!nodeId) return null;
|
||||
return (
|
||||
(nodesQuery.data ?? []).find((item) => String(item.id) === nodeId) ?? null
|
||||
);
|
||||
}, [nodeId, nodesQuery.data]);
|
||||
const node = nodesQuery.data;
|
||||
|
||||
if (!nodeId) {
|
||||
if (!validNodeId) {
|
||||
return (
|
||||
<div className='py-6 px-1'>
|
||||
<EmptyStateWithBorder icon={Server} description={t('missingId')} />
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { Loader2, Plus, RefreshCw, Server } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
@@ -29,46 +29,112 @@ import {
|
||||
import { EmptyStateWithBorder } from '@/components/layout/empty';
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import type { NodeItem, NodeMutationPayload } from '@/lib/services/openflare';
|
||||
import type {
|
||||
NodeItem,
|
||||
NodeListQuery,
|
||||
NodeMutationPayload,
|
||||
NodeStatus,
|
||||
NodeType,
|
||||
} from '@/lib/services/openflare';
|
||||
import { NodeService } from '@/lib/services/openflare';
|
||||
|
||||
import { NodeEditorDialog } from './components/node-editor-dialog';
|
||||
import {
|
||||
filterNodesByType,
|
||||
getFilterDescription,
|
||||
getNodeFilter,
|
||||
NodeTypeFilter,
|
||||
type NodeFilter,
|
||||
} from './components/node-type-filter';
|
||||
import { NodesTable } from './components/nodes-table';
|
||||
import { NodeListControls } from './components/node-list-controls';
|
||||
import { getErrorMessage } from './components/node-utils';
|
||||
|
||||
const nodesQueryKey = ['openflare', 'nodes'];
|
||||
|
||||
export function NodesPageClient() {
|
||||
const searchParams = useSearchParams();
|
||||
const nodeFilter = getNodeFilter(
|
||||
new URLSearchParams(searchParams.toString()),
|
||||
);
|
||||
return <NodesPage key={nodeFilter} nodeFilter={nodeFilter} />;
|
||||
}
|
||||
|
||||
function NodesPage({ nodeFilter }: { nodeFilter: NodeFilter }) {
|
||||
const t = useTranslations('nodes');
|
||||
const tc = useTranslations('common');
|
||||
const searchParams = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const [editingNode, setEditingNode] = useState<NodeItem | null>(null);
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<NodeItem | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [search, setSearch] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [status, setStatus] = useState<NodeStatus | ''>('');
|
||||
const searchTooLong = new TextEncoder().encode(search.trim()).length > 256;
|
||||
|
||||
const nodeFilter = useMemo(
|
||||
() => getNodeFilter(new URLSearchParams(searchParams.toString())),
|
||||
[searchParams],
|
||||
);
|
||||
const resetNodeActions = useCallback(() => {
|
||||
setEditingNode(null);
|
||||
setEditorOpen(false);
|
||||
setDeleteTarget(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (searchTooLong || search.trim() === debouncedSearch) return;
|
||||
const timeout = setTimeout(() => {
|
||||
setDebouncedSearch(search.trim());
|
||||
setPage(1);
|
||||
resetNodeActions();
|
||||
}, 300);
|
||||
return () => clearTimeout(timeout);
|
||||
}, [search, searchTooLong, debouncedSearch, resetNodeActions]);
|
||||
|
||||
const nodeTypes: Record<NodeFilter, NodeType | ''> = {
|
||||
all: '',
|
||||
edge: 'edge_node',
|
||||
relay: 'tunnel_relay',
|
||||
tunnel: 'tunnel_client',
|
||||
};
|
||||
const query = {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
search: debouncedSearch,
|
||||
status,
|
||||
node_type: nodeTypes[nodeFilter],
|
||||
};
|
||||
const nodesQuery = useQuery({
|
||||
queryKey: nodesQueryKey,
|
||||
queryFn: () => NodeService.listNodes(),
|
||||
refetchInterval: 5000,
|
||||
queryKey: [...nodesQueryKey, 'page', query],
|
||||
queryFn: () => NodeService.listNodePage(query),
|
||||
placeholderData: (previousData, previousQuery) => {
|
||||
const previousParams = previousQuery?.queryKey[3] as
|
||||
| NodeListQuery
|
||||
| undefined;
|
||||
return previousParams?.search === query.search &&
|
||||
previousParams?.status === query.status &&
|
||||
previousParams?.node_type === query.node_type &&
|
||||
previousParams?.page_size === query.page_size
|
||||
? previousData
|
||||
: undefined;
|
||||
},
|
||||
refetchInterval: (query) =>
|
||||
query.state.status === 'error' ? false : 15000,
|
||||
refetchIntervalInBackground: false,
|
||||
});
|
||||
|
||||
const nodes = useMemo(() => nodesQuery.data ?? [], [nodesQuery.data]);
|
||||
const filteredNodes = useMemo(
|
||||
() => filterNodesByType(nodes, nodeFilter),
|
||||
[nodeFilter, nodes],
|
||||
const nodes = useMemo(
|
||||
() => nodesQuery.data?.results ?? [],
|
||||
[nodesQuery.data],
|
||||
);
|
||||
const total = nodesQuery.data?.total ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
if (
|
||||
!nodesQuery.isPlaceholderData &&
|
||||
nodesQuery.data?.page === page &&
|
||||
page > totalPages
|
||||
) {
|
||||
setPage(totalPages);
|
||||
resetNodeActions();
|
||||
}
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async (payload: NodeMutationPayload) => {
|
||||
@@ -106,6 +172,7 @@ export function NodesPageClient() {
|
||||
};
|
||||
|
||||
const handleEdit = (node: NodeItem) => {
|
||||
if (nodesQuery.isPlaceholderData) return;
|
||||
setEditingNode(node);
|
||||
setEditorOpen(true);
|
||||
};
|
||||
@@ -115,7 +182,7 @@ export function NodesPageClient() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='py-6 px-1 space-y-6'>
|
||||
<div className='flex w-full flex-col gap-6 py-6 px-1'>
|
||||
<div className='flex items-center justify-between gap-3'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Server className='size-5 text-primary' />
|
||||
@@ -166,8 +233,34 @@ export function NodesPageClient() {
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-4'>
|
||||
<CardContent className='flex flex-col gap-4'>
|
||||
<NodeTypeFilter />
|
||||
<NodeListControls
|
||||
search={search}
|
||||
searchTooLong={searchTooLong}
|
||||
onSearchChange={setSearch}
|
||||
status={status}
|
||||
onStatusChange={(value) => {
|
||||
setStatus(value);
|
||||
setPage(1);
|
||||
resetNodeActions();
|
||||
}}
|
||||
page={nodesQuery.data?.page ?? page}
|
||||
pageSize={pageSize}
|
||||
onPageSizeChange={(value) => {
|
||||
setPageSize(value);
|
||||
setPage(1);
|
||||
resetNodeActions();
|
||||
}}
|
||||
total={total}
|
||||
totalPages={totalPages}
|
||||
loading={nodesQuery.isFetching || nodesQuery.isPlaceholderData}
|
||||
hasData={Boolean(nodesQuery.data)}
|
||||
onPageChange={(value) => {
|
||||
setPage(value);
|
||||
resetNodeActions();
|
||||
}}
|
||||
/>
|
||||
|
||||
{nodesQuery.isLoading ? (
|
||||
<LoadingStateWithBorder
|
||||
@@ -182,21 +275,26 @@ export function NodesPageClient() {
|
||||
className='justify-center'
|
||||
/>
|
||||
</div>
|
||||
) : filteredNodes.length === 0 ? (
|
||||
) : nodes.length === 0 ? (
|
||||
<EmptyStateWithBorder
|
||||
icon={Server}
|
||||
description={
|
||||
nodes.length === 0 ? t('emptyAll') : t('emptyFilter')
|
||||
debouncedSearch || status || nodeFilter !== 'all'
|
||||
? t('emptyFilter')
|
||||
: t('emptyAll')
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<NodesTable
|
||||
nodes={filteredNodes}
|
||||
nodes={nodes}
|
||||
deletingId={
|
||||
deleteMutation.isPending ? (deleteTarget?.id ?? null) : null
|
||||
}
|
||||
onEdit={handleEdit}
|
||||
onDelete={setDeleteTarget}
|
||||
onDelete={(node) => {
|
||||
if (!nodesQuery.isPlaceholderData) setDeleteTarget(node);
|
||||
}}
|
||||
actionsDisabled={nodesQuery.isPlaceholderData}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
@@ -205,13 +303,17 @@ export function NodesPageClient() {
|
||||
<NodeEditorDialog
|
||||
open={editorOpen}
|
||||
node={editingNode}
|
||||
submitting={saveMutation.isPending}
|
||||
submitting={
|
||||
saveMutation.isPending ||
|
||||
(Boolean(editingNode) && nodesQuery.isPlaceholderData)
|
||||
}
|
||||
onClose={() => {
|
||||
setEditorOpen(false);
|
||||
setEditingNode(null);
|
||||
}}
|
||||
onSubmit={async (payload) => {
|
||||
await saveMutation.mutateAsync(payload);
|
||||
if (!editingNode || !nodesQuery.isPlaceholderData)
|
||||
await saveMutation.mutateAsync(payload);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -227,14 +329,22 @@ export function NodesPageClient() {
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>
|
||||
<AlertDialogCancel
|
||||
disabled={
|
||||
deleteMutation.isPending || nodesQuery.isPlaceholderData
|
||||
}
|
||||
>
|
||||
{tc('cancel')}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className='bg-destructive text-white hover:bg-destructive/90'
|
||||
disabled={deleteMutation.isPending}
|
||||
disabled={
|
||||
deleteMutation.isPending || nodesQuery.isPlaceholderData
|
||||
}
|
||||
onClick={() =>
|
||||
deleteTarget && deleteMutation.mutate(deleteTarget.id)
|
||||
deleteTarget &&
|
||||
!nodesQuery.isPlaceholderData &&
|
||||
deleteMutation.mutate(deleteTarget.id)
|
||||
}
|
||||
>
|
||||
{deleteMutation.isPending ? t('deleting') : t('confirmDelete')}
|
||||
|
||||
@@ -38,6 +38,8 @@ export type {
|
||||
NodeAgentUpdatePayload,
|
||||
NodeBootstrapToken,
|
||||
NodeItem,
|
||||
NodeListQuery,
|
||||
NodeListResult,
|
||||
NodeMutationPayload,
|
||||
NodeHealthEvent,
|
||||
NodeObservability,
|
||||
|
||||
@@ -4,6 +4,8 @@ import type {
|
||||
NodeAgentUpdatePayload,
|
||||
NodeBootstrapToken,
|
||||
NodeItem,
|
||||
NodeListQuery,
|
||||
NodeListResult,
|
||||
NodeMutationPayload,
|
||||
NodeObservability,
|
||||
ReleaseChannel,
|
||||
@@ -16,6 +18,16 @@ export class NodeService extends OpenFlareBaseService {
|
||||
return this.get<NodeItem[]>('/');
|
||||
}
|
||||
|
||||
static async listNodePage(
|
||||
query: NodeListQuery = {},
|
||||
): Promise<NodeListResult> {
|
||||
return this.get<NodeListResult>('/page', { ...query });
|
||||
}
|
||||
|
||||
static async getNode(id: number): Promise<NodeItem> {
|
||||
return this.get<NodeItem>(`/${id}`);
|
||||
}
|
||||
|
||||
static async createNode(payload: NodeMutationPayload): Promise<NodeItem> {
|
||||
return this.post<NodeItem>('/', payload);
|
||||
}
|
||||
|
||||
@@ -56,6 +56,21 @@ export interface NodeItem {
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface NodeListQuery {
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
search?: string;
|
||||
status?: NodeStatus | '';
|
||||
node_type?: NodeType | '';
|
||||
}
|
||||
|
||||
export interface NodeListResult {
|
||||
total: number;
|
||||
results: NodeItem[];
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
export interface NodeBootstrapToken {
|
||||
discovery_token: string;
|
||||
}
|
||||
|
||||
@@ -120,6 +120,17 @@
|
||||
}
|
||||
},
|
||||
"nodes": {
|
||||
"pagination": {
|
||||
"search": "Search nodes",
|
||||
"searchPlaceholder": "Name, node ID or IP",
|
||||
"searchTooLong": "Search text is too long. Shorten it to continue.",
|
||||
"allStatuses": "All statuses",
|
||||
"pageSize": "Per page",
|
||||
"summary": "Page {page} of {totalPages} · {total} nodes",
|
||||
"navigation": "Node pages",
|
||||
"previous": "Previous",
|
||||
"next": "Next"
|
||||
},
|
||||
"title": "Nodes",
|
||||
"applyLogs": "Apply logs",
|
||||
"create": "Add node",
|
||||
|
||||
@@ -120,6 +120,17 @@
|
||||
}
|
||||
},
|
||||
"nodes": {
|
||||
"pagination": {
|
||||
"search": "搜索节点",
|
||||
"searchPlaceholder": "名称、节点标识或 IP",
|
||||
"searchTooLong": "搜索内容过长,请缩短后重试。",
|
||||
"allStatuses": "全部状态",
|
||||
"pageSize": "每页数量",
|
||||
"summary": "第 {page} / {totalPages} 页 · 共 {total} 个节点",
|
||||
"navigation": "节点分页",
|
||||
"previous": "上一页",
|
||||
"next": "下一页"
|
||||
},
|
||||
"title": "节点管理",
|
||||
"applyLogs": "应用记录",
|
||||
"create": "新增节点",
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import {
|
||||
act,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react';
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
|
||||
|
||||
import { NodesPageClient } from '@/app/(main)/nodes/page-client';
|
||||
import { NodeDetailPageClient } from '@/app/(main)/nodes/detail/page-client';
|
||||
import { NodeService, type NodeItem } from '@/lib/services/openflare';
|
||||
import en from '@/messages/en.json';
|
||||
|
||||
let params = new URLSearchParams();
|
||||
vi.mock('next/navigation', () => ({ useSearchParams: () => params }));
|
||||
vi.mock('@/lib/services/openflare', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/lib/services/openflare')>()),
|
||||
NodeService: {
|
||||
listNodePage: vi.fn(),
|
||||
listNodes: vi.fn(),
|
||||
getNode: vi.fn(),
|
||||
deleteNode: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('@/app/(main)/nodes/components/node-editor-dialog', () => ({
|
||||
NodeEditorDialog: () => null,
|
||||
}));
|
||||
vi.mock('@/app/(main)/nodes/components/edge-node-detail', () => ({
|
||||
EdgeNodeDetail: ({ node }: { node: NodeItem }) => (
|
||||
<div>Node detail {node.id}</div>
|
||||
),
|
||||
}));
|
||||
vi.mock('@/app/(main)/nodes/components/relay-node-detail', () => ({
|
||||
RelayNodeDetail: () => null,
|
||||
}));
|
||||
vi.mock('@/app/(main)/nodes/components/tunnel-node-detail', () => ({
|
||||
TunnelNodeDetail: () => null,
|
||||
}));
|
||||
|
||||
function node(id: number): NodeItem {
|
||||
return { id, name: `Edge ${id}`, node_type: 'edge_node' } as NodeItem;
|
||||
}
|
||||
function renderPage(detail = false) {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: 0 } },
|
||||
});
|
||||
const result = render(
|
||||
<NextIntlClientProvider locale='en' messages={en} timeZone='UTC'>
|
||||
<QueryClientProvider client={client}>
|
||||
{detail ? <NodeDetailPageClient /> : <NodesPageClient />}
|
||||
</QueryClientProvider>
|
||||
</NextIntlClientProvider>,
|
||||
);
|
||||
return { ...result, client };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
params = new URLSearchParams();
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(NodeService.listNodePage).mockImplementation(
|
||||
async (query = {}) => ({
|
||||
page: query.page ?? 1,
|
||||
page_size: query.page_size ?? 20,
|
||||
total: 41,
|
||||
results: [node(query.page ?? 1)],
|
||||
}),
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('fetches only visible pages and debounces server search while resetting the page', async () => {
|
||||
renderPage();
|
||||
await screen.findByText('Edge 1');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
|
||||
await screen.findByText('Edge 2');
|
||||
expect(NodeService.listNodePage).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ page: 2, page_size: 20 }),
|
||||
);
|
||||
expect(NodeService.listNodes).not.toHaveBeenCalled();
|
||||
fireEvent.change(screen.getByLabelText('Search nodes'), {
|
||||
target: { value: 'test' },
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(NodeService.listNodePage).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ page: 1, search: 'test' }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('refetches the previous valid page after deleting the only node on the last page', async () => {
|
||||
let deleted = false;
|
||||
vi.mocked(NodeService.listNodePage).mockImplementation(
|
||||
async (query = {}) => ({
|
||||
page: query.page ?? 1,
|
||||
page_size: 20,
|
||||
total: deleted ? 20 : 21,
|
||||
results:
|
||||
deleted && query.page === 2 ? [] : [node(query.page === 2 ? 21 : 1)],
|
||||
}),
|
||||
);
|
||||
vi.mocked(NodeService.deleteNode).mockImplementation(async () => {
|
||||
deleted = true;
|
||||
});
|
||||
renderPage();
|
||||
await screen.findByText('Edge 1');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
|
||||
await screen.findByText('Edge 21');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
fireEvent.click(
|
||||
within(await screen.findByRole('alertdialog')).getByRole('button', {
|
||||
name: 'Delete',
|
||||
}),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(NodeService.listNodePage).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ page: 1 }),
|
||||
),
|
||||
);
|
||||
await screen.findByText('Edge 1');
|
||||
});
|
||||
|
||||
it('resets the page immediately when the URL node type changes', async () => {
|
||||
const page = renderPage();
|
||||
await screen.findByText('Edge 1');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
|
||||
await screen.findByText('Edge 2');
|
||||
params = new URLSearchParams('filter=relay');
|
||||
page.rerender(
|
||||
<NextIntlClientProvider locale='en' messages={en} timeZone='UTC'>
|
||||
<QueryClientProvider client={page.client}>
|
||||
<NodesPageClient />
|
||||
</QueryClientProvider>
|
||||
</NextIntlClientProvider>,
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(NodeService.listNodePage).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ page: 1, node_type: 'tunnel_relay' }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps page errors retryable through refresh', async () => {
|
||||
vi.mocked(NodeService.listNodePage).mockRejectedValueOnce(
|
||||
new Error('temporary failure'),
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByText('temporary failure');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Refresh now' }));
|
||||
await screen.findByText('Edge 1');
|
||||
});
|
||||
|
||||
it('fetches one detail and refetches it on shared node invalidation', async () => {
|
||||
params = new URLSearchParams('id=42');
|
||||
vi.mocked(NodeService.getNode).mockResolvedValue(node(42));
|
||||
const { client } = renderPage(true);
|
||||
await screen.findByText('Node detail 42');
|
||||
expect(NodeService.getNode).toHaveBeenCalledWith(42);
|
||||
expect(NodeService.listNodes).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
await client.invalidateQueries({ queryKey: ['openflare', 'nodes'] });
|
||||
});
|
||||
expect(NodeService.getNode).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason: Error) => void;
|
||||
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
|
||||
resolve = resolvePromise;
|
||||
reject = rejectPromise;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
it('validates the UTF-8 search limit before requesting and recovers after shortening', async () => {
|
||||
renderPage();
|
||||
await screen.findByText('Edge 1');
|
||||
const input = screen.getByLabelText('Search nodes');
|
||||
for (const search of ['a'.repeat(256), '汉'.repeat(85) + 'a']) {
|
||||
fireEvent.change(input, { target: { value: search } });
|
||||
await waitFor(() =>
|
||||
expect(NodeService.listNodePage).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ search }),
|
||||
),
|
||||
);
|
||||
}
|
||||
const calls = vi.mocked(NodeService.listNodePage).mock.calls.length;
|
||||
fireEvent.change(input, { target: { value: '汉'.repeat(86) } });
|
||||
expect(input).toHaveAttribute('aria-invalid', 'true');
|
||||
expect(screen.getByRole('alert')).toHaveTextContent(
|
||||
'Search text is too long',
|
||||
);
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 350));
|
||||
});
|
||||
expect(NodeService.listNodePage).toHaveBeenCalledTimes(calls);
|
||||
fireEvent.change(input, { target: { value: 'short' } });
|
||||
await waitFor(() =>
|
||||
expect(NodeService.listNodePage).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ search: 'short' }),
|
||||
),
|
||||
);
|
||||
expect(input).not.toHaveAttribute('aria-invalid');
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('retains the loaded page and total during navigation without leaving stale node actions', async () => {
|
||||
const pending =
|
||||
deferred<Awaited<ReturnType<typeof NodeService.listNodePage>>>();
|
||||
vi.mocked(NodeService.listNodePage).mockImplementation(async (query = {}) =>
|
||||
query.page === 2
|
||||
? pending.promise
|
||||
: { page: 1, page_size: 20, total: 41, results: [node(1)] },
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByText('Edge 1');
|
||||
expect(screen.getByRole('link', { name: 'Details' })).toHaveAttribute(
|
||||
'href',
|
||||
'/nodes/detail?id=1',
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('button', { name: 'Edit' })).toBeDisabled(),
|
||||
);
|
||||
expect(screen.getByText('Edge 1')).toBeInTheDocument();
|
||||
expect(screen.getByText('Page 1 of 3 · 41 nodes')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Delete' })).toBeDisabled();
|
||||
expect(screen.getByRole('button', { name: 'Details' })).toBeDisabled();
|
||||
expect(
|
||||
screen.queryByRole('link', { name: 'Details' }),
|
||||
).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
|
||||
expect(NodeService.deleteNode).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
pending.resolve({ page: 2, page_size: 20, total: 41, results: [node(2)] });
|
||||
});
|
||||
await screen.findByText('Edge 2');
|
||||
expect(screen.queryByText('Edge 1')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Page 2 of 3 · 41 nodes')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Edit' })).toBeEnabled();
|
||||
expect(screen.getByRole('link', { name: 'Details' })).toHaveAttribute(
|
||||
'href',
|
||||
'/nodes/detail?id=2',
|
||||
);
|
||||
});
|
||||
|
||||
it('does not reuse nodes or totals from a different search while it is loading', async () => {
|
||||
const pending =
|
||||
deferred<Awaited<ReturnType<typeof NodeService.listNodePage>>>();
|
||||
vi.mocked(NodeService.listNodePage).mockImplementation(async (query = {}) =>
|
||||
query.search
|
||||
? pending.promise
|
||||
: { page: 1, page_size: 20, total: 41, results: [node(1)] },
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByText('Edge 1');
|
||||
fireEvent.change(screen.getByLabelText('Search nodes'), {
|
||||
target: { value: 'another' },
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(NodeService.listNodePage).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ search: 'another' }),
|
||||
),
|
||||
);
|
||||
expect(screen.queryByText('Edge 1')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Page 1 of 3 · 41 nodes')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('link', { name: 'Details' }),
|
||||
).not.toBeInTheDocument();
|
||||
await act(async () => {
|
||||
pending.resolve({ page: 1, page_size: 20, total: 1, results: [node(9)] });
|
||||
});
|
||||
await screen.findByText('Edge 9');
|
||||
expect(screen.getByText('Page 1 of 1 · 1 nodes')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('drops placeholder actions and unknown totals after a failed page request and allows retry', async () => {
|
||||
const pending =
|
||||
deferred<Awaited<ReturnType<typeof NodeService.listNodePage>>>();
|
||||
vi.mocked(NodeService.listNodePage).mockImplementation(async (query = {}) =>
|
||||
query.page === 2
|
||||
? pending.promise
|
||||
: { page: 1, page_size: 20, total: 41, results: [node(1)] },
|
||||
);
|
||||
renderPage();
|
||||
await screen.findByText('Edge 1');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('button', { name: 'Edit' })).toBeDisabled(),
|
||||
);
|
||||
await act(async () => {
|
||||
pending.reject(new Error('page request failed'));
|
||||
});
|
||||
await screen.findByText('page request failed');
|
||||
expect(screen.queryByText('Edge 1')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/Page [0-9]+ of/)).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Delete' }),
|
||||
).not.toBeInTheDocument();
|
||||
vi.mocked(NodeService.listNodePage).mockResolvedValue({
|
||||
page: 2,
|
||||
page_size: 20,
|
||||
total: 41,
|
||||
results: [node(2)],
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Refresh now' }));
|
||||
await screen.findByText('Edge 2');
|
||||
expect(screen.getByText('Page 2 of 3 · 41 nodes')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('closes an open node confirmation when a background refresh clamps a depleted page', async () => {
|
||||
let removed = false;
|
||||
vi.mocked(NodeService.listNodePage).mockImplementation(
|
||||
async (query = {}) => ({
|
||||
page: query.page ?? 1,
|
||||
page_size: 20,
|
||||
total: removed ? 20 : 21,
|
||||
results:
|
||||
removed && query.page === 2 ? [] : [node(query.page === 2 ? 21 : 1)],
|
||||
}),
|
||||
);
|
||||
const { client } = renderPage();
|
||||
await screen.findByText('Edge 1');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next' }));
|
||||
await screen.findByText('Edge 21');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
|
||||
await screen.findByRole('alertdialog');
|
||||
removed = true;
|
||||
await act(async () => {
|
||||
await client.invalidateQueries({ queryKey: ['openflare', 'nodes'] });
|
||||
});
|
||||
await screen.findByText('Edge 1');
|
||||
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
|
||||
expect(NodeService.deleteNode).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { AxiosResponse } from 'axios';
|
||||
import { beforeEach, expect, it, vi } from 'vitest';
|
||||
import apiClient from '@/lib/services/core/api-client';
|
||||
import { NodeService } from '@/lib/services/openflare/node.service';
|
||||
|
||||
vi.mock('@/lib/services/core/api-client', () => ({
|
||||
default: { get: vi.fn() },
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(apiClient.get).mockReset();
|
||||
});
|
||||
|
||||
it('keeps legacy arrays and requests bounded pages and individual details separately', async () => {
|
||||
vi.mocked(apiClient.get).mockResolvedValue({
|
||||
data: { error_msg: '', data: [] },
|
||||
} as AxiosResponse);
|
||||
await NodeService.listNodes();
|
||||
expect(apiClient.get).toHaveBeenLastCalledWith(
|
||||
'/api/v1/d/nodes/',
|
||||
expect.objectContaining({ params: undefined }),
|
||||
);
|
||||
await NodeService.listNodePage({
|
||||
page: 2,
|
||||
page_size: 20,
|
||||
status: 'online',
|
||||
node_type: 'tunnel_relay',
|
||||
search: 'edge',
|
||||
});
|
||||
expect(apiClient.get).toHaveBeenLastCalledWith(
|
||||
'/api/v1/d/nodes/page',
|
||||
expect.objectContaining({
|
||||
params: {
|
||||
page: 2,
|
||||
page_size: 20,
|
||||
status: 'online',
|
||||
node_type: 'tunnel_relay',
|
||||
search: 'edge',
|
||||
},
|
||||
}),
|
||||
);
|
||||
await NodeService.getNode(42);
|
||||
expect(apiClient.get).toHaveBeenLastCalledWith(
|
||||
'/api/v1/d/nodes/42',
|
||||
expect.objectContaining({ params: undefined }),
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user