mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-11-16 14:54:23 +08:00
feat(cloudflare): 支持分组级自动与手动 TTL 配置 (#62)
This commit is contained in:
@@ -12,7 +12,13 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field';
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
@@ -64,6 +70,12 @@ export function GroupDialog({
|
||||
const [backupNodeID, setBackupNodeID] = useState('none');
|
||||
const [defaultProxied, setDefaultProxied] = useState(true);
|
||||
const [enabled, setEnabled] = useState(true);
|
||||
const [ttlMode, setTtlMode] = useState<'auto' | 'manual'>('auto');
|
||||
const [manualTTL, setManualTTL] = useState('300');
|
||||
const ttl = ttlMode === 'auto' ? 1 : Number(manualTTL);
|
||||
const invalidTTL =
|
||||
ttlMode === 'manual' &&
|
||||
(!manualTTL.trim() || !Number.isInteger(ttl) || ttl < 60 || ttl > 86400);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -83,6 +95,9 @@ export function GroupDialog({
|
||||
);
|
||||
setDefaultProxied(group?.default_proxied ?? true);
|
||||
setEnabled(group?.enabled ?? true);
|
||||
const groupTTL = group ? (group.ttl ?? 300) : 1;
|
||||
setTtlMode(groupTTL === 1 ? 'auto' : 'manual');
|
||||
setManualTTL(String(groupTTL === 1 ? 300 : groupTTL));
|
||||
}, [group, open]);
|
||||
|
||||
return (
|
||||
@@ -209,6 +224,54 @@ export function GroupDialog({
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
<Field>
|
||||
<FieldLabel id='cf-ttl-mode-label'>{t('ttl')}</FieldLabel>
|
||||
<ToggleGroup
|
||||
type='single'
|
||||
variant='outline'
|
||||
value={ttlMode}
|
||||
aria-labelledby='cf-ttl-mode-label'
|
||||
aria-describedby='cf-ttl-hint'
|
||||
className='grid w-full grid-cols-2'
|
||||
onValueChange={(value) => {
|
||||
if (value === 'auto' || value === 'manual') {
|
||||
setTtlMode(value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ToggleGroupItem value='auto' className='w-full'>
|
||||
{t('ttlAuto')}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value='manual' className='w-full'>
|
||||
{t('ttlManual')}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
<FieldDescription id='cf-ttl-hint'>{t('ttlHint')}</FieldDescription>
|
||||
</Field>
|
||||
{ttlMode === 'manual' && (
|
||||
<Field data-invalid={invalidTTL}>
|
||||
<FieldLabel htmlFor='cf-ttl-seconds'>
|
||||
{t('ttlSeconds')}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id='cf-ttl-seconds'
|
||||
type='number'
|
||||
min={60}
|
||||
max={86400}
|
||||
step={1}
|
||||
required
|
||||
value={manualTTL}
|
||||
aria-invalid={invalidTTL}
|
||||
aria-describedby={
|
||||
invalidTTL ? 'cf-ttl-hint cf-ttl-error' : 'cf-ttl-hint'
|
||||
}
|
||||
onChange={(event) => setManualTTL(event.target.value)}
|
||||
/>
|
||||
{invalidTTL && (
|
||||
<FieldError id='cf-ttl-error'>{t('ttlError')}</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
)}
|
||||
<Field orientation='horizontal'>
|
||||
<FieldLabel htmlFor='cf-default-proxied'>
|
||||
{t('defaultProxied')}
|
||||
@@ -235,10 +298,12 @@ export function GroupDialog({
|
||||
<Button
|
||||
disabled={
|
||||
pending ||
|
||||
invalidTTL ||
|
||||
!name.trim() ||
|
||||
(targetMode === 'node' ? !primaryNodeID : !recordContent.trim())
|
||||
}
|
||||
onClick={() =>
|
||||
onClick={() => {
|
||||
if (invalidTTL) return;
|
||||
onSubmit({
|
||||
name: name.trim(),
|
||||
target_mode: targetMode,
|
||||
@@ -251,9 +316,10 @@ export function GroupDialog({
|
||||
? Number(backupNodeID)
|
||||
: null,
|
||||
default_proxied: defaultProxied,
|
||||
ttl,
|
||||
enabled,
|
||||
})
|
||||
}
|
||||
});
|
||||
}}
|
||||
>
|
||||
{t('save')}
|
||||
</Button>
|
||||
|
||||
@@ -371,6 +371,11 @@ export function CloudflareGroupDetailPageClient() {
|
||||
: 'nodeTargetMode',
|
||||
)}
|
||||
</Badge>
|
||||
<Badge variant='outline'>
|
||||
{group.ttl === 1
|
||||
? t('ttlAutoSummary')
|
||||
: t('ttlSecondsSummary', { seconds: group.ttl ?? 300 })}
|
||||
</Badge>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -1390,6 +1390,8 @@ export interface CloudflareGroup {
|
||||
primary_node: CloudflareNodeOption;
|
||||
backup_node: CloudflareNodeOption | null;
|
||||
active_node: CloudflareNodeOption;
|
||||
/** 1 表示自动,手动 TTL 为 60..86400 秒。 */
|
||||
ttl: number;
|
||||
default_proxied: boolean;
|
||||
enabled: boolean;
|
||||
member_count: number;
|
||||
@@ -1404,6 +1406,8 @@ export interface CloudflareGroupPayload {
|
||||
record_content: string;
|
||||
primary_node_id: number;
|
||||
backup_node_id: number | null;
|
||||
/** 省略时保留旧调用方行为;1 表示自动,手动为 60..86400 秒。 */
|
||||
ttl?: number;
|
||||
default_proxied: boolean;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"cloudflare": {
|
||||
"ttlAutoSummary": "DNS-only TTL: Auto (about 300 seconds)",
|
||||
"ttlSecondsSummary": "DNS-only TTL: {seconds} seconds",
|
||||
"groupDialog": {
|
||||
"ttl": "Group TTL",
|
||||
"ttlAuto": "Auto",
|
||||
"ttlManual": "Manual",
|
||||
"ttlSeconds": "TTL (seconds)",
|
||||
"ttlHint": "Changes apply to all DNS-only (gray-cloud) members in this group; proxied (orange-cloud) members always use Auto. Auto is currently about 300 seconds.",
|
||||
"ttlError": "Enter a whole number of seconds between 60 and 86400."
|
||||
},
|
||||
"move": "Move",
|
||||
"batchMove": "Batch Move",
|
||||
"batchRemove": "Batch Delete",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"cloudflare": {
|
||||
"ttlAutoSummary": "TTL только DNS: авто (около 300 секунд)",
|
||||
"ttlSecondsSummary": "TTL только DNS: {seconds} сек.",
|
||||
"groupDialog": {
|
||||
"ttl": "TTL группы",
|
||||
"ttlAuto": "Авто",
|
||||
"ttlManual": "Вручную",
|
||||
"ttlSeconds": "TTL (секунды)",
|
||||
"ttlHint": "Изменения применяются ко всем участникам группы в режиме «только DNS» (серое облако); для проксируемых записей (оранжевое облако) TTL всегда автоматический. Сейчас Auto — около 300 секунд.",
|
||||
"ttlError": "Введите целое число секунд от 60 до 86400."
|
||||
},
|
||||
"move": "Переместить",
|
||||
"batchMove": "Пакетное перемещение",
|
||||
"batchRemove": "Пакетное удаление",
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
{
|
||||
"cloudflare": {
|
||||
"ttlAutoSummary": "灰云 TTL:自动(约 300 秒)",
|
||||
"ttlSecondsSummary": "灰云 TTL:{seconds} 秒",
|
||||
"groupDialog": {
|
||||
"ttl": "分组 TTL",
|
||||
"ttlAuto": "自动",
|
||||
"ttlManual": "手动",
|
||||
"ttlSeconds": "TTL(秒)",
|
||||
"ttlHint": "修改将应用于分组内所有灰云(仅 DNS)成员;橙云始终自动。Auto 当前约为 300 秒。",
|
||||
"ttlError": "请输入 60 至 86400 之间的整数秒数。"
|
||||
},
|
||||
"move": "移动",
|
||||
"batchMove": "批量移动",
|
||||
"batchRemove": "批量删除",
|
||||
|
||||
@@ -63,6 +63,7 @@ const mockGroup = {
|
||||
primary_node: { id: 1, name: '主节点', ip: '192.0.2.1' },
|
||||
backup_node: null,
|
||||
active_node: { id: 1, name: '主节点', ip: '192.0.2.1' },
|
||||
ttl: 300,
|
||||
default_proxied: true,
|
||||
enabled: true,
|
||||
member_count: 2,
|
||||
@@ -79,6 +80,7 @@ const mockTargetGroup = {
|
||||
primary_node: { id: 2, name: '备用节点', ip: '192.0.2.2' },
|
||||
backup_node: null,
|
||||
active_node: { id: 2, name: '备用节点', ip: '192.0.2.2' },
|
||||
ttl: 1,
|
||||
default_proxied: false,
|
||||
enabled: true,
|
||||
member_count: 0,
|
||||
@@ -171,6 +173,21 @@ describe('Cloudflare group detail refresh', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ ttl: 1, label: '灰云 TTL:自动(约 300 秒)' },
|
||||
{ ttl: 600, label: '灰云 TTL:600 秒' },
|
||||
])(
|
||||
'shows the group TTL $ttl in the detail summary',
|
||||
async ({ ttl, label }) => {
|
||||
vi.mocked(CloudflareService.getGroup).mockResolvedValue({
|
||||
group: { ...mockGroup, ttl },
|
||||
members: [],
|
||||
});
|
||||
renderPage();
|
||||
expect(await screen.findByText(label)).toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
it('refreshes detail data when the refresh button is clicked', async () => {
|
||||
renderPage();
|
||||
|
||||
|
||||
@@ -115,6 +115,7 @@ describe('Cloudflare overview', () => {
|
||||
primary_node: { id: 1, name: '主节点', ip: '192.0.2.1' },
|
||||
backup_node: null,
|
||||
active_node: { id: 1, name: '主节点', ip: '192.0.2.1' },
|
||||
ttl: 300,
|
||||
default_proxied: true,
|
||||
enabled: true,
|
||||
member_count: 2,
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { GroupDialog } from '@/app/(main)/cloudflare/components/group-dialog';
|
||||
import type { CloudflareGroup } from '@/lib/services/openflare';
|
||||
import zhCN from '@/messages/zh-CN.json';
|
||||
|
||||
const node = { id: 1, name: '主节点', ip: '192.0.2.1' };
|
||||
const group: CloudflareGroup = {
|
||||
id: 7,
|
||||
name: '生产节点',
|
||||
target_mode: 'node',
|
||||
record_type: 'A',
|
||||
record_content: '',
|
||||
primary_node: node,
|
||||
backup_node: null,
|
||||
active_node: node,
|
||||
ttl: 900,
|
||||
default_proxied: true,
|
||||
enabled: true,
|
||||
member_count: 2,
|
||||
created_at: '',
|
||||
updated_at: '',
|
||||
};
|
||||
|
||||
function renderDialog(
|
||||
overrides: Partial<ComponentProps<typeof GroupDialog>> = {},
|
||||
) {
|
||||
const props: ComponentProps<typeof GroupDialog> = {
|
||||
open: true,
|
||||
onOpenChange: vi.fn(),
|
||||
nodes: [],
|
||||
pending: false,
|
||||
onSubmit: vi.fn(),
|
||||
...overrides,
|
||||
};
|
||||
const view = (nextProps: ComponentProps<typeof GroupDialog>) => (
|
||||
<NextIntlClientProvider
|
||||
locale='zh-CN'
|
||||
messages={zhCN}
|
||||
timeZone='Asia/Shanghai'
|
||||
>
|
||||
<GroupDialog {...nextProps} />
|
||||
</NextIntlClientProvider>
|
||||
);
|
||||
const result = render(view(props));
|
||||
return {
|
||||
...props,
|
||||
rerenderDialog: (nextProps: Partial<ComponentProps<typeof GroupDialog>>) =>
|
||||
result.rerender(view({ ...props, ...nextProps })),
|
||||
};
|
||||
}
|
||||
|
||||
function fillCustomTarget() {
|
||||
fireEvent.change(screen.getByLabelText('分组名称'), {
|
||||
target: { value: '自定义分组' },
|
||||
});
|
||||
fireEvent.click(screen.getByRole('radio', { name: '自定义' }));
|
||||
fireEvent.change(screen.getByLabelText('记录值'), {
|
||||
target: { value: '192.0.2.10' },
|
||||
});
|
||||
}
|
||||
|
||||
function manualInput() {
|
||||
return screen.getByRole('spinbutton', { name: 'TTL(秒)' });
|
||||
}
|
||||
|
||||
function save() {
|
||||
fireEvent.click(screen.getByRole('button', { name: '保存' }));
|
||||
}
|
||||
|
||||
describe('Cloudflare group TTL', () => {
|
||||
it('defaults new groups to Auto and sends ttl=1', () => {
|
||||
const { onSubmit } = renderDialog();
|
||||
expect(screen.getByRole('radiogroup', { name: '分组 TTL' })).toBeVisible();
|
||||
expect(screen.getByRole('radio', { name: '自动' })).toBeChecked();
|
||||
expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/Auto 当前约为 300 秒/)).toBeVisible();
|
||||
|
||||
fillCustomTarget();
|
||||
save();
|
||||
expect(onSubmit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ target_mode: 'custom', ttl: 1 }),
|
||||
);
|
||||
});
|
||||
|
||||
it.each(['node', 'custom'] as const)(
|
||||
'saves a manual TTL for a %s target even when default_proxied is enabled',
|
||||
(targetMode) => {
|
||||
const { onSubmit } = renderDialog({
|
||||
group: {
|
||||
...group,
|
||||
target_mode: targetMode,
|
||||
record_content: targetMode === 'custom' ? '192.0.2.10' : '',
|
||||
},
|
||||
});
|
||||
expect(
|
||||
screen.getByRole('switch', { name: '新成员默认开启橙云' }),
|
||||
).toBeChecked();
|
||||
expect(screen.getByRole('radio', { name: '手动' })).toBeChecked();
|
||||
expect(manualInput()).toHaveValue(900);
|
||||
expect(manualInput()).toBeEnabled();
|
||||
fireEvent.change(manualInput(), { target: { value: '600' } });
|
||||
save();
|
||||
expect(onSubmit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
target_mode: targetMode,
|
||||
ttl: 600,
|
||||
default_proxied: true,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('allows a new custom group to save a manual TTL', () => {
|
||||
const { onSubmit } = renderDialog();
|
||||
fillCustomTarget();
|
||||
fireEvent.click(screen.getByRole('radio', { name: '手动' }));
|
||||
fireEvent.change(manualInput(), { target: { value: '1200' } });
|
||||
save();
|
||||
expect(onSubmit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ target_mode: 'custom', ttl: 1200 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('reflects Auto on edit and does not allow deselecting it', () => {
|
||||
const { onSubmit } = renderDialog({ group: { ...group, ttl: 1 } });
|
||||
fireEvent.click(screen.getByRole('radio', { name: '自动' }));
|
||||
expect(screen.getByRole('radio', { name: '自动' })).toBeChecked();
|
||||
expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument();
|
||||
save();
|
||||
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ ttl: 1 }));
|
||||
});
|
||||
|
||||
it.each(['', '60.5', '59', '86401', '0', '-1'])(
|
||||
'rejects invalid manual TTL %j with an accessible error',
|
||||
(value) => {
|
||||
const { onSubmit } = renderDialog({ group });
|
||||
fireEvent.change(manualInput(), { target: { value } });
|
||||
expect(manualInput()).toHaveAttribute('aria-invalid', 'true');
|
||||
expect(manualInput()).toHaveAccessibleDescription(
|
||||
/请输入 60 至 86400 之间的整数秒数/,
|
||||
);
|
||||
expect(screen.getByRole('alert')).toHaveTextContent(
|
||||
'请输入 60 至 86400 之间的整数秒数。',
|
||||
);
|
||||
expect(screen.getByRole('button', { name: '保存' })).toBeDisabled();
|
||||
save();
|
||||
expect(onSubmit).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([60, 86400])(
|
||||
'accepts the inclusive manual TTL boundary %i',
|
||||
(ttl) => {
|
||||
const { onSubmit } = renderDialog({ group });
|
||||
fireEvent.change(manualInput(), { target: { value: String(ttl) } });
|
||||
expect(manualInput()).toHaveAttribute('aria-invalid', 'false');
|
||||
save();
|
||||
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ ttl }));
|
||||
},
|
||||
);
|
||||
|
||||
it('switches invalid manual input to Auto and sends 1 without stale errors', () => {
|
||||
const { onSubmit } = renderDialog({ group });
|
||||
fireEvent.change(manualInput(), { target: { value: '' } });
|
||||
expect(screen.getByRole('alert')).toBeVisible();
|
||||
fireEvent.click(screen.getByRole('radio', { name: '自动' }));
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument();
|
||||
save();
|
||||
expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining({ ttl: 1 }));
|
||||
});
|
||||
|
||||
it('resets a new group to Auto after closing and reopening', () => {
|
||||
const { rerenderDialog, onOpenChange } = renderDialog();
|
||||
fireEvent.click(screen.getByRole('radio', { name: '手动' }));
|
||||
fireEvent.change(manualInput(), { target: { value: '' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '取消' }));
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
rerenderDialog({ open: false });
|
||||
rerenderDialog({ open: true });
|
||||
expect(screen.getByRole('radio', { name: '自动' })).toBeChecked();
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('radio', { name: '手动' }));
|
||||
expect(manualInput()).toHaveValue(300);
|
||||
});
|
||||
|
||||
it('restores saved TTL after reopening and reflects a different group', () => {
|
||||
const { rerenderDialog } = renderDialog({ group });
|
||||
fireEvent.change(manualInput(), { target: { value: '600' } });
|
||||
rerenderDialog({ open: false });
|
||||
rerenderDialog({ open: true });
|
||||
expect(manualInput()).toHaveValue(900);
|
||||
rerenderDialog({ group: { ...group, id: 8, ttl: 1800 } });
|
||||
expect(manualInput()).toHaveValue(1800);
|
||||
rerenderDialog({ group: { ...group, id: 9, ttl: 1 } });
|
||||
expect(screen.getByRole('radio', { name: '自动' })).toBeChecked();
|
||||
expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses 300 seconds for legacy responses without ttl', () => {
|
||||
const { ttl: _ttl, ...legacyGroup } = group;
|
||||
const { onSubmit } = renderDialog({
|
||||
group: legacyGroup as CloudflareGroup,
|
||||
});
|
||||
expect(manualInput()).toHaveValue(300);
|
||||
save();
|
||||
expect(onSubmit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ ttl: 300 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user