- {dataSource.length === 0 ? (
-
- ) : (
- dataSource.map((record) =>
- record.transitive ? (
-
-
-
-
-
{record.name}
-
- } style={{ margin: 0 }}>
- {t('pages.nodes.subNode')}
-
-
-
-
- ) : (
-
- {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events -- mouse click-to-expand mirrors the keyboard-accessible chevron disclosure button */}
-
{
- if (!(e.target as HTMLElement).closest('.card-actions'))
- toggleExpanded(record.id);
- }}
- >
-
toggleExpanded(record.id))}
- />
-
- {record.name}
-
-
- setStatsNodeId(record.id)}
- onKeyDown={activateOnKey(() => setStatsNodeId(record.id))}
- />
-
- onToggleEnable(record, v)}
- />
-
- {t('pages.nodes.probe')}
- >
- ),
- onClick: () => onProbe(record),
- },
- ...(isUpdateEligible(record)
- ? [
- {
- key: 'update',
- label: (
- <>
- {' '}
- {t('pages.nodes.updatePanel')}
- >
- ),
- onClick: () => onUpdateNode(record),
- },
- ]
- : []),
- {
- key: 'edit',
- label: (
- <>
- {t('edit')}
- >
- ),
- onClick: () => onEdit(record),
- },
- {
- key: 'delete',
- danger: true,
- label: (
- <>
- {t('delete')}
- >
- ),
- onClick: () => onDelete(record),
- },
- ],
- }}
- >
- }
- aria-label={t('more')}
- />
-
-
-
-
- {expandedIds.has(record.id) && (
-
-
-
- )}
-
- ),
- )
- )}
+
+
+
+ {table}
+
+ {hasNodes && (
+
+
+ {t('pages.nodes.fleet.footnote', {
+ coverage: summary
+ ? summary.reporting + '/' + summary.registered
+ : rows.some((row) => row.kind === 'master' && reportingSample(row.telemetry))
+ ? '1/1'
+ : '0/1',
+ })}
+
+
+ :
+ }
+ onClick={() => setShowAddress((visible) => !visible)}
+ />
+
-
- setStatsNodeId(null)}
- >
- {statsNode && (
-
- {statsNode.remark && (
-
- {t('pages.nodes.name')}
- {statsNode.remark}
-
- )}
-
-
{t('pages.nodes.address')}
-
- {statsNode.url}
-
-
- {showAddress ? (
- setShowAddress(false)}
- onKeyDown={activateOnKey(() => setShowAddress(false))}
- />
- ) : (
- setShowAddress(true)}
- onKeyDown={activateOnKey(() => setShowAddress(true))}
- />
- )}
-
-
-
- {t('pages.nodes.status')}
-
-
- {(() => {
- const { tip, iconColor } = statusIssue(statsNode);
- return tip ? (
-
-
-
- ) : null;
- })()}
-
-
- {t('pages.nodes.cpu')}
-
- {formatPct(statsNode.cpuPct, !statsNode.unavailableMetrics?.includes('cpu'))}
-
-
-
- {t('pages.nodes.mem')}
- {formatPct(statsNode.memPct)}
-
-
- {t('pages.nodes.networkSpeed')}
-
-
-
- {t('pages.nodes.xrayVersion')}
- {statsNode.xrayVersion || '-'}
-
-
-
- {t('pages.nodes.panelVersion') || 'Panel version'}
-
- {statsNode.panelVersion || '-'}
-
-
- {t('pages.nodes.uptime')}
-
- {formatUptime(
- statsNode.uptimeSecs,
- !statsNode.unavailableMetrics?.includes('uptime'),
- )}
-
-
-
- {t('pages.nodes.latency')}
-
- {statsNode.latencyMs && statsNode.latencyMs > 0
- ? `${statsNode.latencyMs} ms`
- : '-'}
-
-
-
- {t('clients')}
-
- {statsNode.clientCount || 0}
-
- {statsNode.activeCount ? (
-
- {statsNode.activeCount} {t('subscription.active')}
-
- ) : null}
- {statsNode.disabledCount ? (
-
- {statsNode.disabledCount} {t('disabled')}
-
- ) : null}
- {statsNode.depletedCount ? (
-
- {statsNode.depletedCount} {t('depleted')}
-
- ) : null}
-
-
-
- {t('pages.nodes.lastHeartbeat')}
- {relativeTime(statsNode.lastHeartbeat)}
-
-
- )}
-
- >
- ) : (
- nodeTable
- )}
-
+ )}
+
+
);
}
diff --git a/frontend/src/pages/nodes/NodeNetworkSpeed.tsx b/frontend/src/pages/nodes/NodeNetworkSpeed.tsx
index 5158b4f16..baae090c9 100644
--- a/frontend/src/pages/nodes/NodeNetworkSpeed.tsx
+++ b/frontend/src/pages/nodes/NodeNetworkSpeed.tsx
@@ -15,8 +15,6 @@ export default function NodeNetworkSpeed({
node: NodeRecord;
receivedAt?: number;
}) {
- const { t } = useTranslation();
- const { token } = theme.useToken();
const expiration =
receivedAt && node.heartbeatAgeMillis != null
? receivedAt + HEARTBEAT_FRESHNESS_MS - node.heartbeatAgeMillis
@@ -40,15 +38,36 @@ export default function NodeNetworkSpeed({
};
const fresh = useSyncExternalStore(subscribe, isFresh);
const available = node.enable && node.status === 'online' && !node.transitive && fresh;
+ return (
+
+ );
+}
+
+export function NetworkSpeedValues({
+ up,
+ down,
+ uploadFirst,
+}: {
+ up?: number | null;
+ down?: number | null;
+ uploadFirst?: boolean;
+}) {
+ const { t } = useTranslation();
+ const { token } = theme.useToken();
const directions = [
{
- key: 'netDown' as const,
+ rate: down,
+ isUpload: false,
label: t('pages.index.download'),
Icon: ArrowDownOutlined,
color: token.colorTextTertiary,
},
{
- key: 'netUp' as const,
+ rate: up,
+ isUpload: true,
label: t('pages.index.upload'),
Icon: ArrowUpOutlined,
color: token.colorPrimary,
@@ -56,30 +75,27 @@ export default function NodeNetworkSpeed({
];
return (
- {directions.map(({ key, label, Icon, color }) => {
- const rate = node[key];
- const value =
- available &&
- !node.unavailableMetrics?.includes(key) &&
- typeof rate === 'number' &&
- Number.isFinite(rate) &&
- rate >= 0
- ? SizeFormatter.speedFormat(rate)
- : '—';
- return (
-
-
-
- {value}
-
-
- );
- })}
+ {(uploadFirst ? directions.reverse() : directions).map(
+ ({ rate, label, Icon, color, isUpload }) => {
+ const value =
+ typeof rate === 'number' && Number.isFinite(rate) && rate >= 0
+ ? SizeFormatter.speedFormat(rate)
+ : '—';
+ return (
+
+
+
+ {value}
+
+
+ );
+ },
+ )}
);
}
diff --git a/frontend/src/pages/nodes/NodesPage.tsx b/frontend/src/pages/nodes/NodesPage.tsx
index 3d63b30f5..0623ba6de 100644
--- a/frontend/src/pages/nodes/NodesPage.tsx
+++ b/frontend/src/pages/nodes/NodesPage.tsx
@@ -4,30 +4,18 @@ import { useQuery } from '@tanstack/react-query';
import {
Alert,
Button,
- Card,
Checkbox,
- Col,
ConfigProvider,
Input,
Layout,
Modal,
Result,
- Row,
Spin,
- Statistic,
Typography,
message,
} from 'antd';
-import {
- CheckCircleOutlined,
- CloseCircleOutlined,
- CloudServerOutlined,
- ThunderboltOutlined,
-} from '@ant-design/icons';
-
import { useTheme } from '@/hooks/useTheme';
-import { useMediaQuery } from '@/hooks/useMediaQuery';
-import { useNodesQuery } from '@/api/queries/useNodesQuery';
+import { useNodeOverviewQuery } from '@/api/queries/useNodesQuery';
import type { NodeRecord } from '@/api/queries/useNodesQuery';
import { useNodeMutations } from '@/api/queries/useNodeMutations';
import AppSidebar from '@/layouts/AppSidebar';
@@ -70,14 +58,23 @@ function UpdateChannelChoice({ onChange }: { onChange: (dev: boolean) => void })
export default function NodesPage() {
const { t } = useTranslation();
const { isDark, isUltra, antdThemeConfig } = useTheme();
- const { isMobile } = useMediaQuery();
const [modal, modalContextHolder] = Modal.useModal();
const [messageApi, messageContextHolder] = message.useMessage();
useEffect(() => {
setMessageInstance(messageApi);
}, [messageApi]);
- const { nodes, nodesUpdatedAt, loading, fetched, fetchError, refetch, totals } = useNodesQuery();
+ const {
+ nodes,
+ master,
+ fleet,
+ nodesUpdatedAt,
+ loading,
+ fetched,
+ fetchError,
+ refreshError,
+ refetch,
+ } = useNodeOverviewQuery();
const {
create,
update,
@@ -360,74 +357,29 @@ export default function NodesPage() {
}
/>
) : (
-
-
-
-
-
- }
- />
-
-
-
- }
- />
-
-
-
- }
- />
-
-
- 0 ? `${totals.avgLatency} ms` : '-'}
- prefix={}
- />
-
-
-
-
-
-
- setMtlsOpen(true)}
- onEdit={onEdit}
- onDelete={onDelete}
- onProbe={onProbe}
- onToggleEnable={onToggleEnable}
- onUpdateNode={onUpdateNode}
- onUpdateSelected={onUpdateSelected}
- onRestart={onRestart}
- restartingIds={restartingIds}
- />
-
-
+ <>
+ {refreshError &&
}
+
setMtlsOpen(true)}
+ onEdit={onEdit}
+ onDelete={onDelete}
+ onProbe={onProbe}
+ onToggleEnable={onToggleEnable}
+ onUpdateNode={onUpdateNode}
+ onUpdateSelected={onUpdateSelected}
+ onRestart={onRestart}
+ restartingIds={restartingIds}
+ />
+ >
)}
diff --git a/frontend/src/pages/nodes/fleetTelemetry.ts b/frontend/src/pages/nodes/fleetTelemetry.ts
new file mode 100644
index 000000000..3e8449923
--- /dev/null
+++ b/frontend/src/pages/nodes/fleetTelemetry.ts
@@ -0,0 +1,103 @@
+import { useCallback, useMemo, useState, useSyncExternalStore } from 'react';
+import type { NodeTelemetry } from '@/generated/types';
+
+const FRESHNESS_MS = 30_000;
+
+function expires(sample: NodeTelemetry, receivedAt?: number) {
+ return receivedAt && sample.sampleAgeMillis != null
+ ? receivedAt + FRESHNESS_MS - sample.sampleAgeMillis
+ : sample.sampledAt + FRESHNESS_MS;
+}
+
+export function freshTelemetry(
+ sample: NodeTelemetry | null | undefined,
+ now: number,
+ receivedAt?: number,
+) {
+ if (!sample) return undefined;
+ const remaining = expires(sample, receivedAt) - now;
+ return remaining > 0 && remaining <= FRESHNESS_MS ? sample : undefined;
+}
+
+export function useTelemetryClock(
+ samples: readonly (NodeTelemetry | null | undefined)[],
+ receivedAt?: number,
+) {
+ const [mountedAt] = useState(Date.now);
+ const deadlines = useMemo(
+ () =>
+ samples
+ .flatMap((sample) => (sample ? [expires(sample, receivedAt)] : []))
+ .sort((a, b) => a - b),
+ [samples, receivedAt],
+ );
+ const subscribe = useCallback(
+ (refresh: () => void) => {
+ let timer: number | undefined;
+ const schedule = () => {
+ const now = Date.now();
+ const deadline = deadlines.find((time) => time > now && time <= now + FRESHNESS_MS);
+ if (deadline !== undefined) {
+ timer = window.setTimeout(() => {
+ refresh();
+ schedule();
+ }, deadline - now);
+ }
+ };
+ schedule();
+ return () => window.clearTimeout(timer);
+ },
+ [deadlines],
+ );
+ const snapshot = () => {
+ const now = Date.now();
+ const latestExpiry = deadlines.reduce((last, time) => (time <= now ? time : last), 0);
+ return Math.max(mountedAt, receivedAt ?? 0, latestExpiry);
+ };
+ return useSyncExternalStore(subscribe, snapshot, snapshot);
+}
+
+export function aggregateTelemetry(samples: NodeTelemetry[]) {
+ const cpu = samples.filter((host) => host.cpuPct != null);
+ const memory = samples.filter(
+ (host) =>
+ host.memTotalBytes != null &&
+ host.memTotalBytes > 0 &&
+ host.memUsedBytes != null &&
+ host.memUsedBytes <= host.memTotalBytes,
+ );
+ function sum(key: keyof NodeTelemetry, hosts = samples) {
+ let total: number | undefined;
+ for (const sample of hosts) {
+ const value = sample[key];
+ if (typeof value === 'number') total = (total ?? 0) + value;
+ }
+ return total;
+ }
+ const telemetry: NodeTelemetry = {
+ sampledAt: 0,
+ cpuPct: cpu.length ? (sum('cpuPct', cpu) ?? 0) / cpu.length : undefined,
+ logicalCores: cpu.every((host) => host.logicalCores != null)
+ ? sum('logicalCores', cpu)
+ : undefined,
+ memUsedBytes: sum('memUsedBytes', memory),
+ memTotalBytes: sum('memTotalBytes', memory),
+ memAvailableBytes: memory.every((host) => host.memAvailableBytes != null)
+ ? sum('memAvailableBytes', memory)
+ : undefined,
+ netUp: sum('netUp'),
+ netDown: sum('netDown'),
+ tcpCount: sum('tcpCount'),
+ udpCount: sum('udpCount'),
+ load1: sum('load1'),
+ load5: sum('load5'),
+ load15: sum('load15'),
+ };
+ return { telemetry, cpuHosts: cpu.length, memoryHosts: memory.length };
+}
+
+export function reportingSample(sample: NodeTelemetry | null | undefined): sample is NodeTelemetry {
+ if (!sample) return false;
+ const { sampledAt: _time, sampleAgeMillis: _age, resourceScope: _scope, ...metrics } = sample;
+ return Object.values(metrics).some((metric) => typeof metric === 'number');
+}
diff --git a/frontend/src/pages/xray/routing/RuleFormModal.stories.tsx b/frontend/src/pages/xray/routing/RuleFormModal.stories.tsx
new file mode 100644
index 000000000..c07972ea3
--- /dev/null
+++ b/frontend/src/pages/xray/routing/RuleFormModal.stories.tsx
@@ -0,0 +1,134 @@
+import type { Meta, StoryObj } from '@storybook/react-vite';
+import { expect, fn, waitFor, within } from 'storybook/test';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { useState } from 'react';
+import type { ComponentProps, ReactNode } from 'react';
+import { ThemeProvider } from '@/hooks/useTheme';
+import { AntdRootConfig } from '@/i18n/AntdRootConfig';
+
+import { HttpUtil, Msg } from '@/utils';
+import RuleFormModal from './RuleFormModal';
+
+function QueryFixture({ children }: { children: ReactNode }) {
+ const [client] = useState(
+ () => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
+ );
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+function RoutingRuleFixture(props: ComponentProps) {
+ const [open, setOpen] = useState(props.open);
+ return (
+ {
+ props.onClose();
+ setOpen(false);
+ }}
+ onConfirm={(rule) => {
+ props.onConfirm(rule);
+ setOpen(false);
+ }}
+ />
+ );
+}
+
+const meta = {
+ title: 'Xray/Routing Rule',
+ component: RuleFormModal,
+ render: (args) => ,
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+ args: {
+ open: true,
+ rule: { user: ['existing@test'], outboundTag: 'direct' },
+ inboundTags: [],
+ outboundTags: ['direct'],
+ balancerTags: [],
+ onClose: fn(),
+ onConfirm: fn(),
+ },
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+
+function largeCatalog(size: number): Story {
+ const requests: Array<{ path: string; search: string; count: number }> = [];
+ const target = `client-${size}@test`;
+ const legacyList = '/panel/api/clients/list';
+ const suggestionsPath = '/panel/api/clients/userSuggestions';
+
+ return {
+ beforeEach: () => {
+ requests.length = 0;
+ const get = HttpUtil.get;
+ const fixture = Array.from({ length: size }, (_, index) => `client-${index + 1}@test`);
+ HttpUtil.get = async (path: string, params?: unknown) => {
+ if (path === legacyList) {
+ requests.push({ path, search: '', count: size });
+ return new Msg(true, '', fixture.map((email) => ({ email })) as T);
+ }
+ if (path === suggestionsPath) {
+ const { search } = params as { search: string };
+ const emails = fixture.filter((email) => email.includes(search)).slice(0, 50);
+ requests.push({ path, search, count: emails.length });
+ return new Msg(true, '', { emails } as T);
+ }
+ return new Msg(true, '', [] as T);
+ };
+ return () => {
+ HttpUtil.get = get;
+ };
+ },
+ play: async ({ args, canvasElement, userEvent }) => {
+ const screen = within(canvasElement.ownerDocument.body);
+ const dialog = await screen.findByRole('dialog');
+ const picker = within(dialog).getByRole('combobox', { name: 'User' });
+ await expect(requests).toEqual([]);
+ await userEvent.click(picker);
+ await waitFor(() =>
+ expect(requests).toEqual([{ path: suggestionsPath, search: '', count: 50 }]),
+ );
+
+ const search = target.replace('client-', '');
+ await userEvent.type(picker, search);
+ const option = await screen.findByText(target, {
+ selector: '.ant-select-item-option-content',
+ });
+ await userEvent.click(option);
+ await userEvent.type(picker, 'manual@test,existing@test,');
+ await expect(screen.getByRole('button', { name: 'Remove existing@test' })).toBeVisible();
+ await expect(screen.getByRole('button', { name: `Remove ${target}` })).toBeVisible();
+ await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+ await expect(args.onConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({
+ user: ['existing@test', target, 'manual@test'],
+ outboundTag: 'direct',
+ }),
+ );
+ await expect(requests.filter(({ search }) => search)).toEqual([
+ { path: suggestionsPath, search, count: 1 },
+ ]);
+ await expect(
+ requests.every(({ path, count }) => path === suggestionsPath && count <= 50),
+ ).toBe(true);
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ },
+ };
+}
+
+export const Thousand = largeCatalog(1_000);
+export const TenThousand = largeCatalog(10_000);
+export const FiftyThousand = largeCatalog(50_000);
diff --git a/frontend/src/pages/xray/routing/RuleFormModal.tsx b/frontend/src/pages/xray/routing/RuleFormModal.tsx
index 00881894e..a85b8ef0e 100644
--- a/frontend/src/pages/xray/routing/RuleFormModal.tsx
+++ b/frontend/src/pages/xray/routing/RuleFormModal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Form, Input, Modal, Select, Space, Switch } from 'antd';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
@@ -71,6 +71,73 @@ function csv(value: string): string[] {
.filter(Boolean);
}
+function RoutingUserField({ active }: { active: boolean }) {
+ const { t } = useTranslation();
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const [search, setSearch] = useState('');
+ const { data, isFetching, isError } = useClientOptions(
+ active && pickerOpen ? search.trim() : null,
+ );
+ const user = useWatch({ name: 'user' }) ?? '';
+ const selectedUsers = useMemo(() => csv(user), [user]);
+ const options = useMemo(
+ () =>
+ [...new Set([...(data ?? []), ...selectedUsers])].map((email) => ({
+ value: email,
+ label: email,
+ })),
+ [data, selectedUsers],
+ );
+ const status = isFetching
+ ? t('loading')
+ : isError
+ ? t('pages.xray.ruleForm.userLoadError')
+ : !data?.length
+ ? t('pages.xray.ruleForm.userEmpty')
+ : undefined;
+ const showStatusInMenu = Boolean(search || options.length);
+
+ return (
+ csv(typeof value === 'string' ? value : ''),
+ output: (value) => (Array.isArray(value) ? value.join(',') : ''),
+ }}
+ onAfterChange={() => setSearch('')}
+ >
+
+ );
+}
+
export default function RuleFormModal({
open,
rule,
@@ -86,21 +153,6 @@ export default function RuleFormModal({
const { data: inboundOptions } = useInboundOptions();
const remarkByTag = useMemo(() => buildRemarkByTag(inboundOptions || []), [inboundOptions]);
- const {
- data: clientEmails = [],
- isFetching: clientsLoading,
- isError: clientsError,
- } = useClientOptions(open);
- const user = useWatch({ control: methods.control, name: 'user' }) ?? '';
- const selectedUsers = useMemo(() => csv(user), [user]);
- const userOptions = useMemo(
- () =>
- [...new Set([...clientEmails, ...selectedUsers])].map((email) => ({
- value: email,
- label: email,
- })),
- [clientEmails, selectedUsers],
- );
useEffect(() => {
if (!open) return;
@@ -286,33 +338,7 @@ export default function RuleFormModal({
- csv(typeof value === 'string' ? value : ''),
- output: (value) => (Array.isArray(value) ? value.join(',') : ''),
- }}
- >
-
-
+
v ?? {});
export const ActiveInboundsByNodeSchema = z
- .record(z.string(), nullableStringArray)
+ .record(z.string(), z.array(z.string()).nullable())
.nullable()
.transform((v) => v ?? {});
diff --git a/frontend/src/schemas/node.ts b/frontend/src/schemas/node.ts
index ae52b366e..504d23e50 100644
--- a/frontend/src/schemas/node.ts
+++ b/frontend/src/schemas/node.ts
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { NodeFleetCountsSchema, NodeMasterViewSchema, NodeTelemetrySchema } from '@/generated/zod';
export const NodeRecordSchema = z
.object({
@@ -23,6 +24,7 @@ export const NodeRecordSchema = z
panelVersion: z.string().optional(),
uptimeSecs: z.number().optional(),
unavailableMetrics: z.array(z.string()).optional(),
+ telemetry: NodeTelemetrySchema.optional(),
inboundCount: z.number().optional(),
clientCount: z.number().optional(),
onlineCount: z.number().optional(),
@@ -54,6 +56,11 @@ export const NodeRecordSchema = z
.loose();
export const NodeListSchema = z.array(NodeRecordSchema);
+export const NodeOverviewSchema = z.object({
+ nodes: NodeListSchema,
+ master: NodeMasterViewSchema,
+ fleet: NodeFleetCountsSchema,
+});
export const ProbeResultSchema = z
.object({
diff --git a/frontend/src/test/client-bulk-add-subid.test.tsx b/frontend/src/test/client-bulk-add-subid.test.tsx
new file mode 100644
index 000000000..460dad161
--- /dev/null
+++ b/frontend/src/test/client-bulk-add-subid.test.tsx
@@ -0,0 +1,122 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, screen, waitFor } from '@testing-library/react';
+
+import ClientBulkAddModal from '@/pages/clients/ClientBulkAddModal';
+import { HttpUtil, Msg } from '@/utils';
+import { renderWithProviders } from './test-utils';
+
+const { bulkCreate } = vi.hoisted(() => ({ bulkCreate: vi.fn() }));
+vi.mock('@/hooks/useClients', () => ({ useClients: () => ({ bulkCreate }) }));
+
+function mockHttp() {
+ vi.spyOn(HttpUtil, 'get').mockImplementation(async (url) => {
+ if (typeof url === 'string' && url.includes('fail2banStatus'))
+ return new Msg(true, '', { enabled: true, installed: true, usable: true, windows: false });
+ return new Msg(true, '', {});
+ });
+ vi.spyOn(HttpUtil, 'post').mockImplementation(async (url) => {
+ if (url !== '/panel/api/clients/renewalPreview')
+ return new Msg(true, '', { datepicker: 'gregorian' });
+ return new Msg(true, '', {
+ timeZone: 'Asia/Taipei',
+ renewAt: '',
+ validThrough: '',
+ nextExpiry: '',
+ suggestedExpiryTime: 1893427200000,
+ suggestedExpiry: '2030-01-01T00:00:00+08:00',
+ renewals: 0,
+ canRenew: false,
+ delayedStart: false,
+ });
+ });
+}
+
+function renderModal(onOpenChange = vi.fn()) {
+ renderWithProviders(
+ ,
+ );
+ return onOpenChange;
+}
+
+function fillBatch(quantity: string, subId: string) {
+ fireEvent.click(screen.getByRole('button', { name: 'Select all' }));
+ fireEvent.change(screen.getByLabelText('Number of Clients'), { target: { value: quantity } });
+ fireEvent.change(screen.getByLabelText('Subscription ID'), { target: { value: subId } });
+}
+
+async function submit() {
+ const button = document.querySelector('.ant-modal-footer .ant-btn-primary');
+ if (!button) throw new Error('Create button missing');
+ await waitFor(() => expect(button.classList.contains('ant-btn-loading')).toBe(false));
+ fireEvent.click(button);
+}
+
+function subIdsOf(call: unknown[]): string[] {
+ const payloads = call[0] as { client: { subId: string } }[];
+ return payloads.map((p) => p.client.subId);
+}
+
+describe('ClientBulkAddModal subscription IDs', () => {
+ beforeEach(() => {
+ bulkCreate.mockClear();
+ bulkCreate.mockResolvedValue(new Msg(true, '', { created: 3, skipped: [] }));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('sends the typed prefix for server allocation without fetching all clients', async () => {
+ mockHttp();
+ renderModal();
+ fillBatch('3', 'test123');
+ await submit();
+ await waitFor(() => expect(bulkCreate).toHaveBeenCalledTimes(1));
+ expect(subIdsOf(bulkCreate.mock.calls[0])).toEqual(['', '', '']);
+ expect(bulkCreate.mock.calls[0][0]).toEqual(
+ Array.from({ length: 3 }, () => expect.objectContaining({ subIdPrefix: 'test123' })),
+ );
+ expect(
+ vi.mocked(HttpUtil.get).mock.calls.some(([url]) => url === '/panel/api/clients/list'),
+ ).toBe(false);
+ });
+
+ it('keeps a typed ID exact for a single client', async () => {
+ mockHttp();
+ renderModal();
+ fillBatch('1', 'test123');
+ await submit();
+ await waitFor(() => expect(bulkCreate).toHaveBeenCalledTimes(1));
+ expect(subIdsOf(bulkCreate.mock.calls[0])).toEqual(['test123']);
+ expect(bulkCreate.mock.calls[0][0][0].subIdPrefix).toBeUndefined();
+ });
+
+ it('leaves the form open for retry when server allocation fails', async () => {
+ mockHttp();
+ bulkCreate.mockResolvedValueOnce(new Msg(false, 'Could not allocate subscription IDs', null));
+ const onOpenChange = renderModal();
+ fillBatch('3', 'test123');
+ await submit();
+ await screen.findByText('Could not allocate subscription IDs');
+ expect(onOpenChange).not.toHaveBeenCalled();
+ expect((screen.getByLabelText('Subscription ID') as HTMLInputElement).value).toBe('test123');
+ await submit();
+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
+ });
+
+ it('gives each client a different random ID when Subscription ID is empty', async () => {
+ mockHttp();
+ renderModal();
+ fillBatch('3', '');
+ await submit();
+ await waitFor(() => expect(bulkCreate).toHaveBeenCalledTimes(1));
+ const subIds = subIdsOf(bulkCreate.mock.calls[0]);
+ expect(subIds).toHaveLength(3);
+ expect(new Set(subIds).size).toBe(3);
+ for (const subId of subIds) expect(subId).toMatch(/^[a-z0-9]{16}$/);
+ });
+});
diff --git a/frontend/src/test/container-history.test.tsx b/frontend/src/test/container-history.test.tsx
index 45cdc0e72..bf7903fc3 100644
--- a/frontend/src/test/container-history.test.tsx
+++ b/frontend/src/test/container-history.test.tsx
@@ -1,5 +1,5 @@
import { act, renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { Status } from '@/models/status';
import { useOverviewHistory } from '@/pages/index/useOverviewHistory';
@@ -12,8 +12,11 @@ vi.mock('@/utils', async (importOriginal) => {
beforeEach(() => {
get.mockReset();
+ vi.spyOn(Date, 'now').mockReturnValue(10_000);
});
+afterEach(() => vi.restoreAllMocks());
+
it('keeps missing samples out of trends and resets a changed metric scope', async () => {
get.mockImplementation(async (path: string) => ({
success: true,
@@ -37,6 +40,7 @@ it('keeps missing samples out of trends and resets a changed metric scope', asyn
expect(result.current.series.cpu).toEqual([10, 20]);
rerender({ status: new Status({ cpu: 50 }) });
expect(result.current.series.cpu).toEqual([50]);
+ await act(async () => undefined);
});
it('ignores a legacy seed that resolves after the scope changes', async () => {
diff --git a/frontend/src/test/detach-clients-modal.test.tsx b/frontend/src/test/detach-clients-modal.test.tsx
index 89d3352bb..5b9928308 100644
--- a/frontend/src/test/detach-clients-modal.test.tsx
+++ b/frontend/src/test/detach-clients-modal.test.tsx
@@ -1,8 +1,9 @@
-import { describe, expect, it } from 'vitest';
-import { screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, screen, waitFor } from '@testing-library/react';
import DetachClientsModal from '@/pages/inbounds/clients/DetachClientsModal';
import { DBInbound } from '@/models/dbinbound';
+import { HttpUtil, Msg } from '@/utils';
import { renderWithProviders } from './test-utils';
@@ -27,10 +28,153 @@ function sourceInbound() {
}
describe('DetachClientsModal', () => {
- it('lists the attached clients when first mounted already open', async () => {
+ it('uses the bounded server page instead of rendering embedded settings clients', async () => {
+ const get = vi.spyOn(HttpUtil, 'get').mockResolvedValue(
+ new Msg(true, '', {
+ items: [{ id: 12, email: 'server@test', comment: '', enable: true, inScope: false }],
+ total: 50000,
+ attached: 50000,
+ }),
+ );
renderWithProviders( {}} />);
- expect(await screen.findByText('alice@test')).toBeTruthy();
- expect(screen.getByText('bob@test')).toBeTruthy();
+ expect(await screen.findByText('server@test')).toBeTruthy();
+ expect(screen.queryByText('alice@test')).toBeNull();
+ expect(get).toHaveBeenCalledWith(
+ '/panel/api/clients/detachCandidates',
+ expect.objectContaining({ inboundId: 7, page: 1 }),
+ expect.anything(),
+ );
+ });
+
+ it('keeps page and frozen selections separate and sends only the scope and exclusions', async () => {
+ const status = '/panel/api/clients/bulkDetach/job-1';
+ const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (url, params) => {
+ if (url === status) {
+ return new Msg(true, '', {
+ running: false,
+ processed: 49999,
+ total: 49999,
+ result: { detached: 49998, skipped: 1, errors: 0 },
+ });
+ }
+ const { page, search, scopeToken } = params as {
+ page: number;
+ search: string;
+ scopeToken?: string;
+ };
+ const id = page === 2 || search ? 101 : 1;
+ return new Msg(true, '', {
+ items: [
+ {
+ id,
+ email: 'client-' + id + '@test',
+ comment: '',
+ enable: true,
+ inScope: Boolean(scopeToken),
+ },
+ ],
+ total: search ? 1 : 50000,
+ attached: 50000,
+ });
+ });
+ const post = vi
+ .spyOn(HttpUtil, 'post')
+ .mockImplementation(
+ async (url) =>
+ new Msg(
+ true,
+ '',
+ url.endsWith('/freeze') ? { scopeToken: 'frozen', total: 50000 } : { jobId: 'job-1' },
+ ),
+ );
+ const detached = vi.fn();
+ const close = vi.fn();
+ renderWithProviders(
+ ,
+ );
+ await screen.findByText('client-1@test');
+ fireEvent.click(screen.getByRole('button', { name: 'Select this page' }));
+ expect(screen.getByText('1 selected')).toBeTruthy();
+ fireEvent.click(screen.getByText('2', { exact: true }));
+ await waitFor(() =>
+ expect(get).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ page: 2 }),
+ expect.anything(),
+ ),
+ );
+ await screen.findByText('client-101@test');
+ expect(screen.getByText('1 selected')).toBeTruthy();
+ expect(
+ screen.getByRole('checkbox', { name: 'client-101@test' }).checked,
+ ).toBe(false);
+ fireEvent.click(screen.getByRole('button', { name: 'Select all attached clients' }));
+ const choice = () =>
+ screen.getByRole('checkbox', { name: 'client-101@test' });
+ await waitFor(() => expect(choice().checked).toBe(true));
+ fireEvent.click(choice());
+ expect(screen.getByText('49999 selected')).toBeTruthy();
+ fireEvent.change(screen.getByRole('searchbox', { name: 'Search' }), {
+ target: { value: '101' },
+ });
+ await waitFor(() => expect(choice().checked).toBe(false));
+ fireEvent.click(choice());
+ expect(screen.getByText('50000 selected')).toBeTruthy();
+ fireEvent.click(choice());
+ fireEvent.click(screen.getByRole('button', { name: 'Detach Clients' }));
+ await waitFor(() => expect(detached).toHaveBeenCalledTimes(1));
+ expect(close).toHaveBeenCalledTimes(1);
+ expect(post).toHaveBeenCalledWith(
+ '/panel/api/clients/bulkDetach',
+ {
+ requestId: expect.any(String),
+ inboundIds: [7],
+ selection: { mode: 'allMatching', scopeToken: 'frozen', excludedClientIds: [101] },
+ },
+ expect.anything(),
+ );
+ });
+
+ it('ignores an older search response after the server page has changed', async () => {
+ let release!: (value: Msg) => void;
+ const old = new Promise((resolve) => {
+ release = resolve;
+ });
+ const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (_url, params) => {
+ const { search } = params as { search: string };
+ if (search === 'old') return old;
+ return new Msg(true, '', {
+ items: [
+ { id: 2, email: search + '-current@test', comment: '', enable: true, inScope: false },
+ ],
+ total: 1,
+ attached: 2,
+ });
+ });
+ renderWithProviders( {}} />);
+ await screen.findByText('-current@test');
+ const search = screen.getByRole('searchbox', { name: 'Search' });
+ fireEvent.change(search, { target: { value: 'old' } });
+ await waitFor(() =>
+ expect(get).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ search: 'old' }),
+ expect.anything(),
+ ),
+ );
+ fireEvent.change(search, { target: { value: 'new' } });
+ await screen.findByText('new-current@test');
+ await act(async () =>
+ release(
+ new Msg(true, '', {
+ items: [{ id: 3, email: 'stale@test', comment: '', enable: true }],
+ total: 1,
+ attached: 2,
+ }),
+ ),
+ );
+ expect(screen.queryByText('stale@test')).toBeNull();
+ expect(screen.getByText('new-current@test')).toBeTruthy();
});
});
diff --git a/frontend/src/test/geodata-section.test.tsx b/frontend/src/test/geodata-section.test.tsx
index 6b7e842f9..72893b09b 100644
--- a/frontend/src/test/geodata-section.test.tsx
+++ b/frontend/src/test/geodata-section.test.tsx
@@ -15,11 +15,11 @@ const STANDARD_SOURCES = [
file: 'geosite.dat',
},
{
- url: 'https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat',
+ url: 'https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geoip.dat',
file: 'geoip_IR.dat',
},
{
- url: 'https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat',
+ url: 'https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geosite.dat',
file: 'geosite_IR.dat',
},
{
diff --git a/frontend/src/test/host-address-tags.test.tsx b/frontend/src/test/host-address-tags.test.tsx
new file mode 100644
index 000000000..1bddd69f5
--- /dev/null
+++ b/frontend/src/test/host-address-tags.test.tsx
@@ -0,0 +1,180 @@
+import { fireEvent, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { HostRecord } from '@/api/queries/useHostsQuery';
+import HostFormModal from '@/pages/hosts/HostFormModal';
+import { HttpUtil, Msg } from '@/utils';
+import { renderWithProviders } from './test-utils';
+
+const ipv6 = '[2001:db8::a]:8443';
+const cidr = '192.0.2.0/24';
+const host = {
+ groupId: 'g1',
+ remark: 'Fixture host',
+ inboundIds: [1],
+ hosts: [ipv6, cidr],
+} as HostRecord;
+
+function renderHost() {
+ const save = vi.fn().mockResolvedValue({ success: true });
+ renderWithProviders(
+ {}}
+ />,
+ );
+ return save;
+}
+
+describe('Host address tags', () => {
+ beforeEach(() => {
+ vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', []));
+ });
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it.each(['Edit', 'Copy'])(
+ 'keeps all addresses when Backspace is pressed on %s',
+ async (action) => {
+ const user = userEvent.setup();
+ const save = renderHost();
+ const button = screen.getByRole('button', { name: `${action} ${ipv6}` });
+ button.focus();
+ expect(document.activeElement).toBe(button);
+ await user.keyboard('{Backspace}');
+
+ expect(screen.getByRole('button', { name: `Remove ${ipv6}` })).not.toBeNull();
+ expect(screen.getByRole('button', { name: `Remove ${cidr}` })).not.toBeNull();
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ expect(save).toHaveBeenCalledWith(expect.objectContaining({ hosts: [ipv6, cidr] }));
+ },
+ );
+
+ it('pastes single and mixed-delimiter addresses and copies the exact tag text', async () => {
+ vi.stubGlobal('isSecureContext', true);
+ const user = userEvent.setup();
+ const save = renderHost();
+ const address = await screen.findByRole('combobox', { name: 'Address' });
+ await user.click(address);
+ await user.paste('Example.TEST:444');
+ expect(screen.getByRole('button', { name: 'Remove Example.TEST:444' })).not.toBeNull();
+ await user.paste(
+ 'proxy.test;192.0.2.7:443,\r\n2001:db8::7\tother.test duplicate.test duplicate.test',
+ );
+ expect(screen.getByRole('button', { name: 'Remove 2001:db8::7' })).not.toBeNull();
+
+ const copy = screen.getByRole('button', { name: `Copy ${ipv6}` });
+ copy.focus();
+ await user.keyboard('{Enter}');
+ await waitFor(async () => expect(await navigator.clipboard.readText()).toBe(ipv6));
+ const remark = screen.getByRole('textbox', { name: 'Remark' });
+ await user.click(remark);
+ await user.keyboard('{Control>}a{/Control}');
+ await user.paste();
+ expect(remark.value).toBe(ipv6);
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ expect(save).toHaveBeenCalledWith(
+ expect.objectContaining({
+ hosts: [
+ ipv6,
+ cidr,
+ 'Example.TEST:444',
+ 'proxy.test',
+ '192.0.2.7:443',
+ '2001:db8::7',
+ 'other.test',
+ 'duplicate.test',
+ ],
+ }),
+ );
+ });
+
+ it('edits one tag with Enter, cancels with Escape and keeps removal working', async () => {
+ const user = userEvent.setup();
+ const save = renderHost();
+ const address = await screen.findByRole('combobox', { name: 'Address' });
+ await user.dblClick(screen.getByText(ipv6, { exact: true }));
+ let edit = screen.getByRole('textbox', { name: `Edit ${ipv6}` });
+ expect(document.activeElement).toBe(edit);
+ expect(address.getAttribute('aria-expanded')).toBe('false');
+ await user.clear(edit);
+ await user.paste('[2001:db8::f]:8443');
+ await user.keyboard('{Enter}');
+ const replaced = screen.getByRole('button', { name: 'Edit [2001:db8::f]:8443' });
+ expect(document.activeElement).toBe(replaced);
+ expect(address.getAttribute('aria-expanded')).toBe('false');
+ expect(save).not.toHaveBeenCalled();
+
+ await user.keyboard('{Enter}');
+ edit = screen.getByRole('textbox', { name: 'Edit [2001:db8::f]:8443' });
+ await user.clear(edit);
+ await user.type(edit, cidr);
+ await user.keyboard('{Enter}');
+ expect(await screen.findByText('This address is already in the list.')).not.toBeNull();
+ expect(document.activeElement).toBe(edit);
+ await user.clear(edit);
+ await user.type(edit, 'cancelled.test');
+ await user.keyboard('{Escape}');
+ expect(screen.getByRole('dialog')).not.toBeNull();
+ expect(document.activeElement).toBe(
+ screen.getByRole('button', { name: 'Edit [2001:db8::f]:8443' }),
+ );
+ expect(screen.queryByText('cancelled.test')).toBeNull();
+
+ fireEvent.paste(address, { clipboardData: { getData: () => 'append.test' } });
+ await user.click(screen.getByRole('button', { name: 'Remove append.test' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ expect(save).toHaveBeenCalledWith(
+ expect.objectContaining({ hosts: ['[2001:db8::f]:8443', cidr] }),
+ );
+ });
+
+ it('saves the address being edited when the operator clicks Save', async () => {
+ const user = userEvent.setup();
+ const save = renderHost();
+ await user.dblClick(screen.getByText(ipv6, { exact: true }));
+ const editor = screen.getByRole('textbox', { name: `Edit ${ipv6}` });
+ await user.clear(editor);
+ await user.type(editor, 'replacement.test');
+ await user.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ expect(save).toHaveBeenCalledWith(
+ expect.objectContaining({ hosts: ['replacement.test', cidr] }),
+ );
+ });
+
+ it('keeps an invalid draft and blocks saving until it is corrected', async () => {
+ const user = userEvent.setup();
+ const save = renderHost();
+ await user.dblClick(screen.getByText(ipv6, { exact: true }));
+ const editor = screen.getByRole('textbox', { name: `Edit ${ipv6}` });
+ const saveButton = screen.getByRole('button', { name: 'Save' });
+ await user.clear(editor);
+ await user.type(editor, cidr);
+ await user.click(saveButton);
+ expect(await screen.findByText('This address is already in the list.')).not.toBeNull();
+ expect(save).not.toHaveBeenCalled();
+ expect(editor.value).toBe(cidr);
+ expect(screen.getByRole('textbox', { name: `Edit ${ipv6}` })).toBe(editor);
+
+ await user.clear(editor);
+ await user.type(editor, 'corrected.test');
+ await user.tab();
+ const replacement = screen.getByRole('button', { name: 'Edit corrected.test' });
+ expect(document.activeElement).not.toBe(replacement);
+ await user.click(saveButton);
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ expect(save).toHaveBeenCalledWith(expect.objectContaining({ hosts: ['corrected.test', cidr] }));
+ });
+});
diff --git a/frontend/src/test/host-form-session.test.tsx b/frontend/src/test/host-form-session.test.tsx
new file mode 100644
index 000000000..800e6b5e5
--- /dev/null
+++ b/frontend/src/test/host-form-session.test.tsx
@@ -0,0 +1,143 @@
+import { useState, type ComponentProps } from 'react';
+import { act, fireEvent, screen, waitFor } from '@testing-library/react';
+import { ConfigProvider } from 'antd';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { HostRecord } from '@/api/queries/useHostsQuery';
+import HostFormModal from '@/pages/hosts/HostFormModal';
+import { HttpUtil, Msg } from '@/utils';
+import { chooseSelectOption, renderWithProviders } from './test-utils';
+
+const inboundOptions = [{ id: 1, remark: 'Fixture inbound', tag: 'in', protocol: 'vless' }];
+const first = {
+ groupId: 'first',
+ remark: 'First host',
+ inboundIds: [1],
+ hosts: ['first.example.test'],
+ port: 8443,
+} as HostRecord;
+const second = {
+ ...first,
+ groupId: 'second',
+ remark: 'Second host',
+ hosts: ['second.example.test'],
+ port: 443,
+} as HostRecord;
+
+function Sessions({ save }: { save: ComponentProps['save'] }) {
+ const [host, setHost] = useState(null);
+ const [open, setOpen] = useState(false);
+ function show(next: HostRecord | null) {
+ setHost(next);
+ setOpen(true);
+ }
+ return (
+
+
+
+
+
+
+
+ );
+}
+
+async function openSession(name = 'New session') {
+ fireEvent.click(screen.getByRole('button', { name }));
+ return screen.findByRole('textbox', { name: 'Remark' });
+}
+
+function fillDraft(remark: HTMLElement) {
+ fireEvent.change(remark, { target: { value: 'Draft host' } });
+ const inbound = screen.getByRole('combobox', { name: 'Inbounds' });
+ chooseSelectOption(inbound.id, 'Fixture inbound');
+ fireEvent.change(screen.getByRole('spinbutton', { name: 'Port' }), { target: { value: '9443' } });
+ const address = screen.getByRole('combobox', { name: 'Address' });
+ fireEvent.change(address, { target: { value: 'draft.example.test,' } });
+}
+
+async function closeSession() {
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+}
+
+describe('Host form sessions', () => {
+ beforeEach(() => {
+ vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', []));
+ });
+
+ it.each(['success', 'rejection', 'error', 'cancel'])(
+ 'starts from Add defaults after a previous %s',
+ async (result) => {
+ const save = vi.fn().mockResolvedValue({ success: result === 'success', msg: 'Cannot save' });
+ if (result === 'error') {
+ save.mockRejectedValue(new Error('Request failed'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ }
+ renderWithProviders();
+ const remark = await openSession();
+ fillDraft(remark);
+ if (result !== 'cancel') {
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ expect(save).toHaveBeenCalledWith(
+ expect.objectContaining({
+ remark: 'Draft host',
+ port: 9443,
+ hosts: ['draft.example.test'],
+ }),
+ );
+ }
+ if (result === 'success') {
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ } else {
+ expect(screen.getByRole('textbox', { name: 'Remark' }).value).toBe(
+ 'Draft host',
+ );
+ await closeSession();
+ }
+
+ expect((await openSession()).value).toBe('');
+ expect(screen.getByRole('spinbutton', { name: 'Port' }).value).toBe('0');
+ expect(screen.queryByRole('button', { name: 'Remove draft.example.test' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Remove Fixture inbound' })).toBeNull();
+ },
+ );
+
+ it('loads a different Edit host and then opens a clean Add form', async () => {
+ renderWithProviders();
+ expect((await openSession('First session')).value).toBe('First host');
+ expect((await openSession('Second session')).value).toBe('Second host');
+ expect(screen.getByRole('button', { name: 'Remove second.example.test' })).not.toBeNull();
+ await closeSession();
+ expect((await openSession()).value).toBe('');
+ expect(screen.queryByRole('button', { name: 'Remove second.example.test' })).toBeNull();
+ });
+
+ it('keeps a later session open when a cancelled request finishes', async () => {
+ let resolve!: (value: { success: boolean }) => void;
+ const pending = new Promise<{ success: boolean }>((done) => {
+ resolve = done;
+ });
+ const save = vi.fn().mockReturnValue(pending);
+ renderWithProviders();
+ await openSession('First session');
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ fireEvent.click(screen.getByRole('button', { name: 'Close externally' }));
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect((await openSession('Second session')).value).toBe('Second host');
+ await act(async () => resolve({ success: true }));
+ expect(screen.getByRole('textbox', { name: 'Remark' }).value).toBe(
+ 'Second host',
+ );
+ });
+});
diff --git a/frontend/src/test/inbound-info-live-traffic.test.tsx b/frontend/src/test/inbound-info-live-traffic.test.tsx
new file mode 100644
index 000000000..e47f5a65c
--- /dev/null
+++ b/frontend/src/test/inbound-info-live-traffic.test.tsx
@@ -0,0 +1,83 @@
+import { act, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router';
+import { expect, it, vi } from 'vitest';
+
+import { keys } from '@/api/queryKeys';
+import InboundsPage from '@/pages/inbounds/InboundsPage';
+import { HttpUtil, Msg } from '@/utils';
+
+import { makeTestQueryClient, renderWithProviders } from './test-utils';
+
+const socket = vi.hoisted(() => ({
+ handlers: {} as Record void>,
+}));
+vi.mock('@/hooks/useWebSocket', () => ({
+ useWebSocket: (handlers: typeof socket.handlers) => {
+ socket.handlers = handlers;
+ },
+}));
+vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
+
+it('keeps the selected inbound info tab and loaded IPs across live counter updates', async () => {
+ const client = { email: 'edge@example.test', enable: true, limitIp: 1 };
+ const stats = { email: client.email, up: 0, down: 0, total: 0, expiryTime: 0, enable: true };
+ const inbound = {
+ id: 7,
+ protocol: 'socks',
+ remark: 'Edge',
+ tag: 'inbound-7000',
+ port: 7000,
+ enable: true,
+ settings: { clients: [client] },
+ streamSettings: { network: 'tcp', security: 'none' },
+ clientStats: [stats],
+ };
+ const queryClient = makeTestQueryClient();
+ queryClient.setDefaultOptions({ queries: { retry: false, staleTime: Infinity } });
+ queryClient.setQueryData(keys.inbounds.slim(), [inbound]);
+ queryClient.setQueryData(keys.settings.defaults(), { ipLimitEnable: true });
+ queryClient.setQueryData(keys.hosts.list(), []);
+ queryClient.setQueryData(keys.nodes.list(), []);
+ queryClient.setQueryData(keys.clients.onlines(), []);
+ queryClient.setQueryData(keys.clients.onlinesByGuid(), {});
+ queryClient.setQueryData(keys.clients.activeInbounds(), {});
+ queryClient.setQueryData(keys.clients.lastOnline(), {});
+ vi.mocked(HttpUtil.get).mockResolvedValue(
+ new Msg(true, '', { inbound, totalPeers: 0, peerOffset: 0 }),
+ );
+ const clientIp = '192.0.2.5';
+ const post = vi
+ .mocked(HttpUtil.post)
+ .mockImplementation(
+ async (url) => new Msg(true, '', url.startsWith('/panel/api/clients/ips/') ? [clientIp] : {}),
+ );
+
+ const user = userEvent.setup();
+ renderWithProviders(
+
+
+ ,
+ { queryClient },
+ );
+ await user.click(await screen.findByRole('button', { name: /^more$/i }));
+ await user.click(await screen.findByRole('menuitem', { name: 'Inbound Information' }));
+ const dialog = within(await screen.findByRole('dialog', { name: 'Inbound Information' }));
+ await dialog.findByText(clientIp);
+ const inboundTab = dialog.getByRole('tab', { name: 'Inbound' });
+ await user.click(inboundTab);
+
+ act(() =>
+ socket.handlers.client_stats({
+ inbounds: [{ id: inbound.id, up: 1024, down: 0, total: 0, enable: true }],
+ clients: [{ ...stats, up: 1024 }],
+ }),
+ );
+
+ expect(inboundTab.getAttribute('aria-selected')).toBe('true');
+ await user.click(dialog.getByRole('tab', { name: 'Client' }));
+ expect(dialog.getByText(clientIp)).toBeTruthy();
+ expect(post.mock.calls.filter(([url]) => url.startsWith('/panel/api/clients/ips/'))).toHaveLength(
+ 1,
+ );
+});
diff --git a/frontend/src/test/inbound-peer-export.test.ts b/frontend/src/test/inbound-peer-export.test.ts
new file mode 100644
index 000000000..12a748833
--- /dev/null
+++ b/frontend/src/test/inbound-peer-export.test.ts
@@ -0,0 +1,135 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { BlobReader, TextWriter, ZipReader } from '@zip.js/zip.js';
+
+import { buildInboundPeerArchive } from '@/pages/inbounds/info/peerExport';
+
+const inboundID = 19;
+const serverKey = 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=';
+const peerKey = 'AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=';
+
+function exportPage(peerOffset: number, totalPeers = 2, protocol = 'wireguard') {
+ return {
+ inbound: {
+ id: inboundID,
+ protocol,
+ port: 51820,
+ listen: '',
+ remark: 'edge',
+ settings: {
+ secretKey: serverKey,
+ server: { publicKey: serverKey, h1: '10-20' },
+ clients: [
+ {
+ email: `client-${peerOffset + 1}`,
+ publicKey: serverKey,
+ privateKey: peerKey,
+ allowedIPs: [`10.8.0.${peerOffset + 2}/32`],
+ },
+ ],
+ },
+ streamSettings: {
+ externalProxy: [
+ { dest: 'edge-a.example.test', port: 4443, forceTls: 'same', remark: 'A' },
+ { dest: 'edge-b.example.test', port: 5443, forceTls: 'same', remark: 'B' },
+ ],
+ },
+ },
+ totalPeers,
+ peerOffset,
+ };
+}
+
+function mockExport(pages: unknown[]) {
+ const data = new TextEncoder().encode(pages.map((page) => JSON.stringify(page) + '\n').join(''));
+ const stream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(data.subarray(0, 61));
+ controller.enqueue(data.subarray(61));
+ controller.close();
+ },
+ });
+ const fetch = vi
+ .fn()
+ .mockResolvedValue(
+ new Response(stream, { headers: { 'Content-Type': 'application/x-ndjson' } }),
+ );
+ vi.stubGlobal('fetch', fetch);
+ vi.stubGlobal('window', { setTimeout, location: { hostname: 'panel.example.test' } });
+ return fetch;
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+it.each(['wireguard', 'amneziawg'])(
+ 'archives ordered %s peer configurations and links for every host',
+ async (protocol) => {
+ const fetch = mockExport([exportPage(0, 2, protocol), exportPage(1, 2, protocol)]);
+ const archive = await buildInboundPeerArchive(inboundID, {}, new AbortController().signal);
+ expect(fetch.mock.calls.map(([url]) => url)).toEqual([
+ `/panel/api/inbounds/${inboundID}/peerExport`,
+ ]);
+ const zip = new ZipReader(new BlobReader(archive));
+ try {
+ const files = await zip.getEntries();
+ expect(files.map((file) => file.filename)).toEqual([
+ 'peer-1-1.conf',
+ 'peer-1-2.conf',
+ 'peer-2-1.conf',
+ 'peer-2-2.conf',
+ 'links.txt',
+ ]);
+ const result = await Promise.all(
+ files.map((file) => {
+ if (file.directory) throw new Error('Unexpected directory');
+ return file.getData(new TextWriter());
+ }),
+ );
+ expect(result[0]).toContain('# edge-A-1');
+ expect(result[0]).toContain('Endpoint = edge-a.example.test:4443');
+ expect(result[3]).toContain('# edge-B-2');
+ expect(result[3]).toContain('Address = 10.8.0.3/32');
+ const links = result[4]!.split('\r\n');
+ expect(links).toHaveLength(4);
+ if (protocol === 'wireguard') {
+ expect(new URL(links[3]!).hash).toBe('#edge-B-2');
+ } else {
+ const encoded = links[3]!.slice('vpn://'.length).replace(/-/g, '+').replace(/_/g, '/');
+ expect(atob(encoded)).toBe(result[3]);
+ }
+ } finally {
+ await zip.close();
+ }
+ },
+);
+
+it('does not publish an archive when a peer stream ends before its advertised total', async () => {
+ mockExport([exportPage(0)]);
+ await expect(
+ buildInboundPeerArchive(inboundID, {}, new AbortController().signal),
+ ).rejects.toThrow('Incomplete inbound peer export');
+});
+
+it('cancels the reader when the export is interrupted', async () => {
+ const controller = new AbortController();
+ const cancel = vi.fn();
+ const stream = new ReadableStream({
+ start(reader) {
+ reader.enqueue(new TextEncoder().encode(JSON.stringify(exportPage(0)) + '\n'));
+ controller.abort();
+ },
+ cancel,
+ });
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValue(
+ new Response(stream, { headers: { 'Content-Type': 'application/x-ndjson' } }),
+ ),
+ );
+ vi.stubGlobal('window', { setTimeout, location: { hostname: 'panel.example.test' } });
+ await expect(buildInboundPeerArchive(inboundID, {}, controller.signal)).rejects.toMatchObject({
+ name: 'AbortError',
+ });
+ expect(cancel).toHaveBeenCalledOnce();
+});
diff --git a/frontend/src/test/inbounds-ws-identity.test.tsx b/frontend/src/test/inbounds-ws-identity.test.tsx
index 8760dc78c..70118871f 100644
--- a/frontend/src/test/inbounds-ws-identity.test.tsx
+++ b/frontend/src/test/inbounds-ws-identity.test.tsx
@@ -1,18 +1,27 @@
-import type { ReactNode } from 'react';
-import { act, renderHook, waitFor } from '@testing-library/react';
+import { useLayoutEffect, type ReactNode } from 'react';
+import { act, fireEvent, renderHook, screen, waitFor, within } from '@testing-library/react';
import { QueryClientProvider } from '@tanstack/react-query';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+import { MemoryRouter } from 'react-router';
import { keys } from '@/api/queryKeys';
+import { getSharedWebSocketClient } from '@/api/websocket';
+import { useWebSocket } from '@/hooks/useWebSocket';
+import InboundsPage from '@/pages/inbounds/InboundsPage';
+import { HttpUtil, Msg } from '@/utils';
import { useInbounds } from '@/pages/inbounds/useInbounds';
-import { makeTestQueryClient } from './test-utils';
+import { makeTestQueryClient, renderWithProviders } from './test-utils';
+
+vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
+vi.mock('@/pages/inbounds/form/InboundFormModal', () => ({ default: () => null }));
function seedInbounds() {
const rows = [1, 2].map((id) => ({
id,
protocol: 'vless',
tag: `in-${id}`,
+ originNodeGuid: `node-${id}`,
enable: true,
up: 10,
down: 20,
@@ -33,7 +42,7 @@ function seedInbounds() {
const wrapper = ({ children }: { children: ReactNode }) => (
{children}
);
- return { rows, wrapper };
+ return { queryClient, rows, wrapper };
}
async function renderInbounds() {
@@ -71,6 +80,7 @@ describe('inbound websocket merges keep unchanged state', () => {
it('still rebuilds exactly the rows whose numbers moved', async () => {
const { result } = await renderInbounds();
const before = result.current.dbInbounds;
+ const countsBefore = result.current.clientCount;
act(() =>
result.current.applyClientStatsEvent({
@@ -85,8 +95,10 @@ describe('inbound websocket merges keep unchanged state', () => {
const [first, second] = result.current.dbInbounds;
expect(first).not.toBe(before[0]);
expect(first.up).toBe(99);
+ expect(result.current.clientCount[1]).toBe(countsBefore[1]);
expect(second).not.toBe(before[1]);
expect(second.clientStats?.[0]?.up).toBe(5);
+ expect(result.current.clientCount[2]).not.toBe(countsBefore[2]);
});
it('keeps the client rollup when a traffic push repeats the same online sets', async () => {
@@ -105,3 +117,280 @@ describe('inbound websocket merges keep unchanged state', () => {
expect(result.current.clientCount).toBe(rollup);
});
});
+
+it('reuses unaffected rollups and client metadata on large online updates', async () => {
+ const { queryClient, rows, wrapper } = seedInbounds();
+ const clients = Array.from({ length: 4000 }, (_, i) => ({
+ email: `client-${i}@x`,
+ enable: true,
+ comment: 'shared subscription',
+ }));
+ const settings = JSON.stringify({ clients });
+ queryClient.setQueryData(
+ keys.inbounds.slim(),
+ Array.from({ length: 30 }, (_, i) => ({
+ ...rows[i % 2],
+ id: i + 1,
+ tag: `large-${i + 1}`,
+ settings,
+ })),
+ );
+ const { result } = renderHook(() => useInbounds(), { wrapper });
+ await waitFor(() => expect(result.current.clientCount[30]?.clients).toBe(4000));
+ const before = result.current.clientCount;
+ act(() =>
+ result.current.applyTrafficEvent({
+ onlineByGuid: { 'node-1': [clients[0].email], 'node-2': [clients[1].email] },
+ activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] },
+ }),
+ );
+ await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[0].email]));
+ const initial = result.current.clientCount;
+ expect(initial[1].active).toBe(before[1].active);
+ expect(initial[1].online).toEqual([clients[0].email]);
+
+ act(() =>
+ result.current.applyTrafficEvent({
+ onlineByGuid: { 'node-1': [clients[2].email], 'node-2': [clients[1].email] },
+ activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] },
+ }),
+ );
+ await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[2].email]));
+ expect(result.current.clientCount[1].active).toBe(initial[1].active);
+ for (let id = 2; id <= 30; id++) {
+ expect(result.current.clientCount[id]).toBe(initial[id]);
+ }
+});
+
+it('loads inbounds whose clientStats is null in the slim response', () => {
+ const { rows, queryClient, wrapper } = seedInbounds();
+ queryClient.setQueryData(keys.inbounds.slim(), [
+ { ...rows[0], protocol: 'mixed', settings: '{}', clientStats: null },
+ { ...rows[1], settings: '{"clients":[]}', clientStats: null },
+ ]);
+ const { result } = renderHook(() => useInbounds(), { wrapper });
+ expect(result.current.fetched).toBe(true);
+ expect(result.current.dbInbounds.map((row) => row.id)).toEqual([1, 2]);
+ expect(result.current.clientCount[1]).toBeUndefined();
+ expect(result.current.clientCount[2].clients).toBe(0);
+});
+
+it('withholds large inbound rollups until they match the refetched structure', async () => {
+ const { queryClient, rows, wrapper } = seedInbounds();
+ const withClients = (count: number, remark: string) => ({
+ ...rows[0],
+ remark,
+ settings: JSON.stringify({
+ clients: Array.from({ length: count }, (_, i) => ({
+ email: `member-${i}@example.test`,
+ enable: true,
+ })),
+ }),
+ });
+ const seed = withClients(7000, 'initial');
+ queryClient.setQueryData(keys.inbounds.slim(), [seed]);
+ const displayed: { remark: string; fetched: boolean; pending: boolean; count?: number }[] = [];
+ const { result } = renderHook(
+ () => {
+ const data = useInbounds();
+ useLayoutEffect(() => {
+ const row = data.dbInbounds[0];
+ if (row)
+ displayed.push({
+ remark: row.remark,
+ fetched: data.fetched,
+ pending: data.clientCountsPending,
+ count: data.clientCount[row.id]?.clients,
+ });
+ });
+ return data;
+ },
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(7000));
+ for (const [count, remark] of [
+ [8000, 'large refetch'],
+ [1, 'small refetch'],
+ [9000, 'large again'],
+ ] as const) {
+ act(() => queryClient.setQueryData(keys.inbounds.slim(), [withClients(count, remark)]));
+ await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(count));
+ expect(displayed.filter((view) => view.remark === remark)).toEqual(
+ expect.arrayContaining([{ remark, fetched: true, pending: false, count }]),
+ );
+ for (const view of displayed.filter((view) => view.remark === remark)) {
+ expect(view.fetched).toBe(true);
+ expect(view.count).toBe(view.pending ? undefined : count);
+ }
+ }
+});
+
+it('keeps the search, node filter and selection through large-list refetch and detail hydration', async () => {
+ const { queryClient, rows } = seedInbounds();
+ const clients = (count: number) =>
+ JSON.stringify({
+ clients: Array.from({ length: count }, (_, i) => ({
+ email: `member-${i}@example.test`,
+ enable: true,
+ })),
+ });
+ const local = { ...rows[0], remark: 'Kept local', settings: clients(7000) };
+ const remote = { ...rows[1], remark: 'Kept remote', nodeId: 7 };
+ queryClient.setQueryData(keys.inbounds.slim(), [local, remote]);
+ queryClient.setQueryDefaults(keys.nodes.list(), { staleTime: Infinity });
+ queryClient.setQueryData(keys.nodes.list(), [
+ { id: 7, name: 'Remote', enable: true, status: 'online' },
+ ]);
+ queryClient.setQueryData(keys.hosts.list(), []);
+ const get = vi.mocked(HttpUtil.get);
+ const fallback = get.getMockImplementation();
+ get.mockImplementation(async (url, ...args) =>
+ url === '/panel/api/inbounds/get/1'
+ ? new Msg(true, '', { ...local, remark: 'Kept hydrated', settings: clients(9000) })
+ : ((await fallback?.(url, ...args)) ?? new Msg(true, '', [])),
+ );
+
+ const view = renderWithProviders(
+
+
+ ,
+ { queryClient },
+ );
+ try {
+ await screen.findAllByText('7000');
+ const search = screen.getByRole('textbox', { name: 'Search' });
+ fireEvent.change(search, { target: { value: 'Kept' } });
+ fireEvent.mouseDown(screen.getByRole('combobox', { name: 'Nodes' }));
+ fireEvent.click(await screen.findByText('Local (this panel)'));
+ const row = () => screen.getByRole('row', { name: /Kept (local|refetched|hydrated)/ });
+ fireEvent.click(within(row()).getByRole('checkbox'));
+ const expectContext = () => {
+ expect(screen.getByRole('textbox', { name: 'Search' })).toBe(search);
+ expect((search as HTMLInputElement).value).toBe('Kept');
+ expect(screen.queryByText('Kept remote')).toBeNull();
+ expect((within(row()).getByRole('checkbox') as HTMLInputElement).checked).toBe(true);
+ };
+ expectContext();
+
+ act(() =>
+ queryClient.setQueryData(keys.inbounds.slim(), [
+ { ...local, remark: 'Kept refetched', settings: clients(8000) },
+ remote,
+ ]),
+ );
+ await screen.findAllByText('8000');
+ expectContext();
+
+ fireEvent.click(within(row()).getByRole('button', { name: 'Edit' }));
+ await screen.findAllByText('9000');
+ expectContext();
+ } finally {
+ view.unmount();
+ getSharedWebSocketClient().disconnect();
+ if (fallback) get.mockImplementation(fallback);
+ }
+});
+
+it('reuses the current rollup cache for subscribed websocket updates after defaults change', async () => {
+ const { queryClient, wrapper } = seedInbounds();
+ const sockets: EventTarget[] = [];
+ class FixtureSocket extends EventTarget {
+ static readonly CONNECTING = 0;
+ static readonly OPEN = 1;
+ readyState = FixtureSocket.CONNECTING;
+ constructor() {
+ super();
+ sockets.push(this);
+ }
+ close() {}
+ }
+ const socketClient = getSharedWebSocketClient();
+ socketClient.disconnect();
+ vi.stubGlobal('WebSocket', FixtureSocket);
+ const { result, unmount } = renderHook(
+ () => {
+ const data = useInbounds();
+ useWebSocket({ client_stats: data.applyClientStatsEvent });
+ return data;
+ },
+ { wrapper },
+ );
+
+ try {
+ await waitFor(() => expect(result.current.clientCount[1]?.clients).toBe(1));
+ act(() => queryClient.setQueryData(keys.settings.defaults(), { expireDiff: 3 }));
+ await waitFor(() => expect(result.current.expireDiff).toBe(3 * 86400000));
+ const afterDefaults = result.current.clientCount[1];
+ const [socket] = sockets;
+ if (!socket) throw new Error('WebSocket was not connected');
+ act(() =>
+ socket.dispatchEvent(
+ new MessageEvent('message', {
+ data: JSON.stringify({
+ type: 'client_stats',
+ payload: { inbounds: [{ id: 1, up: 99 }] },
+ }),
+ }),
+ ),
+ );
+ expect(result.current.dbInbounds[0].up).toBe(99);
+ expect(result.current.clientCount[1]).toBe(afterDefaults);
+ } finally {
+ unmount();
+ socketClient.disconnect();
+ vi.unstubAllGlobals();
+ }
+});
+
+it('does not attribute shared online clients without matching inbound activity', async () => {
+ const { rows, queryClient, wrapper } = seedInbounds();
+ queryClient.setQueryData(
+ keys.inbounds.slim(),
+ rows.map((row) => ({
+ ...row,
+ originNodeGuid: 'shared-node',
+ settings: JSON.stringify({ clients: [{ email: 'c1@x', enable: true }] }),
+ })),
+ );
+ const { result } = renderHook(() => useInbounds(), { wrapper });
+ await waitFor(() => expect(result.current.dbInbounds).toHaveLength(2));
+ const publish = (
+ onlineByGuid: Record,
+ activeInbounds: Record,
+ ) => act(() => result.current.applyTrafficEvent({ onlineByGuid, activeInbounds }));
+ publish({ 'shared-node': ['c1@x'] }, {});
+ expect(result.current.clientCount[1].online).toEqual([]);
+ expect(result.current.clientCount[1].onlineAttribution).toBe('unavailable');
+ expect(result.current.clientCount[2].onlineAttribution).toBe('unavailable');
+ publish({ 'shared-node': ['c1@x'] }, { 'shared-node': ['in-2', '\0'] });
+ expect(result.current.clientCount[1].onlineAttribution).toBe('unavailable');
+ expect(result.current.clientCount[2].onlineAttribution).toBe('inbound');
+ expect(result.current.clientCount[2].online).toEqual(['c1@x']);
+ publish({ 'shared-node': ['c1@x'] }, { 'shared-node': [] });
+ expect(result.current.clientCount[1].online).toEqual([]);
+ expect(result.current.clientCount[1].onlineAttribution).toBe('inbound');
+ publish({ 'shared-node': ['c1@x'] }, { 'shared-node': ['in-2'] });
+ expect(result.current.clientCount[1].online).toEqual([]);
+ expect(result.current.clientCount[2].online).toEqual(['c1@x']);
+ publish({}, {});
+ expect(result.current.clientCount[2].onlineAttribution).toBe('unavailable');
+ publish({ 'shared-node': ['c1@x'] }, { 'shared-node': null });
+ expect(result.current.clientCount[2].onlineAttribution).toBe('node');
+ expect(result.current.clientCount[2].online).toEqual(['c1@x']);
+ publish({ 'shared-node': [] }, { 'shared-node': [] });
+ expect(result.current.clientCount[2].onlineAttribution).toBe('inbound');
+ expect(result.current.clientCount[2].online).toEqual([]);
+});
+
+it('keeps online status pending while the activity query is unresolved', async () => {
+ const { queryClient, wrapper } = seedInbounds();
+ queryClient.removeQueries({ queryKey: keys.clients.activeInbounds() });
+ const post = vi.spyOn(HttpUtil, 'post').mockImplementation(() => new Promise(() => {}));
+ try {
+ const { result } = renderHook(() => useInbounds(), { wrapper });
+ await waitFor(() => expect(result.current.clientCount[1].onlineAttribution).toBe('pending'));
+ expect(result.current.clientCount[1].online).toEqual([]);
+ } finally {
+ post.mockRestore();
+ }
+});
diff --git a/frontend/src/test/network-traffic-status.test.tsx b/frontend/src/test/network-traffic-status.test.tsx
index 4136741ad..466b3c107 100644
--- a/frontend/src/test/network-traffic-status.test.tsx
+++ b/frontend/src/test/network-traffic-status.test.tsx
@@ -39,8 +39,6 @@ describe('network traffic status', () => {
down={[200]}
labels={['12:00']}
isMobile={false}
- range={2}
- onRangeChange={() => undefined}
/>,
);
expect(
diff --git a/frontend/src/test/node-fleet-monitoring.test.tsx b/frontend/src/test/node-fleet-monitoring.test.tsx
new file mode 100644
index 000000000..e83b90a0e
--- /dev/null
+++ b/frontend/src/test/node-fleet-monitoring.test.tsx
@@ -0,0 +1,147 @@
+import { act, fireEvent, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { expect, it, vi } from 'vitest';
+import NodeList from '@/pages/nodes/NodeList';
+import type { NodeRecord } from '@/schemas/node';
+import { renderWithProviders } from './test-utils';
+
+const counts = {
+ inboundCount: 1,
+ clientCount: 2,
+ activeCount: 2,
+ disabledCount: 0,
+ depletedCount: 0,
+ onlineCount: 1,
+};
+const noop = () => {};
+const actions = {
+ onAdd: noop,
+ onMtls: noop,
+ onEdit: noop,
+ onDelete: noop,
+ onProbe: noop,
+ onToggleEnable: noop,
+ onUpdateNode: noop,
+ onUpdateSelected: noop,
+ onRestart: noop,
+};
+
+it('hides Master and All nodes without a remote, even with fresh Master telemetry', async () => {
+ const onAdd = vi.fn();
+ const sampledAt = Date.now();
+ function list(nodes: NodeRecord[]) {
+ return (
+
+ );
+ }
+ const view = renderWithProviders(list([]));
+ expect(screen.getAllByRole('row')).toHaveLength(2);
+ expect(screen.queryByRole('searchbox')).toBeNull();
+ expect(screen.queryByText('All nodes')).toBeNull();
+ expect(screen.queryByRole('rowheader', { name: 'Master' })).toBeNull();
+ expect(screen.queryByRole('switch')).toBeNull();
+ await userEvent.click(screen.getByRole('button', { name: /add node/i }));
+ expect(onAdd).toHaveBeenCalledOnce();
+ view.rerender(list([{ id: 1, name: 'disabled edge', enable: false, status: 'online' }]));
+ const rows = screen.getAllByRole('row');
+ expect(rows[1].textContent).toContain('All nodes');
+ expect(rows[1].textContent).toContain('1/2 reporting');
+ expect(rows[2].textContent).toContain('Master');
+ expect(rows[3].textContent).toContain('disabled edge');
+ fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'unmatched' } });
+ expect(screen.getAllByRole('row')).toHaveLength(3);
+ expect(screen.getByText('1/2 reporting')).toBeTruthy();
+ view.rerender(list([]));
+ expect(screen.getAllByRole('row')).toHaveLength(2);
+ expect(screen.queryByText(/totals use reporting nodes/)).toBeNull();
+});
+
+it('keeps the column headings over an empty-state row until a remote is registered', () => {
+ function list(nodes: NodeRecord[]) {
+ return (
+
+ );
+ }
+ const view = renderWithProviders(list([]));
+ const table = within(screen.getByRole('table'));
+ expect(table.getByRole('columnheader', { name: 'Status' })).toBeTruthy();
+ expect(table.getByRole('cell', { name: 'Nothing here yet' })).toBeTruthy();
+ view.rerender(list([{ id: 1, name: 'edge', enable: true, status: 'online' }]));
+ expect(screen.queryByText('Nothing here yet')).toBeNull();
+ expect(screen.getByRole('rowheader', { name: 'edge' })).toBeTruthy();
+});
+
+it('expires only the stale host and keeps weighted RAM and live byte rates separate', () => {
+ vi.useFakeTimers();
+ try {
+ const now = Date.now();
+ renderWithProviders(
+ ,
+ );
+ const fleet = () => within(screen.getByRole('row', { name: /All nodes/ }));
+ expect(fleet().getByText(/10 GB \/ 24 GB · 41.7%/)).toBeTruthy();
+ expect(fleet().getByText('30.0%')).toBeTruthy();
+ expect(fleet().getByLabelText(/download 3.00 KB\/s/i)).toBeTruthy();
+ act(() => vi.advanceTimersByTime(501));
+ expect(fleet().getByText('1/2 reporting')).toBeTruthy();
+ expect(fleet().getByText('40.0%')).toBeTruthy();
+ expect(fleet().getByLabelText(/download 2.00 KB\/s/i)).toBeTruthy();
+ expect(
+ within(screen.getByRole('row', { name: /edge/ })).getByLabelText(/download —/i),
+ ).toBeTruthy();
+ } finally {
+ vi.useRealTimers();
+ }
+});
diff --git a/frontend/src/test/node-form-token.test.tsx b/frontend/src/test/node-form-token.test.tsx
new file mode 100644
index 000000000..9ab5fd585
--- /dev/null
+++ b/frontend/src/test/node-form-token.test.tsx
@@ -0,0 +1,200 @@
+import { useState } from 'react';
+import { fireEvent, screen, waitFor, within } from '@testing-library/react';
+import { expect, it, vi } from 'vitest';
+
+import NodeFormModal from '@/pages/nodes/NodeFormModal';
+import type { NodeRecord, ProbeResult } from '@/schemas/node';
+import { Msg } from '@/utils';
+import { chooseSelectOption, renderWithProviders } from './test-utils';
+
+const stored: NodeRecord = {
+ id: 11,
+ name: 'Primary',
+ address: 'primary.example.test',
+ port: 2053,
+ status: 'online',
+ enable: true,
+ hasApiToken: true,
+};
+const other: NodeRecord = { ...stored, id: 22, name: 'Secondary', tlsVerifyMode: 'pin' };
+const unexpectedValue = 'unrelated-fixture';
+const apiTokenLabel = { selector: 'input' };
+
+function setup() {
+ const probe = vi.fn(async (payload: Partial) =>
+ payload.apiToken === 'incorrect-fixture'
+ ? new Msg(false, 'Credential rejected')
+ : new Msg(true, '', { status: 'online', latencyMs: 1 }),
+ );
+ const save = vi.fn(async (_payload: Partial) => new Msg(true));
+ const fingerprint = vi.fn(
+ async (_payload: Partial) => new Msg(true, '', 'fixture-pin'),
+ );
+ const inbounds = vi.fn(async (_payload: Partial) => new Msg(true, '', []));
+
+ function Page() {
+ const [node, setNode] = useState(null);
+ const [open, setOpen] = useState(false);
+ return (
+ <>
+
+
+
+
+ >
+ );
+ }
+
+ const view = renderWithProviders();
+ return { ...view, probe, save, fingerprint, inbounds };
+}
+
+function openForm(name: string) {
+ fireEvent.click(screen.getByRole('button', { name }));
+ return within(screen.getByRole('dialog'));
+}
+
+it('keeps the stored token on first open even if a password input receives an unexpected value', async () => {
+ for (let i = 0; i < 2; i++) {
+ const { probe, save, unmount } = setup();
+ const dialog = openForm('Edit primary');
+ const unexpectedInput = dialog.queryByLabelText('API Token', apiTokenLabel);
+ if (unexpectedInput) {
+ fireEvent.change(unexpectedInput, { target: { value: unexpectedValue } });
+ }
+ fireEvent.click(dialog.getByRole('button', { name: 'Test Connection' }));
+ await waitFor(() => expect(probe).toHaveBeenCalledTimes(1));
+ expect(probe.mock.calls[0]?.[0]).toMatchObject({ id: 11 });
+ expect(probe.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
+ fireEvent.click(dialog.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ expect(save.mock.calls[0]?.[0]).toMatchObject({ id: 11 });
+ expect(save.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
+ unmount();
+ }
+});
+
+it('ignores autofill in replacement mode, probes explicit edits, and clears them across opens', async () => {
+ const { probe, save, fingerprint, inbounds } = setup();
+ const dialog = openForm('Edit primary');
+ fireEvent.click(dialog.getByRole('checkbox', { name: 'Replace API Token' }));
+ const input = dialog.getByLabelText('API Token', apiTokenLabel);
+ expect(input.value).toBe('');
+ fireEvent.input(input, {
+ target: { value: unexpectedValue },
+ inputType: 'insertReplacementText',
+ });
+ expect(input.value).toBe('');
+ fireEvent.click(dialog.getByRole('button', { name: 'Test Connection' }));
+ await waitFor(() => expect(probe).toHaveBeenCalledTimes(1));
+ expect(probe.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
+
+ fireEvent.input(input, {
+ target: { value: 'incorrect-fixture' },
+ inputType: 'insertFromPaste',
+ });
+ fireEvent.click(dialog.getByRole('button', { name: 'Save' }));
+ await dialog.findByText('Credential rejected');
+ expect(probe.mock.calls[1]?.[0]).toMatchObject({ id: 11, apiToken: 'incorrect-fixture' });
+ expect(save).not.toHaveBeenCalled();
+ fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
+
+ const reopened = openForm('Edit primary');
+ expect(reopened.queryByLabelText('API Token', apiTokenLabel)).toBeNull();
+ expect(reopened.queryByText('Credential rejected')).toBeNull();
+ fireEvent.click(reopened.getByRole('button', { name: 'Cancel' }));
+
+ const secondary = openForm('Edit secondary');
+ fireEvent.click(secondary.getByRole('button', { name: 'Fetch' }));
+ await waitFor(() => expect(fingerprint).toHaveBeenCalledTimes(1));
+ expect(fingerprint.mock.calls[0]?.[0]).toMatchObject({ id: 22 });
+ expect(fingerprint.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
+ chooseSelectOption(secondary.getByLabelText('Inbound import').id, 'Selected inbounds');
+ fireEvent.mouseDown(secondary.getByRole('combobox', { name: 'Inbounds' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Load inbounds from node' }));
+ await waitFor(() => expect(inbounds).toHaveBeenCalledTimes(1));
+ expect(inbounds.mock.calls[0]?.[0]).toMatchObject({ id: 22 });
+ expect(inbounds.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
+});
+
+it('updates the probe credential when undoing and redoing a replacement', async () => {
+ const { probe } = setup();
+ const dialog = openForm('Edit primary');
+ fireEvent.click(dialog.getByRole('checkbox', { name: 'Replace API Token' }));
+ const input = dialog.getByLabelText('API Token', apiTokenLabel);
+ const replacement = 'replacement-fixture';
+ fireEvent.input(input, { target: { value: replacement }, inputType: 'insertFromPaste' });
+ fireEvent.input(input, { target: { value: '' }, inputType: 'historyUndo' });
+ expect(input.value).toBe('');
+ fireEvent.click(dialog.getByRole('button', { name: 'Test Connection' }));
+ await waitFor(() => expect(probe).toHaveBeenCalledTimes(1));
+ expect(probe.mock.calls[0]?.[0]).toMatchObject({ id: 11 });
+ expect(probe.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
+
+ fireEvent.input(input, { target: { value: replacement }, inputType: 'historyRedo' });
+ expect(input.value).toBe(replacement);
+ fireEvent.click(dialog.getByRole('button', { name: 'Test Connection' }));
+ await waitFor(() => expect(probe).toHaveBeenCalledTimes(2));
+ expect(probe.mock.calls[1]?.[0]).toMatchObject({ id: 11, apiToken: replacement });
+});
+
+it('requires an entered token for ordinary additions and allows mTLS additions without one', async () => {
+ const { probe, save } = setup();
+ const editing = openForm('Edit primary');
+ fireEvent.click(editing.getByRole('checkbox', { name: 'Replace API Token' }));
+ fireEvent.input(editing.getByLabelText('API Token', apiTokenLabel), {
+ target: { value: 'explicit-fixture' },
+ inputType: 'insertFromPaste',
+ });
+ fireEvent.click(editing.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
+ expect(save.mock.calls[0]?.[0]).toMatchObject({ id: 11, apiToken: 'explicit-fixture' });
+
+ const adding = openForm('Add node');
+ const token = adding.getByLabelText('API Token', apiTokenLabel);
+ expect(token.value).toBe('');
+ fireEvent.change(adding.getByLabelText('Name'), { target: { value: 'New node' } });
+ fireEvent.change(adding.getByLabelText('Address'), { target: { value: 'new.example.test' } });
+ fireEvent.change(token, { target: { value: unexpectedValue } });
+ fireEvent.click(adding.getByRole('button', { name: 'Save' }));
+ await screen.findByText('Name, address, port and API token are required');
+ expect(probe).toHaveBeenCalledTimes(1);
+ chooseSelectOption(
+ adding.getByLabelText('TLS verification').id,
+ 'Mutual TLS (client certificate)',
+ );
+ fireEvent.click(adding.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(save).toHaveBeenCalledTimes(2));
+ expect(save.mock.calls[1]?.[0]).toMatchObject({ id: 0, tlsVerifyMode: 'mtls' });
+ expect(save.mock.calls[1]?.[0]).not.toHaveProperty('apiToken');
+});
diff --git a/frontend/src/test/node-list-a11y.test.tsx b/frontend/src/test/node-list-a11y.test.tsx
index 8d86fa442..532d6d649 100644
--- a/frontend/src/test/node-list-a11y.test.tsx
+++ b/frontend/src/test/node-list-a11y.test.tsx
@@ -18,11 +18,10 @@ const failing: NodeRecord = {
lastError: 'dial tcp 10.0.0.2:2053: i/o timeout',
};
-function renderList(isMobile: boolean) {
+function renderList() {
renderWithProviders(
{
it('announces the node error from the status column', () => {
- renderList(false);
+ renderList();
expect(screen.getByRole('img', { name: failing.lastError }).tagName).toBe('SPAN');
});
- it.each([false, true])('names the enable switch (mobile=%s)', (isMobile) => {
- renderList(isMobile);
+ it('names the enable switch', () => {
+ renderList();
expect(screen.getByRole('switch', { name: 'Enabled' }).getAttribute('aria-checked')).toBe(
'true',
diff --git a/frontend/src/test/node-list-online-total.test.tsx b/frontend/src/test/node-list-online-total.test.tsx
index d6bbc9eea..fe5ce9431 100644
--- a/frontend/src/test/node-list-online-total.test.tsx
+++ b/frontend/src/test/node-list-online-total.test.tsx
@@ -1,4 +1,4 @@
-import { screen, within } from '@testing-library/react';
+import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';
@@ -9,10 +9,7 @@ import { renderWithProviders } from './test-utils';
const noop = () => {};
-function renderNode(
- counts: Pick,
- isMobile = false,
-) {
+function renderNode(counts: Pick) {
const node: NodeRecord = {
id: 1,
name: 'edge',
@@ -25,7 +22,6 @@ function renderNode(
renderWithProviders(
{
renderNode(counts);
expect(screen.getByText('7')).toBeTruthy();
- expect(screen.queryByText(/\d \/ \d/)).toBeNull();
- });
-
- it('shows synced / total in the mobile stats dialog', async () => {
- renderNode({ onlineCount: 3, onlineTotalCount: 12 }, true);
-
- await userEvent.click(screen.getByRole('button', { name: 'More Information' }));
-
- expect(within(await screen.findByRole('dialog')).getByText('3 / 12 Online')).toBeTruthy();
+ expect(screen.queryByText(/^\d+ \/ \d+$/)).toBeNull();
});
});
diff --git a/frontend/src/test/node-list-rerender.test.tsx b/frontend/src/test/node-list-rerender.test.tsx
index 486ffc94a..8e232dd32 100644
--- a/frontend/src/test/node-list-rerender.test.tsx
+++ b/frontend/src/test/node-list-rerender.test.tsx
@@ -44,7 +44,6 @@ describe('NodeList re-render', () => {
const noop = () => {};
const props = {
nodes,
- isMobile: false,
latestVersion: '3.0.1',
selectedIds: [] as number[],
onSelectionChange: noop,
diff --git a/frontend/src/test/node-list-rowkey.test.tsx b/frontend/src/test/node-list-rowkey.test.tsx
index 7b1dcc216..1e303bae6 100644
--- a/frontend/src/test/node-list-rowkey.test.tsx
+++ b/frontend/src/test/node-list-rowkey.test.tsx
@@ -24,7 +24,6 @@ describe('NodeList desktop table row keys', () => {
renderWithProviders(
) {
renderWithProviders(
{};
describe('node metric availability', () => {
- it.each([false, true])(
- 'does not present unavailable CPU as measured zero (mobile=%s)',
- (isMobile) => {
- const node = NodeRecordSchema.parse({
- id: 1,
- name: 'edge',
- status: 'online',
- enable: true,
- cpuPct: 0,
- memPct: 44.4,
- uptimeSecs: 0,
- unavailableMetrics: ['cpu', 'uptime'],
- });
- renderWithProviders(
- ,
- );
- if (isMobile) fireEvent.click(screen.getByRole('button', { name: 'More Information' }));
- expect(screen.queryByText('0.0%')).toBeNull();
- expect(screen.getAllByText('—').length).toBeGreaterThanOrEqual(2);
- },
- );
- it('keeps a measured zero CPU and an unprobed uptime apart', () => {
+ it('does not present unavailable CPU as measured zero', () => {
const node = NodeRecordSchema.parse({
id: 1,
name: 'edge',
@@ -52,6 +17,34 @@ describe('node metric availability', () => {
cpuPct: 0,
memPct: 44.4,
uptimeSecs: 0,
+ unavailableMetrics: ['cpu', 'uptime'],
+ });
+ renderWithProviders(
+ ,
+ );
+ expect(screen.queryByText('0.0%')).toBeNull();
+ expect(screen.getAllByText('—').length).toBeGreaterThanOrEqual(2);
+ });
+ it('keeps a measured zero CPU and an unprobed uptime apart', () => {
+ const node = NodeRecordSchema.parse({
+ id: 1,
+ name: 'edge',
+ status: 'online',
+ enable: true,
+ telemetry: { sampledAt: Date.now(), cpuPct: 0 },
});
renderWithProviders(
{
/>,
);
expect(screen.getByText('0.0%')).not.toBeNull();
- const headers = screen.getAllByRole('columnheader').map((h) => h.textContent);
- const cells = within(screen.getAllByRole('row')[1]).getAllByRole('cell');
- expect(cells[headers.indexOf('Uptime')].textContent).toBe('-');
+ const cell = within(screen.getAllByRole('row')[1]).getByTitle('Uptime');
+ expect(cell.textContent).toBe('Up —');
});
});
@@ -90,43 +82,40 @@ describe('node network speed', () => {
onUpdateSelected: noop,
onRestart: noop,
};
- it.each([false, true])(
- 'renders current directions and preserves measured zero (mobile=%s)',
- (isMobile) => {
- const node = NodeRecordSchema.parse({
- id: 1,
- name: 'edge',
- enable: true,
- status: 'online',
- lastHeartbeat: Math.floor(Date.now() / 1000),
- netDown: 2048,
- netUp: 0,
- });
- function Fixture() {
- const [record, setRecord] = useState(node);
- return (
- <>
-
-
- >
- );
- }
- renderWithProviders();
- if (isMobile) fireEvent.click(screen.getByRole('button', { name: 'More Information' }));
- expect(screen.getByLabelText(/^download .*2\.00 KB\/s$/i).textContent).toContain('2.00 KB/s');
- expect(screen.getByLabelText(/^upload .*0 B\/s$/i).textContent).toContain('0 B/s');
- // A heartbeat cache update must also refresh the open mobile stats dialog.
- fireEvent.click(screen.getByText('Age sample'));
- expect(screen.getByLabelText(/^download .*—$/i).textContent).toContain('—');
- },
- );
+ it('renders current directions and preserves measured zero', () => {
+ const node = NodeRecordSchema.parse({
+ id: 1,
+ name: 'edge',
+ enable: true,
+ status: 'online',
+ lastHeartbeat: Math.floor(Date.now() / 1000),
+ telemetry: { sampledAt: Date.now(), netDown: 2048, netUp: 0 },
+ });
+ function Fixture() {
+ const [record, setRecord] = useState(node);
+ return (
+ <>
+
+
+ >
+ );
+ }
+ renderWithProviders();
+ expect(screen.getByLabelText(/^download .*2\.00 KB\/s$/i).textContent).toContain('2.00 KB/s');
+ expect(screen.getByLabelText(/^upload .*0 B\/s$/i).textContent).toContain('0 B/s');
+ fireEvent.click(screen.getByText('Age sample'));
+ expect(screen.getByLabelText(/^download .*—$/i).textContent).toContain('—');
+ });
it.each([-120, 120])('expires throughput with %s seconds of clock skew', (skew) => {
vi.useFakeTimers();
diff --git a/frontend/src/test/node-overview-refresh.test.tsx b/frontend/src/test/node-overview-refresh.test.tsx
new file mode 100644
index 000000000..bd5b581b3
--- /dev/null
+++ b/frontend/src/test/node-overview-refresh.test.tsx
@@ -0,0 +1,47 @@
+import { act, fireEvent, screen, within } from '@testing-library/react';
+import { expect, it, vi } from 'vitest';
+
+import { keys } from '@/api/queryKeys';
+import NodesPage from '@/pages/nodes/NodesPage';
+import { HttpUtil, Msg } from '@/utils';
+import { makeTestQueryClient, renderWithProviders } from './test-utils';
+
+vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
+
+it('keeps node actions and the current filter after an overview refresh fails', async () => {
+ const counts = {
+ inboundCount: 0,
+ clientCount: 0,
+ activeCount: 0,
+ disabledCount: 0,
+ depletedCount: 0,
+ onlineCount: 0,
+ };
+ let available = true;
+ const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (path) => {
+ if (path !== '/panel/api/nodes/overview') return new Msg(true, '', {});
+ return available
+ ? new Msg(true, '', {
+ nodes: [{ id: 1, name: 'edge-one', enable: true, status: 'online' }],
+ master: { counts },
+ fleet: counts,
+ })
+ : new Msg(false, 'Overview unavailable');
+ });
+ const queryClient = makeTestQueryClient();
+ try {
+ renderWithProviders(, { queryClient });
+ const search = await screen.findByRole('searchbox');
+ fireEvent.change(search, { target: { value: 'edge' } });
+ const row = screen.getByRole('row', { name: /edge-one/ });
+
+ available = false;
+ await act(async () => queryClient.refetchQueries({ queryKey: keys.nodes.overview() }));
+ expect(await screen.findByText('Overview unavailable')).toBeTruthy();
+ expect(screen.getByRole('searchbox')).toBe(search);
+ expect((search as HTMLInputElement).value).toBe('edge');
+ expect(within(row).getByRole('button', { name: 'Edit' })).toBeTruthy();
+ } finally {
+ get.mockRestore();
+ }
+});
diff --git a/frontend/src/test/node-reported-url-segments.test.tsx b/frontend/src/test/node-reported-url-segments.test.tsx
index f1dc24fcd..05ff2f422 100644
--- a/frontend/src/test/node-reported-url-segments.test.tsx
+++ b/frontend/src/test/node-reported-url-segments.test.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react';
-import { act, render, renderHook } from '@testing-library/react';
+import { act, render, renderHook, waitFor } from '@testing-library/react';
import { QueryClientProvider } from '@tanstack/react-query';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -22,7 +22,7 @@ describe('node-reported values stay one URL path segment', () => {
post.mockClear();
});
- it('encodes the client email in the inbound info IP-log request', () => {
+ it('encodes the client email in the inbound info IP-log request', async () => {
const dbInbound = new DBInbound({
id: 2,
protocol: 'http',
@@ -35,7 +35,11 @@ describe('node-reported values stay one URL path segment', () => {
render( {}} dbInbound={dbInbound} ipLimitEnable />);
- expect(post).toHaveBeenCalledWith(`/panel/api/clients/ips/${encoded}`);
+ await waitFor(() => {
+ expect(post).toHaveBeenCalledWith(`/panel/api/clients/ips/${encoded}`, undefined, {
+ signal: expect.any(AbortSignal),
+ });
+ });
});
it('encodes the host group id in the host mutations', async () => {
diff --git a/frontend/src/test/node-restart.test.tsx b/frontend/src/test/node-restart.test.tsx
index 6ba9cf782..172f48eb3 100644
--- a/frontend/src/test/node-restart.test.tsx
+++ b/frontend/src/test/node-restart.test.tsx
@@ -8,29 +8,17 @@ import type { NodeRecord } from '@/schemas/node';
import { renderWithProviders } from './test-utils';
const state = vi.hoisted(() => ({
- isMobile: false,
nodes: [] as NodeRecord[],
refetch: vi.fn(),
}));
-vi.mock('@/hooks/useMediaQuery', () => ({ useMediaQuery: () => ({ isMobile: state.isMobile }) }));
vi.mock('@/api/queries/useNodesQuery', () => ({
- useNodesQuery: () => ({
+ useNodeOverviewQuery: () => ({
nodes: state.nodes,
loading: false,
fetched: true,
fetchError: '',
refetch: state.refetch,
- totals: {
- total: state.nodes.length,
- online: 0,
- offline: 1,
- avgLatency: 0,
- inbounds: 0,
- clients: 0,
- onlineClients: 0,
- depleted: 0,
- },
}),
}));
vi.mock('@/pages/nodes/NodeFormModal', () => ({ default: () => null }));
@@ -38,7 +26,6 @@ vi.mock('@/pages/nodes/NodeHistoryPanel', () => ({ default: () => null }));
vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
beforeEach(() => {
- state.isMobile = false;
state.nodes = [{ id: 7, name: 'edge-seven', guid: 'seven', enable: true, status: 'offline' }];
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', {}));
});
@@ -51,43 +38,39 @@ async function openRestart(label: string) {
}
describe('remote node restart', () => {
- it.each([false, true])(
- 'confirms each action and sends only the selected request (mobile=%s)',
- async (mobile) => {
- state.isMobile = mobile;
- const post = vi
- .spyOn(HttpUtil, 'post')
- .mockResolvedValue({ success: true, msg: '', obj: null });
- renderWithProviders(
-
-
- ,
- );
- let dialog = await openRestart('Restart Xray');
- expect(dialog.textContent).toContain('edge-seven');
- expect(post).not.toHaveBeenCalled();
- fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));
+ it('confirms each action and sends only the selected request', async () => {
+ const post = vi
+ .spyOn(HttpUtil, 'post')
+ .mockResolvedValue({ success: true, msg: '', obj: null });
+ renderWithProviders(
+
+
+ ,
+ );
+ let dialog = await openRestart('Restart Xray');
+ expect(dialog.textContent).toContain('edge-seven');
+ expect(post).not.toHaveBeenCalled();
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));
+
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(post).not.toHaveBeenCalled();
+ for (const [label, action, success] of [
+ ['Restart Xray', 'restartXray', 'Xray restarted on the node.'],
+ [
+ 'Restart Panel',
+ 'restartPanel',
+ 'Panel restart request accepted. The node may be temporarily unavailable.',
+ ],
+ ]) {
+ dialog = await openRestart(label);
+ fireEvent.click(within(dialog).getByRole('button', { name: label }));
+ await screen.findByText(success);
+ expect(post.mock.calls.at(-1)?.[0]).toBe(`/panel/api/nodes/${action}/7`);
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
- expect(post).not.toHaveBeenCalled();
- for (const [label, action, success] of [
- ['Restart Xray', 'restartXray', 'Xray restarted on the node.'],
- [
- 'Restart Panel',
- 'restartPanel',
- 'Panel restart request accepted. The node may be temporarily unavailable.',
- ],
- ]) {
- dialog = await openRestart(label);
- fireEvent.click(within(dialog).getByRole('button', { name: label }));
- await screen.findByText(success);
- expect(post.mock.calls.at(-1)?.[0]).toBe(`/panel/api/nodes/${action}/7`);
-
- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
- }
- expect(post).toHaveBeenCalledTimes(2);
- },
- );
+ }
+ expect(post).toHaveBeenCalledTimes(2);
+ });
it('keeps both actions disabled while the request is pending and reports a node rejection without retrying', async () => {
let finish!: (msg: Msg) => void;
@@ -116,32 +99,28 @@ describe('remote node restart', () => {
expect(post).toHaveBeenCalledTimes(1);
});
- it.each([false, true])(
- 'does not offer restart for transitive nodes and disables it for disabled nodes (mobile=%s)',
- async (mobile) => {
- state.isMobile = mobile;
- state.nodes = [
- { id: 0, name: 'child', guid: 'child', transitive: true, enable: true, status: 'online' },
- ];
- const view = renderWithProviders(
-
-
- ,
+ it('does not offer restart for transitive nodes and disables it for disabled nodes', async () => {
+ state.nodes = [
+ { id: 0, name: 'child', guid: 'child', transitive: true, enable: true, status: 'online' },
+ ];
+ const view = renderWithProviders(
+
+
+ ,
+ );
+ expect(screen.queryByRole('button', { name: /^more$/i })).toBeNull();
+ view.unmount();
+ state.nodes = [{ id: 7, name: 'disabled', enable: false }];
+ renderWithProviders(
+
+
+ ,
+ );
+ fireEvent.click(screen.getByRole('button', { name: /^more$/i }));
+ for (const name of ['Restart Xray', 'Restart Panel']) {
+ expect((await screen.findByRole('menuitem', { name })).getAttribute('aria-disabled')).toBe(
+ 'true',
);
- expect(screen.queryByRole('button', { name: /^more$/i })).toBeNull();
- view.unmount();
- state.nodes = [{ id: 7, name: 'disabled', enable: false }];
- renderWithProviders(
-
-
- ,
- );
- fireEvent.click(screen.getByRole('button', { name: /^more$/i }));
- for (const name of ['Restart Xray', 'Restart Panel']) {
- expect((await screen.findByRole('menuitem', { name })).getAttribute('aria-disabled')).toBe(
- 'true',
- );
- }
- },
- );
+ }
+ });
});
diff --git a/frontend/src/test/overview-global-range.test.tsx b/frontend/src/test/overview-global-range.test.tsx
new file mode 100644
index 000000000..35e3722f9
--- /dev/null
+++ b/frontend/src/test/overview-global-range.test.tsx
@@ -0,0 +1,150 @@
+import { fireEvent, screen, waitFor, within } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+import IndexPage from '@/pages/index/IndexPage';
+import { renderWithProviders } from './test-utils';
+
+const { get, chart } = vi.hoisted(() => ({ get: vi.fn(), chart: vi.fn() }));
+
+vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
+vi.mock('@/components/sponsor/SponsorSlot', () => ({ default: () => null }));
+vi.mock('@/components/viz', async (importOriginal) => {
+ const original = await importOriginal();
+ return {
+ ...original,
+ Sparkline: ({ data, data2 }: { data: number[]; data2?: number[] }) => {
+ chart(data, data2);
+ return null;
+ },
+ };
+});
+vi.mock('@/api/queries/useStatusQuery', async () => {
+ const { Status } = await import('@/models/status');
+ const status = new Status({ cpu: 12, mem: { current: 10, total: 100 } });
+ return { useStatusQuery: () => ({ status, fetched: true, fetchError: '', refresh: vi.fn() }) };
+});
+vi.mock('@/utils', async (importOriginal) => {
+ const original = await importOriginal();
+ return { ...original, HttpUtil: { get, post: vi.fn().mockResolvedValue({ success: false }) } };
+});
+
+const key = '3x-ui:overview-range:/test/';
+const rangeControl = () => screen.getByRole('combobox', { name: 'Time range' });
+const historyRequests = () =>
+ get.mock.calls
+ .map(([path]) => String(path))
+ .filter((path) => /\/(overviewHistory|history)\//.test(path));
+
+beforeEach(() => {
+ vi.stubGlobal('X_UI_BASE_PATH', '/test/');
+ window.localStorage.clear();
+ get.mockReset();
+ chart.mockClear();
+ get.mockImplementation(async (path: string) => {
+ if (path.includes('/overviewHistory/')) {
+ const range = Number(path.split('/').at(-1));
+ return {
+ success: true,
+ obj: Object.fromEntries(
+ ['cpu', 'mem', 'swap', 'diskUsage', 'netUp', 'netDown', 'tcpCount', 'udpCount'].map(
+ (metric, i) => [metric, [{ t: 1, v: range + i }]],
+ ),
+ ),
+ };
+ }
+ return { success: true, obj: [] };
+ });
+});
+
+afterEach(() => {
+ window.localStorage.clear();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+it('uses one action-bar selector to update all chart summaries and save the range', async () => {
+ renderWithProviders();
+ const control = rangeControl();
+ const metrics = screen.getByRole('button', { name: 'Xray Metrics' });
+ expect(metrics.closest('.ov-bar')?.contains(control)).toBe(true);
+
+ fireEvent.mouseDown(control);
+ fireEvent.click(await screen.findByRole('option', { name: '30m' }));
+ await waitFor(() => expect(window.localStorage.getItem(key)).toBe('30'));
+ expect(
+ await within(screen.getByRole('group', { name: 'CPU' })).findAllByText('30%'),
+ ).toHaveLength(2);
+ expect(
+ await within(screen.getByRole('group', { name: 'RAM' })).findAllByText('31%'),
+ ).toHaveLength(2);
+ expect(historyRequests()).toContain('/panel/api/server/overviewHistory/30');
+ for (const value of [30, 31, 32, 33]) {
+ expect(chart).toHaveBeenCalledWith([value], undefined);
+ }
+ expect(chart).toHaveBeenCalledWith([34], [35]);
+ expect(chart).toHaveBeenCalledWith([36], [37]);
+});
+
+it.each([5, 30, 60, 360, 720])(
+ 'restores %im on mount without querying the default history window',
+ async (range) => {
+ window.localStorage.setItem(key, String(range));
+ const first = renderWithProviders();
+ await waitFor(() =>
+ expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/' + range]),
+ );
+ first.unmount();
+ get.mockClear();
+ renderWithProviders();
+ await waitFor(() =>
+ expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/' + range]),
+ );
+ },
+);
+
+it.each([null, '2', '90', 'bad'])('uses the live range for %s', async (saved) => {
+ if (saved !== null) window.localStorage.setItem(key, saved);
+ window.localStorage.setItem('3x-ui:overview-range:/another-panel/', '720');
+ renderWithProviders();
+ expect(rangeControl()).toBeTruthy();
+ await waitFor(() => expect(historyRequests()).toContain('/panel/api/server/history/cpu/2'));
+ expect(historyRequests().some((path) => path.includes('/overviewHistory/'))).toBe(false);
+});
+
+it('renders even when storage is blocked', async () => {
+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation((name) => {
+ if (name === key) throw new DOMException('Storage blocked', 'SecurityError');
+ return null;
+ });
+ renderWithProviders();
+ expect(rangeControl()).toBeTruthy();
+ await waitFor(() => expect(historyRequests()).toContain('/panel/api/server/history/cpu/2'));
+});
+
+it('applies a new range and updates its charts when saving the preference is blocked', async () => {
+ window.localStorage.setItem(key, '30');
+ const originalSetItem = Storage.prototype.setItem;
+ const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(function (
+ this: Storage,
+ name,
+ value,
+ ) {
+ if (name === key) throw new DOMException('Storage blocked', 'QuotaExceededError');
+ originalSetItem.call(this, name, value);
+ });
+ renderWithProviders();
+ await waitFor(() => expect(historyRequests()).toEqual(['/panel/api/server/overviewHistory/30']));
+
+ fireEvent.mouseDown(rangeControl());
+ fireEvent.click(await screen.findByRole('option', { name: '1h' }));
+
+ expect(setItem).toHaveBeenCalledWith(key, '60');
+ expect(window.localStorage.getItem(key)).toBe('30');
+ expect(
+ await within(screen.getByRole('group', { name: 'CPU' })).findAllByText('60%'),
+ ).toHaveLength(2);
+ expect(historyRequests()).toEqual([
+ '/panel/api/server/overviewHistory/30',
+ '/panel/api/server/overviewHistory/60',
+ ]);
+});
diff --git a/frontend/src/test/overview-ranged-history.test.tsx b/frontend/src/test/overview-ranged-history.test.tsx
index d3573bebd..a24b335b5 100644
--- a/frontend/src/test/overview-ranged-history.test.tsx
+++ b/frontend/src/test/overview-ranged-history.test.tsx
@@ -2,7 +2,8 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, expect, it, vi } from 'vitest';
import { Status } from '@/models/status';
-import { useOverviewHistory } from '@/pages/index/useOverviewHistory';
+import { mean, peak, useOverviewHistory } from '@/pages/index/useOverviewHistory';
+import { TimeFormatter } from '@/utils';
const { get } = vi.hoisted(() => ({ get: vi.fn() }));
vi.mock('@/utils', async (importOriginal) => {
@@ -110,7 +111,232 @@ it('keeps sampling the live trend while a longer range is shown', async () => {
);
await waitFor(() => expect(result.current.series.cpu).toEqual([90]));
rerender({ status: new Status({ cpu: 12 }), bucket: 720 });
- rerender({ status: new Status({ cpu: 13 }), bucket: 2 });
+ await act(async () => rerender({ status: new Status({ cpu: 13 }), bucket: 2 }));
expect(result.current.series.cpu).toEqual([11, 12, 13]);
});
+
+it('only seeds buckets older than the live samples collected while a longer range was open', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
+ try {
+ get.mockImplementation(async (path: string) => ({
+ success: true,
+ obj: ranged(path)
+ ? rollups(90)
+ : [
+ { t: 96, v: 20 },
+ { t: 98, v: 30 },
+ { t: 100, v: 91 },
+ { t: 102, v: 92 },
+ { t: 104, v: 93 },
+ ],
+ }));
+ const { result, rerender } = renderHook(
+ ({ status, bucket }) => useOverviewHistory(status, true, bucket),
+ { initialProps: { status: new Status({ cpu: 11 }), bucket: 60 } },
+ );
+ now.mockReturnValue(103_000);
+ rerender({ status: new Status({ cpu: 12 }), bucket: 60 });
+ now.mockReturnValue(105_000);
+ rerender({ status: new Status({ cpu: 13 }), bucket: 2 });
+
+ await waitFor(() => expect(result.current.series.cpu).toEqual([20, 30, 11, 12, 13]));
+ expect(result.current.labels).toHaveLength(5);
+ } finally {
+ now.mockRestore();
+ }
+});
+
+it('seeds a changed resource scope only up to its first status sample', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
+ try {
+ get.mockResolvedValue({
+ success: true,
+ obj: [{ t: 98, v: 20 }],
+ });
+ const { result, rerender } = renderHook(({ status }) => useOverviewHistory(status, true, 2), {
+ initialProps: { status: new Status({ cpu: 11, resourceScope: 'host' }) },
+ });
+ await waitFor(() => expect(result.current.series.cpu).toEqual([20, 11]));
+
+ now.mockReturnValue(111_000);
+ get.mockClear();
+ get.mockResolvedValue({
+ success: true,
+ obj: [
+ { t: 108, v: 30 },
+ { t: 110, v: 99 },
+ ],
+ });
+ rerender({ status: new Status({ cpu: 12, resourceScope: 'container' }) });
+
+ await waitFor(() => expect(result.current.series.cpu).toEqual([30, 12]));
+ expect(get.mock.calls.map(([path]) => path)).toEqual([
+ '/panel/api/server/history/cpu/2',
+ '/panel/api/server/history/swap/2',
+ ]);
+ } finally {
+ now.mockRestore();
+ }
+});
+
+const liveRequests = () =>
+ get.mock.calls.map(([path]) => String(path)).filter((path) => path.includes('/history/'));
+
+function sample(resourceScope: string, cpu: number, swap: number, up: number) {
+ return new Status({
+ resourceScope,
+ cpu,
+ swap: { current: swap, total: 100 },
+ netIO: { up, down: 0 },
+ });
+}
+
+it('reseeds CPU and SWAP after sampling A → B → A while the live seed is disabled', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
+ try {
+ get.mockResolvedValue({ success: true, obj: [{ t: 98, v: 7 }] });
+ const { result, rerender } = renderHook(
+ ({ status, bucket }) => useOverviewHistory(status, true, bucket),
+ { initialProps: { status: sample('host', 11, 15, 8), bucket: 2 } },
+ );
+ await waitFor(() => expect(result.current.series.cpu).toEqual([7, 11]));
+ get.mockClear();
+
+ get.mockImplementation(async (path: string) => ({
+ success: true,
+ obj: ranged(path)
+ ? rollups(90)
+ : [
+ { t: 104, v: path.includes('/cpu/') ? 24 : 32 },
+ { t: 108, v: 99 },
+ ],
+ }));
+ now.mockReturnValue(105_000);
+ rerender({ status: sample('container', 41, 42, 9), bucket: 30 });
+ now.mockReturnValue(109_000);
+ const host = sample('host', 20, 36, 10);
+ rerender({ status: host, bucket: 30 });
+ expect(liveRequests()).toEqual([]);
+
+ rerender({ status: host, bucket: 2 });
+ await waitFor(() => expect(result.current.series.cpu).toEqual([24, 20]));
+ expect(result.current.series.swap).toEqual([32, 36]);
+ expect(result.current.series.netUp).toEqual([7, 8, 9, 10]);
+ expect(result.current.labels).toHaveLength(4);
+ expect(liveRequests()).toEqual([
+ '/panel/api/server/history/cpu/2',
+ '/panel/api/server/history/swap/2',
+ ]);
+ } finally {
+ now.mockRestore();
+ }
+});
+
+it('seeds the first live visit from separate CPU/SWAP and unscoped cutoffs', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
+ try {
+ get.mockImplementation(async (path: string) => ({
+ success: true,
+ obj: ranged(path)
+ ? rollups(90)
+ : [
+ { t: 104, v: 88 },
+ { t: 98, v: 7 },
+ { t: 102, v: 24 },
+ { t: 100, v: 20 },
+ { t: 104, v: 28 },
+ { t: 106, v: 99 },
+ { t: 108, v: 99 },
+ ],
+ }));
+ const { result, rerender } = renderHook(
+ ({ status, bucket }) => useOverviewHistory(status, true, bucket),
+ { initialProps: { status: sample('host', 11, 15, 8), bucket: 30 } },
+ );
+ now.mockReturnValue(107_000);
+ rerender({ status: sample('container', 30, 40, 9), bucket: 30 });
+ expect(liveRequests()).toEqual([]);
+
+ now.mockReturnValue(109_000);
+ rerender({ status: sample('container', 41, 43, 10), bucket: 2 });
+ await waitFor(() => expect(result.current.series.cpu).toEqual([7, 20, 24, 28, 30, 41]));
+ expect(result.current.series.swap).toEqual([7, 20, 24, 28, 40, 43]);
+ expect(mean(result.current.series.cpu)).toBe(25);
+ expect(peak(result.current.series.swap)).toBe(43);
+ expect(result.current.series.netUp).toEqual([7, 8, 9, 10]);
+ expect(result.current.labels).toEqual([98, 101, 107, 109].map(TimeFormatter.formatClock));
+ expect(liveRequests()).toHaveLength(metricKeys.length);
+ } finally {
+ now.mockRestore();
+ }
+});
+
+it('discards late live and ranged responses through rapid range and scope changes', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(101_000);
+ try {
+ let releaseLive!: (msg: { success: boolean; obj: { t: number; v: number }[] }) => void;
+ const oldLive = new Promise<{ success: boolean; obj: { t: number; v: number }[] }>(
+ (resolve) => {
+ releaseLive = resolve;
+ },
+ );
+ let releaseRanged!: (msg: { success: boolean; obj: Rollups }) => void;
+ const oldRanged = new Promise<{ success: boolean; obj: Rollups }>((resolve) => {
+ releaseRanged = resolve;
+ });
+ get.mockReturnValue(oldLive);
+ const { result, rerender } = renderHook(
+ ({ status, bucket }) => useOverviewHistory(status, true, bucket),
+ { initialProps: { status: sample('host', 11, 15, 8), bucket: 2 } },
+ );
+
+ now.mockReturnValue(105_000);
+ get.mockClear();
+ get.mockReturnValue(oldRanged);
+ rerender({ status: sample('container', 90, 91, 9), bucket: 30 });
+ now.mockReturnValue(107_000);
+ get.mockResolvedValue({ success: true, obj: rollups(44) });
+ const host = sample('host', 20, 36, 10);
+ rerender({ status: host, bucket: 60 });
+ await waitFor(() => expect(result.current.series.cpu).toEqual([44]));
+ expect(liveRequests()).toEqual([]);
+
+ await act(async () => releaseRanged({ success: true, obj: rollups(99) }));
+ expect(result.current.series.cpu).toEqual([44]);
+
+ get.mockResolvedValue({ success: true, obj: [{ t: 98, v: 7 }] });
+ rerender({ status: host, bucket: 2 });
+ await waitFor(() => expect(result.current.series.cpu).toEqual([7, 20]));
+ await act(async () => releaseLive({ success: true, obj: [{ t: 96, v: 99 }] }));
+ expect(result.current.series.cpu).toEqual([7, 20]);
+ expect(result.current.series.swap).toEqual([7, 36]);
+ expect(result.current.series.netUp).toEqual([7, 8, 9, 10]);
+ expect(result.current.labels).toHaveLength(4);
+ } finally {
+ now.mockRestore();
+ }
+});
+
+it.each([
+ ['ahead', 2_300],
+ ['behind', 1_700],
+] as const)(
+ 'keeps live history ordered and bounded when the server clock is far %s',
+ async (_, serverTime) => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(2_001_000);
+ try {
+ get.mockResolvedValue({ success: true, obj: [{ t: serverTime, v: 99 }] });
+ const sampledHost = sample('host', 20, 36, 10);
+ const { result } = renderHook(() => useOverviewHistory(sampledHost, true));
+ await act(async () => undefined);
+ expect(liveRequests()).toHaveLength(metricKeys.length);
+ expect(result.current.series.cpu).toEqual([20]);
+ expect(result.current.series.swap).toEqual([36]);
+ expect(result.current.series.netUp).toEqual([10]);
+ expect(result.current.labels).toEqual([TimeFormatter.formatClock(2_001)]);
+ } finally {
+ now.mockRestore();
+ }
+ },
+);
diff --git a/frontend/src/test/overview-stop-confirm.test.tsx b/frontend/src/test/overview-stop-confirm.test.tsx
index 105a8f6c3..3f19fea48 100644
--- a/frontend/src/test/overview-stop-confirm.test.tsx
+++ b/frontend/src/test/overview-stop-confirm.test.tsx
@@ -25,6 +25,8 @@ function renderBar(
panelVersion="v3.10.1"
latestVersion="v3.10.1"
updateAvailable={false}
+ historyRange={2}
+ onHistoryRangeChange={() => undefined}
onStopXray={onStopXray}
onRestartXray={onRestartXray}
onOpenLogs={noop}
diff --git a/frontend/src/test/overview-update-tag-keyboard.test.tsx b/frontend/src/test/overview-update-tag-keyboard.test.tsx
index 93ee645e9..cf33af949 100644
--- a/frontend/src/test/overview-update-tag-keyboard.test.tsx
+++ b/frontend/src/test/overview-update-tag-keyboard.test.tsx
@@ -21,6 +21,8 @@ describe('OverviewActionBar update tag', () => {
panelVersion="v3.10.1"
latestVersion="v3.10.2"
updateAvailable
+ historyRange={2}
+ onHistoryRangeChange={() => undefined}
onStopXray={noop}
onRestartXray={noop}
onOpenLogs={noop}
diff --git a/frontend/src/test/routing-user-suggestions.test.tsx b/frontend/src/test/routing-user-suggestions.test.tsx
new file mode 100644
index 000000000..421ef331f
--- /dev/null
+++ b/frontend/src/test/routing-user-suggestions.test.tsx
@@ -0,0 +1,72 @@
+import { act, fireEvent, screen, waitFor } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+
+import RuleFormModal, { type RoutingRule } from '@/pages/xray/routing/RuleFormModal';
+import { HttpUtil, Msg } from '@/utils';
+import { renderWithProviders } from './test-utils';
+
+const suggestionsURL = '/panel/api/clients/userSuggestions';
+
+function renderRule(rule: RoutingRule | null = null) {
+ const onConfirm = vi.fn();
+ renderWithProviders(
+ ,
+ );
+ const input = screen.getByRole('combobox', { name: 'User' });
+ return { input, onConfirm };
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+it('defers requests until the picker opens, debounces, and discards a late response', async () => {
+ let respondToOldSearch: ((value: Msg) => void) | undefined;
+ const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (url, params) => {
+ if (url !== suggestionsURL) return new Msg(true, '', []);
+ const { search } = params as { search: string };
+ if (search === 'old') return new Promise((resolve) => (respondToOldSearch = resolve));
+ return new Msg(true, '', { emails: search === 'new' ? ['new-user@test'] : [] });
+ });
+ const requests = () => get.mock.calls.filter(([url]) => url.startsWith('/panel/api/clients/'));
+
+ const { input } = renderRule();
+ expect(requests()).toEqual([]);
+ fireEvent.change(input, { target: { value: 'old' } });
+ await waitFor(() => expect(respondToOldSearch).toBeTypeOf('function'));
+ await act(async () => {
+ fireEvent.change(input, { target: { value: 'n' } });
+ fireEvent.change(input, { target: { value: 'ne' } });
+ fireEvent.change(input, { target: { value: 'new' } });
+ });
+ expect(requests()).toHaveLength(1);
+ expect(requests()[0][2]?.signal?.aborted).toBe(true);
+ await screen.findByRole('option', { name: 'new-user@test' });
+ await act(async () => {
+ respondToOldSearch?.(new Msg(true, '', { emails: ['old-user@test'] }));
+ });
+ expect(screen.queryByRole('option', { name: 'old-user@test' })).toBeNull();
+ expect(requests().map(([, params]) => params)).toEqual([{ search: 'old' }, { search: 'new' }]);
+});
+
+it('preserves selected users and saves comma-delimited tags even when suggestions fail', async () => {
+ vi.spyOn(HttpUtil, 'get').mockImplementation(async (url) =>
+ url === suggestionsURL ? new Msg(false, 'offline') : new Msg(true, '', []),
+ );
+ const { input, onConfirm } = renderRule({ user: 'saved@test,remove@test' });
+ fireEvent.change(input, { target: { value: 'typed' } });
+ await screen.findByText('Could not load users');
+ expect(screen.getByRole('button', { name: 'Remove saved@test' })).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Remove remove@test' }));
+ fireEvent.change(input, { target: { value: 'manual@test,saved@test,manual@test,' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+ expect(onConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ user: ['saved@test', 'manual@test'] }),
+ );
+});
diff --git a/frontend/src/test/rule-form-preserve-fields.test.tsx b/frontend/src/test/rule-form-preserve-fields.test.tsx
index 07656a5e4..59370f277 100644
--- a/frontend/src/test/rule-form-preserve-fields.test.tsx
+++ b/frontend/src/test/rule-form-preserve-fields.test.tsx
@@ -3,10 +3,18 @@ import { fireEvent, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import RuleFormModal from '@/pages/xray/routing/RuleFormModal';
-import { keys } from '@/api/queryKeys';
import { HttpUtil, Msg } from '@/utils';
-import { chooseSelectOption, renderWithProviders } from './test-utils';
+import { renderWithProviders } from './test-utils';
+
+function mockUserSuggestions(...emails: string[]) {
+ return vi
+ .spyOn(HttpUtil, 'get')
+ .mockImplementation(
+ async (path) =>
+ new Msg(true, '', path === '/panel/api/clients/userSuggestions' ? { emails } : []),
+ );
+}
describe('RuleFormModal edit preserves unsurfaced fields', () => {
afterEach(() => vi.restoreAllMocks());
@@ -37,12 +45,7 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
});
it('selects existing clients for the user criterion', async () => {
- vi.spyOn(HttpUtil, 'get').mockResolvedValue(
- new Msg(true, '', [
- { id: 1, email: 'alice@example.com' },
- { id: 2, email: 'bob@example.com' },
- ]),
- );
+ const get = mockUserSuggestions('alice@example.com', 'bob@example.com');
const onConfirm = vi.fn();
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
@@ -59,16 +62,19 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
{ queryClient },
);
- await waitFor(() =>
- expect(HttpUtil.get).toHaveBeenCalledWith('/panel/api/clients/list', undefined, {
- silent: true,
- }),
- );
- await waitFor(() => expect(queryClient.getQueryData(keys.clients.all())).toHaveLength(2));
- const userField = screen.getByLabelText('User');
+ const userField = screen.getByRole('combobox', { name: 'User' });
expect(screen.getByText('Select users')).toBeTruthy();
- chooseSelectOption(userField.id, 'alice@example.com');
- chooseSelectOption(userField.id, 'bob@example.com');
+ fireEvent.mouseDown(userField);
+ for (const email of ['alice@example.com', 'bob@example.com']) {
+ fireEvent.click(
+ await screen.findByText(email, { selector: '.ant-select-item-option-content' }),
+ );
+ }
+ expect(get).toHaveBeenCalledWith(
+ '/panel/api/clients/userSuggestions',
+ { search: '' },
+ expect.objectContaining({ silent: true }),
+ );
fireEvent.click(screen.getByRole('button', { name: 'Create' }));
expect(onConfirm).toHaveBeenCalledWith(
@@ -77,9 +83,7 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
});
it('preserves a saved user that is no longer in the client list', async () => {
- vi.spyOn(HttpUtil, 'get').mockResolvedValue(
- new Msg(true, '', [{ id: 1, email: 'alice@example.com' }]),
- );
+ mockUserSuggestions('alice@example.com');
const onConfirm = vi.fn();
renderWithProviders(
@@ -103,9 +107,7 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
});
it('accepts a custom user identifier that is not a client record', async () => {
- vi.spyOn(HttpUtil, 'get').mockResolvedValue(
- new Msg(true, '', [{ id: 1, email: 'alice@example.com' }]),
- );
+ mockUserSuggestions('alice@example.com');
const onConfirm = vi.fn();
renderWithProviders(
diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts
index 622514ccc..24b29656c 100644
--- a/frontend/src/utils/index.ts
+++ b/frontend/src/utils/index.ts
@@ -763,6 +763,11 @@ export class CPUFormatter {
static cpuCoreFormat(cores: number): string {
return cores === 1 ? '1 Core' : cores + ' Cores';
}
+
+ static cpuSpecFormat(cores: number, threads: number, speedMhz: number): string {
+ const spec = `${CPUFormatter.cpuCoreFormat(cores)} / ${threads}T`;
+ return speedMhz > 0 ? `${spec} · ${CPUFormatter.cpuSpeedFormat(speedMhz)}` : spec;
+ }
}
export class TimeFormatter {
diff --git a/frontend/vite.config.js b/frontend/vite.config.js
index d91e52342..a30126508 100644
--- a/frontend/vite.config.js
+++ b/frontend/vite.config.js
@@ -289,10 +289,11 @@ export default defineConfig({
'^/(?:[^/]+/)?(login|logout|getTwoFactorEnable|csrf-token|sponsors|panel|server)(?:/|$)': makeBackendProxy(BACKEND_TARGET),
'^/$': makeBackendProxy(BACKEND_TARGET),
'^/[^/]+/$': makeBackendProxy(BACKEND_TARGET),
+ // No changeOrigin: the panel rejects an upgrade whose Origin port differs
+ // from the Host port, so Host must stay the dev server the page came from.
'^/(?:[^/]+/)?ws$': {
target: 'ws://localhost:2053',
ws: true,
- changeOrigin: true,
rewrite: rewriteToBackend,
},
},
diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts
index e4662d006..87be7d5c7 100644
--- a/frontend/vitest.config.ts
+++ b/frontend/vitest.config.ts
@@ -42,7 +42,16 @@ export default defineConfig({
{
extends: true,
optimizeDeps: {
- include: ['aria-query', 'lz-string', 'pretty-format', 'dom-accessibility-api'],
+ // Lazy-loaded stories must not trigger an optimizer reload mid-test.
+ include: [
+ 'aria-query',
+ 'lz-string',
+ 'pretty-format',
+ 'dom-accessibility-api',
+ '@tanstack/react-query-devtools',
+ 'react-router',
+ 'react-router/dom',
+ ],
},
plugins: [storybookTest({ configDir: path.join(dirname, '.storybook') })],
test: {
diff --git a/go.mod b/go.mod
index a22b40d5b..e2e5dccf8 100644
--- a/go.mod
+++ b/go.mod
@@ -18,16 +18,16 @@ require (
github.com/joho/godotenv v1.5.1
github.com/klauspost/compress v1.20.5
github.com/mattn/go-sqlite3 v1.14.53
- github.com/modelcontextprotocol/go-sdk v1.8.0
+ github.com/modelcontextprotocol/go-sdk v1.9.0
github.com/mymmrac/telego v1.14.0
github.com/nicksnyder/go-i18n/v2 v2.7.0
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7
github.com/quic-go/quic-go v0.66.0
github.com/refraction-networking/utls v1.8.3-0.20261108164504-a13c59ffe98b
github.com/robfig/cron/v3 v3.0.1
- github.com/shirou/gopsutil/v4 v4.26.10
+ github.com/shirou/gopsutil/v4 v4.26.11
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
- github.com/valyala/fasthttp v1.80.0
+ github.com/valyala/fasthttp v1.81.0
github.com/vishvananda/netlink v1.3.1
github.com/xlzd/gotp v0.1.0
github.com/xtls/xray-core v1.260327.1-0.20261109052709-676eaf66f8f0
diff --git a/go.sum b/go.sum
index ff9c839ba..5f59316e1 100644
--- a/go.sum
+++ b/go.sum
@@ -140,8 +140,8 @@ github.com/mattn/go-sqlite3 v1.14.53 h1:mnTM0owzUMrKuLo+0w51NUiB0ir2Fo7kFXlPt/l3
github.com/mattn/go-sqlite3 v1.14.53/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
-github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
-github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
+github.com/modelcontextprotocol/go-sdk v1.9.0 h1:XVjBrIMg82x7ff2bqwSPgRThLp4TC1lGTX74Ofaie1g=
+github.com/modelcontextprotocol/go-sdk v1.9.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -190,8 +190,8 @@ github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
-github.com/shirou/gopsutil/v4 v4.26.10 h1:MJN6euesJx53MVEjscYeyRSRcrdIcy3sz5k9nosjldg=
-github.com/shirou/gopsutil/v4 v4.26.10/go.mod h1:XpkIrcUMQhwte/dGxu57KtnMMFsbKelI7PP23zweKBk=
+github.com/shirou/gopsutil/v4 v4.26.11 h1:o1ZqIGUDTc3L0t245IEnQI3Yso8EVFunN/Kb2DpqTsc=
+github.com/shirou/gopsutil/v4 v4.26.11/go.mod h1:hBBe7kP+fLoN6mB78ZXDHZ2sYFI25yHyrErDVCvNb2M=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -216,8 +216,8 @@ github.com/ugorji/go/codec v1.3.2 h1:zkEASHHyEClGeURfgNT9PJZVfAbs9oEX9QXggwWNJbc
github.com/ugorji/go/codec v1.3.2/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
-github.com/valyala/fasthttp v1.80.0 h1:10pVr/QLFGbSX8ikDS0i+wOi2AGY2Sy0TACVpoiG+7U=
-github.com/valyala/fasthttp v1.80.0/go.mod h1:oulvtxx5dQeORu6sKWaJItcnWXRqiGmrTFQ4gmZjLFM=
+github.com/valyala/fasthttp v1.81.0 h1:/mTcnzriVgu17nQU2yKQp0Z53EQcmP6mmH4DNuUC0Eo=
+github.com/valyala/fasthttp v1.81.0/go.mod h1:dP2CcfIhdN6jmScbPXp6gQvSky6pe0gPT5Lybo9SBIE=
github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4=
github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE=
github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=
diff --git a/install.sh b/install.sh
index 89f2a1967..ccd1ce5a5 100644
--- a/install.sh
+++ b/install.sh
@@ -2042,8 +2042,6 @@ EOF
echo -e "${green}SSL certificate already configured. No action needed.${plain}"
fi
fi
-
- ${xui_folder}/x-ui migrate
}
xui_env_file_path() {
@@ -2530,6 +2528,10 @@ install_x-ui() {
chmod +x /usr/bin/x-ui
mkdir -p /var/log/x-ui
config_after_install
+ if ! "${xui_folder}/x-ui" migrate; then
+ echo -e "${red}ERROR: Database migration failed; stopping installation.${plain}" >&2
+ exit 1
+ fi
setup_fail2ban "$fail2ban_mode"
# Etckeeper compatibility
diff --git a/internal/amneziawgnet/relay_e2e_test.go b/internal/amneziawgnet/relay_e2e_test.go
index 2d5a5756c..753ff6545 100644
--- a/internal/amneziawgnet/relay_e2e_test.go
+++ b/internal/amneziawgnet/relay_e2e_test.go
@@ -152,7 +152,7 @@ func TestSocksRelayAgainstRealXray(t *testing.T) {
}
defer func() {
_ = cmd.Process.Kill()
- _, _ = cmd.Process.Wait()
+ _ = cmd.Wait()
}()
waitForPort(t, socksPort)
@@ -268,20 +268,10 @@ func TestSocksRelayAgainstRealXray(t *testing.T) {
t.Fatalf("UDP echo = %q, want %q (xray log follows)\n%s", gotUDP, udpMsg, xrayLog.String())
}
- // Real per-peer stats attribution: stop xray so its log is complete, then
- // look for both directions' counters keyed by the peer's real email --
- // the exact proof Finding 3 established manually in Phase 0.
- _ = cmd.Process.Kill()
- _, _ = cmd.Process.Wait()
- log := xrayLog.String()
- wantUp := fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail)
- wantDown := fmt.Sprintf("user>>>%s>>>traffic>>>downlink", wantEmail)
- if !strings.Contains(log, wantUp) {
- t.Errorf("xray log missing uplink stats counter %q\nfull log:\n%s", wantUp, log)
- }
- if !strings.Contains(log, wantDown) {
- t.Errorf("xray log missing downlink stats counter %q\nfull log:\n%s", wantDown, log)
- }
+ waitForXrayCounters(t, &xrayLog,
+ fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail),
+ fmt.Sprintf("user>>>%s>>>traffic>>>downlink", wantEmail),
+ )
}
// TestManagerEnsureAutomaticallyWiresRelay is Phase 3's own real proof: unlike
@@ -392,7 +382,7 @@ func TestManagerEnsureAutomaticallyWiresRelay(t *testing.T) {
}
defer func() {
_ = cmd.Process.Kill()
- _, _ = cmd.Process.Wait()
+ _ = cmd.Wait()
}()
waitForPort(t, socksPort)
@@ -462,12 +452,23 @@ func TestManagerEnsureAutomaticallyWiresRelay(t *testing.T) {
t.Errorf("TCP echo = %q, want %q", buf, tcpMsg)
}
- _ = cmd.Process.Kill()
- _, _ = cmd.Process.Wait()
- log := xrayLog.String()
- wantUp := fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail)
- if !strings.Contains(log, wantUp) {
- t.Errorf("xray log missing uplink stats counter %q (Manager.Ensure's automatic relay wiring may not be attributing traffic correctly)\nfull log:\n%s", wantUp, log)
+ waitForXrayCounters(t, &xrayLog, fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail))
+}
+
+func waitForXrayCounters(t *testing.T, log *syncBuffer, counters ...string) {
+ t.Helper()
+ deadline := time.Now().Add(3 * time.Second)
+ for _, counter := range counters {
+ for {
+ output := log.String()
+ if strings.Contains(output, counter) {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("xray log missing stats counter %q\nfull log:\n%s", counter, output)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
}
}
diff --git a/internal/database/db.go b/internal/database/db.go
index f5f530211..98410f506 100644
--- a/internal/database/db.go
+++ b/internal/database/db.go
@@ -37,9 +37,11 @@ import (
"gorm.io/gorm/logger"
)
-var db *gorm.DB
-
-var connectionGeneration atomic.Uint64
+var (
+ db *gorm.DB
+ publishedDB atomic.Pointer[gorm.DB]
+ connectionGeneration atomic.Uint64
+)
// ConnectionGeneration invalidates read histories when InitDB replaces the database pool.
func ConnectionGeneration() uint64 { return connectionGeneration.Load() }
@@ -52,13 +54,11 @@ const (
)
func IsPostgres() bool {
- if db == nil {
- return config.GetDBKind() == "postgres"
- }
- return db.Name() == "postgres"
+ return config.GetDBKind() == DialectPostgres
}
func Dialect() string {
+ db := GetDB()
if db == nil {
return ""
}
@@ -141,6 +141,15 @@ func migrateNodeClientTrafficDippedWhileFrozenColumn(tx *gorm.DB) error {
return migrator.AddColumn(&model.NodeClientTraffic{}, "DippedWhileFrozen")
}
+// Existing nodes start with NULL telemetry until their next successful heartbeat.
+func migrateNodeTelemetryColumn(tx *gorm.DB) error {
+ migrator := tx.Migrator()
+ if !migrator.HasTable(&model.Node{}) || migrator.HasColumn(&model.Node{}, "telemetry") {
+ return nil
+ }
+ return migrator.AddColumn(&model.Node{}, "Telemetry")
+}
+
func migrateClientKeepAliveRangeColumn() error {
migrator := db.Migrator()
if !migrator.HasTable(&model.ClientRecord{}) || migrator.HasColumn(&model.ClientRecord{}, "wg_keep_alive_range") {
@@ -149,6 +158,40 @@ func migrateClientKeepAliveRangeColumn() error {
return migrator.AddColumn(&model.ClientRecord{}, "KeepAliveRange")
}
+func migrateClientInboundIncarnationColumn() error {
+ migrator := db.Migrator()
+ if !migrator.HasTable(&model.ClientInbound{}) || migrator.HasColumn(&model.ClientInbound{}, "incarnation") {
+ return nil
+ }
+ // Existing links can retain the empty identity. Every later insert receives a new one.
+ return migrator.AddColumn(&model.ClientInbound{}, "Incarnation")
+}
+
+func ensureClientInboundIncarnationTrigger() error {
+ return db.Transaction(func(tx *gorm.DB) error {
+ if tx.Name() == DialectSQLite {
+ return tx.Exec(`CREATE TRIGGER IF NOT EXISTS client_inbounds_incarnation_insert
+ AFTER INSERT ON client_inbounds BEGIN
+ UPDATE client_inbounds SET incarnation = lower(hex(randomblob(16)))
+ WHERE client_id = NEW.client_id AND inbound_id = NEW.inbound_id;
+ END`).Error
+ }
+ if err := tx.Exec(`CREATE OR REPLACE FUNCTION set_client_inbound_incarnation()
+ RETURNS trigger LANGUAGE plpgsql AS $$
+ BEGIN
+ NEW.incarnation := md5(random()::text || random()::text || random()::text || clock_timestamp()::text);
+ RETURN NEW;
+ END $$`).Error; err != nil {
+ return err
+ }
+ if err := tx.Exec("DROP TRIGGER IF EXISTS client_inbounds_incarnation_insert ON client_inbounds").Error; err != nil {
+ return err
+ }
+ return tx.Exec(`CREATE TRIGGER client_inbounds_incarnation_insert
+ BEFORE INSERT ON client_inbounds FOR EACH ROW EXECUTE FUNCTION set_client_inbound_incarnation()`).Error
+ })
+}
+
func initModels() error {
if err := dropSnapshotRevisionTriggers(db); err != nil {
return err
@@ -156,6 +199,9 @@ func initModels() error {
if err := migrateClientKeepAliveRangeColumn(); err != nil {
return err
}
+ if err := migrateClientInboundIncarnationColumn(); err != nil {
+ return err
+ }
if err := migrateClientTrafficLastSubFetchColumn(); err != nil {
return err
}
@@ -171,6 +217,9 @@ func initModels() error {
if err := migrateNodeClientTrafficDippedWhileFrozenColumn(db); err != nil {
return err
}
+ if err := migrateNodeTelemetryColumn(db); err != nil {
+ return err
+ }
models := allModels()
for _, mdl := range models {
if IsPostgres() && postgresModelSettled(mdl) {
@@ -257,6 +306,9 @@ func initModels() error {
return err
}
}
+ if err := ensureClientInboundIncarnationTrigger(); err != nil {
+ return err
+ }
return migrateSnapshotRevisions(db)
}
@@ -3483,6 +3535,27 @@ func isTableEmpty(tableName string) (bool, error) {
}
func InitDB(dbPath string) error {
+ return InitDBBeforePublish(dbPath, nil)
+}
+
+// InitDBBeforePublish initializes a replacement pool and runs finish before
+// making it visible to requests and jobs. If finish fails, the initialized
+// pool is still published so the panel can report the error and recover.
+func InitDBBeforePublish(dbPath string, finish func(*gorm.DB) error) error {
+ return openDB(dbPath, true, nil, finish)
+}
+
+// InitDB completes startup or recovery on a fenced connection before publishing the pool.
+func (l *MaintenanceLease) InitDB(dbPath string, finish func(*gorm.DB) error) error {
+ return openDB(dbPath, true, l, finish)
+}
+
+// OpenInitializedDB opens a pool for routine CLI work while a panel owns the schema.
+func OpenInitializedDB(dbPath string) error {
+ return openDB(dbPath, false, nil, nil)
+}
+
+func openDB(dbPath string, initialize bool, lease *MaintenanceLease, finish func(*gorm.DB) error) error {
var gormLogger logger.Interface
if config.IsDebug() {
gormLogger = logger.New(
@@ -3572,24 +3645,56 @@ func InitDB(dbPath string) error {
sqlDB.SetConnMaxLifetime(time.Hour)
sqlDB.SetConnMaxIdleTime(30 * time.Minute)
- if err := initModels(); err != nil {
- return err
+ if !initialize {
+ publishedDB.Store(db)
+ connectionGeneration.Add(1)
+ return nil
+ }
+ var finishErr error
+ initializeOn := func(conn *gorm.DB) error {
+ // The schema and seeder helpers use the private handle, never the published pool.
+ pool := db
+ db = conn
+ defer func() { db = pool }()
+ if lease != nil && conn.Name() == DialectPostgres {
+ if _, err := PendingPostgresRestoreForSchema(conn); err != nil {
+ return err
+ }
+ }
+ if err := initModels(); err != nil {
+ return err
+ }
+ isUsersEmpty, err := isTableEmpty("users")
+ if err != nil {
+ return err
+ }
+ if isUsersEmpty {
+ if err := seedRandomSubscriptionPaths(); err != nil {
+ return err
+ }
+ }
+ if err := runSeeders(isUsersEmpty); err != nil {
+ return err
+ }
+ if finish != nil {
+ finishErr = finish(conn)
+ }
+ if lease != nil {
+ return finishErr
+ }
+ return nil
+ }
+ if lease == nil {
+ err = initializeOn(db)
+ } else {
+ err = lease.WithPostgresWork(db, initializeOn)
}
-
- isUsersEmpty, err := isTableEmpty("users")
if err != nil {
return err
}
- if isUsersEmpty {
- if err := seedRandomSubscriptionPaths(); err != nil {
- return err
- }
- }
- if err := runSeeders(isUsersEmpty); err != nil {
- return err
- }
+ publishedDB.Store(db)
connectionGeneration.Add(1)
- return nil
+ return finishErr
}
func normalizeApiTokenCreatedAtSeconds() error {
@@ -3598,6 +3703,22 @@ func normalizeApiTokenCreatedAtSeconds() error {
UpdateColumn("created_at", gorm.Expr("created_at / ?", 1000)).Error
}
+// Keep restore state in its own schema so a full archive can replace application
+// schemas without dropping the admission barrier or depending on a local file.
+func migratePostgresRestoreState(conn *gorm.DB) error {
+ var exists bool
+ if err := conn.Raw("SELECT to_regnamespace(?) IS NOT NULL", PostgresMaintenanceSchema).Scan(&exists).Error; err != nil {
+ return err
+ }
+ if !exists {
+ if err := conn.Exec("CREATE SCHEMA IF NOT EXISTS " + PostgresMaintenanceSchema).Error; err != nil {
+ return err
+ }
+ }
+ return conn.Exec("CREATE TABLE IF NOT EXISTS " + postgresRestoreStateTable +
+ " (id smallint PRIMARY KEY CHECK (id = 1), app_schema text NOT NULL)").Error
+}
+
func migrateApiTokenScopeAndExpiry() error {
m := db.Migrator()
if !m.HasColumn(&model.ApiToken{}, "Scope") {
@@ -3614,13 +3735,15 @@ func migrateApiTokenScopeAndExpiry() error {
Updates(map[string]any{"scope": model.ApiScopeAdmin, "expires_at": 0}).Error
}
+var postgresStartupDelays = [...]time.Duration{0, 2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second, 30 * time.Second}
+
// openPostgresWithRetry retries the initial PostgreSQL connection with
// backoff so a database that starts slower than the panel (or drops out
// briefly) does not immediately kill the process and trip systemd's
// restart loop. Every failed attempt logs the real driver error, which
// used to be buried behind a generic startup failure.
func openPostgresWithRetry(dsn string, c *gorm.Config) (*gorm.DB, error) {
- delays := []time.Duration{0, 2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second, 30 * time.Second}
+ delays := postgresStartupDelays
var lastErr error
for i, delay := range delays {
if delay > 0 {
@@ -3721,7 +3844,7 @@ func CloseDB() error {
}
func GetDB() *gorm.DB {
- return db
+ return publishedDB.Load()
}
func IsNotFound(err error) bool {
diff --git a/internal/database/db_reopen_test.go b/internal/database/db_reopen_test.go
index c3c856161..ccec56542 100644
--- a/internal/database/db_reopen_test.go
+++ b/internal/database/db_reopen_test.go
@@ -1,8 +1,12 @@
package database
import (
+ "database/sql"
+ "errors"
"path/filepath"
"testing"
+
+ "gorm.io/gorm"
)
// A replaced pool that stays open keeps its database file open; Windows then
@@ -25,3 +29,28 @@ func TestInitDBClosesThePoolItReplaces(t *testing.T) {
t.Fatalf("replaced pool Ping() = %v, want sql: database is closed", err)
}
}
+
+func TestInitDBKeepsRestorePoolPrivate(t *testing.T) {
+ initMigrateDB(t)
+ previous := GetDB()
+ dbPath := filepath.Join(t.TempDir(), "restored.db")
+ finishErr := errors.New("restore migration failed")
+ var replacement *gorm.DB
+ err := InitDBBeforePublish(dbPath, func(db *gorm.DB) error {
+ replacement = db
+ if GetDB() != previous || db == previous {
+ t.Fatal("the replacement pool was visible during restore migration")
+ }
+ if err := GetDB().Exec("SELECT 1").Error; !errors.Is(err, sql.ErrConnDone) &&
+ (err == nil || err.Error() != "sql: database is closed") {
+ t.Fatalf("request could still use the old pool: %v", err)
+ }
+ if err := db.Exec("SELECT 1").Error; err != nil {
+ t.Fatalf("restore could not use the replacement pool: %v", err)
+ }
+ return finishErr
+ })
+ if !errors.Is(err, finishErr) || GetDB() != replacement {
+ t.Fatalf("restore failure was not surfaced with a usable pool: %v", err)
+ }
+}
diff --git a/internal/database/maintenance.go b/internal/database/maintenance.go
new file mode 100644
index 000000000..a228cc7a8
--- /dev/null
+++ b/internal/database/maintenance.go
@@ -0,0 +1,510 @@
+package database
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/config"
+)
+
+// PostgreSQL scopes advisory keys to a database. Share this key with writer transactions.
+const postgresMaintenanceKey int64 = 0x3378756964626d74
+
+const MaintenanceWait = 5 * time.Second
+
+var ErrMaintenanceBusy = errors.New("database maintenance lock is busy; the database is in use by another process")
+
+type maintenanceBackend interface {
+ setMode(context.Context, bool) error
+ close() error
+}
+
+// MaintenanceLease holds a shared runtime or exclusive maintenance lock independently of the app pool.
+type MaintenanceLease struct {
+ backend maintenanceBackend
+ available atomic.Bool
+}
+
+var runtimeMaintenanceLease atomic.Pointer[MaintenanceLease]
+
+func SetRuntimeMaintenanceLease(lease *MaintenanceLease) {
+ runtimeMaintenanceLease.Store(lease)
+}
+
+var ErrMaintenanceUnavailable = errors.New("database maintenance connection is unavailable")
+
+func RuntimeMaintenanceAvailable() bool {
+ lease := runtimeMaintenanceLease.Load()
+ return lease == nil || lease.available.Load()
+}
+
+// AcquireStartupMaintenance retries PostgreSQL connection setup independently
+// of the shorter advisory lock wait.
+func AcquireStartupMaintenance(ctx context.Context) (*MaintenanceLease, error) {
+ if config.GetDBKind() != DialectPostgres {
+ lock, cancel := context.WithTimeout(ctx, MaintenanceWait)
+ defer cancel()
+ return AcquireConfiguredMaintenance(lock, true)
+ }
+ cfg, err := postgresMaintenanceConfig(config.GetDBDSN())
+ if err != nil {
+ return nil, err
+ }
+ for _, delay := range postgresStartupDelays {
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(delay):
+ }
+ attempt, cancel := context.WithTimeout(ctx, MaintenanceWait)
+ var conn *pgx.Conn
+ conn, err = pgx.ConnectConfig(attempt, cfg)
+ cancel()
+ if err == nil {
+ lock, cancelLock := context.WithTimeout(ctx, MaintenanceWait)
+ defer cancelLock()
+ return acquireMaintenance(lock, &postgresMaintenance{cfg: cfg, conn: conn}, true)
+ }
+ log.Printf("connect for PostgreSQL maintenance: %v", err)
+ }
+ return nil, fmt.Errorf("connect for PostgreSQL maintenance: %w", err)
+}
+
+func AcquireConfiguredMaintenance(ctx context.Context, exclusive bool) (*MaintenanceLease, error) {
+ if config.GetDBKind() == DialectPostgres {
+ return AcquirePostgresMaintenance(ctx, config.GetDBDSN(), exclusive)
+ }
+ return AcquireSQLiteMaintenance(ctx, config.GetDBPath(), exclusive)
+}
+
+// TryConfiguredMaintenance checks once for contention but still bounds connection setup by ctx.
+func TryConfiguredMaintenance(ctx context.Context, exclusive bool) (*MaintenanceLease, error) {
+ return AcquireConfiguredMaintenance(context.WithValue(ctx, noMaintenanceRetry{}, true), exclusive)
+}
+
+type noMaintenanceRetry struct{}
+
+func postgresMaintenanceConfig(dsn string) (*pgx.ConnConfig, error) {
+ cfg, err := pgx.ParseConfig(dsn)
+ if err != nil {
+ return nil, fmt.Errorf("configure PostgreSQL maintenance connection: %w", err)
+ }
+ cfg.RuntimeParams["application_name"] = "3x-ui-maintenance"
+ return cfg, nil
+}
+
+func AcquirePostgresMaintenance(ctx context.Context, dsn string, exclusive bool) (*MaintenanceLease, error) {
+ cfg, err := postgresMaintenanceConfig(dsn)
+ if err != nil {
+ return nil, err
+ }
+ conn, err := pgx.ConnectConfig(ctx, cfg)
+ if err != nil {
+ return nil, fmt.Errorf("connect for PostgreSQL maintenance: %w", err)
+ }
+ return acquireMaintenance(ctx, &postgresMaintenance{cfg: cfg, conn: conn}, exclusive)
+}
+
+// SQLiteDatabasePath follows the final link even while its target is being replaced.
+func SQLiteDatabasePath(dbPath string) (string, error) {
+ target, err := filepath.Abs(dbPath)
+ if err != nil {
+ return "", err
+ }
+ for range 255 {
+ parent, err := filepath.EvalSymlinks(filepath.Dir(target))
+ if err != nil {
+ return "", err
+ }
+ target = filepath.Join(parent, filepath.Base(target))
+ info, err := os.Lstat(target)
+ if errors.Is(err, os.ErrNotExist) {
+ return target, nil
+ }
+ if err != nil {
+ return "", err
+ }
+ if info.Mode()&os.ModeSymlink == 0 {
+ return target, nil
+ }
+ link, err := os.Readlink(target)
+ if err != nil {
+ return "", err
+ }
+ if !filepath.IsAbs(link) {
+ link = filepath.Join(parent, link)
+ }
+ target = link
+ }
+ return "", fmt.Errorf("too many symlinks resolving the SQLite database path %q", dbPath)
+}
+
+func AcquireSQLiteMaintenance(ctx context.Context, dbPath string, exclusive bool) (*MaintenanceLease, error) {
+ if err := os.MkdirAll(filepath.Dir(dbPath), 0o700); err != nil {
+ return nil, err
+ }
+ target, err := SQLiteDatabasePath(dbPath)
+ if err != nil {
+ return nil, err
+ }
+ intent, err := os.OpenFile(target+".maintenance-intent", os.O_RDWR|os.O_CREATE, 0o600)
+ if err != nil {
+ return nil, err
+ }
+ owner, err := os.OpenFile(target+".maintenance-lock", os.O_RDWR|os.O_CREATE, 0o600)
+ if err != nil {
+ _ = intent.Close()
+ return nil, err
+ }
+ return acquireMaintenance(ctx, &sqliteMaintenance{owner: owner, intent: intent}, exclusive)
+}
+
+func acquireMaintenance(ctx context.Context, backend maintenanceBackend, exclusive bool) (*MaintenanceLease, error) {
+ lease := &MaintenanceLease{backend: backend}
+ if pg, ok := backend.(*postgresMaintenance); ok {
+ pg.onLoss = func() { lease.available.Store(false) }
+ }
+ if err := lease.SetExclusive(ctx, exclusive); err != nil {
+ return nil, errors.Join(err, lease.Close())
+ }
+ lease.available.Store(true)
+ return lease, nil
+}
+
+func (l *MaintenanceLease) SetExclusive(ctx context.Context, exclusive bool) error {
+ started := time.Now()
+ err := l.backend.setMode(ctx, exclusive)
+ if errors.Is(err, ErrMaintenanceUnavailable) {
+ l.available.Store(false)
+ }
+ if exclusive {
+ log.Printf("database maintenance: pid=%d lock_wait_ms=%d acquired=%t", os.Getpid(), time.Since(started).Milliseconds(), err == nil)
+ }
+ return err
+}
+
+func (l *MaintenanceLease) Close() error {
+ l.available.Store(false)
+ return l.backend.close()
+}
+
+// AcquireRestoreMaintenance upgrades the panel's lease after local work has drained.
+func AcquireRestoreMaintenance(ctx context.Context) (*MaintenanceLease, func() error, error) {
+ if lease := runtimeMaintenanceLease.Load(); lease != nil {
+ if err := lease.SetExclusive(ctx, true); err != nil {
+ return nil, nil, err
+ }
+ return lease, func() error {
+ timeout, cancel := context.WithTimeout(context.Background(), MaintenanceWait)
+ defer cancel()
+ return lease.SetExclusive(timeout, false)
+ }, nil
+ }
+ lease, err := AcquireConfiguredMaintenance(ctx, true)
+ if err != nil {
+ return nil, nil, err
+ }
+ return lease, lease.Close, nil
+}
+
+// CheckRuntimeConnection stops admitting work if the PostgreSQL lease is lost.
+func (l *MaintenanceLease) CheckRuntimeConnection(ctx context.Context) error {
+ pg, ok := l.backend.(*postgresMaintenance)
+ if !ok {
+ return nil
+ }
+ pg.mu.Lock()
+ defer pg.mu.Unlock()
+ if pg.conn == nil {
+ l.available.Store(false)
+ return ErrMaintenanceUnavailable
+ }
+ if err := pg.conn.Ping(ctx); err != nil {
+ l.available.Store(false)
+ return errors.Join(err, pg.dropConnection())
+ }
+ return nil
+}
+
+// RecoverRuntimeConnection reconnects shared runtime sessions. An interrupted
+// exclusive operation requires recovery under a new maintenance lease.
+func (l *MaintenanceLease) RecoverRuntimeConnection(ctx context.Context) error {
+ pg, ok := l.backend.(*postgresMaintenance)
+ if !ok {
+ return nil
+ }
+ pg.mu.Lock()
+ defer pg.mu.Unlock()
+ if pg.closed {
+ return ErrMaintenanceUnavailable
+ }
+ if pg.conn != nil {
+ return nil
+ }
+ if pg.exclusive {
+ return ErrMaintenanceUnavailable
+ }
+ conn, err := pgx.ConnectConfig(ctx, pg.cfg)
+ if err != nil {
+ return err
+ }
+ pg.conn = conn
+ if err := pg.setModeLocked(ctx, false); err != nil {
+ return errors.Join(err, pg.dropConnection())
+ }
+ l.available.Store(true)
+ return nil
+}
+
+// LockPostgresWriter keeps a conflicting transaction protected even if the
+// runtime's dedicated connection drops while the transaction is in flight.
+func LockPostgresWriter(tx *gorm.DB) error {
+ if tx.Error != nil {
+ return tx.Error
+ }
+ if tx.Name() != DialectPostgres {
+ return nil
+ }
+ var locked bool
+ if err := tx.Raw("SELECT pg_try_advisory_xact_lock_shared(?)", postgresMaintenanceKey).Scan(&locked).Error; err != nil {
+ return err
+ }
+ if !locked {
+ return ErrMaintenanceBusy
+ }
+ if err := tx.Raw("SELECT pg_try_advisory_xact_lock_shared(?)", postgresMaintenanceWorkKey).Scan(&locked).Error; err != nil {
+ return err
+ }
+ if !locked {
+ return ErrMaintenanceBusy
+ }
+ return nil
+}
+
+func waitMaintenance(ctx context.Context, try func() (bool, error)) error {
+ busy := false
+ for {
+ if err := ctx.Err(); err != nil {
+ if busy {
+ return errors.Join(ErrMaintenanceBusy, err)
+ }
+ return err
+ }
+ ok, err := try()
+ if err != nil {
+ if busy && ctx.Err() != nil {
+ return errors.Join(ErrMaintenanceBusy, ctx.Err())
+ }
+ return err
+ }
+ if ok {
+ return nil
+ }
+ if ctx.Value(noMaintenanceRetry{}) != nil {
+ return ErrMaintenanceBusy
+ }
+ busy = true
+ select {
+ case <-ctx.Done():
+ return errors.Join(ErrMaintenanceBusy, ctx.Err())
+ case <-time.After(50 * time.Millisecond):
+ }
+ }
+}
+
+type postgresMaintenance struct {
+ mu sync.Mutex
+ cfg *pgx.ConnConfig
+ conn *pgx.Conn
+ closed bool
+ held bool
+ exclusive bool
+ workContext context.Context
+ cancelWork context.CancelFunc
+ onLoss func()
+}
+
+func (p *postgresMaintenance) setMode(ctx context.Context, exclusive bool) error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return p.setModeLocked(ctx, exclusive)
+}
+
+func (p *postgresMaintenance) setModeLocked(ctx context.Context, exclusive bool) error {
+ if p.conn == nil || p.closed {
+ return ErrMaintenanceUnavailable
+ }
+ if p.held && p.exclusive == exclusive {
+ return nil
+ }
+ lock, unlock := "SELECT pg_try_advisory_lock_shared($1)", "SELECT pg_advisory_unlock_shared($1)"
+ unlockOld := "SELECT pg_advisory_unlock($1)"
+ if exclusive {
+ lock, unlock, unlockOld = "SELECT pg_try_advisory_lock($1)", unlockOld, unlock
+ }
+ if err := waitMaintenance(ctx, func() (bool, error) {
+ var ok bool
+ if err := p.conn.QueryRow(ctx, lock, postgresMaintenanceKey).Scan(&ok); err != nil {
+ return false, errors.Join(ErrMaintenanceUnavailable, err, p.dropConnection())
+ }
+ if !ok {
+ return false, nil
+ }
+ // The new lease must also be compatible with work still running
+ // on a separate execution session.
+ if err := p.conn.QueryRow(ctx, lock, postgresMaintenanceWorkKey).Scan(&ok); err != nil {
+ return false, errors.Join(ErrMaintenanceUnavailable, err, p.dropConnection())
+ }
+ key := postgresMaintenanceKey
+ if ok {
+ key = postgresMaintenanceWorkKey
+ }
+ var released bool
+ if err := p.conn.QueryRow(ctx, unlock, key).Scan(&released); err != nil || !released {
+ return false, errors.Join(ErrMaintenanceUnavailable, err, p.dropConnection())
+ }
+ if !ok || exclusive {
+ return ok, nil
+ }
+ pending, err := postgresRestorePending(func(query string, result *bool) error {
+ return p.conn.QueryRow(ctx, query).Scan(result)
+ })
+ if err != nil || pending {
+ if pending {
+ err = ErrPostgresRestorePending
+ }
+ return false, errors.Join(err, p.dropConnection())
+ }
+ return true, nil
+ }); err != nil {
+ return err
+ }
+ if p.held {
+ var released bool
+ if err := p.conn.QueryRow(ctx, unlockOld, postgresMaintenanceKey).Scan(&released); err != nil || !released {
+ return errors.Join(ErrMaintenanceUnavailable, errors.New("could not release previous PostgreSQL maintenance mode"), err, p.dropConnection())
+ }
+ }
+ p.held, p.exclusive = true, exclusive
+ if exclusive {
+ p.watchWorkLocked()
+ } else if p.cancelWork != nil {
+ p.cancelWork()
+ p.cancelWork = nil
+ }
+ return nil
+}
+
+func (p *postgresMaintenance) watchWorkLocked() {
+ if p.cancelWork == nil {
+ p.workContext, p.cancelWork = context.WithCancel(context.Background())
+ go p.watchWork(p.workContext)
+ }
+}
+
+func (p *postgresMaintenance) watchWork(ctx context.Context) {
+ ticker := time.NewTicker(time.Second)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ }
+ p.mu.Lock()
+ if ctx.Err() != nil {
+ p.mu.Unlock()
+ return
+ }
+ ping, cancel := context.WithTimeout(ctx, MaintenanceWait)
+ err := p.conn.Ping(ping)
+ cancel()
+ if err != nil {
+ _ = p.dropConnection()
+ }
+ p.mu.Unlock()
+ }
+}
+
+func (p *postgresMaintenance) close() error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.closed = true
+ return p.dropConnection()
+}
+
+func (p *postgresMaintenance) dropConnection() error {
+ if p.onLoss != nil {
+ p.onLoss()
+ }
+ if p.cancelWork != nil {
+ p.cancelWork()
+ p.cancelWork = nil
+ }
+ conn := p.conn
+ p.conn, p.held = nil, false
+ if conn == nil {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), MaintenanceWait)
+ defer cancel()
+ return conn.Close(ctx)
+}
+
+type sqliteMaintenance struct {
+ mu sync.Mutex
+ owner, intent *os.File
+ held bool
+ exclusive bool
+}
+
+func (s *sqliteMaintenance) setMode(ctx context.Context, exclusive bool) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.held && s.exclusive == exclusive {
+ return nil
+ }
+ if err := waitMaintenance(ctx, func() (bool, error) { return s.tryMode(exclusive) }); err != nil {
+ return err
+ }
+ s.held, s.exclusive = true, exclusive
+ return nil
+}
+
+func (s *sqliteMaintenance) tryMode(exclusive bool) (locked bool, err error) {
+ intent, err := tryMaintenanceFileLock(s.intent, true)
+ if !intent || err != nil {
+ return false, err
+ }
+ defer func() { err = errors.Join(err, unlockMaintenanceFile(s.intent)) }()
+ if s.held {
+ if err := unlockMaintenanceFile(s.owner); err != nil {
+ return false, err
+ }
+ }
+ locked, err = tryMaintenanceFileLock(s.owner, exclusive)
+ if !locked && s.held {
+ // Restore the old mode before letting another process try to acquire.
+ ok, relock := tryMaintenanceFileLock(s.owner, s.exclusive)
+ if !ok || relock != nil {
+ return false, errors.Join(err, errors.New("lost previous SQLite maintenance mode"), relock)
+ }
+ }
+ return locked, err
+}
+
+func (s *sqliteMaintenance) close() error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return errors.Join(s.owner.Close(), s.intent.Close())
+}
diff --git a/internal/database/maintenance_file_unix.go b/internal/database/maintenance_file_unix.go
new file mode 100644
index 000000000..5e5646b17
--- /dev/null
+++ b/internal/database/maintenance_file_unix.go
@@ -0,0 +1,26 @@
+//go:build !windows
+
+package database
+
+import (
+ "errors"
+ "os"
+
+ "golang.org/x/sys/unix"
+)
+
+func tryMaintenanceFileLock(file *os.File, exclusive bool) (bool, error) {
+ mode := unix.LOCK_SH
+ if exclusive {
+ mode = unix.LOCK_EX
+ }
+ err := unix.Flock(int(file.Fd()), mode|unix.LOCK_NB)
+ if errors.Is(err, unix.EWOULDBLOCK) {
+ return false, nil
+ }
+ return err == nil, err
+}
+
+func unlockMaintenanceFile(file *os.File) error {
+ return unix.Flock(int(file.Fd()), unix.LOCK_UN)
+}
diff --git a/internal/database/maintenance_file_windows.go b/internal/database/maintenance_file_windows.go
new file mode 100644
index 000000000..ffc6adb39
--- /dev/null
+++ b/internal/database/maintenance_file_windows.go
@@ -0,0 +1,24 @@
+package database
+
+import (
+ "errors"
+ "os"
+
+ "golang.org/x/sys/windows"
+)
+
+func tryMaintenanceFileLock(file *os.File, exclusive bool) (bool, error) {
+ flags := uint32(windows.LOCKFILE_FAIL_IMMEDIATELY)
+ if exclusive {
+ flags |= windows.LOCKFILE_EXCLUSIVE_LOCK
+ }
+ err := windows.LockFileEx(windows.Handle(file.Fd()), flags, 0, 1, 0, &windows.Overlapped{})
+ if errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
+ return false, nil
+ }
+ return err == nil, err
+}
+
+func unlockMaintenanceFile(file *os.File) error {
+ return windows.UnlockFileEx(windows.Handle(file.Fd()), 0, 1, 0, &windows.Overlapped{})
+}
diff --git a/internal/database/maintenance_test.go b/internal/database/maintenance_test.go
new file mode 100644
index 000000000..9a6007bc2
--- /dev/null
+++ b/internal/database/maintenance_test.go
@@ -0,0 +1,405 @@
+package database
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+)
+
+func TestMaintenanceLockHelper(t *testing.T) {
+ if os.Getenv("XUI_TEST_MAINTENANCE_HELPER") != "1" {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), MaintenanceWait)
+ defer cancel()
+ lease, err := AcquireConfiguredMaintenance(ctx, os.Getenv("XUI_TEST_EXCLUSIVE") == "true")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lease.Close()
+ fmt.Println("maintenance-lock-held")
+ time.Sleep(time.Minute)
+}
+
+func TestMaintenanceAcrossProcesses(t *testing.T) {
+ t.Setenv("XUI_DB_FOLDER", t.TempDir())
+ if os.Getenv("XUI_DB_TYPE") == DialectPostgres && os.Getenv("XUI_DB_DSN") == "" {
+ t.Skip("PostgreSQL fixture DSN required")
+ }
+ for _, exclusive := range []bool{false, true} {
+ t.Run(fmt.Sprintf("exclusive=%t", exclusive), func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
+ defer cancel()
+ child := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMaintenanceLockHelper$")
+ child.Env = append(os.Environ(), "XUI_TEST_MAINTENANCE_HELPER=1", fmt.Sprintf("XUI_TEST_EXCLUSIVE=%t", exclusive))
+ child.Stderr = os.Stderr
+ stdout, err := child.StdoutPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := child.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ if child.ProcessState == nil {
+ _ = child.Process.Kill()
+ _ = child.Wait()
+ }
+ }()
+ scanner := bufio.NewScanner(stdout)
+ for scanner.Scan() && scanner.Text() != "maintenance-lock-held" {
+ t.Log(scanner.Text())
+ }
+ if scanner.Text() != "maintenance-lock-held" {
+ t.Fatalf("subprocess exited before acquiring maintenance lock: %v", scanner.Err())
+ }
+ if lease, err := TryConfiguredMaintenance(ctx, true); !errors.Is(err, ErrMaintenanceBusy) {
+ if lease != nil {
+ _ = lease.Close()
+ }
+ t.Fatalf("exclusive lock with subprocess running: %v, want busy", err)
+ }
+ if exclusive {
+ if lease, err := TryConfiguredMaintenance(ctx, false); !errors.Is(err, ErrMaintenanceBusy) {
+ if lease != nil {
+ _ = lease.Close()
+ }
+ t.Fatalf("runtime lock with maintenance running: %v, want busy", err)
+ }
+ } else {
+ lease, err := TryConfiguredMaintenance(ctx, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lease.Close()
+ if err := lease.SetExclusive(context.WithValue(ctx, noMaintenanceRetry{}, true), true); !errors.Is(err, ErrMaintenanceBusy) {
+ t.Fatalf("runtime lock upgrade with another holder: %v, want busy", err)
+ }
+ _ = lease.Close()
+ }
+ if err := child.Process.Kill(); err != nil {
+ t.Fatal(err)
+ }
+ if err := child.Wait(); err == nil {
+ t.Fatal("subprocess exited normally")
+ }
+ lease, err := AcquireConfiguredMaintenance(ctx, true)
+ if err != nil {
+ t.Fatalf("acquire after abrupt subprocess exit: %v", err)
+ }
+ defer lease.Close()
+ if err := lease.SetExclusive(ctx, false); err != nil {
+ t.Fatal(err)
+ }
+ peer, err := TryConfiguredMaintenance(ctx, false)
+ if err != nil {
+ t.Fatalf("acquire shared after downgrade: %v", err)
+ }
+ defer peer.Close()
+ })
+ }
+}
+
+func TestSQLiteMaintenanceSurvivesFileReplacement(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "x-ui.db")
+ if err := os.WriteFile(path, []byte("old"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ lease, err := AcquireSQLiteMaintenance(t.Context(), path, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lease.Close()
+ if err := os.Rename(path, path+".backup"); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte("new"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 150*time.Millisecond)
+ defer cancel()
+ if peer, err := AcquireSQLiteMaintenance(ctx, path, false); !errors.Is(err, ErrMaintenanceBusy) {
+ if peer != nil {
+ _ = peer.Close()
+ }
+ t.Fatalf("shared lock on replacement file: %v, want busy", err)
+ }
+}
+
+func TestSQLiteMaintenanceKeepsDanglingAliasLocked(t *testing.T) {
+ dir := t.TempDir()
+ live := filepath.Join(dir, "live.db")
+ alias := filepath.Join(dir, "alias.db")
+ if err := os.WriteFile(live, []byte("old"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink("live.db", alias); err != nil {
+ t.Skipf("cannot create SQLite symlink: %v", err)
+ }
+ lease, err := AcquireSQLiteMaintenance(t.Context(), alias, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lease.Close()
+ if err := os.Rename(live, live+".backup"); err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.WithValue(t.Context(), noMaintenanceRetry{}, true)
+ if peer, err := AcquireSQLiteMaintenance(ctx, alias, true); !errors.Is(err, ErrMaintenanceBusy) {
+ if peer != nil {
+ _ = peer.Close()
+ }
+ t.Fatalf("second exclusive lock while the alias target is absent: %v, want busy", err)
+ }
+}
+
+func TestPostgresRuntimeMaintenanceReacquiresAfterSessionLoss(t *testing.T) {
+ if os.Getenv("XUI_DB_TYPE") != DialectPostgres || os.Getenv("XUI_DB_DSN") == "" {
+ t.Skip("requires PostgreSQL")
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
+ defer cancel()
+ lease, err := AcquireConfiguredMaintenance(ctx, false)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lease.Close()
+ SetRuntimeMaintenanceLease(lease)
+ defer SetRuntimeMaintenanceLease(nil)
+
+ other, err := pgx.Connect(ctx, os.Getenv("XUI_DB_DSN"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer other.Close(ctx)
+ var killed bool
+ pid := lease.backend.(*postgresMaintenance).conn.PgConn().PID()
+ if err := other.QueryRow(ctx, "SELECT pg_terminate_backend($1)", int32(pid)).Scan(&killed); err != nil || !killed {
+ t.Fatalf("terminate the fixture lease: %v, killed = %t", err, killed)
+ }
+ if err := lease.CheckRuntimeConnection(ctx); err == nil || RuntimeMaintenanceAvailable() {
+ t.Fatalf("lost session still admits work: %v", err)
+ }
+
+ maintenance, err := AcquireConfiguredMaintenance(ctx, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer maintenance.Close()
+ tryOnce := context.WithValue(ctx, noMaintenanceRetry{}, true)
+ if err := lease.RecoverRuntimeConnection(tryOnce); !errors.Is(err, ErrMaintenanceBusy) || RuntimeMaintenanceAvailable() {
+ t.Fatalf("recovery ignored an exclusive holder: %v", err)
+ }
+ if err := maintenance.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := lease.RecoverRuntimeConnection(ctx); err != nil || !RuntimeMaintenanceAvailable() {
+ t.Fatalf("did not recover the previous shared lease: %v", err)
+ }
+ if peer, err := TryConfiguredMaintenance(ctx, true); !errors.Is(err, ErrMaintenanceBusy) {
+ if peer != nil {
+ _ = peer.Close()
+ }
+ t.Fatalf("recovered session did not hold the lock: %v", err)
+ }
+}
+
+func TestPostgresExclusiveRestoreFenceSurvivesSessionLoss(t *testing.T) {
+ if os.Getenv("XUI_DB_TYPE") != DialectPostgres || os.Getenv("XUI_DB_DSN") == "" {
+ t.Skip("requires PostgreSQL")
+ }
+ cleanup, err := testpg.IsolatePackage("restore_fence")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ t.Setenv("XUI_DB_FOLDER", t.TempDir())
+ ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
+ defer cancel()
+ lease, err := AcquireConfiguredMaintenance(ctx, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lease.Close()
+ if err := lease.InitDB("", MarkPostgresRestorePending); err != nil {
+ t.Fatal(err)
+ }
+ defer CloseDB()
+ fence, err := lease.PostgresFence()
+ if err != nil {
+ t.Fatal(err)
+ }
+ worker, err := pgx.Connect(ctx, os.Getenv("XUI_DB_DSN"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer worker.Close(ctx)
+ importTx, err := worker.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer importTx.Rollback(ctx)
+ if _, err := importTx.Exec(ctx, fence.TransactionFenceSQL()); err != nil {
+ t.Fatalf("take the same transaction fence as the archive restore: %v", err)
+ }
+ if _, err := importTx.Exec(ctx, "INSERT INTO settings (key, value) VALUES ('restore-probe', 'uncommitted')"); err != nil {
+ t.Fatal(err)
+ }
+
+ var terminated bool
+ err = GetDB().Raw("SELECT pg_terminate_backend(?)", fence.pid).Scan(&terminated).Error
+ if err != nil || !terminated {
+ t.Fatalf("terminate the fixture's coordinating session: %t, %v", terminated, err)
+ }
+ if err := lease.CheckRuntimeConnection(ctx); err == nil {
+ t.Fatal("lease did not detect the lost session")
+ }
+ if fence.Context.Err() == nil {
+ t.Fatal("the archive command was not canceled")
+ }
+ if err := lease.RecoverRuntimeConnection(ctx); !errors.Is(err, ErrMaintenanceUnavailable) {
+ t.Fatalf("an exclusive restore was allowed to reconnect: %v", err)
+ }
+ for _, exclusive := range []bool{true, false} {
+ if other, err := TryConfiguredMaintenance(ctx, exclusive); !errors.Is(err, ErrMaintenanceBusy) {
+ if other != nil {
+ _ = other.Close()
+ }
+ t.Fatalf("another lease entered while archive writes could commit: exclusive=%t, %v", exclusive, err)
+ }
+ }
+ if err := lease.WithPostgresWork(GetDB(), ClearPostgresRestorePending); !errors.Is(err, ErrMaintenanceUnavailable) {
+ t.Fatalf("the old owner could clear the recovery marker: %v", err)
+ }
+ if err := importTx.Rollback(ctx); err != nil {
+ t.Fatal(err)
+ }
+ var written int64
+ if err := GetDB().Table("settings").Where("key = ?", "restore-probe").Count(&written).Error; err != nil || written != 0 {
+ t.Fatalf("aborted archive writes persisted: %d, %v", written, err)
+ }
+ if pending, err := PostgresRestorePending(GetDB()); err != nil || !pending {
+ t.Fatalf("recovery marker disappeared after session loss: %t, %v", pending, err)
+ }
+ other, err := TryConfiguredMaintenance(ctx, true)
+ if err != nil {
+ t.Fatalf("new exclusive owner cannot enter recovery: %v", err)
+ }
+ defer other.Close()
+ if err := other.WithPostgresWork(GetDB(), ClearPostgresRestorePending); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestPostgresCLIWorkFenceSurvivesSessionLoss(t *testing.T) {
+ if os.Getenv("XUI_DB_TYPE") != DialectPostgres || os.Getenv("XUI_DB_DSN") == "" {
+ t.Skip("requires PostgreSQL")
+ }
+ cleanup, err := testpg.IsolatePackage("cli_work_fence")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ t.Setenv("XUI_DB_FOLDER", t.TempDir())
+ for _, exclusive := range []bool{false, true} {
+ t.Run(fmt.Sprintf("exclusive=%t", exclusive), func(t *testing.T) {
+ ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
+ defer cancel()
+ if err := InitDB(""); err != nil {
+ t.Fatal(err)
+ }
+ defer CloseDB()
+ observer, err := pgx.Connect(ctx, os.Getenv("XUI_DB_DSN"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer observer.Close(ctx)
+ lease, err := AcquireConfiguredMaintenance(ctx, exclusive)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer lease.Close()
+
+ entered := make(chan context.Context, 1)
+ proceed, done := make(chan struct{}), make(chan struct{})
+ release := sync.OnceFunc(func() { close(proceed) })
+ var commandErr error
+ go func() {
+ defer close(done)
+ commandErr = lease.RunCLIWork(func() error {
+ // Ordinary CLI services use GetDB and open their own transactions.
+ return GetDB().Transaction(func(tx *gorm.DB) error {
+ if err := tx.Exec("INSERT INTO settings (key, value) VALUES ('cli-fence-probe', 'uncommitted')").Error; err != nil {
+ return err
+ }
+ entered <- tx.Statement.Context
+ <-proceed
+ return tx.Exec("UPDATE settings SET value = 'after loss' WHERE key = 'cli-fence-probe'").Error
+ })
+ })
+ }()
+ defer func() {
+ release()
+ <-done
+ }()
+ var workContext context.Context
+ select {
+ case workContext = <-entered:
+ case <-done:
+ t.Fatalf("CLI failed to reach the transaction barrier: %v", commandErr)
+ case <-ctx.Done():
+ t.Fatal(ctx.Err())
+ }
+
+ // Hold the watcher before terminating only its session so the
+ // competing process tests the execution fence before cancellation.
+ func() {
+ pg := lease.backend.(*postgresMaintenance)
+ pg.mu.Lock()
+ defer pg.mu.Unlock()
+ var terminated bool
+ pid := int32(pg.conn.PgConn().PID())
+ if err := observer.QueryRow(ctx, "SELECT pg_terminate_backend($1, 2000)", pid).Scan(&terminated); err != nil || !terminated {
+ t.Fatalf("terminate the CLI lease backend: %t, %v", terminated, err)
+ }
+ if other, err := TryConfiguredMaintenance(ctx, true); !errors.Is(err, ErrMaintenanceBusy) {
+ if other != nil {
+ _ = other.Close()
+ }
+ t.Fatalf("exclusive maintenance entered while CLI writes were still active: %v", err)
+ }
+ }()
+ select {
+ case <-workContext.Done():
+ case <-ctx.Done():
+ t.Fatal("CLI work context was not canceled after losing the lease")
+ }
+ release()
+ <-done
+ if !errors.Is(commandErr, context.Canceled) && !errors.Is(commandErr, ErrMaintenanceUnavailable) {
+ t.Fatalf("CLI did not fail after lease loss: %v", commandErr)
+ }
+ var persisted bool
+ if err := observer.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM settings WHERE key = 'cli-fence-probe')").Scan(&persisted); err != nil || persisted {
+ t.Fatalf("interrupted CLI transaction persisted: %t, %v", persisted, err)
+ }
+ other, err := TryConfiguredMaintenance(ctx, true)
+ if err != nil {
+ t.Fatalf("exclusive maintenance cannot enter after CLI work ended: %v", err)
+ }
+ defer other.Close()
+ })
+ }
+}
diff --git a/internal/database/migrate_data.go b/internal/database/migrate_data.go
index 0f7bf68e8..33fe6929b 100644
--- a/internal/database/migrate_data.go
+++ b/internal/database/migrate_data.go
@@ -76,6 +76,27 @@ func migrationModels() []any {
// so a failed migration leaves the destination data unchanged. Source data is
// left untouched.
func MigrateData(srcPath, dstDSN string) error {
+ ctx, cancel := context.WithTimeout(context.Background(), MaintenanceWait)
+ defer cancel()
+ lease, err := AcquirePostgresMaintenance(ctx, dstDSN, true)
+ if err != nil {
+ return err
+ }
+ defer lease.Close()
+ return lease.MigrateData(srcPath, dstDSN)
+}
+
+// MigrateData copies into PostgreSQL while the destination connection holds an execution fence.
+func (l *MaintenanceLease) MigrateData(srcPath, dstDSN string) error {
+ return l.migrateData(srcPath, dstDSN, false)
+}
+
+// RestoreSQLiteData copies into a target already marked for restore recovery.
+func (l *MaintenanceLease) RestoreSQLiteData(srcPath, dstDSN string) error {
+ return l.migrateData(srcPath, dstDSN, true)
+}
+
+func (l *MaintenanceLease) migrateData(srcPath, dstDSN string, restoring bool) error {
if _, err := os.Stat(srcPath); err != nil {
return fmt.Errorf("source sqlite not found at %s: %w", srcPath, err)
}
@@ -109,6 +130,22 @@ func MigrateData(srcPath, dstDSN string) error {
defer dstSQL.Close()
dstSQL.SetConnMaxLifetime(time.Hour)
+ return l.WithPostgresWork(dst, func(conn *gorm.DB) error {
+ pending, err := PendingPostgresRestoreForSchema(conn)
+ if err != nil {
+ return err
+ }
+ if pending && !restoring {
+ return ErrPostgresRestorePending
+ }
+ if restoring && !pending {
+ return errors.New("PostgreSQL restore must be marked pending before copying data")
+ }
+ return copyMigrationData(src, conn)
+ })
+}
+
+func copyMigrationData(src, dst *gorm.DB) error {
log.Println("Creating destination schema...")
for _, m := range migrationModels() {
if err := dst.AutoMigrate(m); err != nil {
diff --git a/internal/database/model/model.go b/internal/database/model/model.go
index 8c1c6f657..f797e9227 100644
--- a/internal/database/model/model.go
+++ b/internal/database/model/model.go
@@ -922,10 +922,11 @@ type Node struct {
MemPct float64 `json:"memPct" example:"45.1"`
UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
// Nil on legacy rows and responses: zero remains a valid measured value.
- UnavailableMetrics []string `json:"unavailableMetrics,omitempty" gorm:"serializer:json;column:unavailable_metrics"`
- NetUp uint64 `json:"netUp" gorm:"column:net_up" example:"1048576"`
- NetDown uint64 `json:"netDown" gorm:"column:net_down" example:"2097152"`
- LastError string `json:"lastError"`
+ UnavailableMetrics []string `json:"unavailableMetrics,omitempty" gorm:"serializer:json;column:unavailable_metrics"`
+ Telemetry *NodeTelemetry `json:"telemetry,omitempty" gorm:"serializer:json;type:text"`
+ NetUp uint64 `json:"netUp" gorm:"column:net_up" example:"1048576"`
+ NetDown uint64 `json:"netDown" gorm:"column:net_down" example:"2097152"`
+ LastError string `json:"lastError"`
// XrayState and XrayError are captured from the remote node's /panel/api/server/status
// during heartbeats. They let the central panel distinguish "panel API reachable"
@@ -980,8 +981,11 @@ type NodeSummary struct {
PanelVersion string `json:"panelVersion"`
XrayVersion string `json:"xrayVersion"`
// XrayState/XrayError forwarded so masters can surface xray failure on transitive sub-nodes too.
- XrayState string `json:"xrayState"`
- XrayError string `json:"xrayError,omitempty"`
+ XrayState string `json:"xrayState"`
+ XrayError string `json:"xrayError,omitempty"`
+ Enabled *bool `json:"enabled,omitempty"`
+ BasePath string `json:"basePath,omitempty"`
+ Telemetry *NodeTelemetry `json:"telemetry,omitempty"`
}
type ClientReverse struct {
@@ -1183,6 +1187,8 @@ type ClientInbound struct {
InboundId int `json:"inboundId" gorm:"primaryKey;column:inbound_id;index"`
FlowOverride string `json:"flowOverride" gorm:"column:flow_override"`
CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"`
+ // Incarnation changes only when the membership is inserted.
+ Incarnation string `json:"-" gorm:"->;not null;default:''"`
}
func (ClientInbound) TableName() string { return "client_inbounds" }
diff --git a/internal/database/model/node_telemetry.go b/internal/database/model/node_telemetry.go
new file mode 100644
index 000000000..5d3cdee0b
--- /dev/null
+++ b/internal/database/model/node_telemetry.go
@@ -0,0 +1,22 @@
+package model
+
+// NodeTelemetry describes one host sample. Nil metrics were not measured.
+type NodeTelemetry struct {
+ SampledAt int64 `json:"sampledAt" example:"1700000000000"`
+ SampleAgeMillis *int64 `json:"sampleAgeMillis,omitempty" example:"125"`
+ ResourceScope string `json:"resourceScope,omitempty" example:"container"`
+ CpuPct *float64 `json:"cpuPct,omitempty" example:"12.5"`
+ PhysicalCores *int `json:"physicalCores,omitempty" example:"4"`
+ LogicalCores *int `json:"logicalCores,omitempty" example:"8"`
+ MemUsedBytes *uint64 `json:"memUsedBytes,omitempty" example:"2147483648"`
+ MemTotalBytes *uint64 `json:"memTotalBytes,omitempty" example:"4294967296"`
+ MemAvailableBytes *uint64 `json:"memAvailableBytes,omitempty" example:"1073741824"`
+ TCPCount *int `json:"tcpCount,omitempty" example:"75"`
+ UDPCount *int `json:"udpCount,omitempty" example:"12"`
+ Load1 *float64 `json:"load1,omitempty" example:"0.25"`
+ Load5 *float64 `json:"load5,omitempty" example:"0.18"`
+ Load15 *float64 `json:"load15,omitempty" example:"0.12"`
+ UptimeSecs *uint64 `json:"uptimeSecs,omitempty" example:"3600"`
+ NetUp *uint64 `json:"netUp,omitempty" example:"1024"`
+ NetDown *uint64 `json:"netDown,omitempty" example:"2048"`
+}
diff --git a/internal/database/node_telemetry_migration_test.go b/internal/database/node_telemetry_migration_test.go
new file mode 100644
index 000000000..7707af334
--- /dev/null
+++ b/internal/database/node_telemetry_migration_test.go
@@ -0,0 +1,42 @@
+package database
+
+import (
+ "testing"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+func TestMigrateNodeTelemetryColumn(t *testing.T) {
+ initMigrateDB(t)
+ tx := GetDB().Begin()
+ if tx.Error != nil {
+ t.Fatal(tx.Error)
+ }
+ t.Cleanup(func() { tx.Rollback() })
+ node := model.Node{Name: "legacy", Address: "192.0.2.1", Port: 2053}
+ if err := tx.Create(&node).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Exec("ALTER TABLE nodes DROP COLUMN telemetry").Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := migrateNodeTelemetryColumn(tx); err != nil {
+ t.Fatal(err)
+ }
+ var stored model.Node
+ if err := tx.First(&stored, node.Id).Error; err != nil || stored.Telemetry != nil || stored.Name != node.Name {
+ t.Fatalf("legacy row after migration: %+v, %v", stored, err)
+ }
+ sample := model.Node{Telemetry: &model.NodeTelemetry{SampledAt: 123, LogicalCores: new(8)}}
+ if err := tx.Model(&stored).Updates(sample).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := migrateNodeTelemetryColumn(tx); err != nil {
+ t.Fatal(err)
+ }
+ stored = model.Node{}
+ if err := tx.First(&stored, node.Id).Error; err != nil ||
+ stored.Telemetry == nil || stored.Telemetry.LogicalCores == nil || *stored.Telemetry.LogicalCores != 8 {
+ t.Fatalf("repeat migration lost saved telemetry: %+v, %v", stored.Telemetry, err)
+ }
+}
diff --git a/internal/database/postgres_maintenance_fence.go b/internal/database/postgres_maintenance_fence.go
new file mode 100644
index 000000000..b5eb9adbb
--- /dev/null
+++ b/internal/database/postgres_maintenance_fence.go
@@ -0,0 +1,163 @@
+package database
+
+import (
+ "context"
+ "database/sql/driver"
+ "errors"
+ "fmt"
+
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+)
+
+// The executing connection holds this key even if the coordinating session disappears.
+const postgresMaintenanceWorkKey int64 = postgresMaintenanceKey + 1
+
+type PostgresMaintenanceFence struct {
+ Context context.Context
+ pid int32
+ start int64
+ exclusive bool
+}
+
+func (l *MaintenanceLease) PostgresFence() (PostgresMaintenanceFence, error) {
+ return l.postgresFence(true)
+}
+
+func (l *MaintenanceLease) postgresFence(requireExclusive bool) (PostgresMaintenanceFence, error) {
+ pg, ok := l.backend.(*postgresMaintenance)
+ if !ok {
+ return PostgresMaintenanceFence{}, ErrMaintenanceUnavailable
+ }
+ pg.mu.Lock()
+ defer pg.mu.Unlock()
+ if pg.conn == nil || !pg.held || (requireExclusive && !pg.exclusive) {
+ return PostgresMaintenanceFence{}, ErrMaintenanceUnavailable
+ }
+ pg.watchWorkLocked()
+ ctx, cancel := context.WithTimeout(pg.workContext, MaintenanceWait)
+ defer cancel()
+ fence := PostgresMaintenanceFence{Context: pg.workContext, pid: int32(pg.conn.PgConn().PID()), exclusive: pg.exclusive}
+ err := pg.conn.QueryRow(ctx, `SELECT (extract(epoch FROM backend_start) * 1000000)::bigint
+ FROM pg_stat_activity WHERE pid = pg_backend_pid()`).Scan(&fence.start)
+ if err != nil {
+ l.available.Store(false)
+ return PostgresMaintenanceFence{}, errors.Join(ErrMaintenanceUnavailable, err, pg.dropConnection())
+ }
+ return fence, nil
+}
+
+func (f PostgresMaintenanceFence) ownerSQL() string {
+ mode := "ShareLock"
+ if f.exclusive {
+ mode = "ExclusiveLock"
+ }
+ return fmt.Sprintf(`SELECT EXISTS (
+ SELECT 1 FROM pg_locks AS l JOIN pg_stat_activity AS s USING (pid)
+ WHERE l.locktype = 'advisory' AND l.mode = '%s' AND l.granted
+ AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database())
+ AND l.classid = %d AND l.objid = %d AND l.objsubid = 1
+ AND l.pid = %d AND (extract(epoch FROM s.backend_start) * 1000000)::bigint = %d
+ )`, mode, uint64(postgresMaintenanceKey)>>32, uint32(postgresMaintenanceKey&0xffffffff), f.pid, f.start)
+}
+
+// TransactionFenceSQL fences an external SQL restore on the connection that executes it.
+// It must run first inside the same transaction as the archive.
+func (f PostgresMaintenanceFence) TransactionFenceSQL() string {
+ return fmt.Sprintf(`DO $xui$ BEGIN
+ IF NOT pg_try_advisory_xact_lock(%d) THEN
+ RAISE EXCEPTION 'PostgreSQL maintenance work is already executing';
+ END IF;
+ IF NOT (%s) THEN
+ RAISE EXCEPTION 'PostgreSQL maintenance ownership was lost';
+ END IF;
+ END $xui$`, postgresMaintenanceWorkKey, f.ownerSQL())
+}
+
+// WithPostgresWork runs maintenance through a pinned and fenced connection.
+// The caller must use the provided GORM handle for every statement.
+func (l *MaintenanceLease) WithPostgresWork(db *gorm.DB, work func(*gorm.DB) error) error {
+ return l.withPostgresWork(db, true, work)
+}
+
+// RunCLIWork binds a standalone CLI's database handles to its lease for the
+// duration of the command. It must not be used by the running panel.
+func (l *MaintenanceLease) RunCLIWork(work func() error) error {
+ return l.withPostgresWork(GetDB(), false, func(conn *gorm.DB) error {
+ pool, previous := db, publishedDB.Swap(conn)
+ db = conn
+ defer func() {
+ db = pool
+ publishedDB.Store(previous)
+ }()
+ return work()
+ })
+}
+
+func (l *MaintenanceLease) withPostgresWork(db *gorm.DB, requireExclusive bool, work func(*gorm.DB) error) (err error) {
+ if db.Name() != DialectPostgres {
+ return work(db)
+ }
+ fence, err := l.postgresFence(requireExclusive)
+ if err != nil {
+ return err
+ }
+ pool, err := db.DB()
+ if err != nil {
+ return err
+ }
+ raw, err := pool.Conn(fence.Context)
+ if err != nil {
+ return err
+ }
+ defer raw.Close()
+ // Populate both GORM's default and statement connection. Its default
+ // transaction callbacks reset the statement to the default connection.
+ fenced, err := gorm.Open(postgres.New(postgres.Config{Conn: raw}), &gorm.Config{
+ Logger: db.Logger, NamingStrategy: db.NamingStrategy, DisableAutomaticPing: true,
+ DisableForeignKeyConstraintWhenMigrating: db.DisableForeignKeyConstraintWhenMigrating,
+ })
+ if err != nil {
+ return err
+ }
+ conn := fenced.WithContext(fence.Context)
+ discard := func() { _ = raw.Raw(func(any) error { return driver.ErrBadConn }) }
+ take, release := "SELECT pg_try_advisory_lock_shared(?)", "SELECT pg_advisory_unlock_shared(?)"
+ if fence.exclusive {
+ take, release = "SELECT pg_try_advisory_lock(?)", "SELECT pg_advisory_unlock(?)"
+ }
+ var locked bool
+ if err := conn.Raw(take, postgresMaintenanceWorkKey).Scan(&locked).Error; err != nil {
+ discard()
+ return err
+ }
+ if !locked {
+ return ErrMaintenanceBusy
+ }
+ defer func() {
+ ctx, cancel := context.WithTimeout(context.Background(), MaintenanceWait)
+ defer cancel()
+ var released bool
+ unlockErr := conn.WithContext(ctx).Raw(release, postgresMaintenanceWorkKey).Scan(&released).Error
+ if unlockErr != nil || !released {
+ // Never return a session that might retain its fence to the app pool.
+ discard()
+ err = errors.Join(err, ErrMaintenanceUnavailable, unlockErr)
+ }
+ }()
+ checkOwner := func() error {
+ var held bool
+ err := conn.Raw(fence.ownerSQL()).Scan(&held).Error
+ if err != nil || !held {
+ return errors.Join(ErrMaintenanceUnavailable, err)
+ }
+ return nil
+ }
+ if err := checkOwner(); err != nil {
+ return err
+ }
+ if err := work(conn); err != nil {
+ return err
+ }
+ return checkOwner()
+}
diff --git a/internal/database/postgres_restore_pending.go b/internal/database/postgres_restore_pending.go
new file mode 100644
index 000000000..9f7ed638e
--- /dev/null
+++ b/internal/database/postgres_restore_pending.go
@@ -0,0 +1,69 @@
+package database
+
+import (
+ "errors"
+
+ "gorm.io/gorm"
+)
+
+const PostgresMaintenanceSchema = "xui_maintenance"
+
+const postgresRestoreStateTable = PostgresMaintenanceSchema + ".restore_pending"
+
+var ErrPostgresRestorePending = errors.New("PostgreSQL restore migration is pending")
+
+func postgresRestorePending(scan func(string, *bool) error) (bool, error) {
+ var exists bool
+ if err := scan("SELECT to_regclass('"+postgresRestoreStateTable+"') IS NOT NULL", &exists); err != nil || !exists {
+ return false, err
+ }
+ var pending bool
+ err := scan("SELECT EXISTS (SELECT 1 FROM "+postgresRestoreStateTable+")", &pending)
+ return pending, err
+}
+
+// PostgresRestorePending reads recovery state from the panel's PostgreSQL schema.
+func PostgresRestorePending(db *gorm.DB) (bool, error) {
+ return postgresRestorePending(func(query string, result *bool) error {
+ return db.Raw(query).Scan(result).Error
+ })
+}
+
+// MarkPostgresRestorePending records interrupted work outside the tables copied
+// by restore. The caller must hold the maintenance execution fence.
+func MarkPostgresRestorePending(db *gorm.DB) error {
+ if err := migratePostgresRestoreState(db); err != nil {
+ return err
+ }
+ if err := checkPostgresRestoreSchema(db); err != nil {
+ return err
+ }
+ return db.Exec("INSERT INTO " + postgresRestoreStateTable + " (id, app_schema) VALUES (1, current_schema()) ON CONFLICT DO NOTHING").Error
+}
+
+// PendingPostgresRestoreForSchema refuses repair from an unrelated search path.
+func PendingPostgresRestoreForSchema(db *gorm.DB) (bool, error) {
+ pending, err := PostgresRestorePending(db)
+ if err != nil || !pending {
+ return pending, err
+ }
+ return true, checkPostgresRestoreSchema(db)
+}
+
+func checkPostgresRestoreSchema(db *gorm.DB) error {
+ var otherSchema bool
+ err := db.Raw("SELECT EXISTS (SELECT 1 FROM " + postgresRestoreStateTable + " WHERE app_schema IS DISTINCT FROM current_schema())").Scan(&otherSchema).Error
+ if err == nil && otherSchema {
+ return errors.New("PostgreSQL restore is pending for a different application schema; use its original search_path to recover")
+ }
+ return err
+}
+
+// ClearPostgresRestorePending is only safe after repair succeeds under the fence.
+func ClearPostgresRestorePending(db *gorm.DB) error {
+ pending, err := PendingPostgresRestoreForSchema(db)
+ if err != nil || !pending {
+ return err
+ }
+ return db.Exec("DELETE FROM " + postgresRestoreStateTable + " WHERE id = 1").Error
+}
diff --git a/internal/mtproto/manager.go b/internal/mtproto/manager.go
index 79005991e..f5ff0ffe8 100644
--- a/internal/mtproto/manager.go
+++ b/internal/mtproto/manager.go
@@ -429,7 +429,8 @@ func (m *Manager) StopAll() {
// CollectTraffic scrapes each running mtg /stats endpoint for the byte deltas since the
// previous scrape, per client and per inbound's fronted connections, and the online emails.
-func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) {
+// The returned tags identify inbounds whose scrape succeeded, including idle ones.
+func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string, []string) {
type snap struct {
id int
apiPort int
@@ -453,7 +454,7 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) {
var out []Traffic
var fronted []FrontedTraffic
- var online []string
+ var online, observedTags []string
now := time.Now().Unix()
for _, s := range snaps {
stats, ok := scrapeStats(s.apiPort, s.apiToken)
@@ -466,6 +467,7 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) {
m.mu.Unlock()
continue
}
+ observedTags = append(observedTags, s.tag)
newLast := make(map[string]clientCounters, len(stats.Users))
for email, u := range stats.Users {
now := u.counters()
@@ -495,7 +497,7 @@ func (m *Manager) CollectTraffic() ([]Traffic, []FrontedTraffic, []string) {
}
m.mu.Unlock()
}
- return out, fronted, online
+ return out, fronted, online, observedTags
}
// ClientIPs returns the addresses mtg reported connected at the last scrape,
diff --git a/internal/mtproto/manager_client_ips_test.go b/internal/mtproto/manager_client_ips_test.go
index c790f6922..562fd5d3e 100644
--- a/internal/mtproto/manager_client_ips_test.go
+++ b/internal/mtproto/manager_client_ips_test.go
@@ -66,7 +66,10 @@ func TestClientIPsFollowTheLastScrape(t *testing.T) {
// A scrape that fails says nothing about who is connected: the addresses of the
// previous one must not stay "live", or a client that left keeps counting.
srv.Close()
- mgr.CollectTraffic()
+ _, _, _, observed := mgr.CollectTraffic()
+ if len(observed) != 0 {
+ t.Fatalf("a failed scrape must leave the inbound unobserved, got %v", observed)
+ }
if got := mgr.ClientIPs(); len(got) != 0 {
t.Fatalf("a failed scrape must drop the known addresses, got %v", fmt.Sprint(got))
}
diff --git a/internal/mtproto/manager_fronting_test.go b/internal/mtproto/manager_fronting_test.go
index df9b06c61..47067e297 100644
--- a/internal/mtproto/manager_fronting_test.go
+++ b/internal/mtproto/manager_fronting_test.go
@@ -76,7 +76,7 @@ func TestCollectTrafficReportsFrontedBytes(t *testing.T) {
nil,
}
for i, want := range wants {
- clients, fronted, _ := mgr.CollectTraffic()
+ clients, fronted, _, _ := mgr.CollectTraffic()
if len(clients) != 0 {
t.Fatalf("scrape %d: fronted bytes must not be attributed to a client: %+v", i+1, clients)
}
@@ -104,7 +104,10 @@ func TestCollectTrafficWithoutFrontingCounters(t *testing.T) {
mgr.procs[1].apiPort = serverPort(t, srv)
mgr.CollectTraffic()
- clients, fronted, online := mgr.CollectTraffic()
+ clients, fronted, online, tags := mgr.CollectTraffic()
+ if !reflect.DeepEqual(tags, []string{"inbound-1"}) {
+ t.Fatalf("successfully polled inbounds = %v, want [inbound-1]", tags)
+ }
if want := []Traffic{{Tag: "inbound-1", Email: "alice", Up: 10, Down: 20}}; !reflect.DeepEqual(clients, want) {
t.Fatalf("clients = %+v, want %+v", clients, want)
}
diff --git a/internal/nodee2e/node_detach_scoped_test.go b/internal/nodee2e/node_detach_scoped_test.go
new file mode 100644
index 000000000..e92628705
--- /dev/null
+++ b/internal/nodee2e/node_detach_scoped_test.go
@@ -0,0 +1,77 @@
+package nodee2e
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+func TestScopedDetachReconcilesOfflineNode(t *testing.T) {
+ bin := panelBinary(t)
+ master, node := newPanel(t, bin, "detach-master"), newPanel(t, bin, "detach-node")
+ master.start()
+ node.start()
+ port := freePort(t)
+ node.call(http.MethodPost, "/panel/api/inbounds/add",
+ vlessInbound("detach-source", port, nil, vlessClient("detach-me"), vlessClient("keep-me")))
+ enrollTrafficNode(t, master, node)
+ var source inboundView
+ eventually(t, settleTimeout, "master adopts both clients", func() (bool, string) {
+ var ok bool
+ source, ok = master.inboundOnPort(port)
+ return ok && len(source.emails()) == 2, fmt.Sprint(source.emails())
+ })
+ var page struct {
+ Items []struct {
+ ID int `json:"id"`
+ Email string `json:"email"`
+ }
+ }
+ if err := json.Unmarshal(master.call(http.MethodGet, fmt.Sprintf("/panel/api/clients/detachCandidates?inboundId=%d", source.Id), nil), &page); err != nil {
+ t.Fatal(err)
+ }
+ var keep int
+ for _, item := range page.Items {
+ if item.Email == "keep-me" {
+ keep = item.ID
+ }
+ }
+ if keep == 0 || len(page.Items) != 2 {
+ t.Fatalf("source candidates: %+v", page)
+ }
+ var frozen struct{ ScopeToken string }
+ if err := json.Unmarshal(master.call(http.MethodPost, "/panel/api/clients/detachCandidates/freeze", map[string]any{"inboundId": source.Id}), &frozen); err != nil {
+ t.Fatal(err)
+ }
+ node.stop()
+ id := uuid.NewString()
+ master.call(http.MethodPost, "/panel/api/clients/bulkDetach", map[string]any{
+ "inboundIds": []int{source.Id}, "requestId": id,
+ "selection": map[string]any{"mode": "allMatching", "scopeToken": frozen.ScopeToken, "excludedClientIds": []int{keep}},
+ })
+ eventually(t, 10*time.Second, "scoped detachment commits and queues reconciliation", func() (bool, string) {
+ var status struct {
+ Running bool
+ Error string
+ Result struct {
+ Detached, Skipped, Errors int
+ NodePending bool
+ }
+ }
+ raw := master.call(http.MethodGet, "/panel/api/clients/bulkDetach/"+id, nil)
+ if err := json.Unmarshal(raw, &status); err != nil {
+ t.Fatal(err)
+ }
+ return !status.Running && status.Error == "" && status.Result.Detached == 1 &&
+ status.Result.Skipped == 0 && status.Result.Errors == 0 && status.Result.NodePending, string(raw)
+ })
+ node.start()
+ eventually(t, 90*time.Second, "node applies detach and keeps the excluded client", func() (bool, string) {
+ ib, ok := node.inboundOnPort(port)
+ return ok && len(ib.emails()) == 1 && ib.client("keep-me") != nil, fmt.Sprint(ib.emails())
+ })
+}
diff --git a/internal/nodee2e/node_snapshot_test.go b/internal/nodee2e/node_snapshot_test.go
index 6cf4f7388..50fdfa891 100644
--- a/internal/nodee2e/node_snapshot_test.go
+++ b/internal/nodee2e/node_snapshot_test.go
@@ -3,6 +3,7 @@ package nodee2e
import (
"bytes"
"compress/gzip"
+ "context"
"encoding/json"
"fmt"
"io"
@@ -11,9 +12,14 @@ import (
"net/http/httputil"
"net/url"
"os"
+ "slices"
"strconv"
"sync/atomic"
"testing"
+ "time"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
)
func TestNodeSnapshotVersionCompatibility(t *testing.T) {
@@ -39,7 +45,7 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) {
token := node.mintToken("snapshot-link", "node-sync")
master.start()
node.start()
- var lists, compact, full, unchanged atomic.Int32
+ var catalogs, lists, compact, full, unchanged, clientAdds atomic.Int32
target, err := url.Parse(node.url())
if err != nil {
t.Fatal(err)
@@ -84,10 +90,14 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) {
}
front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
switch req.URL.Path {
+ case "/panel/api/inbounds/catalog":
+ catalogs.Add(1)
case "/panel/api/inbounds/list":
lists.Add(1)
case "/panel/api/inbounds/trafficSnapshot":
compact.Add(1)
+ case "/panel/api/clients/add":
+ clientAdds.Add(1)
}
proxy.ServeHTTP(w, req)
}))
@@ -101,11 +111,30 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) {
t.Fatal(err)
}
inboundPort := freePort(t)
+ secondaryPort := freePort(t)
var source inboundView
if err := json.Unmarshal(node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix", inboundPort, nil, vlessClient("matrix-first"))), &source); err != nil {
t.Fatal(err)
}
- master.call(http.MethodPost, "/panel/api/nodes/add", map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true})
+ params := map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true}
+ if version.master == current {
+ var options []inboundView
+ obj := master.call(http.MethodPost, "/panel/api/nodes/inbounds", params)
+ if err := json.Unmarshal(obj, &options); err != nil || len(options) != 1 || options[0].Id != source.Id {
+ t.Fatalf("read node options: %s, %v", obj, err)
+ }
+ var wantLists int32
+ if version.node != current {
+ wantLists = 1
+ }
+ if got := lists.Swap(0); catalogs.Load() != 1 || got != wantLists {
+ t.Fatalf("node options used catalog=%d and full list=%d, want 1 and %d", catalogs.Load(), got, wantLists)
+ }
+ }
+ if version.master == current {
+ node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix-secondary", secondaryPort, nil))
+ }
+ master.call(http.MethodPost, "/panel/api/nodes/add", params)
eventually(t, settleTimeout, "version pair synchronizes and reaches steady state", func() (bool, string) {
ib, ok := master.inboundOnPort(inboundPort)
ready := lists.Load() >= 3
@@ -136,6 +165,50 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) {
master.start()
eventually(t, settleTimeout, "master restart reacquires complete structure", func() (bool, string) { return full.Load() > before, fmt.Sprint(full.Load()) })
}
+ if version.master == current {
+ first, hasFirst := master.inboundOnPort(inboundPort)
+ second, hasSecond := master.inboundOnPort(secondaryPort)
+ if !hasFirst || !hasSecond {
+ t.Fatal("master did not adopt both inbounds")
+ }
+ const email = "matrix-shared-create"
+ master.call(http.MethodPost, "/panel/api/clients/add", map[string]any{
+ "client": map[string]any{"email": email, "enable": true}, "inboundIds": []int{first.Id, second.Id},
+ })
+ if got := clientAdds.Load(); got != 1 {
+ t.Fatalf("node-sync received %d add requests, want one", got)
+ }
+ var tags []string
+ for _, port := range []int{inboundPort, secondaryPort} {
+ if ib, ok := node.inboundOnPort(port); !ok || ib.client(email) == nil {
+ t.Fatalf("node did not apply the grouped client on port %d", port)
+ } else {
+ tags = append(tags, ib.Tag)
+ }
+ }
+ admin := runtime.NewRemote(&model.Node{
+ Name: "matrix-admin", Scheme: "http", Address: address.Hostname(), Port: port,
+ BasePath: "/", ApiToken: node.token, Enable: true, AllowPrivateAddress: true,
+ }, nil)
+ const adminEmail = "matrix-admin-create"
+ raw, err := json.Marshal(vlessClient(adminEmail))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
+ defer cancel()
+ if _, ack, err := admin.AddClientGroup(ctx, tags, raw); err != nil || !slices.Equal(ack, []bool{true, true}) {
+ t.Fatalf("admin grouped add acknowledged %v, err=%v", ack, err)
+ }
+ if got := clientAdds.Load(); got != 2 {
+ t.Fatalf("admin sent %d add requests, want one", got-1)
+ }
+ for _, port := range []int{inboundPort, secondaryPort} {
+ if ib, ok := node.inboundOnPort(port); !ok || ib.client(adminEmail) == nil {
+ t.Fatalf("admin grouped client absent on port %d", port)
+ }
+ }
+ }
})
}
}
diff --git a/internal/sub/clash_service.go b/internal/sub/clash_service.go
index 7ccb42692..dcc50772a 100644
--- a/internal/sub/clash_service.go
+++ b/internal/sub/clash_service.go
@@ -249,6 +249,10 @@ func legacyClashProxy(proxy map[string]any) map[string]any {
if _, reality := proxy["reality-opts"]; reality {
return nil
}
+ // Legacy Clash would treat Mihomo's HTTPUpgrade options as ordinary WebSocket.
+ if opts, ok := proxy["ws-opts"].(map[string]any); ok && opts["v2ray-http-upgrade"] == true {
+ return nil
+ }
var fields []string
var cipher string
@@ -1185,10 +1189,13 @@ func (s *SubClashService) applyTransport(proxy map[string]any, network string, s
}
}
return true
- case "ws":
+ case "ws", "httpupgrade":
proxy["network"] = "ws"
- ws, _ := stream["wsSettings"].(map[string]any)
+ ws, _ := stream[network+"Settings"].(map[string]any)
wsOpts := map[string]any{}
+ if network == "httpupgrade" {
+ wsOpts["v2ray-http-upgrade"] = true
+ }
if ws != nil {
if path, ok := ws["path"].(string); ok && path != "" {
wsOpts["path"] = path
@@ -1220,28 +1227,6 @@ func (s *SubClashService) applyTransport(proxy map[string]any, network string, s
proxy["grpc-opts"] = grpcOpts
}
return true
- case "httpupgrade":
- proxy["network"] = "httpupgrade"
- hu, _ := stream["httpupgradeSettings"].(map[string]any)
- opts := map[string]any{}
- if hu != nil {
- if path, ok := hu["path"].(string); ok && path != "" {
- opts["path"] = path
- }
- host := ""
- if v, ok := hu["host"].(string); ok && v != "" {
- host = v
- } else if headers, ok := hu["headers"].(map[string]any); ok {
- host = searchHost(headers)
- }
- if host != "" {
- opts["headers"] = map[string]any{"Host": host}
- }
- }
- if len(opts) > 0 {
- proxy["http-upgrade-opts"] = opts
- }
- return true
case "xhttp":
proxy["network"] = "xhttp"
xhttp, _ := stream["xhttpSettings"].(map[string]any)
diff --git a/internal/sub/clash_service_test.go b/internal/sub/clash_service_test.go
index ae80a7fe8..6b4309859 100644
--- a/internal/sub/clash_service_test.go
+++ b/internal/sub/clash_service_test.go
@@ -117,6 +117,7 @@ func TestLegacyClashProxyCompatibility(t *testing.T) {
{"name": "vl", "type": "vless"},
{"name": "hy", "type": "hysteria2"},
{"name": "xh", "type": "vmess", "cipher": "auto", "network": "xhttp"},
+ {"name": "hu", "type": "vmess", "cipher": "auto", "network": "ws", "ws-opts": map[string]any{"v2ray-http-upgrade": true}},
{"name": "reality", "type": "vmess", "cipher": "auto", "network": "tcp", "reality-opts": map[string]any{}},
} {
if got := legacyClashProxy(proxy); got != nil {
@@ -421,27 +422,45 @@ func TestApplyTransport_HTTPUpgrade(t *testing.T) {
proxy := map[string]any{}
stream := map[string]any{
"httpupgradeSettings": map[string]any{
- "path": "/hu",
- "host": "example.com",
+ "path": "/hu",
+ "host": "example.com",
+ "headers": map[string]any{"host": "ignored.example.com"},
},
}
if !svc.applyTransport(proxy, "httpupgrade", stream) {
t.Fatalf("applyTransport returned false for httpupgrade")
}
- if proxy["network"] != "httpupgrade" {
- t.Fatalf("network = %v, want httpupgrade", proxy["network"])
+ if proxy["network"] != "ws" {
+ t.Fatalf("network = %v, want ws", proxy["network"])
}
- opts, ok := proxy["http-upgrade-opts"].(map[string]any)
- if !ok {
- t.Fatalf("http-upgrade-opts missing: %#v", proxy["http-upgrade-opts"])
+ want := map[string]any{"path": "/hu", "headers": map[string]any{"Host": "example.com"}, "v2ray-http-upgrade": true}
+ if !reflect.DeepEqual(proxy["ws-opts"], want) {
+ t.Fatalf("ws-opts = %#v, want %#v", proxy["ws-opts"], want)
}
- if opts["path"] != "/hu" {
- t.Fatalf("path = %v, want /hu", opts["path"])
+ if _, exists := proxy["http-upgrade-opts"]; exists {
+ t.Fatalf("invalid http-upgrade-opts key: %#v", proxy)
}
- headers, _ := opts["headers"].(map[string]any)
- if headers["Host"] != "example.com" {
- t.Fatalf("headers.Host = %v, want example.com", headers["Host"])
+}
+
+func TestClashHTTPUpgradeForInboundAndExternalLink(t *testing.T) {
+ svc := &SubClashService{SubService: &SubService{}}
+ const id = "11111111-2222-4333-8444-555555555555"
+ stream := svc.streamData(`{"network":"httpupgrade","httpupgradeSettings":{"path":"/upgrade","headers":{"host":"host.example"}},"security":"tls","tlsSettings":{"serverName":"sni.example"}}`)
+ inbound := &model.Inbound{Protocol: model.VMESS, Listen: "203.0.113.1", Port: 443, Remark: "vmess"}
+ for _, tc := range []struct {
+ protocol string
+ proxy map[string]any
+ }{
+ {"vmess", svc.buildProxy(svc.SubService, inbound, model.Client{ID: id}, stream, nil)},
+ {"vless", svc.clashProxyFromExternal("vless://"+id+"@203.0.113.1:443?type=httpupgrade&host=host.example&path=%2Fupgrade&security=tls&sni=sni.example#vless", "vless")},
+ } {
+ t.Run(tc.protocol, func(t *testing.T) {
+ want := map[string]any{"path": "/upgrade", "headers": map[string]any{"Host": "host.example"}, "v2ray-http-upgrade": true}
+ if tc.proxy["type"] != tc.protocol || tc.proxy["network"] != "ws" || tc.proxy["tls"] != true || tc.proxy["servername"] != "sni.example" || !reflect.DeepEqual(tc.proxy["ws-opts"], want) {
+ t.Fatalf("unexpected HTTPUpgrade proxy: %#v", tc.proxy)
+ }
+ })
}
}
diff --git a/internal/sub/mutation_audit_test.go b/internal/sub/mutation_audit_test.go
index 8530c9235..99e77a276 100644
--- a/internal/sub/mutation_audit_test.go
+++ b/internal/sub/mutation_audit_test.go
@@ -478,24 +478,21 @@ func TestEnsureUniqueProxyNames_SuffixSequence(t *testing.T) {
}
}
-// --- clash_service.go:422,447 — empty transport opts must NOT add the *-opts key ---
-
func TestApplyTransport_EmptyOptsOmitted(t *testing.T) {
svc := &SubClashService{}
- // httpupgrade with no path/host → opts empty → no http-upgrade-opts key (clash:422).
- huProxy := map[string]any{}
- if !svc.applyTransport(huProxy, "httpupgrade", map[string]any{"httpupgradeSettings": map[string]any{}}) {
- t.Fatal("httpupgrade must still be buildable")
- }
- if huProxy["network"] != "httpupgrade" {
- t.Fatalf("network = %v, want httpupgrade", huProxy["network"])
- }
- if _, ok := huProxy["http-upgrade-opts"]; ok {
- t.Fatalf("empty opts must not set http-upgrade-opts: %#v", huProxy["http-upgrade-opts"])
+ // HTTPUpgrade still needs the mode flag without a configured Host or path.
+ for _, stream := range []map[string]any{nil, {"httpupgradeSettings": map[string]any{}}} {
+ huProxy := map[string]any{}
+ if !svc.applyTransport(huProxy, "httpupgrade", stream) || huProxy["network"] != "ws" {
+ t.Fatalf("HTTPUpgrade must use ws even without options: %#v", huProxy)
+ }
+ if opts, ok := huProxy["ws-opts"].(map[string]any); !ok || len(opts) != 1 || opts["v2ray-http-upgrade"] != true {
+ t.Fatalf("HTTPUpgrade must always set the mode flag: %#v", huProxy)
+ }
}
- // xhttp with no path/host/mode → opts empty → no xhttp-opts key (clash:447).
+ // xhttp with no path, Host or mode requires no options block.
xhProxy := map[string]any{}
if !svc.applyTransport(xhProxy, "xhttp", map[string]any{"xhttpSettings": map[string]any{}}) {
t.Fatal("xhttp must still be buildable")
diff --git a/internal/sub/sub.go b/internal/sub/sub.go
index a2d1f4066..c75cd9840 100644
--- a/internal/sub/sub.go
+++ b/internal/sub/sub.go
@@ -55,6 +55,7 @@ func (s *Server) initRouter() (*gin.Engine, error) {
gin.SetMode(gin.ReleaseMode)
engine := gin.Default()
+ engine.Use(middleware.DatabaseWork(service.BeginDatabaseWork))
subDomain, err := s.settingService.GetSubDomain()
if err != nil {
diff --git a/internal/util/sys/cpu_times.go b/internal/util/sys/cpu_times.go
index 18194397a..39200f565 100644
--- a/internal/util/sys/cpu_times.go
+++ b/internal/util/sys/cpu_times.go
@@ -1,6 +1,25 @@
package sys
-import "github.com/shirou/gopsutil/v4/cpu"
+import (
+ "errors"
+
+ "github.com/shirou/gopsutil/v4/cpu"
+)
+
+// CPUSpeedMHz reports 0 when the platform exposes no clock speed.
+func CPUSpeedMHz() (float64, error) {
+ infos, err := cpu.Info()
+ if err != nil {
+ return 0, err
+ }
+ if len(infos) == 0 {
+ return 0, errors.New("could not find cpu info")
+ }
+ if infos[0].Mhz > 0 {
+ return infos[0].Mhz, nil
+ }
+ return platformCPUSpeedMHz()
+}
// CPUBusyPercent is the busy share of CPU time between two cumulative samples,
// counting iowait as busy; ok is false when no time elapsed or the counters reset.
diff --git a/internal/util/sys/sys_darwin.go b/internal/util/sys/sys_darwin.go
index 218228213..501b8c7e6 100644
--- a/internal/util/sys/sys_darwin.go
+++ b/internal/util/sys/sys_darwin.go
@@ -2,11 +2,40 @@
package sys
+/*
+#cgo LDFLAGS: -framework IOKit -framework CoreFoundation
+#include
+#include
+
+static CFDataRef copyPCoreVoltageStates(void) {
+ io_iterator_t devices;
+ if (IOServiceGetMatchingServices(MACH_PORT_NULL, IOServiceMatching("AppleARMIODevice"), &devices) != KERN_SUCCESS) {
+ return NULL;
+ }
+ CFDataRef states = NULL;
+ io_object_t device;
+ while (states == NULL && (device = IOIteratorNext(devices)) != 0) {
+ CFTypeRef value = IORegistryEntryCreateCFProperty(device, CFSTR("voltage-states5-sram"), kCFAllocatorDefault, 0);
+ if (value != NULL && CFGetTypeID(value) == CFDataGetTypeID()) {
+ states = value;
+ } else if (value != NULL) {
+ CFRelease(value);
+ }
+ IOObjectRelease(device);
+ }
+ IOObjectRelease(devices);
+ return states;
+}
+*/
+import "C"
+
import (
"encoding/binary"
+ "errors"
"fmt"
"sync"
"syscall"
+ "unsafe"
"github.com/shirou/gopsutil/v4/net"
"golang.org/x/sys/unix"
@@ -89,3 +118,33 @@ func CPUPercentRaw() (float64, error) {
}
return pct, nil
}
+
+// gopsutil reads the table only from the "pmgr" node; M6 moved it to
+// "pmgr-child", so every AppleARMIODevice is searched for it here.
+func platformCPUSpeedMHz() (float64, error) {
+ states := C.copyPCoreVoltageStates()
+ if states == 0 {
+ return 0, errors.New("no AppleARMIODevice carries voltage-states5-sram")
+ }
+ defer C.CFRelease(C.CFTypeRef(states))
+ return appleSiliconMaxMHz(C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(states)), C.int(C.CFDataGetLength(states))))
+}
+
+// No core clocks below 100 MHz, so a smaller frequency word is in kHz.
+const appleSiliconKHzCeiling = 100_000_000
+
+// appleSiliconMaxMHz reads a voltage-states table of little-endian
+// (frequency, millivolt) pairs: Hz through M3, kHz from M4 on.
+func appleSiliconMaxMHz(states []byte) (float64, error) {
+ var fastest uint64
+ for pair := 0; pair+8 <= len(states); pair += 8 {
+ fastest = max(fastest, uint64(binary.LittleEndian.Uint32(states[pair:])))
+ }
+ if fastest == 0 {
+ return 0, errors.New("voltage-states table holds no frequency")
+ }
+ if fastest < appleSiliconKHzCeiling {
+ fastest *= 1000
+ }
+ return float64(fastest) / 1_000_000, nil
+}
diff --git a/internal/util/sys/sys_linux.go b/internal/util/sys/sys_linux.go
index 4cca0fe57..e17683947 100644
--- a/internal/util/sys/sys_linux.go
+++ b/internal/util/sys/sys_linux.go
@@ -16,6 +16,8 @@ import (
var SIGUSR1 = syscall.SIGUSR1
+func platformCPUSpeedMHz() (float64, error) { return 0, nil }
+
// countConnections returns the number of entries in a /proc/net/{tcp,udp}[6]
// file. Returns 0 if the file is absent (e.g. /proc/net/tcp6 when IPv6 is
// disabled) and excludes the column header line.
diff --git a/internal/util/sys/sys_windows.go b/internal/util/sys/sys_windows.go
index a6a39ef2f..b81e68cd9 100644
--- a/internal/util/sys/sys_windows.go
+++ b/internal/util/sys/sys_windows.go
@@ -14,6 +14,8 @@ import (
var SIGUSR1 = syscall.Signal(0)
+func platformCPUSpeedMHz() (float64, error) { return 0, nil }
+
// GetConnectionCount returns the number of active connections for the specified protocol ("tcp" or "udp").
func GetConnectionCount(proto string) (int, error) {
if proto != "tcp" && proto != "udp" {
diff --git a/internal/web/controller/api.go b/internal/web/controller/api.go
index 879b6e930..984db6b05 100644
--- a/internal/web/controller/api.go
+++ b/internal/web/controller/api.go
@@ -38,6 +38,10 @@ func NewAPIController(g *gin.RouterGroup, router http.Handler) *APIController {
return a
}
+func (a *APIController) LastStatus() *service.Status {
+ return a.serverController.serverService.LastStatus()
+}
+
// requireMCPEnabled hides the MCP endpoint until the operator turns it on: it hands
// a token's whole API reach to whatever agent holds that token.
func (a *APIController) requireMCPEnabled(c *gin.Context) {
@@ -114,6 +118,7 @@ var monitorScopeAllow = map[string]struct{}{
var nodeSyncScopeAllow = map[string]map[string]struct{}{
"/server/status": {http.MethodGet: {}},
"/inbounds/list": {http.MethodGet: {}},
+ "/inbounds/catalog": {http.MethodGet: {}},
"/inbounds/trafficSnapshot": {http.MethodGet: {}},
"/inbounds/add": {http.MethodPost: {}},
"/inbounds/del/:id": {http.MethodPost: {}},
@@ -236,6 +241,7 @@ func (a *APIController) initRouter(g *gin.RouterGroup, router http.Handler) {
// Nodes API — multi-panel management
nodes := api.Group("/nodes")
a.nodeController = NewNodeController(nodes)
+ a.nodeController.localStatus = a.LastStatus
// Hosts API — per-inbound override endpoints for subscription links
hosts := api.Group("/hosts")
diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go
index 1287fa777..d89d48290 100644
--- a/internal/web/controller/client.go
+++ b/internal/web/controller/client.go
@@ -54,7 +54,10 @@ func NewClientController(g *gin.RouterGroup) *ClientController {
func (a *ClientController) initRouter(g *gin.RouterGroup) {
g.GET("/list", a.list)
g.GET("/list/paged", a.listPaged)
+ g.GET("/userSuggestions", a.userSuggestions)
g.GET("/attachCandidates", a.attachCandidates)
+ g.GET("/detachCandidates", a.detachCandidates)
+ g.POST("/detachCandidates/freeze", a.freezeDetachCandidates)
g.GET("/get", a.get)
g.GET("/get/:email", a.get)
g.GET("/get/subId/:subId", a.getBySubId)
@@ -92,6 +95,7 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) {
g.POST("/bulkAttach", a.bulkAttach)
g.GET("/bulkAttach/:id", a.attachStatus)
g.POST("/bulkDetach", a.bulkDetach)
+ g.GET("/bulkDetach/:id", a.detachStatus)
g.POST("/bulkResetTraffic", a.bulkResetTraffic)
g.POST("/resetTraffic/:email", a.resetTrafficByEmail)
g.POST("/updateTraffic/:email", a.updateTrafficByEmail)
@@ -155,6 +159,11 @@ func (a *ClientController) attachCandidates(c *gin.Context) {
jsonObj(c, result, nil)
}
+func (a *ClientController) userSuggestions(c *gin.Context) {
+ result, err := a.clientService.ListUserSuggestions(c.Request.Context(), c.Query("search"))
+ jsonObj(c, result, err)
+}
+
func (a *ClientController) buildClientPayload(rec *model.ClientRecord) (gin.H, error) {
inboundIds, err := a.clientService.GetInboundIdsForRecord(rec.Id)
if err != nil {
@@ -269,7 +278,7 @@ func (a *ClientController) create(c *gin.Context) {
return
}
clientSvc := a.clientService.TrackNodeApplies()
- needRestart, err := clientSvc.Create(&a.inboundService, &payload)
+ needRestart, err := clientSvc.CreateWithContext(c.Request.Context(), &a.inboundService, &payload)
// Flagged before the error check: a partly-applied create leaves clients
// committed on the inbounds that succeeded, and those still need the restart.
if needRestart {
@@ -403,6 +412,8 @@ func (a *ClientController) resetAllTraffics(c *gin.Context) {
}
type bulkAdjustRequest struct {
+ Group string `json:"group"`
+ ScopeToken string `json:"scopeToken"`
Emails []string `json:"emails"`
AddDays int `json:"addDays"`
AddBytes int64 `json:"addBytes"`
@@ -419,22 +430,36 @@ func (a *ClientController) bulkAdjust(c *gin.Context) {
return
}
clientSvc := a.clientService.TrackNodeApplies()
+ scope, err := resolveGroupBulkScope(c, req.Emails, req.Group, req.ScopeToken)
+ if err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
var result service.BulkAdjustResult
var needRestart bool
- var err error
if req.ExternalLinks != nil {
if req.AddDays != 0 || req.AddBytes != 0 || req.Flow != "" || req.LimitHwid != nil || req.AdTag != "" {
jsonMsg(c, "append external links separately from other adjustments", errors.New("externalLinks cannot be combined with other adjustments"))
return
}
- result, err = a.clientService.BulkAppendExternalLinks(req.Emails, req.ExternalLinks)
- } else {
+ if scope == nil {
+ result, err = clientSvc.BulkAppendExternalLinks(req.Emails, req.ExternalLinks)
+ } else {
+ result, err = clientSvc.BulkAppendGroupExternalLinks(scope, req.ExternalLinks)
+ }
+ } else if scope == nil {
result, needRestart, err = clientSvc.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag)
+ } else {
+ result, needRestart, err = clientSvc.BulkAdjustGroup(&a.inboundService, scope, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag)
}
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
+ if req.Group != "" && len(result.Skipped) > 0 {
+ result.SkippedCount = len(result.Skipped)
+ result.Skipped = result.Skipped[:min(len(result.Skipped), 20)]
+ }
if report := clientSvc.NodeApplyResponse(); report != nil {
result.ClientNodeApplyResponse = *report
}
@@ -446,10 +471,22 @@ func (a *ClientController) bulkAdjust(c *gin.Context) {
}
type bulkDeleteRequest struct {
+ Group string `json:"group"`
+ ScopeToken string `json:"scopeToken"`
Emails []string `json:"emails"`
KeepTraffic bool `json:"keepTraffic"`
}
+func resolveGroupBulkScope(c *gin.Context, emails []string, group, scopeToken string) (*service.GroupBulkScope, error) {
+ if group == "" && scopeToken == "" {
+ return nil, nil
+ }
+ if len(emails) != 0 || strings.TrimSpace(group) == "" {
+ return nil, errors.New("use either emails or a group scope")
+ }
+ return service.ResolveGroupBulkScope(c.Request.Context(), group, scopeToken)
+}
+
type bulkAttachRequest struct {
Emails []string `json:"emails"`
InboundIds []int `json:"inboundIds"`
@@ -487,8 +524,10 @@ func (a *ClientController) bulkAttach(c *gin.Context) {
}
type bulkDetachRequest struct {
- Emails []string `json:"emails"`
- InboundIds []int `json:"inboundIds"`
+ Emails []string `json:"emails"`
+ InboundIds []int `json:"inboundIds"`
+ Selection *service.DetachSelection `json:"selection,omitempty"`
+ RequestID string `json:"requestId,omitempty"`
}
func (a *ClientController) bulkDetach(c *gin.Context) {
@@ -497,6 +536,10 @@ func (a *ClientController) bulkDetach(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
+ if req.Selection != nil {
+ a.beginBulkDetach(c, req)
+ return
+ }
clientSvc := a.clientService.TrackNodeApplies()
result, needRestart, err := clientSvc.BulkDetach(&a.inboundService, req.Emails, req.InboundIds)
if err != nil {
@@ -520,11 +563,26 @@ func (a *ClientController) bulkDelete(c *gin.Context) {
return
}
clientSvc := a.clientService.TrackNodeApplies()
- result, needRestart, err := clientSvc.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic)
+ scope, err := resolveGroupBulkScope(c, req.Emails, req.Group, req.ScopeToken)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
+ var result service.BulkDeleteResult
+ var needRestart bool
+ if scope == nil {
+ result, needRestart, err = clientSvc.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic)
+ } else {
+ result, needRestart, err = clientSvc.BulkDeleteGroup(&a.inboundService, scope, req.KeepTraffic)
+ }
+ if err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
+ if req.Group != "" && len(result.Skipped) > 0 {
+ result.SkippedCount = len(result.Skipped)
+ result.Skipped = result.Skipped[:min(len(result.Skipped), 20)]
+ }
if report := clientSvc.NodeApplyResponse(); report != nil {
result.ClientNodeApplyResponse = *report
}
diff --git a/internal/web/controller/client_detach_jobs.go b/internal/web/controller/client_detach_jobs.go
new file mode 100644
index 000000000..1b56b70a4
--- /dev/null
+++ b/internal/web/controller/client_detach_jobs.go
@@ -0,0 +1,253 @@
+package controller
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "sync"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/util/common"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
+)
+
+const detachHistoryTTL = 15 * time.Minute
+
+type savedDetachScope struct {
+ scope *service.DetachScope
+ issued time.Time
+}
+
+type detachScopeStore struct {
+ mu sync.Mutex
+ entries map[string]savedDetachScope
+}
+
+var (
+ detachScopes detachScopeStore
+ freezeDetachMu sync.Mutex
+)
+
+func (s *detachScopeStore) save(scope *service.DetachScope) string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.entries == nil {
+ s.entries = make(map[string]savedDetachScope)
+ }
+ now := time.Now()
+ var oldest string
+ for token, entry := range s.entries {
+ if now.Sub(entry.issued) >= detachHistoryTTL {
+ delete(s.entries, token)
+ } else if oldest == "" || entry.issued.Before(s.entries[oldest].issued) {
+ oldest = token
+ }
+ }
+ if len(s.entries) >= 8 {
+ delete(s.entries, oldest)
+ }
+ token := uuid.NewString()
+ s.entries[token] = savedDetachScope{scope: scope, issued: now}
+ return token
+}
+
+func (s *detachScopeStore) get(token string) *service.DetachScope {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ entry, ok := s.entries[token]
+ if !ok || time.Since(entry.issued) >= detachHistoryTTL {
+ delete(s.entries, token)
+ return nil
+ }
+ return entry.scope
+}
+
+type DetachJobStatus struct {
+ Running bool `json:"running"`
+ Processed int `json:"processed"`
+ Total int `json:"total"`
+ Result *service.DetachSelectionResult `json:"result,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+type detachJob struct {
+ status DetachJobStatus
+ request [sha256.Size]byte
+ generation uint64
+ ended time.Time
+}
+
+type detachJobStore struct {
+ mu sync.Mutex
+ running bool
+ entries map[string]detachJob
+}
+
+var detachJobs detachJobStore
+
+func (s *detachJobStore) start(id string, inboundID int, selection service.DetachSelection, run func(*service.DetachPlan, func(int)) (*service.DetachSelectionResult, error)) error {
+ parsed, err := uuid.Parse(id)
+ if err != nil || parsed == uuid.Nil || id != parsed.String() ||
+ len(selection.ClientIDs) > service.DetachSelectionLimit || len(selection.ExcludedClientIDs) > service.DetachSelectionLimit {
+ return errors.New("invalid client detachment request")
+ }
+ encoded, err := json.Marshal(struct {
+ InboundID int
+ Selection service.DetachSelection
+ }{inboundID, selection})
+ if err != nil {
+ return err
+ }
+ fingerprint := sha256.Sum256(encoded)
+ generation := database.ConnectionGeneration()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.entries == nil {
+ s.entries = make(map[string]detachJob)
+ }
+ var oldest string
+ for key, entry := range s.entries {
+ if entry.status.Running {
+ continue
+ }
+ if time.Since(entry.ended) >= detachHistoryTTL || entry.generation != generation {
+ delete(s.entries, key)
+ } else if oldest == "" || entry.ended.Before(s.entries[oldest].ended) {
+ oldest = key
+ }
+ }
+ if entry, ok := s.entries[id]; ok {
+ if entry.request != fingerprint || entry.generation != generation {
+ return errors.New("detachment request ID is already in use")
+ }
+ return nil
+ }
+ if s.running {
+ return errors.New("another client detachment is running")
+ }
+ plan, err := service.NewDetachPlan(inboundID, selection, detachScopes.get(selection.ScopeToken))
+ if err != nil {
+ return err
+ }
+ if len(s.entries) >= 32 {
+ delete(s.entries, oldest)
+ }
+ s.entries[id] = detachJob{request: fingerprint, generation: generation, status: DetachJobStatus{
+ Running: true, Total: plan.Total(),
+ }}
+ s.running = true
+ common.GoRecover("client-detachment", func() {
+ var result *service.DetachSelectionResult
+ failure := "client detachment interrupted"
+ defer func() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ entry := s.entries[id]
+ entry.ended = time.Now()
+ entry.status.Running, entry.status.Result, entry.status.Error = false, result, failure
+ s.entries[id] = entry
+ s.running = false
+ }()
+ var err error
+ result, err = run(plan, func(n int) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ entry := s.entries[id]
+ entry.status.Processed = n
+ s.entries[id] = entry
+ })
+ if err != nil {
+ failure = err.Error()
+ } else {
+ failure = ""
+ }
+ })
+ return nil
+}
+
+func (s *detachJobStore) get(id string) (DetachJobStatus, bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ entry, ok := s.entries[id]
+ if !ok || entry.generation != database.ConnectionGeneration() ||
+ (!entry.status.Running && time.Since(entry.ended) >= detachHistoryTTL) {
+ return DetachJobStatus{}, false
+ }
+ return entry.status, true
+}
+
+func (a *ClientController) detachCandidates(c *gin.Context) {
+ c.Header("Cache-Control", "no-store")
+ var params service.DetachCandidateParams
+ if err := c.ShouldBindQuery(¶ms); err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
+ var scope *service.DetachScope
+ if token := c.Query("scopeToken"); token != "" {
+ scope = detachScopes.get(token)
+ if scope == nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client detachment selection expired"))
+ return
+ }
+ }
+ page, err := a.clientService.ListDetachCandidates(c.Request.Context(), params, scope)
+ jsonObj(c, page, err)
+}
+
+func (a *ClientController) freezeDetachCandidates(c *gin.Context) {
+ var req struct {
+ InboundID int `json:"inboundId"`
+ }
+ if err := c.ShouldBindJSON(&req); err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
+ if !freezeDetachMu.TryLock() {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("another detachment selection is being prepared"))
+ return
+ }
+ defer freezeDetachMu.Unlock()
+ scope, total, err := a.clientService.FreezeDetachScope(c.Request.Context(), req.InboundID)
+ if err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
+ jsonObj(c, service.DetachScopeSummary{ScopeToken: detachScopes.save(scope), Total: total}, nil)
+}
+
+func (a *ClientController) beginBulkDetach(c *gin.Context, req bulkDetachRequest) {
+ if len(req.Emails) != 0 || len(req.InboundIds) != 1 {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("a scoped detachment requires one inbound and no email list"))
+ return
+ }
+ err := detachJobs.start(req.RequestID, req.InboundIds[0], *req.Selection, func(plan *service.DetachPlan, progress func(int)) (*service.DetachSelectionResult, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+ result, err := a.clientService.ApplyDetachPlan(ctx, plan, progress)
+ if err == nil || (result != nil && result.Detached > 0) {
+ notifyClientsChanged()
+ }
+ return result, err
+ })
+ if err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
+ jsonObj(c, gin.H{"jobId": req.RequestID}, nil)
+}
+
+func (a *ClientController) detachStatus(c *gin.Context) {
+ c.Header("Cache-Control", "no-store")
+ status, ok := detachJobs.get(c.Param("id"))
+ if !ok {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client detachment status unavailable"))
+ return
+ }
+ jsonObj(c, status, nil)
+}
diff --git a/internal/web/controller/client_detach_jobs_test.go b/internal/web/controller/client_detach_jobs_test.go
new file mode 100644
index 000000000..3de3e5547
--- /dev/null
+++ b/internal/web/controller/client_detach_jobs_test.go
@@ -0,0 +1,140 @@
+package controller
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
+)
+
+func TestScopedDetachAPIAndIdempotency(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("scoped_detach_api")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ engine, auth := newAPIAuthTestEngine(t)
+ clients := engine.Group("/panel/api/clients", auth.checkAPIAuth, auth.enforceTokenScope)
+ clients.Use(func(c *gin.Context) {
+ c.Set("I18n", func(_ locale.I18nType, key string, _ ...string) string { return key })
+ c.Next()
+ })
+ controller := &ClientController{}
+ clients.GET("/detachCandidates", controller.detachCandidates)
+ clients.POST("/detachCandidates/freeze", controller.freezeDetachCandidates)
+ clients.POST("/bulkDetach", controller.bulkDetach)
+ clients.GET("/bulkDetach/:id", controller.detachStatus)
+ db := database.GetDB()
+ for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeNodeSync} {
+ if err := db.Create(&model.ApiToken{Name: scope, Token: crypto.HashTokenSHA256(scope), Scope: scope, Enabled: true}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ inbound := model.Inbound{Tag: "detach-api", Protocol: model.VLESS, Settings: `{"clients":[{"email":"detach-api@test","enable":false}]}`}
+ record := model.ClientRecord{Email: "detach-api@test"}
+ if err := db.Create(&inbound).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Create(&record).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Create(&model.ClientInbound{ClientId: record.Id, InboundId: inbound.Id}).Error; err != nil {
+ t.Fatal(err)
+ }
+ request := func(method, path, scope string, body any) *httptest.ResponseRecorder {
+ t.Helper()
+ raw, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(method, "/panel/api/clients"+path, bytes.NewReader(raw))
+ req.Header.Set("Authorization", "Bearer "+scope)
+ req.Header.Set("Content-Type", "application/json")
+ out := httptest.NewRecorder()
+ engine.ServeHTTP(out, req)
+ return out
+ }
+ type envelope struct {
+ Success bool `json:"success"`
+ Obj json.RawMessage `json:"obj"`
+ Msg string `json:"msg"`
+ }
+ admin := model.ApiScopeAdmin
+ candidatePath := fmt.Sprintf("/detachCandidates?inboundId=%d", inbound.Id)
+ if response := request(http.MethodGet, candidatePath, model.ApiScopeNodeSync, nil); response.Code != http.StatusForbidden {
+ t.Fatalf("node-sync got %d: %s", response.Code, response.Body)
+ }
+ read := func(out *httptest.ResponseRecorder) envelope {
+ t.Helper()
+ var res envelope
+ if err := json.Unmarshal(out.Body.Bytes(), &res); err != nil {
+ t.Fatalf("read response: %v (%s)", err, out.Body)
+ }
+ return res
+ }
+ page := read(request(http.MethodGet, candidatePath, admin, nil))
+ var candidates service.DetachCandidatePage
+ if err := json.Unmarshal(page.Obj, &candidates); err != nil || !page.Success || len(candidates.Items) != 1 ||
+ candidates.Items[0].ID != record.Id || candidates.Attached != 1 {
+ t.Fatalf("candidate response = %+v (%s), error %v", candidates, page.Msg, err)
+ }
+ freeze := read(request(http.MethodPost, "/detachCandidates/freeze", admin, gin.H{"inboundId": inbound.Id}))
+ var scoped service.DetachScopeSummary
+ if err := json.Unmarshal(freeze.Obj, &scoped); err != nil || !freeze.Success || scoped.Total != 1 || scoped.ScopeToken == "" {
+ t.Fatalf("freeze response = %+v (%s), error %v", scoped, freeze.Msg, err)
+ }
+ jobID := uuid.NewString()
+ body := bulkDetachRequest{
+ InboundIds: []int{inbound.Id},
+ RequestID: jobID,
+ Selection: &service.DetachSelection{Mode: "allMatching", ScopeToken: scoped.ScopeToken},
+ }
+ start := func(req bulkDetachRequest) envelope {
+ return read(request(http.MethodPost, "/bulkDetach", admin, req))
+ }
+ if res := start(body); !res.Success || !bytes.Contains(res.Obj, []byte(jobID)) {
+ t.Fatalf("job submission: %+v", res)
+ }
+ if res := start(body); !res.Success || !bytes.Contains(res.Obj, []byte(jobID)) {
+ t.Fatalf("duplicate submission: %+v", res)
+ }
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ res := read(request(http.MethodGet, "/bulkDetach/"+jobID, admin, nil))
+ var status DetachJobStatus
+ if err := json.Unmarshal(res.Obj, &status); err != nil || !res.Success {
+ t.Fatalf("job status: %+v, error %v", res, err)
+ }
+ if !status.Running {
+ if status.Error != "" || status.Processed != 1 || status.Result == nil || status.Result.Detached != 1 {
+ t.Fatalf("unexpected terminal status %+v", status)
+ }
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("detachment job did not finish")
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if res := start(body); !res.Success || !bytes.Contains(res.Obj, []byte(jobID)) {
+ t.Fatalf("identical retry did not return the same job: %+v", res)
+ }
+ changed := body
+ changed.Selection = &service.DetachSelection{Mode: "explicit", ClientIDs: []int{record.Id}}
+ if res := start(changed); res.Success {
+ t.Fatal("changed payload reused a request ID")
+ }
+}
diff --git a/internal/web/controller/client_user_suggestions_test.go b/internal/web/controller/client_user_suggestions_test.go
new file mode 100644
index 000000000..ce017a829
--- /dev/null
+++ b/internal/web/controller/client_user_suggestions_test.go
@@ -0,0 +1,97 @@
+package controller
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "slices"
+ "testing"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
+)
+
+func TestClientUserSuggestionsHTTP(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("routing_user_suggestions")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ router, api := newAPIAuthTestEngine(t)
+ NewClientController(router.Group("/base/panel/api/clients", api.checkAPIAuth, api.enforceTokenScope))
+ db := database.GetDB()
+ for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeMonitor, model.ApiScopeNodeSync, model.ApiScopeNodeAdmin} {
+ token := model.ApiToken{Name: scope, Token: crypto.HashTokenSHA256(scope), Enabled: true, Scope: scope}
+ if err := db.Create(&token).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ seeds := []model.ClientRecord{
+ {Email: "literal_%@test", Password: "private", Group: "ignored"},
+ {Email: "literal_ab@test", Comment: "only-in-a-comment"},
+ }
+ if err := db.Create(&seeds).Error; err != nil {
+ t.Fatal(err)
+ }
+ clients := make([]model.ClientRecord, 50000)
+ for i := range clients {
+ clients[i] = model.ClientRecord{Email: fmt.Sprintf("fixture-%05d@test", i)}
+ }
+ if err := db.CreateInBatches(&clients, 100).Error; err != nil {
+ t.Fatal(err)
+ }
+ request := func(scope, search string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodGet, "/base/panel/api/clients/userSuggestions?search="+url.QueryEscape(search)+"&pageSize=50000", nil)
+ req.Header.Set("X-Requested-With", "XMLHttpRequest")
+ if scope != "" {
+ req.Header.Set("Authorization", "Bearer "+scope)
+ }
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ return w
+ }
+ for _, scope := range []string{"", model.ApiScopeMonitor, model.ApiScopeNodeSync, model.ApiScopeNodeAdmin} {
+ want := http.StatusForbidden
+ if scope == "" {
+ want = http.StatusUnauthorized
+ }
+ if got := request(scope, "fixture"); got.Code != want {
+ t.Errorf("scope %q: status = %d, want %d", scope, got.Code, want)
+ }
+ }
+ for _, tt := range []struct {
+ search string
+ count int
+ first string
+ }{
+ {"", 50, "fixture-00000@test"},
+ {"FIXTURE-", 50, "fixture-00000@test"},
+ {"49999@", 1, "fixture-49999@test"},
+ {" LITERAL_% ", 1, "literal_%@test"},
+ {"only-in-a-comment", 0, ""},
+ } {
+ t.Run(tt.search, func(t *testing.T) {
+ w := request(model.ApiScopeAdmin, tt.search)
+ var body struct {
+ Success bool `json:"success"`
+ Msg string `json:"msg"`
+ Obj struct {
+ Emails []string `json:"emails"`
+ } `json:"obj"`
+ }
+ decoder := json.NewDecoder(w.Body)
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&body); w.Code != http.StatusOK || err != nil || !body.Success {
+ t.Fatalf("status = %d, response = %+v, error = %v", w.Code, body, err)
+ }
+ emails := body.Obj.Emails
+ if emails == nil || len(emails) != tt.count || !slices.IsSorted(emails) || (tt.count > 0 && emails[0] != tt.first) {
+ t.Fatalf("search %q: emails = %v, want %d starting with %q", tt.search, emails, tt.count, tt.first)
+ }
+ })
+ }
+}
diff --git a/internal/web/controller/group.go b/internal/web/controller/group.go
index 3abac34b5..4287d474b 100644
--- a/internal/web/controller/group.go
+++ b/internal/web/controller/group.go
@@ -1,8 +1,14 @@
package controller
import (
+ "bufio"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
"strings"
+ "github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
@@ -10,8 +16,9 @@ import (
)
type GroupController struct {
- clientService service.ClientService
- xrayService service.XrayService
+ clientService service.ClientService
+ xrayService service.XrayService
+ settingService service.SettingService
}
func NewGroupController(g *gin.RouterGroup) *GroupController {
@@ -22,6 +29,8 @@ func NewGroupController(g *gin.RouterGroup) *GroupController {
func (a *GroupController) initRouter(g *gin.RouterGroup) {
g.GET("/groups", a.list)
+ g.GET("/groups/clientPage", a.clientPage)
+ g.GET("/groups/subLinks/export", a.exportSubLinks)
g.GET("/groups/:name/emails", a.emails)
g.POST("/groups/create", a.create)
g.POST("/groups/rename", a.rename)
@@ -158,8 +167,10 @@ func (a *GroupController) resetTraffic(c *gin.Context) {
}
type bulkAddToGroupRequest struct {
- Emails []string `json:"emails"`
- Group string `json:"group"`
+ Emails []string `json:"emails"`
+ Group string `json:"group"`
+ InboundID *int `json:"inboundId"`
+ Selection *service.GroupClientSelection `json:"selection"`
}
func (a *GroupController) bulkAdd(c *gin.Context) {
@@ -172,7 +183,21 @@ func (a *GroupController) bulkAdd(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("group name is required"))
return
}
- affected, err := a.clientService.AddToGroup(req.Emails, req.Group)
+ if (req.InboundID != nil && (*req.InboundID <= 0 || req.Selection != nil || len(req.Emails) != 0)) ||
+ (req.Selection != nil && len(req.Emails) != 0) {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope"))
+ return
+ }
+ var affected int
+ var err error
+ switch {
+ case req.InboundID != nil:
+ affected, err = a.clientService.AddInboundToGroup(c.Request.Context(), *req.InboundID, req.Group)
+ case req.Selection != nil:
+ affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "add", *req.Selection)
+ default:
+ affected, err = a.clientService.AddToGroup(req.Emails, req.Group)
+ }
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
@@ -182,7 +207,9 @@ func (a *GroupController) bulkAdd(c *gin.Context) {
}
type bulkRemoveFromGroupRequest struct {
- Emails []string `json:"emails"`
+ Emails []string `json:"emails"`
+ Group string `json:"group"`
+ Selection *service.GroupClientSelection `json:"selection"`
}
func (a *GroupController) bulkRemove(c *gin.Context) {
@@ -191,12 +218,113 @@ func (a *GroupController) bulkRemove(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
- affected, err := a.clientService.RemoveFromGroup(req.Emails)
+ if (req.Selection != nil && len(req.Emails) != 0) || (req.Selection == nil && req.Group != "") {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope"))
+ return
+ }
+ var affected int
+ var err error
+ if req.Selection != nil {
+ affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "remove", *req.Selection)
+ } else {
+ affected, err = a.clientService.RemoveFromGroup(req.Emails)
+ }
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"affected": affected}, nil)
- a.xrayService.SetToNeedRestart()
- notifyClientsChanged()
+ if affected > 0 {
+ a.xrayService.SetToNeedRestart()
+ notifyClientsChanged()
+ }
+}
+
+func (a *GroupController) clientPage(c *gin.Context) {
+ var params service.GroupClientPageParams
+ if err := c.ShouldBindQuery(¶ms); err != nil {
+ jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+ return
+ }
+ page, err := a.clientService.ListGroupClients(c.Request.Context(), params)
+ jsonObj(c, page, err)
+}
+
+func (a *GroupController) exportSubLinks(c *gin.Context) {
+ links, err := a.settingService.GetPanelSubscriptionLinks(c.Request.Host)
+ if err != nil {
+ c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
+ return
+ }
+ group := strings.TrimSpace(c.Query("group"))
+ if !links.Enable || links.URI == "" || group == "" {
+ c.String(http.StatusBadRequest, "group and enabled subscriptions are required")
+ return
+ }
+
+ serveGroupSubscriptionExport(c, links, func(visit func(email, subID string) error) error {
+ return a.clientService.WalkGroupSubscriptionClients(c.Request.Context(), group, visit)
+ })
+}
+
+func serveGroupSubscriptionExport(c *gin.Context, links service.PanelSubscriptionLinks, walk func(func(email, subID string) error) error) {
+ file, err := os.CreateTemp("", "x-ui-group-links-*.txt")
+ if err != nil {
+ groupSubscriptionExportFailed(c, err)
+ return
+ }
+ defer func() {
+ _ = file.Close()
+ _ = os.Remove(file.Name())
+ }()
+
+ // Stage the output so a mid-query failure cannot publish a partial download.
+ if err := writeGroupSubscriptionExport(file, links, walk); err != nil {
+ groupSubscriptionExportFailed(c, err)
+ return
+ }
+ size, err := file.Seek(0, io.SeekCurrent)
+ if err == nil {
+ _, err = file.Seek(0, io.SeekStart)
+ }
+ if err != nil {
+ groupSubscriptionExportFailed(c, err)
+ return
+ }
+ c.DataFromReader(http.StatusOK, size, "text/plain; charset=utf-8", file, map[string]string{
+ "Content-Disposition": `attachment; filename="sub-links.txt"`,
+ "Cache-Control": "no-store",
+ })
+}
+
+func writeGroupSubscriptionExport(dst io.Writer, links service.PanelSubscriptionLinks, walk func(func(email, subID string) error) error) error {
+ out := bufio.NewWriter(dst)
+ first := true
+ err := walk(func(email, subID string) error {
+ if !first {
+ if err := out.WriteByte('\n'); err != nil {
+ return err
+ }
+ }
+ first = false
+ if _, err := fmt.Fprintf(out, "%s\t%s%s", email, links.URI, subID); err != nil {
+ return err
+ }
+ if links.JSONEnable && links.JSONURI != "" {
+ _, err := fmt.Fprintf(out, "\t%s%s", links.JSONURI, subID)
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ return out.Flush()
+}
+
+func groupSubscriptionExportFailed(c *gin.Context, err error) {
+ if c.Request.Context().Err() == nil {
+ logger.Warning("group subscription export failed:", err)
+ c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
+ }
}
diff --git a/internal/web/controller/group_client_pages_test.go b/internal/web/controller/group_client_pages_test.go
new file mode 100644
index 000000000..11b39614a
--- /dev/null
+++ b/internal/web/controller/group_client_pages_test.go
@@ -0,0 +1,325 @@
+package controller
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
+ "github.com/mhsanaei/3x-ui/v3/internal/xray"
+)
+
+const groupAPI = "/panel/api/clients"
+
+func groupTestRouter(t *testing.T) *gin.Engine {
+ t.Helper()
+ cleanup, err := testpg.IsolatePackage("group_client_http")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
+ router := gin.New()
+ routes := router.Group(groupAPI)
+ NewGroupController(routes)
+ NewClientController(routes)
+ return router
+}
+
+func groupAPIRequest(router *gin.Engine, method, route, body string) *httptest.ResponseRecorder {
+ out := httptest.NewRecorder()
+ req := httptest.NewRequest(method, groupAPI+route, strings.NewReader(body))
+ if method == http.MethodPost {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ router.ServeHTTP(out, req)
+ return out
+}
+
+func groupPage(t *testing.T, router *gin.Engine, query string) service.GroupClientPage {
+ t.Helper()
+ out := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?"+query, "")
+ var result struct {
+ Success bool
+ Obj service.GroupClientPage
+ }
+ if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success {
+ t.Fatalf("group page %q returned %s (%v)", query, out.Body, err)
+ }
+ return result.Obj
+}
+
+func groupMutation(t *testing.T, router *gin.Engine, route string, body any, success bool, field string, want int) {
+ t.Helper()
+ payload, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := groupAPIRequest(router, http.MethodPost, route, string(payload))
+ var result struct {
+ Success bool
+ Obj map[string]json.RawMessage
+ }
+ if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || result.Success != success {
+ t.Fatalf("%s returned %s (wanted success=%t): %v", route, out.Body, success, err)
+ }
+ if success {
+ var got int
+ if err := json.Unmarshal(result.Obj[field], &got); err != nil || got != want {
+ t.Fatalf("%s returned %s, want %s=%d", route, out.Body, field, want)
+ }
+ }
+}
+
+func createTestGroupClients(t *testing.T, size, memberCount int) []model.ClientRecord {
+ t.Helper()
+ db := database.GetDB()
+ if err := db.Create(&model.ClientGroup{Name: "staff"}).Error; err != nil {
+ t.Fatal(err)
+ }
+ rows := make([]model.ClientRecord, size)
+ for i := range rows {
+ rows[i] = model.ClientRecord{Email: fmt.Sprintf("client-%06d", i), SubID: fmt.Sprintf("s-%06d", i), Comment: "literal_%", Group: "previous", TotalGB: 1024, Enable: true}
+ if i < memberCount {
+ rows[i].Group = "staff"
+ }
+ }
+ if err := db.CreateInBatches(rows, 300).Error; err != nil {
+ t.Fatal(err)
+ }
+ return rows
+}
+
+func TestGroupClientPageAndFrozenWriteHTTP(t *testing.T) {
+ router := groupTestRouter(t)
+ rows := createTestGroupClients(t, 230, 110)
+ page := groupPage(t, router, "group=staff&mode=add&page=2")
+ if page.Total != 120 || len(page.Items) != 20 || page.Items[0].ID != rows[210].Id {
+ t.Fatalf("second add page = %d rows out of %d, expected clients 210–229", len(page.Items), page.Total)
+ }
+ search := url.QueryEscape("literal_%")
+ frozen := groupPage(t, router, "group=STAFF&mode=add&freeze=true&search="+search)
+ if frozen.Total != 120 || len(frozen.Items) != 0 || frozen.MaxID != rows[229].Id {
+ t.Fatalf("frozen add scope = %+v", frozen)
+ }
+ db := database.GetDB()
+ newer := model.ClientRecord{Email: "newer", Comment: "literal_%", Group: "previous"}
+ if err := db.Create(&newer).Error; err != nil {
+ t.Fatal(err)
+ }
+ alternate := model.ClientRecord{Email: "wildcard-would-match", Comment: "literalXY", Group: "previous"}
+ if err := db.Create(&alternate).Error; err != nil {
+ t.Fatal(err)
+ }
+ last := groupPage(t, router, fmt.Sprintf("group=staff&mode=add&page=2&maxId=%d&scopeSearch=%s", frozen.MaxID, search))
+ if len(last.Items) != 22 || last.Items[20].InScope || last.Items[21].InScope || !last.Items[19].InScope {
+ t.Fatalf("new and out-of-filter clients were included in the frozen scope: %+v", last.Items)
+ }
+ selection := service.GroupClientSelection{
+ Mode: "allMatching", ScopeToken: frozen.ScopeToken,
+ Search: "literal_%", ExcludedClientIDs: []int{rows[110].Id},
+ }
+ body := map[string]any{"group": "staff", "selection": selection}
+ if err := db.Model(&rows[111]).UpdateColumn("group_name", "staff").Error; err != nil {
+ t.Fatal(err)
+ }
+ groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0)
+ staff := groupPage(t, router, "group=staff&mode=remove")
+ if staff.Total != 111 {
+ t.Fatalf("stale selection changed client groups: staff=%d", staff.Total)
+ }
+ if err := db.Model(&rows[111]).UpdateColumn("group_name", "previous").Error; err != nil {
+ t.Fatal(err)
+ }
+ groupMutation(t, router, "/groups/bulkAdd", body, true, "affected", 119)
+ groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0)
+ for _, id := range []int{rows[110].Id, newer.Id, alternate.Id} {
+ var row model.ClientRecord
+ if err := db.First(&row, id).Error; err != nil || row.Group != "previous" {
+ t.Fatalf("client %d left its group: %q, err=%v", id, row.Group, err)
+ }
+ }
+ selection = service.GroupClientSelection{Mode: "explicit", ClientIDs: []int{rows[0].Id, newer.Id}}
+ groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, false, "", 0)
+ selection.ClientIDs = []int{rows[0].Id, rows[0].Id}
+ groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, true, "affected", 1)
+ if page := groupPage(t, router, "group=staff&mode=remove&page=3"); page.Total != 228 || len(page.Items) != 28 {
+ t.Fatalf("remove page after mutations = %d out of %d", len(page.Items), page.Total)
+ }
+}
+
+func TestGroupBulkOperationsRespectFrozenMembersHTTP(t *testing.T) {
+ router := groupTestRouter(t)
+ rows := createTestGroupClients(t, 6, 2)
+ freeze := groupPage(t, router, "group=staff&mode=remove&freeze=true")
+ db := database.GetDB()
+ if err := db.Model(&rows[0]).UpdateColumn("group_name", "previous").Error; err != nil {
+ t.Fatal(err)
+ }
+ groupMutation(t, router, "/bulkDel", map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken}, false, "", 0)
+
+ freeze = groupPage(t, router, "group=staff&mode=remove&freeze=true")
+ body := map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken}
+ newer := model.ClientRecord{Email: "new-member", Group: "staff", TotalGB: 1024}
+ if err := db.Create(&newer).Error; err != nil {
+ t.Fatal(err)
+ }
+ for _, record := range []model.ClientRecord{rows[0], rows[1], newer} {
+ if err := db.Create(&xray.ClientTraffic{Email: record.Email, Total: record.TotalGB, Enable: true}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ groupMutation(t, router, "/bulkAdjust", map[string]any{
+ "group": "staff", "scopeToken": freeze.ScopeToken, "addBytes": 256,
+ }, true, "adjusted", 1)
+ for email, want := range map[string]int64{rows[0].Email: 1024, rows[1].Email: 1280, newer.Email: 1024} {
+ var row xray.ClientTraffic
+ if err := db.Where("email = ?", email).First(&row).Error; err != nil || row.Total != want {
+ t.Fatalf("client %s quota = %d, want %d: %v", email, row.Total, want, err)
+ }
+ }
+ groupMutation(t, router, "/bulkDel", body, true, "deleted", 1)
+ groupMutation(t, router, "/bulkDel", body, false, "", 0)
+ groupMutation(t, router, "/bulkDel", map[string]any{"emails": []string{rows[0].Email}}, true, "deleted", 1)
+ if page := groupPage(t, router, "group=staff&mode=remove"); page.Total != 1 || page.Items[0].ID != newer.Id {
+ t.Fatalf("bulk deletion selected clients outside the frozen scope: %+v", page)
+ }
+}
+
+func TestGroupAdjustCapsReportedSkipsWithoutChangingExplicitResponses(t *testing.T) {
+ router := groupTestRouter(t)
+ rows := createTestGroupClients(t, 25, 25)
+ if err := database.GetDB().Model(&model.ClientRecord{}).
+ Where("group_name = ?", "staff").UpdateColumn("total_gb", 0).Error; err != nil {
+ t.Fatal(err)
+ }
+ emails := make([]string, len(rows))
+ for i, row := range rows {
+ emails[i] = row.Email
+ }
+ var result struct {
+ Success bool
+ Obj service.BulkAdjustResult
+ }
+ groupResponse := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", `{"group":"staff","addBytes":1}`)
+ if err := json.Unmarshal(groupResponse.Body.Bytes(), &result); err != nil || !result.Success ||
+ result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 20 || result.Obj.SkippedCount != 25 {
+ t.Fatalf("group adjust response = %s (%v)", groupResponse.Body, err)
+ }
+ body, err := json.Marshal(map[string]any{"emails": emails, "addBytes": 1})
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", string(body))
+ result.Obj = service.BulkAdjustResult{}
+ if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success ||
+ result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 25 || strings.Contains(out.Body.String(), "skippedCount") {
+ t.Fatalf("explicit adjust response = %s (%v)", out.Body, err)
+ }
+}
+
+func TestGroupSubscriptionExportRejectsFailedReadBeforeSendingFile(t *testing.T) {
+ dir := t.TempDir()
+ t.Setenv("TMPDIR", dir)
+ t.Setenv("TMP", dir)
+ t.Setenv("TEMP", dir)
+
+ router := gin.New()
+ router.GET("/export", func(c *gin.Context) {
+ links := service.PanelSubscriptionLinks{Enable: true, URI: "https://sub.example.test/plain/"}
+ serveGroupSubscriptionExport(c, links, func(visit func(string, string) error) error {
+ for i := range 300 {
+ if err := visit(fmt.Sprintf("client-%03d", i), "example-id"); err != nil {
+ return err
+ }
+ }
+ return errors.New("injected client query failure after reading several pages")
+ })
+ })
+ req := httptest.NewRequest(http.MethodGet, "/export", nil)
+ out := httptest.NewRecorder()
+ router.ServeHTTP(out, req)
+ if out.Code != http.StatusInternalServerError || out.Header().Get("Content-Disposition") != "" ||
+ strings.Contains(out.Body.String(), "https://sub.example.test") {
+ t.Fatalf("failed export sent HTTP %d, disposition %q, and %d bytes", out.Code, out.Header().Get("Content-Disposition"), out.Body.Len())
+ }
+ files, err := os.ReadDir(dir)
+ if err != nil || len(files) != 0 {
+ t.Fatalf("temporary export leaked after failure: %v (%v)", files, err)
+ }
+}
+
+func TestGroupSubscriptionExportAndPagingHTTP(t *testing.T) {
+ sizes := []int{1000}
+ if os.Getenv("XUI_SCALE_TEST") != "" {
+ sizes = append(sizes, 10000, 50000)
+ }
+ for _, size := range sizes {
+ t.Run(fmt.Sprint(size), func(t *testing.T) {
+ testGroupSubscriptionExportAndPaging(t, size)
+ })
+ }
+}
+
+func testGroupSubscriptionExportAndPaging(t *testing.T, size int) {
+ t.Helper()
+ router := groupTestRouter(t)
+ rows := createTestGroupClients(t, size, min(size, 10000))
+ db := database.GetDB()
+ if err := db.Model(&rows[1]).UpdateColumn("sub_id", "").Error; err != nil {
+ t.Fatal(err)
+ }
+ for key, val := range map[string]string{
+ "subEnable": "true", "subURI": "https://sub.example.test/plain/", "subJsonEnable": "true", "subJsonURI": "https://sub.example.test/json/",
+ } {
+ var setting model.Setting
+ if err := db.Where("key = ?", key).Assign(model.Setting{Value: val}).FirstOrCreate(&setting, model.Setting{Key: key}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ total := min(size, 10000) - 1
+ page := groupPage(t, router, "group=staff&mode=links")
+ if os.Getenv("XUI_SCALE_TEST") != "" {
+ pageResponse := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?group=staff&mode=links", "")
+ emailResponse := groupAPIRequest(router, http.MethodGet, "/groups/staff/emails", "")
+ t.Logf("%d clients, %d links: page %d bytes, legacy emails %d bytes", size, total, pageResponse.Body.Len(), emailResponse.Body.Len())
+ }
+ if page.Total != int64(total) || len(page.Items) != 100 || page.Items[1].Email != rows[2].Email {
+ t.Fatalf("link page returned %d rows out of %d", len(page.Items), page.Total)
+ }
+ if size == 50000 {
+ add := groupPage(t, router, "group=staff&mode=add&page=400")
+ if add.Total != 40000 || len(add.Items) != 100 || add.Items[99].Email != rows[49999].Email {
+ t.Fatalf("last page of 40,000 candidates returned %d out of %d", len(add.Items), add.Total)
+ }
+ }
+ out := groupAPIRequest(router, http.MethodGet, "/groups/subLinks/export?group=staff", "")
+ lines := strings.Split(out.Body.String(), "\n")
+ if out.Code != http.StatusOK || out.Header().Get("Cache-Control") != "no-store" || len(lines) != total ||
+ out.Header().Get("Content-Length") != fmt.Sprint(out.Body.Len()) {
+ t.Fatalf("export returned HTTP %d and %d rows, want %d rows", out.Code, len(lines), total)
+ }
+ for index, line := range lines {
+ if index > 0 {
+ index++
+ }
+ row := rows[index]
+ want := row.Email + "\thttps://sub.example.test/plain/" + row.SubID + "\thttps://sub.example.test/json/" + row.SubID
+ if line != want {
+ t.Fatalf("export row %d = %q, want %q", index, line, want)
+ }
+ }
+}
diff --git a/internal/web/controller/group_client_scope_test.go b/internal/web/controller/group_client_scope_test.go
new file mode 100644
index 000000000..6fd83876a
--- /dev/null
+++ b/internal/web/controller/group_client_scope_test.go
@@ -0,0 +1,85 @@
+package controller
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+)
+
+func TestGroupBulkAddResolvesInboundMembershipHTTP(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("group_client_http")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
+ db := database.GetDB()
+ first := model.Inbound{Tag: "source", Port: 50111, Protocol: model.VLESS, Settings: `{"clients":[{"email":"shared"}]}`}
+ second := model.Inbound{Tag: "other", Port: 50112, Protocol: model.VLESS, Settings: `{"clients":[{"email":"shared"},{"email":"other"}]}`}
+ shared := model.ClientRecord{Email: "shared", Group: "previous"}
+ other := model.ClientRecord{Email: "other", Group: "previous"}
+ for _, row := range []any{&first, &second, &shared, &other} {
+ if err := db.Create(row).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ links := []model.ClientInbound{
+ {ClientId: shared.Id, InboundId: first.Id},
+ {ClientId: shared.Id, InboundId: second.Id},
+ {ClientId: other.Id, InboundId: second.Id},
+ }
+ if err := db.Create(&links).Error; err != nil {
+ t.Fatal(err)
+ }
+ originalSettings := second.Settings
+ if err := db.Model(&second).UpdateColumn("settings", "{").Error; err != nil {
+ t.Fatal(err)
+ }
+ router := gin.New()
+ NewGroupController(router.Group("/panel/api/clients"))
+ groupMutation(t, router, "/groups/bulkAdd", map[string]any{"group": "staff", "inboundId": first.Id}, false, "", 0)
+ var unchanged model.ClientRecord
+ if err := db.First(&unchanged, shared.Id).Error; err != nil || unchanged.Group != "previous" {
+ t.Fatalf("malformed sibling inbound left a committed group change: %q, err=%v", unchanged.Group, err)
+ }
+ if err := db.Model(&second).UpdateColumn("settings", originalSettings).Error; err != nil {
+ t.Fatal(err)
+ }
+ body := fmt.Sprintf(`{"group":"staff","inboundId":%d}`, first.Id)
+ for _, want := range []int{1, 0} {
+ req := httptest.NewRequest(http.MethodPost, "/panel/api/clients/groups/bulkAdd", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ out := httptest.NewRecorder()
+ router.ServeHTTP(out, req)
+ var result struct {
+ Success bool
+ Obj struct{ Affected int }
+ }
+ if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success || result.Obj.Affected != want {
+ t.Fatalf("group add returned %s, want %d changed: %v", out.Body, want, err)
+ }
+ }
+ for id, want := range map[int]string{shared.Id: "staff", other.Id: "previous"} {
+ var got model.ClientRecord
+ if err := db.First(&got, id).Error; err != nil || got.Group != want {
+ t.Fatalf("client %d group = %q, want %q: %v", id, got.Group, want, err)
+ }
+ }
+ for _, id := range []int{first.Id, second.Id} {
+ var inbound model.Inbound
+ if err := db.First(&inbound, id).Error; err != nil || !strings.Contains(inbound.Settings, `"group":"staff"`) {
+ t.Fatalf("inbound %d settings were not updated: %s (%v)", id, inbound.Settings, err)
+ }
+ }
+}
diff --git a/internal/web/controller/import_db_restart_test.go b/internal/web/controller/import_db_restart_test.go
index 9b9392797..d4d274e83 100644
--- a/internal/web/controller/import_db_restart_test.go
+++ b/internal/web/controller/import_db_restart_test.go
@@ -14,6 +14,8 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/web/global"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
"github.com/gin-gonic/gin"
@@ -69,6 +71,7 @@ func TestImportDBSchedulesPanelRestart(t *testing.T) {
a := &ServerController{}
engine := gin.New()
+ engine.Use(middleware.DatabaseWork(service.BeginDatabaseWork))
engine.POST("/panel/api/server/importDB", a.importDB)
req := httptest.NewRequest(http.MethodPost, "/panel/api/server/importDB", &body)
req.Header.Set("Content-Type", mw.FormDataContentType())
diff --git a/internal/web/controller/inbound.go b/internal/web/controller/inbound.go
index f89aea5bb..0e64e4bec 100644
--- a/internal/web/controller/inbound.go
+++ b/internal/web/controller/inbound.go
@@ -84,8 +84,11 @@ func (a *InboundController) initRouter(g *gin.RouterGroup) {
g.GET("/trafficSnapshot", a.getTrafficSnapshot)
g.GET("/list/slim", a.getInboundsSlim)
g.GET("/options", a.getInboundOptions)
+ g.GET("/catalog", a.getInboundCatalog)
g.GET("/allLinks", a.getAllInboundLinks)
g.GET("/get/:id", a.getInbound)
+ g.GET("/:id/info", a.getInboundInfo)
+ g.GET(inboundPeerExportRoute, a.exportInboundPeers)
g.GET("/:id/fallbacks", a.getFallbacks)
g.GET("/amneziawgKernelReadiness", a.getAmneziaWGKernelReadiness)
@@ -152,6 +155,15 @@ func (a *InboundController) getInboundOptions(c *gin.Context) {
jsonObj(c, options, nil)
}
+func (a *InboundController) getInboundCatalog(c *gin.Context) {
+ options, err := a.inboundService.GetInboundCatalog(session.GetLoginUser(c).Id)
+ if err != nil {
+ jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
+ return
+ }
+ jsonObj(c, options, nil)
+}
+
// getAmneziaWGKernelReadiness reports whether this host can run an AmneziaWG
// inbound on the kernel module, so the form can disable the toggle and say why.
func (a *InboundController) getAmneziaWGKernelReadiness(c *gin.Context) {
diff --git a/internal/web/controller/inbound_info.go b/internal/web/controller/inbound_info.go
new file mode 100644
index 000000000..01b21d0c5
--- /dev/null
+++ b/internal/web/controller/inbound_info.go
@@ -0,0 +1,92 @@
+package controller
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/logger"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/session"
+)
+
+const (
+ inboundPeerExportRoute = "/:id/peerExport"
+ peerExportWriterKey = "inboundPeerExportResponseController"
+ peerExportWriteTimeout = 30 * time.Second
+)
+
+// CaptureInboundPeerExportWriter preserves access to the transport's deadlines.
+// Register it before gzip, whose writer does not expose the underlying writer.
+func CaptureInboundPeerExportWriter(basePath string) gin.HandlerFunc {
+ route := strings.TrimRight(basePath, "/") + "/panel/api/inbounds" + inboundPeerExportRoute
+ return func(c *gin.Context) {
+ if c.FullPath() == route {
+ c.Set(peerExportWriterKey, http.NewResponseController(c.Writer))
+ }
+ }
+}
+
+func (a *InboundController) getInboundInfo(c *gin.Context) {
+ user := session.GetLoginUser(c)
+ if user == nil {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+ id, idErr := strconv.Atoi(c.Param("id"))
+ page, pageErr := strconv.Atoi(c.DefaultQuery("page", "1"))
+ c.Header("Cache-Control", "no-store")
+ if idErr != nil || pageErr != nil {
+ jsonObj(c, nil, fmt.Errorf("invalid inbound info page"))
+ return
+ }
+ result, err := a.inboundService.GetInboundInfo(c.Request.Context(), user.Id, id, page)
+ jsonObj(c, result, err)
+}
+
+func (a *InboundController) exportInboundPeers(c *gin.Context) {
+ user := session.GetLoginUser(c)
+ if user == nil {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+ id, err := strconv.Atoi(c.Param("id"))
+ if err != nil {
+ c.AbortWithStatus(http.StatusBadRequest)
+ return
+ }
+ c.Header("Cache-Control", "no-store")
+ response, _ := c.Get(peerExportWriterKey)
+ deadlines, _ := response.(*http.ResponseController)
+ if deadlines == nil {
+ deadlines = http.NewResponseController(c.Writer)
+ }
+ enc := json.NewEncoder(c.Writer)
+ err = a.inboundService.WalkInboundPeerPages(c.Request.Context(), user.Id, id, func(page *service.InboundInfoPage) error {
+ // A slow but progressing export can exceed the server's whole-response
+ // deadline. Refresh the budget for each page, including its flush.
+ if err := deadlines.SetWriteDeadline(time.Now().Add(peerExportWriteTimeout)); err != nil && !errors.Is(err, http.ErrNotSupported) {
+ return err
+ }
+ c.Header("Content-Type", "application/x-ndjson")
+ if err := enc.Encode(page); err != nil {
+ return err
+ }
+ c.Writer.Flush()
+ return c.Request.Context().Err()
+ })
+ if err == nil || c.Request.Context().Err() != nil {
+ return
+ }
+ logger.Warning("inbound peer export failed:", err)
+ if !c.Writer.Written() {
+ c.Header("Content-Type", "")
+ c.String(http.StatusBadRequest, "%s", I18nWeb(c, "somethingWentWrong"))
+ }
+}
diff --git a/internal/web/controller/inbound_info_test.go b/internal/web/controller/inbound_info_test.go
new file mode 100644
index 000000000..1bcd7d73a
--- /dev/null
+++ b/internal/web/controller/inbound_info_test.go
@@ -0,0 +1,321 @@
+package controller
+
+import (
+ "compress/gzip"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ gingzip "github.com/gin-contrib/gzip"
+ "github.com/gin-contrib/sessions"
+ "github.com/gin-contrib/sessions/cookie"
+ "github.com/gin-gonic/gin"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/session"
+)
+
+func newInboundInfoTestRouter(t *testing.T, middleware ...gin.HandlerFunc) *gin.Engine {
+ t.Helper()
+ cleanup, err := testpg.IsolatePackage("inbound_info")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
+ router := gin.New()
+ router.Use(middleware...)
+ router.Use(sessions.Sessions("3x-ui", cookie.NewStore([]byte("inbound-info-test-secret"))))
+ router.Use(func(c *gin.Context) {
+ if c.Query("anonymous") != "true" {
+ session.SetAPIAuthUser(c, &model.User{Id: 1})
+ }
+ })
+ NewInboundController(router.Group("/panel/api/inbounds"))
+ return router
+}
+
+type delayedExportListener struct {
+ net.Listener
+ delay time.Duration
+}
+
+func (l delayedExportListener) Accept() (net.Conn, error) {
+ conn, err := l.Listener.Accept()
+ if err != nil {
+ return nil, err
+ }
+ return &delayedExportConn{Conn: conn, delay: l.delay}, nil
+}
+
+type delayedExportConn struct {
+ net.Conn
+ firstWrite sync.Once
+ delay time.Duration
+}
+
+func (c *delayedExportConn) Write(p []byte) (int, error) {
+ c.firstWrite.Do(func() { time.Sleep(c.delay) })
+ return c.Conn.Write(p)
+}
+
+func TestInboundPeerExportOutlastsServerWriteTimeout(t *testing.T) {
+ router := newInboundInfoTestRouter(t, CaptureInboundPeerExportWriter("/"), gingzip.Gzip(gingzip.DefaultCompression))
+ var payload strings.Builder
+ payload.WriteString(`{"secretKey":"server-key","clients":[`)
+ for i := range 103 {
+ if i > 0 {
+ payload.WriteByte(',')
+ }
+ fmt.Fprintf(&payload, `{"email":"client-%05d","privateKey":"secret-%05d"}`, i, i)
+ }
+ payload.WriteString(`]}`)
+ inbound := model.Inbound{UserId: 1, Protocol: model.WireGuard, Tag: "slow-peer-export", Port: 50134, Settings: payload.String()}
+ if err := database.GetDB().Create(&inbound).Error; err != nil {
+ t.Fatal(err)
+ }
+
+ const serverTimeout = 200 * time.Millisecond
+ for _, encoding := range []string{"identity", "gzip"} {
+ t.Run(encoding, func(t *testing.T) {
+ server := httptest.NewUnstartedServer(router)
+ server.Config.WriteTimeout = serverTimeout
+ // Delay the first network write beyond the server's regular deadline.
+ server.Listener = delayedExportListener{Listener: server.Listener, delay: 2 * serverTimeout}
+ server.Start()
+ defer server.Close()
+ client := server.Client()
+ client.Timeout = 5 * time.Second
+ req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, fmt.Sprintf("%s/panel/api/inbounds/%d/peerExport", server.URL, inbound.Id), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Accept-Encoding", encoding)
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("export failed after the regular write timeout: %v", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK || resp.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("export response: status %d, headers %v", resp.StatusCode, resp.Header)
+ }
+
+ var body io.Reader = resp.Body
+ if encoding == "gzip" {
+ if resp.Header.Get("Content-Encoding") != "gzip" {
+ t.Fatal("export did not retain gzip compression")
+ }
+ compressed, err := gzip.NewReader(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer compressed.Close()
+ body = compressed
+ }
+ d := json.NewDecoder(body)
+ received := 0
+ for {
+ var page service.InboundInfoPage
+ err := d.Decode(&page)
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil || page.PeerOffset != received || page.TotalPeers != 103 {
+ t.Fatalf("export lost its position at %d: %v", received, err)
+ }
+ received += checkInboundPeerPage(t, page, received)
+ }
+ if received != 103 {
+ t.Fatalf("export returned %d peers, want 103", received)
+ }
+ })
+ }
+}
+
+func getInboundInfoTestResponse(router *gin.Engine, tail string) *httptest.ResponseRecorder {
+ out := httptest.NewRecorder()
+ router.ServeHTTP(out, httptest.NewRequest(http.MethodGet, "/panel/api/inbounds/"+tail, nil))
+ return out
+}
+
+func decodeInboundInfoPage(t *testing.T, out *httptest.ResponseRecorder) service.InboundInfoPage {
+ t.Helper()
+ var resp struct {
+ Success bool
+ Obj service.InboundInfoPage
+ }
+ if err := json.Unmarshal(out.Body.Bytes(), &resp); err != nil || !resp.Success || resp.Obj.Inbound == nil {
+ t.Fatalf("inbound info returned HTTP %d: %s (%v)", out.Code, out.Body, err)
+ }
+ return resp.Obj
+}
+
+func TestInboundInfoReturnsOnlyTheDisplayedClient(t *testing.T) {
+ router := newInboundInfoTestRouter(t)
+ inbound := model.Inbound{
+ UserId: 1, Protocol: model.VLESS, Tag: "info-standard", Port: 50133,
+ Settings: `{"decryption":"none","clients":[{"email":"selected@test","id":"selected-id"},{"email":"other@test","password":"other-secret"}]}`,
+ }
+ if err := database.GetDB().Create(&inbound).Error; err != nil {
+ t.Fatal(err)
+ }
+ id := strconv.Itoa(inbound.Id)
+ for _, route := range []string{"/info", "/peerExport"} {
+ out := getInboundInfoTestResponse(router, id+route+"?anonymous=true")
+ if out.Code != http.StatusUnauthorized || out.Body.Len() != 0 {
+ t.Fatalf("unauthenticated %s returned HTTP %d: %s", route, out.Code, out.Body)
+ }
+ }
+ if out := getInboundInfoTestResponse(router, id+"/peerExport"); out.Code == http.StatusOK {
+ t.Fatalf("regular inbound returned a peer export: %s", out.Body)
+ }
+ full := getInboundInfoTestResponse(router, "get/"+id)
+ if !strings.Contains(full.Body.String(), "other-secret") {
+ t.Fatalf("full inbound fixture did not expose the unselected field: %s", full.Body)
+ }
+ info := getInboundInfoTestResponse(router, id+"/info")
+ if info.Code != http.StatusOK || !strings.Contains(info.Body.String(), "selected-id") ||
+ strings.Contains(info.Body.String(), "other-secret") || strings.Contains(info.Body.String(), "other@test") {
+ t.Fatalf("info HTTP %d returned %s", info.Code, info.Body)
+ }
+}
+
+func TestInboundInfoPagesAndExportPreserveTunnelPeerOrder(t *testing.T) {
+ router := newInboundInfoTestRouter(t)
+ sizes := []int{103}
+ if os.Getenv("XUI_SCALE_TEST") != "" {
+ sizes = append(sizes, 1000, 10000, 50000)
+ }
+ for _, protocol := range []model.Protocol{model.WireGuard, model.AmneziaWG} {
+ for _, size := range sizes {
+ t.Run(fmt.Sprintf("%s/%d", protocol, size), func(t *testing.T) {
+ var payload strings.Builder
+ payload.WriteString(`{"secretKey":"server-key","clients":[`)
+ for i := range size {
+ if i > 0 {
+ payload.WriteByte(',')
+ }
+ fmt.Fprintf(&payload, `{"email":"client-%05d","privateKey":"secret-%05d"}`, i, i)
+ }
+ payload.WriteString(`],"peers":[{"privateKey":"legacy-secret"}]}`)
+ inbound := model.Inbound{UserId: 1, Protocol: protocol, Tag: fmt.Sprintf("%s-%d", protocol, size), Port: 50134, Settings: payload.String()}
+ if err := database.GetDB().Create(&inbound).Error; err != nil {
+ t.Fatal(err)
+ }
+ id := strconv.Itoa(inbound.Id)
+ out := getInboundInfoTestResponse(router, id+"/info?page=2")
+ page := decodeInboundInfoPage(t, out)
+ if page.PeerOffset != 50 || page.TotalPeers != size || strings.Contains(out.Body.String(), "legacy-secret") {
+ t.Fatalf("unexpected page metadata: offset=%d count=%d", page.PeerOffset, page.TotalPeers)
+ }
+ if n := checkInboundPeerPage(t, page, 50); n != 50 {
+ t.Fatalf("second page returned %d peers", n)
+ }
+ if os.Getenv("XUI_SCALE_TEST") != "" {
+ full := getInboundInfoTestResponse(router, "get/"+id)
+ t.Logf("raw HTTP bodies with %d peers: info page %d bytes, full inbound %d bytes", size, out.Body.Len(), full.Body.Len())
+ }
+ export := getInboundInfoTestResponse(router, id+"/peerExport")
+ if export.Code != http.StatusOK || export.Header().Get("Content-Type") != "application/x-ndjson" {
+ t.Fatalf("peer export response=%d type=%q", export.Code, export.Header().Get("Content-Type"))
+ }
+ d := json.NewDecoder(export.Body)
+ received := 0
+ for {
+ var exported service.InboundInfoPage
+ err := d.Decode(&exported)
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil || exported.TotalPeers != size || exported.PeerOffset != received {
+ t.Fatalf("peer export lost its position at %d: %v", received, err)
+ }
+ received += checkInboundPeerPage(t, exported, received)
+ }
+ if received != size {
+ t.Fatalf("export returned %d peers, want %d", received, size)
+ }
+ })
+ }
+ }
+}
+
+func checkInboundPeerPage(t *testing.T, page service.InboundInfoPage, start int) int {
+ t.Helper()
+ var fields struct {
+ Clients []struct {
+ Email string
+ PrivateKey string
+ }
+ SecretKey string
+ }
+ if err := json.Unmarshal([]byte(page.Inbound.Settings), &fields); err != nil || fields.SecretKey != "server-key" ||
+ len(fields.Clients) == 0 || len(fields.Clients) > 50 {
+ t.Fatalf("bad tunnel page: %d peers, key %q (%v)", len(fields.Clients), fields.SecretKey, err)
+ }
+ for i, c := range fields.Clients {
+ if c.Email != fmt.Sprintf("client-%05d", start+i) || c.PrivateKey != fmt.Sprintf("secret-%05d", start+i) {
+ t.Fatalf("wrong peer at position %d: %+v", start+i, c)
+ }
+ }
+ return len(fields.Clients)
+}
+
+func TestInboundInfoLegacyMalformedAndOwnerScope(t *testing.T) {
+ router := newInboundInfoTestRouter(t)
+ for _, tc := range []struct {
+ name string
+ owner int
+ settings string
+ total int
+ }{
+ {name: "legacy peers", owner: 1, settings: `{"clients":[],"peers":[null,{"publicKey":"legacy-public","privateKey":"legacy-private"}]}`, total: 1},
+ {name: "empty", owner: 1, settings: `{"clients":[],"peers":[]}`, total: 0},
+ {name: "malformed", owner: 1, settings: `{"clients":[{"password":"broken-secret"}]`, total: 0},
+ {name: "foreign owner", owner: 2, settings: `{"peers":[{"privateKey":"foreign-secret"}]}`, total: 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ inbound := model.Inbound{UserId: tc.owner, Protocol: model.WireGuard, Tag: tc.name, Port: 50135, Settings: tc.settings}
+ if err := database.GetDB().Create(&inbound).Error; err != nil {
+ t.Fatal(err)
+ }
+ id := strconv.Itoa(inbound.Id)
+ response := getInboundInfoTestResponse(router, id+"/info")
+ exported := getInboundInfoTestResponse(router, id+"/peerExport")
+ if tc.owner != 1 {
+ if strings.Contains(response.Body.String(), "foreign-secret") || strings.Contains(response.Body.String(), `"success":true`) ||
+ exported.Code == http.StatusOK || strings.Contains(exported.Body.String(), "foreign-secret") {
+ t.Fatalf("foreign inbound exposed by info or export: %s / %s", response.Body, exported.Body)
+ }
+ return
+ }
+ page := decodeInboundInfoPage(t, response)
+ if page.TotalPeers != tc.total {
+ t.Fatalf("total=%d, want %d", page.TotalPeers, tc.total)
+ }
+ if tc.total == 1 {
+ if !strings.Contains(page.Inbound.Settings, "legacy-private") || exported.Code != http.StatusOK ||
+ !strings.Contains(exported.Body.String(), "legacy-private") {
+ t.Fatalf("legacy peer lost: %s / %s", page.Inbound.Settings, exported.Body)
+ }
+ } else if strings.Contains(response.Body.String(), "broken-secret") || exported.Code == http.StatusOK {
+ t.Fatalf("malformed settings exposed: %s / %s", response.Body, exported.Body)
+ }
+ })
+ }
+}
diff --git a/internal/web/controller/node.go b/internal/web/controller/node.go
index fe1a24c5b..9cf1d1825 100644
--- a/internal/web/controller/node.go
+++ b/internal/web/controller/node.go
@@ -18,6 +18,7 @@ import (
type NodeController struct {
nodeService service.NodeService
xrayService service.XrayService
+ localStatus func() *service.Status
}
func NewNodeController(g *gin.RouterGroup) *NodeController {
@@ -28,6 +29,7 @@ func NewNodeController(g *gin.RouterGroup) *NodeController {
func (a *NodeController) initRouter(g *gin.RouterGroup) {
g.GET("/list", a.list)
+ g.GET("/overview", a.overview)
g.GET("/get/:id", a.get)
g.GET("/webCert/:id", a.webCert)
@@ -112,6 +114,15 @@ func (a *NodeController) get(c *gin.Context) {
jsonObj(c, n, nil)
}
+func (a *NodeController) overview(c *gin.Context) {
+ var local *service.Status
+ if a.localStatus != nil {
+ local = a.localStatus()
+ }
+ view, err := a.nodeService.GetNodeOverview(local)
+ jsonMsgObj(c, I18nWeb(c, "pages.nodes.toasts.list"), view, err)
+}
+
// webCert returns the node's own web TLS certificate/key file paths so the
// inbound form's "Set Cert from Panel" can fill paths that exist on the node.
func (a *NodeController) webCert(c *gin.Context) {
diff --git a/internal/web/controller/server.go b/internal/web/controller/server.go
index eeaa22510..e09df9003 100644
--- a/internal/web/controller/server.go
+++ b/internal/web/controller/server.go
@@ -14,6 +14,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
"github.com/mhsanaei/3x-ui/v3/internal/web/entity"
"github.com/mhsanaei/3x-ui/v3/internal/web/global"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
"github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
@@ -110,7 +111,9 @@ func (a *ServerController) startTask() {
}
// status returns the current server status information.
-func (a *ServerController) status(c *gin.Context) { jsonObj(c, a.serverService.CurrentStatus(), nil) }
+func (a *ServerController) status(c *gin.Context) {
+ jsonObj(c, service.StatusWithSampleAge(a.serverService.CurrentStatus()), nil)
+}
func (a *ServerController) getFail2banStatus(c *gin.Context) {
jsonObj(c, a.serverService.GetFail2banStatus(), nil)
@@ -404,7 +407,8 @@ func (a *ServerController) importDB(c *gin.Context) {
// node identity: the safe default for the common case of moving a config to
// a new host. Send keepHostSettings=false to clone a machine wholesale.
keepHostSettings := c.Request.FormValue("keepHostSettings") != "false"
- if err := a.serverService.ImportDB(file, keepHostSettings); err != nil {
+ middleware.ReleaseDatabaseWork(c)
+ if err := a.serverService.ImportDBContext(c.Request.Context(), file, keepHostSettings); err != nil {
jsonMsg(c, I18nWeb(c, "pages.index.importDatabaseError"), err)
return
}
diff --git a/internal/web/job/database_restore_test.go b/internal/web/job/database_restore_test.go
new file mode 100644
index 000000000..ab99756bc
--- /dev/null
+++ b/internal/web/job/database_restore_test.go
@@ -0,0 +1,183 @@
+package job
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ goruntime "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/op/go-logging"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
+ "github.com/mhsanaei/3x-ui/v3/internal/xray"
+)
+
+func TestDatabaseRestoreDrainsAnInFlightNodePoll(t *testing.T) {
+ if goruntime.GOOS == "windows" {
+ t.Skip("the stub xray binary is a shell script")
+ }
+ cleanup, err := testpg.IsolatePackage("restore_job")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ xuilogger.InitLogger(logging.ERROR)
+ uploadPath := filepath.Join(t.TempDir(), "upload.db")
+ backend := os.Getenv("XUI_DB_TYPE")
+ t.Setenv("XUI_DB_TYPE", "sqlite")
+ if err := database.InitDB(uploadPath); err != nil {
+ t.Fatal(err)
+ }
+ restored := &model.Inbound{Tag: "restored", Port: 21023, Protocol: model.VLESS, Settings: `{"clients":[],"decryption":"none"}`, StreamSettings: `{"network":"tcp"}`, Sniffing: "{}"}
+ if err := database.GetDB().Create(restored).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := database.CloseDB(); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("XUI_DB_TYPE", backend)
+ target := t.TempDir()
+ t.Setenv("XUI_DB_FOLDER", target)
+ livePath := filepath.Join(t.TempDir(), "actual.db")
+ configuredPath := filepath.Join(target, "x-ui.db")
+ dbtest.InitDB(t, livePath)
+ if backend != database.DialectPostgres {
+ if err := os.Symlink(livePath, configuredPath); err != nil {
+ t.Fatal(err)
+ }
+ }
+ binDir := t.TempDir()
+ t.Setenv("XUI_BIN_FOLDER", binDir)
+ t.Setenv("XUI_LOG_FOLDER", t.TempDir())
+ if err := os.WriteFile(filepath.Join(binDir, xray.GetBinaryName()), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}}))
+ t.Cleanup(func() { runtime.SetManager(nil) })
+ service.StartTrafficWriter()
+ t.Cleanup(service.StopTrafficWriter)
+
+ fetched, unblock := make(chan struct{}), make(chan struct{})
+ releasePoll := sync.OnceFunc(func() { close(unblock) })
+ markFetched := sync.OnceFunc(func() { close(fetched) })
+ node := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/inbounds/list") {
+ markFetched()
+ <-unblock
+ _, _ = w.Write([]byte(`{"success":true,"obj":[]}`))
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ t.Cleanup(node.Close)
+ t.Cleanup(releasePoll)
+ u, err := url.Parse(node.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ port, err := strconv.Atoi(u.Port())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := database.GetDB().Create(&model.Node{
+ Name: "polling-node", Scheme: u.Scheme, Address: u.Hostname(), Port: port, BasePath: "/", ApiToken: "fixture",
+ Enable: true, Status: "online", AllowPrivateAddress: true, TlsVerifyMode: "verify",
+ }).Error; err != nil {
+ t.Fatal(err)
+ }
+
+ pollDone := make(chan struct{})
+ go func() {
+ defer close(pollDone)
+ NewNodeTrafficSyncJob().Run()
+ }()
+ t.Cleanup(func() {
+ releasePoll()
+ <-pollDone
+ })
+ wait := time.NewTimer(10 * time.Second)
+ defer wait.Stop()
+ select {
+ case <-fetched:
+ case <-wait.C:
+ t.Fatal("node request did not reach the fixture")
+ }
+ upload, err := os.Open(uploadPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer upload.Close()
+ generation := database.ConnectionGeneration()
+ restoreDone := make(chan error, 1)
+ go func() { restoreDone <- (&service.ServerService{}).ImportDB(upload, false) }()
+
+ tick := time.NewTicker(time.Millisecond)
+ defer tick.Stop()
+checkPause:
+ for {
+ select {
+ case err := <-restoreDone:
+ t.Fatalf("restore returned while a node poll was still running: %v", err)
+ case <-wait.C:
+ t.Fatal("restore never paused new node work")
+ case <-tick.C:
+ end, ok := service.BeginDatabaseWork()
+ if !ok {
+ break checkPause
+ }
+ end()
+ }
+ }
+ // Give a broken restore time to reach the swap while the node reply is held.
+ hold := time.NewTimer(500 * time.Millisecond)
+ defer hold.Stop()
+holding:
+ for {
+ select {
+ case err := <-restoreDone:
+ t.Fatalf("restore finished before the node poll drained: %v", err)
+ case <-tick.C:
+ if got := database.ConnectionGeneration(); got != generation {
+ t.Fatalf("database reopened before the in-flight node poll finished: generation %d, want %d", got, generation)
+ }
+ case <-hold.C:
+ break holding
+ }
+ }
+ releasePoll()
+ select {
+ case err := <-restoreDone:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(45 * time.Second):
+ t.Fatal("restore did not finish after the node poll drained")
+ }
+ var row model.Inbound
+ if err := database.GetDB().Where("tag = ?", "restored").First(&row).Error; err != nil || row.Port != restored.Port {
+ t.Fatalf("restored inbound = %+v, error = %v", row, err)
+ }
+ if backend != database.DialectPostgres {
+ if got, err := os.Readlink(configuredPath); err != nil || got != livePath {
+ t.Fatalf("configured database symlink after restore = %q, error = %v", got, err)
+ }
+ }
+ end, ok := service.BeginDatabaseWork()
+ if !ok {
+ t.Fatal("database work did not resume after a successful restore")
+ }
+ end()
+}
diff --git a/internal/web/job/ldap_sync_hung_node_test.go b/internal/web/job/ldap_sync_hung_node_test.go
index 0c9d2c55e..f89ef01f2 100644
--- a/internal/web/job/ldap_sync_hung_node_test.go
+++ b/internal/web/job/ldap_sync_hung_node_test.go
@@ -29,7 +29,7 @@ func ldapHungNodeInbound(t *testing.T, emails []string) (*resetGate, *model.Inbo
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "application/json")
- if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "inbounds/list") {
+ if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "inbounds/catalog") {
_, _ = w.Write([]byte(`{"success":true,"obj":[{"id":1,"tag":"` + tag + `"}]}`))
return
}
diff --git a/internal/web/job/mtproto_job.go b/internal/web/job/mtproto_job.go
index 82a474f07..1e2dfbc02 100644
--- a/internal/web/job/mtproto_job.go
+++ b/internal/web/job/mtproto_job.go
@@ -30,9 +30,7 @@ func (j *MtprotoJob) Run() {
}
routedTags := make(map[string]bool)
- activeTags := make([]string, 0, len(desired))
for _, inst := range desired {
- activeTags = append(activeTags, inst.Tag)
if inst.RouteThroughXray {
routedTags[inst.Tag] = true
}
@@ -41,7 +39,7 @@ func (j *MtprotoJob) Run() {
mgr := mtproto.GetManager()
mgr.Reconcile(desired)
- deltas, fronted, onlineEmails := mgr.CollectTraffic()
+ deltas, fronted, onlineEmails, observedTags := mgr.CollectTraffic()
traffics, clientTraffics := rollUpMtprotoTraffic(deltas, fronted, routedTags)
if len(traffics) > 0 || len(clientTraffics) > 0 {
@@ -50,7 +48,7 @@ func (j *MtprotoJob) Run() {
}
}
- j.inboundService.RefreshLocalOnlineClients(onlineEmails, activeTags)
+ j.inboundService.RefreshLocalOnlineClients(onlineEmails, observedTags)
}
// rollUpMtprotoTraffic turns scraped mtg deltas into inbound and client traffic.
diff --git a/internal/web/job/node_heartbeat_descendants_test.go b/internal/web/job/node_heartbeat_descendants_test.go
index 5c035ffbe..5bb5aa2b9 100644
--- a/internal/web/job/node_heartbeat_descendants_test.go
+++ b/internal/web/job/node_heartbeat_descendants_test.go
@@ -6,6 +6,7 @@ import (
"path/filepath"
"strconv"
"strings"
+ "sync/atomic"
"testing"
"github.com/op/go-logging"
@@ -18,53 +19,43 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
-func transitiveGuids(t *testing.T) []string {
+func transitiveNodes(t *testing.T) []*model.Node {
t.Helper()
tree, err := (&service.NodeService{}).GetNodeTree()
if err != nil {
t.Fatalf("GetNodeTree: %v", err)
}
- var out []string
+ var out []*model.Node
for _, n := range tree {
if n.Transitive {
- out = append(out, n.Guid)
+ out = append(out, n)
}
}
return out
}
-// The heartbeat skips a disabled node and never sees a deleted one, so the
-// sub-nodes it had learned from them stayed on the Nodes page for good.
-func TestHeartbeatDropsSubNodesOfNodesItNoLongerProbes(t *testing.T) {
- cases := []struct {
- name string
- retire func(t *testing.T, nodeID int)
- }{
- {"disabled", func(t *testing.T, nodeID int) {
- if err := (&service.NodeService{}).SetEnable(nodeID, false); err != nil {
- t.Fatalf("SetEnable: %v", err)
- }
- }},
- {"deleted", func(t *testing.T, nodeID int) {
- if err := (&service.NodeService{}).Delete(nodeID); err != nil {
- t.Fatalf("Delete: %v", err)
- }
- }},
- }
- for _, tc := range cases {
- t.Run(tc.name, func(t *testing.T) {
+func TestHeartbeatPreservesUnavailableDescendantsUntilParentIsDeleted(t *testing.T) {
+ for _, state := range []string{"offline", "disabled", "deleted"} {
+ t.Run(state, func(t *testing.T) {
xuilogger.InitLogger(logging.ERROR)
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}}))
t.Cleanup(func() { runtime.SetManager(nil) })
+ svc := &service.NodeService{}
+ t.Cleanup(func() { svc.PruneNodeDescendants(nil) })
+ var offline atomic.Bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "server/status"):
+ if offline.Load() {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
_, _ = w.Write([]byte(`{"success":true,"obj":{"panelGuid":"direct-guid","xray":{"state":"running"}}}`))
case strings.HasSuffix(r.URL.Path, "server/descendants"):
- _, _ = w.Write([]byte(`{"success":true,"obj":[{"guid":"sub-guid","parentGuid":"direct-guid","name":"sub","status":"online"}]}`))
+ _, _ = w.Write([]byte(`{"success":true,"obj":[{"guid":"sub-guid","parentGuid":"direct-guid","name":"sub","status":"online","telemetry":{"sampledAt":1,"sampleAgeMillis":0,"cpuPct":25}}]}`))
default:
_, _ = w.Write([]byte(`{"success":true}`))
}
@@ -82,14 +73,30 @@ func TestHeartbeatDropsSubNodesOfNodesItNoLongerProbes(t *testing.T) {
hb := NewNodeHeartbeatJob()
hb.Run()
- if got := transitiveGuids(t); len(got) != 1 || got[0] != "sub-guid" {
- t.Fatalf("sub-nodes after first heartbeat = %v, want [sub-guid]", got)
+ if got := transitiveNodes(t); len(got) != 1 || got[0].Guid != "sub-guid" || got[0].Telemetry == nil {
+ t.Fatalf("missing live sub-node after first heartbeat: %v", got)
}
- tc.retire(t, node.Id)
+ switch state {
+ case "offline":
+ offline.Store(true)
+ case "disabled":
+ if err := svc.SetEnable(node.Id, false); err != nil {
+ t.Fatal(err)
+ }
+ case "deleted":
+ if err := svc.Delete(node.Id); err != nil {
+ t.Fatal(err)
+ }
+ }
hb.Run()
- if got := transitiveGuids(t); len(got) != 0 {
- t.Fatalf("sub-nodes after the node was %s = %v, want none", tc.name, got)
+ got := transitiveNodes(t)
+ if state == "deleted" {
+ if len(got) != 0 {
+ t.Fatalf("deleted parent left sub-nodes: %v", got)
+ }
+ } else if len(got) != 1 || got[0].Guid != "sub-guid" || got[0].Status != "unknown" || got[0].Telemetry != nil {
+ t.Fatalf("%s parent should retain an unavailable sub-node: %+v", state, got)
}
})
}
diff --git a/internal/web/job/node_heartbeat_job.go b/internal/web/job/node_heartbeat_job.go
index b8fdbe434..e91d80d24 100644
--- a/internal/web/job/node_heartbeat_job.go
+++ b/internal/web/job/node_heartbeat_job.go
@@ -58,10 +58,7 @@ func (j *NodeHeartbeatJob) Run() {
logger.Warning("node heartbeat: load nodes failed:", err)
return
}
- j.nodeService.RetainEnabledNodeDescendants(nodes)
- if len(nodes) == 0 {
- return
- }
+ j.nodeService.PruneNodeDescendants(nodes)
sem := make(chan struct{}, nodeHeartbeatConcurrency)
var wg sync.WaitGroup
@@ -89,6 +86,10 @@ func (j *NodeHeartbeatJob) Run() {
if !websocket.HasClients() {
return
}
+ if len(nodes) == 0 {
+ websocket.BroadcastNodes([]*service.NodeView{})
+ return
+ }
updated, err := j.nodeService.GetNodeTreeView()
if err != nil {
logger.Warning("node heartbeat: load nodes for broadcast failed:", err)
@@ -110,14 +111,13 @@ func (j *NodeHeartbeatJob) probeOne(n *model.Node) service.HeartbeatPatch {
logger.Warning("node heartbeat: update node", n.Id, "failed:", updErr)
}
// Learn the nodes this node manages so the panel can surface them as
- // transitive sub-nodes (#4983). Fresh context — the probe budget above may
- // be spent. Drop them when the node is unreachable.
+ // transitive sub-nodes (#4983). Use a fresh context after the status probe.
if patch.Status == "online" {
dctx, dcancel := context.WithTimeout(context.Background(), nodeHeartbeatRequestTimeout)
j.nodeService.RefreshDescendants(dctx, n)
dcancel()
} else {
- j.nodeService.ClearDescendants(n.Id)
+ j.nodeService.MarkDescendantsUnreachable(n.Id)
}
return patch
}
diff --git a/internal/web/job/node_traffic_isolation_test.go b/internal/web/job/node_traffic_isolation_test.go
index 68bed06a1..82d74a063 100644
--- a/internal/web/job/node_traffic_isolation_test.go
+++ b/internal/web/job/node_traffic_isolation_test.go
@@ -39,11 +39,14 @@ func TestNodeTrafficSyncAllowsHealthyNextTickDuringSlowReconcile(t *testing.T) {
var slowID int
for _, slow := range []bool{true, false} {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") {
+ switch {
+ case slow && strings.HasSuffix(r.URL.Path, "/inbounds/catalog"):
slowReconciles.Add(1)
slowRequests <- struct{}{}
<-release
- } else if !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") {
+ case slow && strings.HasSuffix(r.URL.Path, "/inbounds/list"):
+ slowRequests <- struct{}{}
+ case !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list"):
fastRequests <- struct{}{}
}
w.Header().Set("Content-Type", "application/json")
diff --git a/internal/web/job/node_traffic_sync_job.go b/internal/web/job/node_traffic_sync_job.go
index f86fc0934..383005c7c 100644
--- a/internal/web/job/node_traffic_sync_job.go
+++ b/internal/web/job/node_traffic_sync_job.go
@@ -115,6 +115,11 @@ func (j *NodeTrafficSyncJob) Run() {
return
}
defer j.dispatch.Unlock()
+ end, allowed := service.BeginDatabaseWork()
+ if !allowed {
+ return
+ }
+ defer end()
mgr := runtime.GetManager()
if j.closed || mgr == nil {
return
@@ -151,6 +156,15 @@ func (j *NodeTrafficSyncJob) Run() {
if j.hadNodes && !j.publishing {
j.startPeriodicWorker("node-traffic-publish", &j.publishing, j.publishTraffic)
j.hadNodes = false
+ } else if websocket.HasClients() && !j.inboundService.HasFreshXrayOnlineSample() {
+ // Standalone panels also need to refresh attribution while Xray is unpolled.
+ j.startPeriodicWorker("local-online-publish", &j.publishing, func() {
+ websocket.BroadcastTraffic(map[string]any{
+ "nodeTraffics": []*xray.Traffic{},
+ "onlineByGuid": j.inboundService.GetOnlineClientsByGuid(),
+ "activeInbounds": j.inboundService.GetActiveInboundsByGuid(),
+ })
+ })
}
return
}
@@ -198,7 +212,10 @@ func (j *NodeTrafficSyncJob) Run() {
j.inFlight--
j.dispatch.Unlock()
}()
- j.syncOne(pollCtx, mgr, node, doIPSync, pushGlobals, fetchTimeout)
+ if end, allowed := service.BeginDatabaseWork(); allowed {
+ defer end()
+ j.syncOne(pollCtx, mgr, node, doIPSync, pushGlobals, fetchTimeout)
+ }
})
}
@@ -225,7 +242,10 @@ func (j *NodeTrafficSyncJob) startPeriodicWorker(name string, busy *bool, work f
*busy = false
j.dispatch.Unlock()
}()
- work()
+ if end, allowed := service.BeginDatabaseWork(); allowed {
+ defer end()
+ work()
+ }
})
}
diff --git a/internal/web/job/periodic_traffic_reset_nodes_test.go b/internal/web/job/periodic_traffic_reset_nodes_test.go
index 18619fd1b..525a220f6 100644
--- a/internal/web/job/periodic_traffic_reset_nodes_test.go
+++ b/internal/web/job/periodic_traffic_reset_nodes_test.go
@@ -46,7 +46,7 @@ func resetNode(t *testing.T, gate *resetGate, name, inboundTag string) int {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
- if strings.HasSuffix(r.URL.Path, "/panel/api/inbounds/list") {
+ if strings.HasSuffix(r.URL.Path, "/panel/api/inbounds/catalog") {
w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"success":true,"obj":[{"id":1,"tag":%q}]}`, inboundTag)
return
diff --git a/internal/web/job/tuic_job.go b/internal/web/job/tuic_job.go
index 9ae4abb38..1436f63ad 100644
--- a/internal/web/job/tuic_job.go
+++ b/internal/web/job/tuic_job.go
@@ -41,16 +41,11 @@ func (j *TuicJob) Run() {
return
}
- activeTags := make([]string, 0, len(desired))
- for _, inst := range desired {
- activeTags = append(activeTags, inst.Tag)
- }
-
mgr := tuic.GetManager()
mgr.Reconcile(desired)
_, clientDeltas := mgr.CollectAllTraffic()
- onlineEmails, _ := mgr.GetActiveClients(30 * time.Second)
+ onlineEmails, activeTags := mgr.GetActiveClients(30 * time.Second)
clientTraffics := aggregateTuicClientTraffic(clientDeltas, onlineEmails)
sampledAt := time.Now()
diff --git a/internal/web/job/xray_traffic_job.go b/internal/web/job/xray_traffic_job.go
index b1bd3e1a0..fc09c8bec 100644
--- a/internal/web/job/xray_traffic_job.go
+++ b/internal/web/job/xray_traffic_job.go
@@ -27,6 +27,7 @@ type XrayTrafficJob struct {
type xrayTrafficSample struct {
id string
+ core *xray.Process
traffics []*xray.Traffic
clients []*xray.ClientTraffic
}
@@ -77,11 +78,12 @@ func NewXrayTrafficJob() *XrayTrafficJob {
func (j *XrayTrafficJob) pollTraffic(collect func() ([]*xray.Traffic, []*xray.ClientTraffic, error)) (sample *xrayTrafficSample, needRestart, clientsDisabled bool) {
if j.pending == nil {
+ core := service.XrayProcess()
traffics, clients, err := collect()
if err != nil {
return nil, false, false
}
- j.pending = &xrayTrafficSample{id: uuid.NewString(), traffics: traffics, clients: clients}
+ j.pending = &xrayTrafficSample{id: uuid.NewString(), core: core, traffics: traffics, clients: clients}
}
sample = j.pending
needRestart, clientsDisabled, err := j.inboundService.AddXrayTrafficBatch(sample.id, sample.traffics, sample.clients)
@@ -135,22 +137,25 @@ func (j *XrayTrafficJob) Run() {
// client moves no bytes between polls (the delta heuristic's blind spot),
// while a short-lived connection can close before this poll yet still show
// in the delta. Older cores fall back to deltas alone.
- if onlineUsers, apiMode, ouErr := j.xrayService.GetOnlineUsers(); ouErr != nil {
- logger.Debug("get online users from xray api failed:", ouErr)
- } else if apiMode {
- idleOnline := make([]string, 0, len(onlineUsers))
- for _, u := range onlineUsers {
- if !deltaActive[u.Email] {
- activeEmails = append(activeEmails, u.Email)
- idleOnline = append(idleOnline, u.Email)
+ if sample.core == service.XrayProcess() {
+ if onlineUsers, apiMode, ouErr := j.xrayService.GetOnlineUsers(); ouErr != nil {
+ logger.Debug("get online users from xray api failed:", ouErr)
+ } else if apiMode {
+ idleOnline := make([]string, 0, len(onlineUsers))
+ for _, u := range onlineUsers {
+ if !deltaActive[u.Email] {
+ activeEmails = append(activeEmails, u.Email)
+ idleOnline = append(idleOnline, u.Email)
+ }
+ }
+ // The traffic path only bumps last_online on a non-zero delta; keep the
+ // column fresh for clients kept online purely by a live connection.
+ if err := j.inboundService.BumpClientsLastOnline(idleOnline); err != nil {
+ logger.Warning("bump last online for connected clients failed:", err)
}
}
- // The traffic path only bumps last_online on a non-zero delta; keep the
- // column fresh for clients kept online purely by a live connection.
- if err := j.inboundService.BumpClientsLastOnline(idleOnline); err != nil {
- logger.Warning("bump last online for connected clients failed:", err)
- }
}
+
// Pair the email signal with the inbound tags that moved bytes this poll.
// Xray's user>>>email counter aggregates across every inbound a client is
// attached to, so an online email alone can't say which inbound it used —
@@ -162,7 +167,7 @@ func (j *XrayTrafficJob) Run() {
activeInboundTags = append(activeInboundTags, tr.Tag)
}
}
- j.inboundService.RefreshLocalOnlineClients(activeEmails, activeInboundTags)
+ j.inboundService.PublishXrayOnlineClients(sample.core, activeEmails, activeInboundTags)
if !websocket.HasClients() {
return
diff --git a/internal/web/job/xray_traffic_retry_test.go b/internal/web/job/xray_traffic_retry_test.go
index 5d52354a6..0404945d6 100644
--- a/internal/web/job/xray_traffic_retry_test.go
+++ b/internal/web/job/xray_traffic_retry_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "runtime"
"strings"
"sync/atomic"
"testing"
@@ -23,6 +24,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
"github.com/mhsanaei/3x-ui/v3/internal/web/global"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
@@ -303,3 +305,76 @@ func testXrayTrafficPollRetriesRolledBackSample(t *testing.T) {
})
}
}
+
+func TestXrayTrafficRetryDoesNotPublishOnlineStateAcrossCoreReplacement(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("uses a shell stub for the managed process")
+ }
+ cleanup, err := testpg.IsolatePackage("online_retry")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ dir := t.TempDir()
+ t.Setenv("XUI_DB_FOLDER", dir)
+ t.Setenv("XUI_BIN_FOLDER", dir)
+ t.Setenv("XUI_LOG_FOLDER", dir)
+ dbtest.InitDB(t, filepath.Join(dir, "x-ui.db"))
+ db := database.GetDB()
+ inbound := model.Inbound{Tag: "old-core", Protocol: model.VLESS, Enable: true, Settings: "{}"}
+ if err := db.Create(&inbound).Error; err != nil {
+ t.Fatal(err)
+ }
+ stub := "#!/bin/sh\nif [ \"$1\" = -version ]; then echo 'Xray 0.0.0 test'; exit 0; fi\nexec sleep 60\n"
+ if err := os.WriteFile(xray.GetBinaryPath(), []byte(stub), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ startCore := func(name string) *xray.Process {
+ t.Helper()
+ core := xray.NewTestProcess(&xray.Config{}, filepath.Join(dir, name+".json"))
+ if err := core.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = core.Stop() })
+ t.Cleanup(service.SetXrayProcessForTest(core))
+ return core
+ }
+ old := startCore("old")
+
+ const failure = "test:fail_pending_commit"
+ callback := db.Callback().Update()
+ if err := callback.Before("gorm:update").Register(failure, func(tx *gorm.DB) {
+ if tx.Statement.Table == "inbounds" {
+ _ = tx.AddError(errors.New("injected inbound traffic write failure"))
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ job := NewXrayTrafficJob()
+ sample, _, _ := job.pollTraffic(func() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
+ return []*xray.Traffic{{Tag: inbound.Tag, IsInbound: true, Up: 11}}, nil, nil
+ })
+ if sample != nil || job.pending == nil {
+ t.Fatal("the old core's sample was not retained for retry")
+ }
+ if err := callback.Remove(failure); err != nil {
+ t.Fatal(err)
+ }
+
+ replacement := startCore("replacement")
+ job.Run()
+ if job.pending != nil {
+ t.Fatal("the old core's sample should still commit its accounting delta")
+ }
+ if err := db.First(&inbound, inbound.Id).Error; err != nil {
+ t.Fatal(err)
+ }
+ if inbound.Up != 11 {
+ t.Fatalf("inbound up=%d, want committed delta 11", inbound.Up)
+ }
+ for _, core := range []*xray.Process{old, replacement} {
+ if emails, tags := core.LocalOnlineSnapshot(time.Now().UnixMilli(), 20_000); emails != nil || tags != nil {
+ t.Fatalf("retry published online state across core replacement: %v / %v", emails, tags)
+ }
+ }
+}
diff --git a/internal/web/middleware/database_work.go b/internal/web/middleware/database_work.go
new file mode 100644
index 000000000..182d7d6ed
--- /dev/null
+++ b/internal/web/middleware/database_work.go
@@ -0,0 +1,33 @@
+package middleware
+
+import (
+ "net/http"
+ "sync"
+
+ "github.com/gin-gonic/gin"
+)
+
+const databaseWorkKey = "database-work-release"
+
+// DatabaseWork prevents requests from using a database while its pool is replaced.
+func DatabaseWork(begin func() (func(), bool)) gin.HandlerFunc {
+ return func(c *gin.Context) {
+ end, ok := begin()
+ if !ok {
+ c.AbortWithStatus(http.StatusServiceUnavailable)
+ return
+ }
+ release := sync.OnceFunc(end)
+ c.Set(databaseWorkKey, release)
+ defer release()
+ c.Next()
+ }
+}
+
+// ReleaseDatabaseWork lets the authenticated restore handler drain other requests
+// without waiting for its own admission.
+func ReleaseDatabaseWork(c *gin.Context) {
+ if release, ok := c.Get(databaseWorkKey); ok {
+ release.(func())()
+ }
+}
diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go
index a54cb27d5..83d7b81ca 100644
--- a/internal/web/node_contract_test.go
+++ b/internal/web/node_contract_test.go
@@ -2,23 +2,28 @@ package web
import (
"context"
+ "encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"reflect"
+ "slices"
"strconv"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
"github.com/robfig/cron/v3"
+ "gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
"github.com/mhsanaei/3x-ui/v3/internal/web/global"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
@@ -135,6 +140,79 @@ func seedNodeTraffic(t *testing.T, emails ...string) {
const contractTag = "in-51001-tcp"
+func TestRemoteInboundCatalogScopeAndProjection(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("inbound_catalog")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ node := startContractNode(t)
+ db := database.GetDB()
+ var user model.User
+ if err := db.Order("id ASC").First(&user).Error; err != nil {
+ t.Fatal(err)
+ }
+ owned := masterInbound("owned", true, "private")
+ owned.UserId, owned.Listen = user.Id, "127.0.0.1"
+ other := masterInbound("different owner", true, "private-other")
+ other.UserId, other.Port, other.Tag = user.Id+1, 51002, "in-51002-tcp"
+ if err := db.Create([]*model.Inbound{owned, other}).Error; err != nil {
+ t.Fatal(err)
+ }
+ var reads, wide atomic.Int32
+ if err := db.Callback().Query().After("gorm:query").Register("test:catalog_projection", func(tx *gorm.DB) {
+ if tx.Statement.Table == "inbounds" {
+ reads.Add(1)
+ sql := tx.Statement.SQL.String()
+ if strings.Contains(sql, "*") || strings.Contains(sql, "settings") {
+ wide.Add(1)
+ }
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeNodeAdmin, model.ApiScopeNodeSync, model.ApiScopeMonitor} {
+ t.Run(scope, func(t *testing.T) {
+ node.masterWithToken(t, scope)
+ req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, node.srv.URL+"/panel/api/inbounds/catalog", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer contract-"+scope)
+ resp, err := node.srv.Client().Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if scope == model.ApiScopeMonitor {
+ if resp.StatusCode != http.StatusForbidden {
+ t.Fatalf("monitor catalog status=%d, want forbidden", resp.StatusCode)
+ }
+ return
+ }
+ var envelope struct {
+ Success bool
+ Obj []map[string]any
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&envelope); err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusOK || !envelope.Success || len(envelope.Obj) != 1 {
+ t.Fatalf("catalog status=%d envelope=%+v", resp.StatusCode, envelope)
+ }
+ got := envelope.Obj[0]
+ if len(got) != 6 || got["id"] != float64(owned.Id) || got["tag"] != owned.Tag ||
+ got["remark"] != owned.Remark || got["listen"] != owned.Listen ||
+ got["protocol"] != string(owned.Protocol) || got["port"] != float64(owned.Port) {
+ t.Fatalf("unexpected catalog fields: %v", got)
+ }
+ })
+ }
+ if reads.Load() != 3 || wide.Load() != 0 {
+ t.Fatalf("catalog queries = %d, wide queries = %d", reads.Load(), wide.Load())
+ }
+}
+
func masterInbound(remark string, enable bool, clients ...string) *model.Inbound {
entries := make([]string, 0, len(clients))
for i, email := range clients {
@@ -235,6 +313,35 @@ func TestMasterNodeContract(t *testing.T) {
t.Fatalf("node clients = %v, want c3 among them", got)
}
}},
+ {"AddClientGroup attaches one client to two inbounds", []string{"AddClientGroup"}, func() error {
+ second := masterInbound("grouped", false)
+ second.Tag, second.Port = "in-51002-tcp", 51002
+ if err := master.AddInbound(ctx, second); err != nil {
+ return err
+ }
+ client, err := json.Marshal(model.Client{
+ Email: "grouped", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000004", SubID: "s-grouped", Enable: true,
+ })
+ if err != nil {
+ return err
+ }
+ _, ack, err := master.AddClientGroup(ctx, []string{contractTag, second.Tag}, client)
+ if err == nil && !slices.Equal(ack, []bool{true, true}) {
+ return fmt.Errorf("acknowledged inbounds %v, want both", ack)
+ }
+ return err
+ }, func(t *testing.T) {
+ for _, tag := range []string{contractTag, "in-51002-tcp"} {
+ inbound, ok := nodeRow(t, tag)
+ if !ok {
+ t.Fatalf("node has no inbound %s", tag)
+ }
+ clients, err := (&service.InboundService{}).GetClients(inbound)
+ if err != nil || !slices.ContainsFunc(clients, func(c model.Client) bool { return c.Email == "grouped" }) {
+ t.Fatalf("node inbound %s received no grouped client, err=%v", tag, err)
+ }
+ }
+ }},
{"UpdateUser changes the client's limits", []string{"UpdateUser"}, func() error {
_, err := master.UpdateUser(ctx, masterInbound("updated", false), "c3", model.Client{
Email: "c3", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000003", SubID: "s-c3", Enable: true, TotalGB: 5 << 30,
@@ -421,14 +528,15 @@ func TestMasterNodeContract(t *testing.T) {
// Remote methods that never reach the node, or that this table must not run.
var remoteMethodsOutsideContract = map[string]string{
- "Name": "local label",
- "RecordAdoptedInbound": "local fingerprint bookkeeping",
- "AdoptInboundAlias": "local alias bookkeeping",
- "AdoptedInboundAliases": "local alias bookkeeping",
- "AdvancePushedInbound": "local fingerprint bookkeeping",
- "ForgetPushedInbound": "local fingerprint bookkeeping",
- "ForgetInbound": "local bookkeeping for an inbound the node no longer has",
- "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)",
+ "Name": "local label",
+ "RecordAdoptedInbound": "local fingerprint bookkeeping",
+ "AdoptInboundAlias": "local alias bookkeeping",
+ "AdoptedInboundAliases": "local alias bookkeeping",
+ "AdvancePushedInbound": "local fingerprint bookkeeping",
+ "PreparePushedInboundAdvance": "local fingerprint bookkeeping",
+ "ForgetPushedInbound": "local fingerprint bookkeeping",
+ "ForgetInbound": "local bookkeeping for an inbound the node no longer has",
+ "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)",
}
// A Remote method with no cell is how activeInbounds and bulkResetTraffic
diff --git a/internal/web/runtime/node_snapshot.go b/internal/web/runtime/node_snapshot.go
index ac82098a1..d9bac194b 100644
--- a/internal/web/runtime/node_snapshot.go
+++ b/internal/web/runtime/node_snapshot.go
@@ -2,7 +2,6 @@ package runtime
import (
"context"
- "errors"
"fmt"
"net/http"
"net/url"
@@ -101,8 +100,7 @@ func (r *Remote) FetchTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, er
r.snapshotRevision = ""
r.snapshotStructure = nil
r.snapshotClients = nil
- var status *remoteHTTPError
- if !errors.As(err, &status) || (status.code != http.StatusNotFound && status.code != http.StatusMethodNotAllowed) {
+ if !nodeEndpointUnsupported(err) {
return nil, err
}
r.snapshotUnsupportedUntil = time.Now().Add(5 * time.Minute)
diff --git a/internal/web/runtime/reconcile_skip_test.go b/internal/web/runtime/reconcile_skip_test.go
index 8e225320c..42fc4bd1e 100644
--- a/internal/web/runtime/reconcile_skip_test.go
+++ b/internal/web/runtime/reconcile_skip_test.go
@@ -17,6 +17,11 @@ import (
func TestReconcileInbound_SkipsUnchanged(t *testing.T) {
var pushes atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/panel/api/inbounds/add" {
+ pushes.Add(1)
+ _, _ = w.Write([]byte(`{"success":true,"obj":{"id":7,"tag":"in-1"}}`))
+ return
+ }
if r.Method == http.MethodPost && (strings.Contains(r.URL.Path, "/panel/api/inbounds/update/") ||
strings.Contains(r.URL.Path, "/panel/api/inbounds/add")) {
pushes.Add(1)
@@ -109,6 +114,9 @@ func newCountingNodeServer(t *testing.T, clientsResp string) (*httptest.Server,
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
+ case r.URL.Path == "/panel/api/inbounds/catalog":
+ _, _ = w.Write([]byte(`{"success":true,"obj":[]}`))
+ return
case strings.Contains(r.URL.Path, "/panel/api/inbounds/add"):
counts.adds.Add(1)
case strings.Contains(r.URL.Path, "/panel/api/inbounds/update/"):
diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go
index 8448cabc1..cfdf8c9a1 100644
--- a/internal/web/runtime/remote.go
+++ b/internal/web/runtime/remote.go
@@ -94,6 +94,8 @@ type Remote struct {
mu sync.RWMutex
remoteIDByTag map[string]int
adoptedAliases map[string]string
+ catalogFlight *inboundCatalogFlight
+ catalogVersion uint64
// pushedFP holds the fingerprint of the last inbound wire payload successfully
// pushed, keyed by panel-side tag, so reconcile can skip re-sending an
// unchanged inbound. Guarded by mu; dropped with the Remote on node config change.
@@ -123,12 +125,12 @@ type Remote struct {
}
type RemoteInboundOption struct {
- Id int `json:"id"`
- Tag string `json:"tag"`
- Remark string `json:"remark"`
- Listen string `json:"listen"`
- Protocol model.Protocol `json:"protocol"`
- Port int `json:"port"`
+ Id int `json:"id" example:"7"`
+ Tag string `json:"tag" example:"in-443"`
+ Remark string `json:"remark" example:"VLESS-443"`
+ Listen string `json:"listen" example:"127.0.0.1"`
+ Protocol model.Protocol `json:"protocol" example:"vless"`
+ Port int `json:"port" example:"443"`
}
func NewRemote(n *model.Node, r NodeEgressResolver) *Remote {
@@ -190,7 +192,7 @@ func (r *Remote) nodeSupports(ctx context.Context, capability string) (bool, err
caps := r.nodeCaps
r.mu.RUnlock()
if caps == nil {
- if err := r.refreshRemoteIDs(ctx); err != nil {
+ if _, err := r.loadInboundCatalog(ctx, ""); err != nil {
return false, err
}
r.mu.RLock()
@@ -444,7 +446,7 @@ func (r *Remote) resolveRemoteID(ctx context.Context, tag string) (int, error) {
if id, ok := r.cacheGetTag(tag); ok {
return id, nil
}
- if err := r.refreshRemoteIDs(ctx); err != nil {
+ if _, err := r.loadInboundCatalog(ctx, tag); err != nil {
return 0, err
}
if id, ok := r.cacheGetTag(tag); ok {
@@ -473,27 +475,37 @@ func stripNodeInboundTagPrefix(nodeID int, tag string) string {
// that lives on only one of the two panels: the node may carry the bare tag
// while the central panel stores the prefixed form, or vice versa.
func (r *Remote) cacheGetTag(tag string) (int, bool) {
- if id, ok := r.cacheGet(tag); ok {
- return id, true
- }
- prefix := nodeInboundTagPrefix(r.node.Id)
- if stripped, found := strings.CutPrefix(tag, prefix); found {
- return r.cacheGet(stripped)
- }
- return r.cacheGet(prefix + tag)
-}
-
-func (r *Remote) cacheGet(tag string) (int, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
- id, ok := r.remoteIDByTag[tag]
+ return r.cachedTagID(tag)
+}
+
+// cachedTagID requires r.mu to be held.
+func (r *Remote) cachedTagID(tag string) (int, bool) {
+ return lookupRemoteTag(r.remoteIDByTag, tag, nodeInboundTagPrefix(r.node.Id))
+}
+
+func lookupRemoteTag(ids map[string]int, tag, prefix string) (int, bool) {
+ if id, ok := ids[tag]; ok {
+ return id, true
+ }
+ if stripped, found := strings.CutPrefix(tag, prefix); found {
+ id, ok := ids[stripped]
+ return id, ok
+ }
+ id, ok := ids[prefix+tag]
return id, ok
}
func (r *Remote) cacheSet(tag string, id int) {
r.mu.Lock()
defer r.mu.Unlock()
+ previous, known := r.cachedTagID(tag)
r.remoteIDByTag[tag] = id
+ // Settings-only pushes do not supersede the catalog's ID mapping.
+ if !known || previous != id {
+ r.catalogVersion++
+ }
}
func (r *Remote) cacheDel(tag string) {
@@ -501,19 +513,11 @@ func (r *Remote) cacheDel(tag string) {
defer r.mu.Unlock()
delete(r.remoteIDByTag, tag)
delete(r.pushedFP, tag)
-}
-
-// forgetTag drops every tag form cacheGetTag would match, once the node reports
-// none of them, so the next resolve re-reads the node instead of a deleted id.
-func (r *Remote) forgetTag(tag string) {
- prefix := nodeInboundTagPrefix(r.node.Id)
- bare := strings.TrimPrefix(tag, prefix)
- r.cacheDel(bare)
- r.cacheDel(prefix + bare)
+ r.catalogVersion++
}
func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) {
- if err := r.refreshRemoteIDs(ctx); err != nil {
+ if _, err := r.loadInboundCatalog(ctx, ""); err != nil {
return nil, err
}
r.mu.RLock()
@@ -526,52 +530,8 @@ func (r *Remote) ListRemoteTags(ctx context.Context) ([]string, error) {
}
func (r *Remote) ListInboundOptions(ctx context.Context) ([]RemoteInboundOption, error) {
- env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
- if err != nil {
- return nil, err
- }
- list, err := json_util.DecodeCappedList[RemoteInboundOption](env.Obj, maxNodeInbounds)
- if err != nil {
- return nil, fmt.Errorf("decode inbound list: %w", err)
- }
- return list, nil
-}
-
-func (r *Remote) refreshRemoteIDs(ctx context.Context) error {
- env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
- if err != nil {
- return err
- }
- list, err := json_util.DecodeCappedList[struct {
- Id int `json:"id"`
- Tag string `json:"tag"`
- }](env.Obj, maxNodeInbounds)
- if err != nil {
- return fmt.Errorf("decode inbound list: %w", err)
- }
- next := make(map[string]int, len(list))
- for _, ib := range list {
- if ib.Tag == "" {
- continue
- }
- next[ib.Tag] = ib.Id
- }
- r.mu.Lock()
- // A rebuild sees only node-reported tags, so the adopted aliases must be
- // re-applied or a later op on an adopted inbound re-creates it as a duplicate.
- for centralTag, nodeTag := range r.adoptedAliases {
- // A tag the node reports itself is authoritative; the alias only fills
- // the gap left for a central tag the node knows under another name.
- if _, reported := next[centralTag]; reported {
- continue
- }
- if id, ok := next[nodeTag]; ok {
- next[centralTag] = id
- }
- }
- r.remoteIDByTag = next
- r.mu.Unlock()
- return nil
+ list, err := r.loadInboundCatalog(ctx, "")
+ return slices.Clone(list), err
}
func (r *Remote) AddInbound(ctx context.Context, ib *model.Inbound) error {
@@ -650,16 +610,17 @@ func (r *Remote) SetInboundSubSortIndex(ctx context.Context, ib *model.Inbound,
// whether a push actually happened. This turns a full-fleet reconcile from "send
// every inbound's full settings" into "send only what changed".
func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, existsOnNode bool) (bool, error) {
+ if !existsOnNode {
+ r.ForgetInbound(ib.Tag)
+ err := r.AddInbound(ctx, ib)
+ return err == nil, err
+ }
fp := wireFingerprint(wireInbound(ib, r.node.Id))
- if existsOnNode {
- r.mu.RLock()
- prev, ok := r.pushedFP[ib.Tag]
- r.mu.RUnlock()
- if ok && prev.fingerprint == fp {
- return false, nil
- }
- } else {
- r.forgetTag(ib.Tag)
+ r.mu.RLock()
+ prev, ok := r.pushedFP[ib.Tag]
+ r.mu.RUnlock()
+ if ok && prev.fingerprint == fp {
+ return false, nil
}
if err := r.UpdateInbound(ctx, ib, ib); err != nil {
return false, err
@@ -700,14 +661,22 @@ func (r *Remote) ForgetInbound(tag string) {
bare := strings.TrimPrefix(tag, prefix)
r.mu.Lock()
defer r.mu.Unlock()
- for _, t := range []string{bare, prefix + bare} {
- if alias, ok := r.adoptedAliases[t]; ok {
- delete(r.remoteIDByTag, alias)
- delete(r.adoptedAliases, t)
+ forget := func(t string) {
+ t = strings.TrimPrefix(t, prefix)
+ for _, form := range []string{t, prefix + t} {
+ delete(r.remoteIDByTag, form)
+ delete(r.pushedFP, form)
}
- delete(r.remoteIDByTag, t)
- delete(r.pushedFP, t)
}
+ for central, nodeTag := range r.adoptedAliases {
+ if strings.TrimPrefix(central, prefix) == bare || strings.TrimPrefix(nodeTag, prefix) == bare {
+ forget(central)
+ forget(nodeTag)
+ delete(r.adoptedAliases, central)
+ }
+ }
+ forget(bare)
+ r.catalogVersion++
}
// AdoptInboundAlias records a deployed alias without mutating either panel.
@@ -718,6 +687,7 @@ func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption
r.remoteIDByTag[remote.Tag] = remote.Id
r.remoteIDByTag[ib.Tag] = remote.Id
r.adoptedAliases[ib.Tag] = remote.Tag
+ r.catalogVersion++
r.pushedFP[ib.Tag] = state
r.mu.Unlock()
}
@@ -738,13 +708,21 @@ func (r *Remote) AdoptedInboundAliases() []string {
// node held the exact pre-edit state; otherwise the stale fingerprint stays and
// the next reconcile re-sends the full inbound.
func (r *Remote) AdvancePushedInbound(prevIb, ib *model.Inbound) {
+ r.PreparePushedInboundAdvance(prevIb, ib)()
+}
+
+// PreparePushedInboundAdvance keeps large settings blobs out of pending client batches.
+func (r *Remote) PreparePushedInboundAdvance(prevIb, ib *model.Inbound) func() {
+ tag := ib.Tag
prevFP := wireFingerprint(wireInbound(prevIb, r.node.Id))
next := stampPushedInbound(ib, r.node.Id)
- r.mu.Lock()
- if r.pushedFP[ib.Tag].fingerprint == prevFP {
- r.pushedFP[ib.Tag] = next
+ return func() {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.pushedFP[tag].fingerprint == prevFP {
+ r.pushedFP[tag] = next
+ }
}
- r.mu.Unlock()
}
type pushedInboundClient struct {
@@ -813,12 +791,59 @@ func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model.
if err != nil {
return ClientApplyResult{}, fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err)
}
- payload := map[string]any{
- "client": client,
- "inboundIds": []int{id},
+ return remoteClientApplyResult(r.postClientAdd(ctx, []int{id}, client))
+}
+
+// AddClientGroup returns the subset of tags acknowledged by one existing add RPC.
+func (r *Remote) AddClientGroup(ctx context.Context, tags []string, client json.RawMessage) (ClientApplyResult, []bool, error) {
+ var refreshErr error
+ for _, tag := range tags {
+ if id, ok := r.cacheGetTag(tag); !ok || id <= 0 {
+ _, refreshErr = r.loadInboundCatalog(ctx, "")
+ break
+ }
}
- env, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload)
- return remoteClientApplyResult(env, err)
+ ids := make([]int, 0, len(tags))
+ acknowledged := make([]bool, len(tags))
+ seen := make(map[int]struct{}, len(tags))
+ var missing []error
+ r.mu.RLock()
+ for i, tag := range tags {
+ id, ok := r.cachedTagID(tag)
+ if !ok || id <= 0 {
+ missing = append(missing, fmt.Errorf("%w: tag %q on node %s", errRemoteInboundNotFound, tag, r.node.Name))
+ continue
+ }
+ acknowledged[i] = true
+ if _, duplicate := seen[id]; !duplicate {
+ ids = append(ids, id)
+ seen[id] = struct{}{}
+ }
+ }
+ r.mu.RUnlock()
+ unresolved := errors.Join(refreshErr, errors.Join(missing...))
+ if len(ids) == 0 {
+ return ClientApplyResult{}, nil, unresolved
+ }
+ env, err := r.postClientAdd(ctx, ids, client)
+ if err != nil {
+ return ClientApplyResult{}, nil, errors.Join(err, unresolved)
+ }
+ var ack struct {
+ NodePending bool `json:"nodePending"`
+ }
+ // Legacy success replies omit obj or send null.
+ if len(env.Obj) != 0 {
+ if err := json.Unmarshal(env.Obj, &ack); err != nil {
+ return ClientApplyResult{}, nil, errors.Join(fmt.Errorf("decode grouped client add acknowledgment: %w", err), unresolved)
+ }
+ }
+ return ClientApplyResult{DownstreamPending: ack.NodePending}, acknowledged, unresolved
+}
+
+func (r *Remote) postClientAdd(ctx context.Context, ids []int, client any) (*envelope, error) {
+ payload := map[string]any{"client": client, "inboundIds": ids}
+ return r.do(ctx, http.MethodPost, "panel/api/clients/add", payload)
}
func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) (ClientApplyResult, error) {
@@ -979,11 +1004,11 @@ type TrafficSnapshot struct {
// the per-GUID endpoint — OnlineEmails is the fallback then.
OnlineTree map[string][]string
// ActiveInboundTree is the GUID-keyed subtree of inbound tags that carried
- // traffic within the node's online grace window. Empty when the node is an
- // old build without the endpoint; the master then falls back to email-only
- // online attribution for that node.
- ActiveInboundTree map[string][]string
- LastOnlineMap map[string]int64
+ // traffic within the node's online grace window. Missing keys carry no
+ // per-inbound attribution; an empty slice is a successful idle report.
+ ActiveInboundTree map[string][]string
+ LegacyInboundActivity bool
+ LastOnlineMap map[string]int64
// HostGroups carries the node's per-inbound host overrides (TLS/SNI/
// fingerprint), fetched only when the snapshot holds a not-yet-adopted tag.
HostGroups []*entity.HostGroup
@@ -1003,6 +1028,12 @@ func (r *Remote) FetchHostGroups(ctx context.Context) ([]*entity.HostGroup, erro
return groups, nil
}
+func nodeEndpointUnsupported(err error) bool {
+ var status *remoteHTTPError
+ return errors.As(err, &status) &&
+ (status.code == http.StatusNotFound || status.code == http.StatusMethodNotAllowed)
+}
+
func (r *Remote) fetchLegacyTrafficSnapshot(ctx context.Context) (*TrafficSnapshot, error) {
snap := &TrafficSnapshot{LastOnlineMap: map[string]int64{}}
@@ -1020,7 +1051,7 @@ func (r *Remote) fetchLegacyTrafficSnapshot(ctx context.Context) (*TrafficSnapsh
if err == nil && len(envTree.Obj) > 0 {
_ = decodeCappedValues(envTree.Obj, &snap.OnlineTree, maxNodeMapValues)
}
- if len(snap.OnlineTree) == 0 {
+ if nodeEndpointUnsupported(err) {
envOnlines, err := r.do(ctx, http.MethodPost, "panel/api/clients/onlines", nil)
if err != nil {
logger.Warning("remote", r.node.Name, "onlines fetch failed:", err)
@@ -1038,6 +1069,7 @@ func (r *Remote) fetchLegacyTrafficSnapshot(ctx context.Context) (*TrafficSnapsh
envActiveInbounds, err := r.do(ctx, http.MethodPost, "panel/api/clients/activeInbounds", nil)
if err != nil {
+ snap.LegacyInboundActivity = nodeEndpointUnsupported(err)
logger.Debugf("remote %s active inbounds fetch failed: %v", r.node.Name, err)
} else if len(envActiveInbounds.Obj) > 0 {
_ = decodeCappedValues(envActiveInbounds.Obj, &snap.ActiveInboundTree, maxNodeMapValues)
diff --git a/internal/web/runtime/remote_inbound_catalog.go b/internal/web/runtime/remote_inbound_catalog.go
new file mode 100644
index 000000000..5531cc031
--- /dev/null
+++ b/internal/web/runtime/remote_inbound_catalog.go
@@ -0,0 +1,153 @@
+package runtime
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
+)
+
+type inboundCatalogFlight struct {
+ done chan struct{}
+ cancel context.CancelFunc
+ waiters int
+ options []RemoteInboundOption
+ err error
+}
+
+// loadInboundCatalog shares a refresh across callers. A lookup rechecks its cache
+// under the same lock used to register the flight.
+func (r *Remote) loadInboundCatalog(ctx context.Context, tag string) ([]RemoteInboundOption, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ r.mu.Lock()
+ if tag != "" {
+ if _, ok := lookupRemoteTag(r.remoteIDByTag, tag, nodeInboundTagPrefix(r.node.Id)); ok {
+ r.mu.Unlock()
+ return nil, nil
+ }
+ }
+ flight := r.catalogFlight
+ if flight == nil {
+ // The RPC belongs to the group. Each caller waits on its own context.
+ requestCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), remoteHTTPTimeout)
+ flight = &inboundCatalogFlight{done: make(chan struct{}), cancel: cancel}
+ r.catalogFlight = flight
+ go r.refreshInboundCatalog(requestCtx, flight, r.catalogVersion)
+ }
+ flight.waiters++
+ r.mu.Unlock()
+
+ select {
+ case <-flight.done:
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ return flight.options, flight.err
+ case <-ctx.Done():
+ r.mu.Lock()
+ flight.waiters--
+ if r.catalogFlight == flight && flight.waiters == 0 {
+ r.catalogFlight = nil
+ flight.cancel()
+ }
+ r.mu.Unlock()
+ return nil, ctx.Err()
+ }
+}
+
+func (r *Remote) refreshInboundCatalog(ctx context.Context, flight *inboundCatalogFlight, version uint64) {
+ defer flight.cancel()
+ defer close(flight.done)
+ for attempt := 0; ; attempt++ {
+ options, ids, err := r.fetchInboundCatalog(ctx)
+ r.mu.Lock()
+ if r.catalogFlight != flight {
+ r.mu.Unlock()
+ return
+ }
+ if err == nil && version != r.catalogVersion {
+ // An inbound mutation completed during the read. Retry once within
+ // the same budget, so a stale response cannot revive an old ID.
+ if attempt == 0 {
+ version = r.catalogVersion
+ r.mu.Unlock()
+ continue
+ }
+ err = errors.New("remote inbound catalog changed during refresh")
+ }
+ if err == nil {
+ r.installInboundCatalog(ids)
+ flight.options = options
+ }
+ flight.err = err
+ r.catalogFlight = nil
+ r.mu.Unlock()
+ return
+ }
+}
+
+func (r *Remote) fetchInboundCatalog(ctx context.Context) (list []RemoteInboundOption, ids map[string]int, err error) {
+ // Fetching runs on the shared worker, outside each caller's panic boundary.
+ defer func() {
+ if cause := recover(); cause != nil {
+ list, ids, err = nil, nil, fmt.Errorf("fetch inbound catalog: panic: %v", cause)
+ }
+ }()
+ env, err := r.do(ctx, http.MethodGet, "panel/api/inbounds/catalog", nil)
+ var status *remoteHTTPError
+ legacy := errors.As(err, &status) && (status.code == http.StatusNotFound || status.code == http.StatusMethodNotAllowed)
+ if legacy {
+ env, err = r.do(ctx, http.MethodGet, "panel/api/inbounds/list", nil)
+ }
+ if err != nil {
+ return nil, nil, err
+ }
+ if !legacy && !bytes.HasPrefix(bytes.TrimSpace(env.Obj), []byte("[")) {
+ return nil, nil, errors.New("decode inbound list: catalog must be an array")
+ }
+ list, err = json_util.DecodeCappedList[RemoteInboundOption](env.Obj, maxNodeInbounds)
+ if err != nil {
+ return nil, nil, fmt.Errorf("decode inbound list: %w", err)
+ }
+ ids = make(map[string]int, len(list))
+ for _, ib := range list {
+ if ib.Id <= 0 || ib.Tag == "" {
+ return nil, nil, errors.New("decode inbound list: entry missing a valid ID or tag")
+ }
+ if _, exists := ids[ib.Tag]; exists {
+ return nil, nil, errors.New("decode inbound list: duplicate tag")
+ }
+ ids[ib.Tag] = ib.Id
+ }
+ return list, ids, nil
+}
+
+// installInboundCatalog runs with mu held. Explicit node tags outrank inferred aliases.
+func (r *Remote) installInboundCatalog(ids map[string]int) {
+ prefix := nodeInboundTagPrefix(r.node.Id)
+ aliases := make(map[string]int, len(r.adoptedAliases))
+ for central, nodeTag := range r.adoptedAliases {
+ if _, exists := lookupRemoteTag(ids, central, prefix); exists {
+ continue
+ }
+ if id, ok := lookupRemoteTag(ids, nodeTag, prefix); ok {
+ aliases[central] = id
+ }
+ }
+ for tag, id := range aliases {
+ ids[tag] = id
+ }
+ for tag := range r.pushedFP {
+ oldID, known := lookupRemoteTag(r.remoteIDByTag, tag, prefix)
+ nextID, present := lookupRemoteTag(ids, tag, prefix)
+ if !present || known && nextID != oldID {
+ delete(r.pushedFP, tag)
+ }
+ }
+ r.remoteIDByTag = ids
+}
diff --git a/internal/web/runtime/remote_inbound_catalog_test.go b/internal/web/runtime/remote_inbound_catalog_test.go
new file mode 100644
index 000000000..b34e01edd
--- /dev/null
+++ b/internal/web/runtime/remote_inbound_catalog_test.go
@@ -0,0 +1,334 @@
+package runtime
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+type observedCatalogContext struct {
+ context.Context
+ waiting chan struct{}
+ once sync.Once
+}
+
+func (ctx *observedCatalogContext) Done() <-chan struct{} {
+ ctx.once.Do(func() { close(ctx.waiting) })
+ return ctx.Context.Done()
+}
+
+func TestRemoteInboundCatalogCoalescesMissesAcrossCallerCancellation(t *testing.T) {
+ var modern, legacy atomic.Int32
+ started := make(chan struct{})
+ release := make(chan struct{})
+ var first, cleanup sync.Once
+ unblock := func() { cleanup.Do(func() { close(release) }) }
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch req.URL.Path {
+ case "/panel/api/inbounds/catalog":
+ modern.Add(1)
+ case "/panel/api/inbounds/list":
+ legacy.Add(1)
+ default:
+ http.NotFound(w, req)
+ return
+ }
+ first.Do(func() { close(started) })
+ select {
+ case <-release:
+ fmt.Fprint(w, `{"success":true,"obj":[{"id":43,"tag":"in-443"}]}`)
+ case <-req.Context().Done():
+ }
+ }))
+ t.Cleanup(srv.Close)
+ t.Cleanup(unblock)
+ r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
+ ctx, finish := context.WithTimeout(context.Background(), 4*time.Second)
+ defer finish()
+ leaderCtx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ leader := make(chan error, 1)
+ go func() {
+ _, err := r.resolveRemoteID(leaderCtx, "in-443")
+ leader <- err
+ }()
+ select {
+ case <-started:
+ case <-ctx.Done():
+ t.Fatal("catalog request never started")
+ }
+ const followers = 6
+ results := make(chan error, followers)
+ tag := fmt.Sprintf("n%d-in-443", r.node.Id)
+ for range followers {
+ waiter := &observedCatalogContext{Context: ctx, waiting: make(chan struct{})}
+ go func() {
+ id, err := r.resolveRemoteID(waiter, tag)
+ if err == nil && id != 43 {
+ err = fmt.Errorf("resolved ID = %d, want 43", id)
+ }
+ results <- err
+ }()
+ select {
+ case <-waiter.waiting:
+ case <-ctx.Done():
+ t.Fatal("follower did not join the lookup")
+ }
+ }
+ cancel()
+ select {
+ case err := <-leader:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("canceled caller got %v", err)
+ }
+ case <-ctx.Done():
+ t.Fatal("canceled caller still waits on the catalog")
+ }
+ unblock()
+ for range followers {
+ select {
+ case err := <-results:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-ctx.Done():
+ t.Fatal("follower never received the catalog")
+ }
+ }
+ if id, err := r.resolveRemoteID(ctx, tag); err != nil || id != 43 {
+ t.Fatalf("warm cache = (%d, %v), want 43", id, err)
+ }
+ if modern.Load() != 1 || legacy.Load() != 0 {
+ t.Fatalf("catalog requests = %d, full list requests = %d; want 1 and 0", modern.Load(), legacy.Load())
+ }
+}
+
+func TestRemoteInboundCatalogLegacyFallbackSeedsCache(t *testing.T) {
+ for _, status := range []int{http.StatusNotFound, http.StatusMethodNotAllowed} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ var modern, legacy atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch req.URL.Path {
+ case "/panel/api/inbounds/catalog":
+ modern.Add(1)
+ w.WriteHeader(status)
+ case "/panel/api/inbounds/list":
+ legacy.Add(1)
+ fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"test","port":443,"settings":"large"}]}`)
+ default:
+ http.NotFound(w, req)
+ }
+ }))
+ t.Cleanup(srv.Close)
+ r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
+ ctx := context.Background()
+ options, err := r.ListInboundOptions(ctx)
+ if err != nil || len(options) != 1 || options[0].Port != 443 {
+ t.Fatalf("legacy options=%+v err=%v", options, err)
+ }
+ if id, err := r.resolveRemoteID(ctx, "test"); err != nil || id != 7 {
+ t.Fatalf("legacy ID = %d, err=%v", id, err)
+ }
+ if modern.Load() != 1 || legacy.Load() != 1 {
+ t.Fatalf("catalog requests=%d full list requests=%d, want 1 each", modern.Load(), legacy.Load())
+ }
+ })
+ }
+}
+
+func TestRemoteInboundCatalogSurvivesSettingsOnlyPushes(t *testing.T) {
+ var reads atomic.Int32
+ started := make(chan chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch req.URL.Path {
+ case "/panel/api/inbounds/catalog":
+ reads.Add(1)
+ resume := make(chan struct{})
+ select {
+ case started <- resume:
+ case <-req.Context().Done():
+ return
+ }
+ select {
+ case <-resume:
+ fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"warm"},{"id":8,"tag":"cold"}]}`)
+ case <-req.Context().Done():
+ }
+ case "/panel/api/inbounds/update/7":
+ fmt.Fprint(w, `{"success":true}`)
+ default:
+ http.NotFound(w, req)
+ }
+ }))
+ t.Cleanup(srv.Close)
+ r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
+ r.cacheSet("warm", 7)
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ done := make(chan error, 1)
+ go func() {
+ id, err := r.resolveRemoteID(ctx, "cold")
+ if err == nil && id != 8 {
+ err = fmt.Errorf("cold lookup resolved ID %d, want 8", id)
+ }
+ done <- err
+ }()
+
+ for {
+ select {
+ case resume := <-started:
+ before := &model.Inbound{Tag: "warm", Protocol: model.VLESS, Settings: `{"clients":[]}`}
+ after := *before
+ after.Settings = fmt.Sprintf(`{"clients":[{"email":"client-%d@example.test"}]}`, reads.Load())
+ err := r.UpdateInbound(ctx, before, &after)
+ close(resume)
+ if err != nil {
+ t.Fatal(err)
+ }
+ case err := <-done:
+ if err != nil || reads.Load() != 1 {
+ t.Fatalf("lookup during settings-only updates: reads=%d, err=%v", reads.Load(), err)
+ }
+ return
+ case <-ctx.Done():
+ t.Fatal(ctx.Err())
+ }
+ }
+}
+
+func TestRemoteInboundCatalogDoesNotRestoreDeletedAlias(t *testing.T) {
+ var gets atomic.Int32
+ started := make(chan struct{})
+ release := make(chan struct{})
+ var once sync.Once
+ unblock := func() { once.Do(func() { close(release) }) }
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch req.URL.Path {
+ case "/panel/api/inbounds/catalog", "/panel/api/inbounds/list":
+ if gets.Add(1) == 1 {
+ close(started)
+ <-release
+ fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"adopted"}]}`)
+ } else {
+ fmt.Fprint(w, `{"success":true,"obj":[]}`)
+ }
+ case "/panel/api/inbounds/del/7":
+ fmt.Fprint(w, `{"success":true}`)
+ default:
+ http.NotFound(w, req)
+ }
+ }))
+ t.Cleanup(srv.Close)
+ t.Cleanup(unblock)
+ r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
+ ib := &model.Inbound{Tag: "central", Protocol: model.VLESS}
+ r.AdoptInboundAlias(ib, RemoteInboundOption{Id: 7, Tag: "adopted"})
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ done := make(chan error, 1)
+ go func() {
+ options, err := r.ListInboundOptions(ctx)
+ if err == nil && len(options) != 0 {
+ err = fmt.Errorf("stale catalog returned: %+v", options)
+ }
+ done <- err
+ }()
+ select {
+ case <-started:
+ case <-ctx.Done():
+ t.Fatal("catalog never started")
+ }
+ if err := r.DelInbound(ctx, &model.Inbound{Tag: "adopted"}); err != nil {
+ t.Fatal(err)
+ }
+ unblock()
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := r.cacheGetTag(ib.Tag); ok || gets.Load() != 2 {
+ t.Fatalf("deleted alias still cached or stale read was not retried: gets=%d", gets.Load())
+ }
+}
+
+func TestRemoteInboundCatalogRefreshDetectsRecreatedInbound(t *testing.T) {
+ var remoteID, pushedID atomic.Int32
+ remoteID.Store(7)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch req.URL.Path {
+ case "/panel/api/inbounds/catalog":
+ fmt.Fprintf(w, `{"success":true,"obj":[{"id":%d,"tag":"in-443"}]}`, remoteID.Load())
+ case "/panel/api/inbounds/update/7":
+ pushedID.Store(7)
+ fmt.Fprint(w, `{"success":true}`)
+ case "/panel/api/inbounds/update/8":
+ pushedID.Store(8)
+ fmt.Fprint(w, `{"success":true}`)
+ default:
+ http.NotFound(w, req)
+ }
+ }))
+ t.Cleanup(srv.Close)
+ r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
+ ib := &model.Inbound{Tag: "in-443", Protocol: model.VLESS, Port: 443}
+ ctx := context.Background()
+ if err := r.UpdateInbound(ctx, ib, ib); err != nil || pushedID.Load() != 7 {
+ t.Fatalf("first update used ID %d, err=%v", pushedID.Load(), err)
+ }
+ remoteID.Store(8)
+ if _, err := r.ListInboundOptions(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if pushed, err := r.ReconcileInbound(ctx, ib, true); err != nil || !pushed || pushedID.Load() != 8 {
+ t.Fatalf("reconcile after recreation: pushed=%t, ID=%d, err=%v", pushed, pushedID.Load(), err)
+ }
+}
+
+func TestRemoteInboundCatalogCancelsRPCWhenLastWaiterLeaves(t *testing.T) {
+ var calls atomic.Int32
+ started, canceled := make(chan struct{}), make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if calls.Add(1) == 1 {
+ close(started)
+ <-req.Context().Done()
+ close(canceled)
+ return
+ }
+ fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"valid"}]}`)
+ }))
+ t.Cleanup(srv.Close)
+ r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
+ ctx, finish := context.WithTimeout(context.Background(), 3*time.Second)
+ defer finish()
+ lookup, cancel := context.WithCancel(ctx)
+ defer cancel()
+ done := make(chan error, 1)
+ go func() {
+ _, err := r.resolveRemoteID(lookup, "valid")
+ done <- err
+ }()
+ select {
+ case <-started:
+ case <-ctx.Done():
+ t.Fatal("catalog never started")
+ }
+ cancel()
+ if err := <-done; !errors.Is(err, context.Canceled) {
+ t.Fatalf("lookup error=%v, want canceled", err)
+ }
+ select {
+ case <-canceled:
+ case <-ctx.Done():
+ t.Fatal("abandoned catalog request was not canceled")
+ }
+ if id, err := r.resolveRemoteID(ctx, "valid"); err != nil || id != 7 || calls.Load() != 2 {
+ t.Fatalf("fresh lookup ID=%d err=%v calls=%d", id, err, calls.Load())
+ }
+}
diff --git a/internal/web/runtime/remote_inbound_lookup_test.go b/internal/web/runtime/remote_inbound_lookup_test.go
index a0504029b..05441f24f 100644
--- a/internal/web/runtime/remote_inbound_lookup_test.go
+++ b/internal/web/runtime/remote_inbound_lookup_test.go
@@ -23,11 +23,13 @@ func TestInboundLookupFailureDoesNotAcknowledgeMutation(t *testing.T) {
{"unavailable", http.StatusServiceUnavailable, "", "HTTP 503"},
{"application error", http.StatusOK, `{"success":false,"msg":"node database unavailable"}`, "node database unavailable"},
{"invalid catalog", http.StatusOK, `{"success":true,"obj":{"id":4}}`, "decode inbound list"},
+ {"missing catalog", http.StatusOK, `{"success":true}`, "decode inbound list"},
+ {"invalid row", http.StatusOK, `{"success":true,"obj":[{"id":0,"tag":"in-lookup"}]}`, "decode inbound list"},
} {
t.Run(tc.name, func(t *testing.T) {
var mutations atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- if req.Method != http.MethodGet || !strings.HasSuffix(req.URL.Path, "/panel/api/inbounds/list") {
+ if req.Method != http.MethodGet || !strings.HasSuffix(req.URL.Path, "/panel/api/inbounds/catalog") {
mutations.Add(1)
_, _ = w.Write([]byte(`{"success":true}`))
return
@@ -45,7 +47,7 @@ func TestInboundLookupFailureDoesNotAcknowledgeMutation(t *testing.T) {
t.Errorf("UpdateInbound error = %v, want %q", err, tc.want)
}
if got := mutations.Load(); got != 0 {
- t.Errorf("mutation requests after failed lookup = %d, want 0", got)
+ t.Errorf("mutation or fallback requests after failed lookup = %d, want 0", got)
}
})
}
diff --git a/internal/web/runtime/remote_reset_test.go b/internal/web/runtime/remote_reset_test.go
index 27159e3e6..722d29bff 100644
--- a/internal/web/runtime/remote_reset_test.go
+++ b/internal/web/runtime/remote_reset_test.go
@@ -3,6 +3,7 @@ package runtime
import (
"context"
"encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
"slices"
@@ -62,7 +63,7 @@ func TestRemoteResetInboundTrafficUnknownTagErrors(t *testing.T) {
var resetPosted bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
- if req.URL.Path == "/panel/api/inbounds/list" {
+ if req.URL.Path == "/panel/api/inbounds/catalog" {
_, _ = w.Write([]byte(`{"success":true,"msg":"ok","obj":[]}`))
return
}
@@ -73,8 +74,8 @@ func TestRemoteResetInboundTrafficUnknownTagErrors(t *testing.T) {
r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil)
ib := &model.Inbound{Id: 42, Tag: "n1-in-443"}
- if err := r.ResetInboundTraffic(context.Background(), ib); err == nil {
- t.Fatal("ResetInboundTraffic error = nil, want unknown-tag error")
+ if err := r.ResetInboundTraffic(context.Background(), ib); !errors.Is(err, errRemoteInboundNotFound) {
+ t.Fatalf("ResetInboundTraffic error = %v, want unknown-tag error", err)
}
if resetPosted {
t.Fatal("reset request posted to node despite an unresolved tag")
diff --git a/internal/web/runtime/remote_snapshot_test.go b/internal/web/runtime/remote_snapshot_test.go
index b3cddb33b..87e6ba6eb 100644
--- a/internal/web/runtime/remote_snapshot_test.go
+++ b/internal/web/runtime/remote_snapshot_test.go
@@ -194,3 +194,43 @@ func TestRemoteSnapshotRejectsTruncatedUnchangedCounters(t *testing.T) {
t.Fatalf("partial counters could reach full merge: %+v %v", partial, err)
}
}
+
+func TestLegacySnapshotOnlyUnsupportedActivityEnablesNodeWideAttribution(t *testing.T) {
+ for _, code := range []int{200, 404, 405, 403, 500} {
+ t.Run(fmt.Sprint(code), func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch req.URL.Path {
+ case "/panel/api/inbounds/list", "/panel/api/clients/onlines":
+ fmt.Fprint(w, `{"success":true,"obj":[]}`)
+ case "/panel/api/clients/onlinesByGuid":
+ http.NotFound(w, req)
+ case "/panel/api/clients/activeInbounds":
+ if code == http.StatusOK {
+ fmt.Fprint(w, `{"success":true,"obj":{"online-guid":[],"legacy-descendant":null}}`)
+ } else {
+ w.WriteHeader(code)
+ }
+ default:
+ fmt.Fprint(w, `{"success":true,"obj":{}}`)
+ }
+ }))
+ defer server.Close()
+ remote := NewRemote(nodeForPlainServer(t, server, "verify", "token"), nil)
+ snapshot, err := remote.FetchTrafficSnapshot(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := code == 404 || code == 405; snapshot.LegacyInboundActivity != want {
+ t.Fatalf("legacy activity=%v, want %v", snapshot.LegacyInboundActivity, want)
+ }
+ if code == http.StatusOK {
+ if idle := snapshot.ActiveInboundTree["online-guid"]; idle == nil || len(idle) != 0 {
+ t.Fatalf("lost successful idle sample: %v", snapshot.ActiveInboundTree)
+ }
+ if legacy, present := snapshot.ActiveInboundTree["legacy-descendant"]; !present || legacy != nil {
+ t.Fatalf("lost confirmed legacy descendant: %v", snapshot.ActiveInboundTree)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/web/service/client.go b/internal/web/service/client.go
index 4fd2625e1..64fb9b072 100644
--- a/internal/web/service/client.go
+++ b/internal/web/service/client.go
@@ -68,10 +68,11 @@ type ClientService struct {
var ErrClientNotInInbound = errors.New("client not found in inbound")
type ClientCreatePayload struct {
- Client model.Client `json:"client"`
- InboundIds []int `json:"inboundIds"`
- LimitHwid int `json:"-"`
- Traffic *ClientPortableTraffic `json:"traffic,omitempty"`
+ Client model.Client `json:"client"`
+ InboundIds []int `json:"inboundIds"`
+ LimitHwid int `json:"-"`
+ Traffic *ClientPortableTraffic `json:"traffic,omitempty"`
+ SubIDPrefix string `json:"subIdPrefix,omitempty"`
}
const sqlInChunk = 400
@@ -83,9 +84,10 @@ type clientPayloadWithHwid struct {
func (p *ClientCreatePayload) UnmarshalJSON(data []byte) error {
var raw struct {
- Client json.RawMessage `json:"client"`
- InboundIds []int `json:"inboundIds"`
- Traffic *ClientPortableTraffic `json:"traffic"`
+ Client json.RawMessage `json:"client"`
+ InboundIds []int `json:"inboundIds"`
+ Traffic *ClientPortableTraffic `json:"traffic"`
+ SubIDPrefix string `json:"subIdPrefix"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
@@ -100,6 +102,7 @@ func (p *ClientCreatePayload) UnmarshalJSON(data []byte) error {
p.InboundIds = raw.InboundIds
p.LimitHwid = withHwid.LimitHwid
p.Traffic = raw.Traffic
+ p.SubIDPrefix = raw.SubIDPrefix
// Omit enable → true (legacy API); explicit false is preserved (#6478).
var keys map[string]json.RawMessage
if len(raw.Client) > 0 && json.Unmarshal(raw.Client, &keys) == nil {
@@ -112,12 +115,14 @@ func (p *ClientCreatePayload) UnmarshalJSON(data []byte) error {
func (p ClientCreatePayload) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
- Client clientPayloadWithHwid `json:"client"`
- InboundIds []int `json:"inboundIds"`
- Traffic *ClientPortableTraffic `json:"traffic,omitempty"`
+ Client clientPayloadWithHwid `json:"client"`
+ InboundIds []int `json:"inboundIds"`
+ Traffic *ClientPortableTraffic `json:"traffic,omitempty"`
+ SubIDPrefix string `json:"subIdPrefix,omitempty"`
}{
- Client: clientPayloadWithHwid{Client: p.Client, LimitHwid: p.LimitHwid},
- InboundIds: p.InboundIds,
- Traffic: p.Traffic,
+ Client: clientPayloadWithHwid{Client: p.Client, LimitHwid: p.LimitHwid},
+ InboundIds: p.InboundIds,
+ Traffic: p.Traffic,
+ SubIDPrefix: p.SubIDPrefix,
})
}
diff --git a/internal/web/service/client_attach_selection.go b/internal/web/service/client_attach_selection.go
index a02179f11..5b5654f02 100644
--- a/internal/web/service/client_attach_selection.go
+++ b/internal/web/service/client_attach_selection.go
@@ -148,7 +148,7 @@ func filteredAttachCandidates(q *gorm.DB, sourceID int, search, group string) *g
return q
}
-func writeAttachID(h hash.Hash, id int) {
+func writeClientScopeID(h hash.Hash, id int) {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], uint64(id))
_, _ = h.Write(buf[:])
@@ -156,10 +156,10 @@ func writeAttachID(h hash.Hash, id int) {
func attachScopeHash(sourceID int, targets []int) hash.Hash {
h := sha256.New()
- writeAttachID(h, sourceID)
- writeAttachID(h, len(targets))
+ writeClientScopeID(h, sourceID)
+ writeClientScopeID(h, len(targets))
for _, id := range targets {
- writeAttachID(h, id)
+ writeClientScopeID(h, id)
}
return h
}
@@ -201,14 +201,14 @@ func (s *ClientService) ListAttachCandidates(ctx context.Context, p AttachCandid
if err := rows.Scan(&id); err != nil {
return nil, err
}
- writeAttachID(h, id)
+ writeClientScopeID(h, id)
resp.Eligible++
resp.MaxID = id
}
if err := rows.Err(); err != nil {
return nil, err
}
- writeAttachID(h, resp.MaxID)
+ writeClientScopeID(h, resp.MaxID)
resp.ScopeToken = strconv.Itoa(resp.MaxID) + "." + hex.EncodeToString(h.Sum(nil))
return resp, nil
}
@@ -294,14 +294,14 @@ func (s *ClientService) BulkAttachSelection(ctx context.Context, inboundSvc *Inb
}
records = eligibleRecords[:0]
for _, record := range eligibleRecords {
- writeAttachID(h, record.Id)
+ writeClientScopeID(h, record.Id)
if _, skip := excluded[record.Id]; skip {
delete(excluded, record.Id)
continue
}
records = append(records, record)
}
- writeAttachID(h, maxID)
+ writeClientScopeID(h, maxID)
if len(excluded) > 0 || hex.EncodeToString(h.Sum(nil)) != digest {
return nil, false, stale
}
diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go
index 585689177..98be6dd81 100644
--- a/internal/web/service/client_bulk.go
+++ b/internal/web/service/client_bulk.go
@@ -1,8 +1,11 @@
package service
import (
+ "cmp"
"context"
+ "crypto/rand"
"encoding/json"
+ "errors"
"fmt"
"slices"
"strings"
@@ -300,6 +303,7 @@ type inboundApplyOutcome struct {
// ExternalLinks contains row counts only for append requests.
type BulkAdjustResult struct {
ClientNodeApplyResponse
+ SkippedCount int `json:"skippedCount,omitempty" example:"0"`
Adjusted int `json:"adjusted" example:"2"`
Skipped []BulkAdjustReport `json:"skipped,omitempty" example:"[]"`
ExternalLinks *BulkExternalLinksResult `json:"externalLinks,omitempty"`
@@ -322,6 +326,8 @@ type bulkAdjustEntry struct {
// client. The vision values are the only positive flows xray accepts.
const bulkFlowClear = "none"
+var errGroupAdjustLimitsChanged = errors.New("client limits changed during the group adjustment")
+
// bulkFlowAllowed whitelists the flow directives BulkAdjust accepts. Anything
// outside this set is treated as "" (leave flow untouched) so a malformed or
// hostile value can never be injected into a client's settings. The dropdown in
@@ -345,6 +351,16 @@ var bulkFlowAllowed = map[string]struct{}{
// settings JSON is parsed and written exactly once regardless of how
// many target emails it contains.
func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64, flow string, limitHwid *int, adTag string) (BulkAdjustResult, bool, error) {
+ return s.bulkAdjust(inboundSvc, emails, nil, addDays, addBytes, flow, limitHwid, adTag)
+}
+
+func (s *ClientService) BulkAdjustGroup(inboundSvc *InboundService, scope *GroupBulkScope, addDays int, addBytes int64, flow string, limitHwid *int, adTag string) (BulkAdjustResult, bool, error) {
+ operation := *scope
+ operation.committedAdjustments = make(map[string]bool)
+ return s.bulkAdjust(inboundSvc, scope.emails, &operation, addDays, addBytes, flow, limitHwid, adTag)
+}
+
+func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string, scope *GroupBulkScope, addDays int, addBytes int64, flow string, limitHwid *int, adTag string) (BulkAdjustResult, bool, error) {
result := BulkAdjustResult{}
if len(emails) == 0 {
return result, false, nil
@@ -378,7 +394,7 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
db := database.GetDB()
- recordsByEmail, err := clientRecordsByEmail(db, cleanEmails)
+ recordsByEmail, err := scope.records(db, cleanEmails, false)
if err != nil {
return result, false, err
}
@@ -386,7 +402,7 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
skippedReasons := map[string]string{}
for _, email := range cleanEmails {
if _, ok := recordsByEmail[email]; !ok {
- skippedReasons[email] = "client not found"
+ skippedReasons[email] = scope.skipReason()
}
}
@@ -482,9 +498,10 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
adTagHonored := map[string]bool{}
adTagIneligible := map[string]bool{}
execFailed := map[string]bool{}
+ wasDisabledDepleted := map[string]struct{}{}
adjustIds := sortedInboundIds(emailsByInbound)
adjustResults, adjustPanics := fanoutClientInboundResults(adjustIds, inboundFanoutConcurrency, func(i int) bulkInboundAdjustResult {
- return s.bulkAdjustInboundClients(inboundSvc, adjustIds[i], emailsByInbound[adjustIds[i]], plan, flow, adTag)
+ return s.bulkAdjustInboundClients(inboundSvc, adjustIds[i], emailsByInbound[adjustIds[i]], plan, scope, flow, adTag)
})
for i, ibRes := range adjustResults {
if adjustPanics[i] != nil {
@@ -500,6 +517,9 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
if ibRes.needRestart {
needRestart = true
}
+ for _, email := range ibRes.disabledDepleted {
+ wasDisabledDepleted[email] = struct{}{}
+ }
for email := range ibRes.flowHonored {
flowHonored[email] = true
}
@@ -523,21 +543,16 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
cond, condArgs := depletedCond(db)
candidateEmails := make([]string, 0, len(plan))
for email, entry := range plan {
- if entry.applyExpiry || entry.applyTotal {
+ if (entry.applyExpiry || entry.applyTotal) && (scope == nil || !scope.committedAdjustments[email]) {
candidateEmails = append(candidateEmails, email)
}
}
- wasDisabledDepleted := map[string]struct{}{}
- for _, batch := range chunkStrings(candidateEmails, sqlInChunk) {
- var rows []string
- if err := db.Model(xray.ClientTraffic{}).
- Where(cond+" AND enable = ? AND email IN ?", append(append([]any{}, condArgs...), false, batch)...).
- Pluck("email", &rows).Error; err != nil {
- return result, needRestart, err
- }
- for _, e := range rows {
- wasDisabledDepleted[e] = struct{}{}
- }
+ disabled, err := bulkAdjustDisabledDepleted(db, candidateEmails, cond, condArgs)
+ if err != nil {
+ return result, needRestart, err
+ }
+ for _, email := range disabled {
+ wasDisabledDepleted[email] = struct{}{}
}
wantAdTag := ""
@@ -546,10 +561,13 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
}
adjusted := map[string]struct{}{}
- for email, entry := range plan {
- if execFailed[email] {
- continue
+ if scope != nil {
+ for email := range scope.committedAdjustments {
+ adjusted[email] = struct{}{}
}
+ }
+ apply := func(tx *gorm.DB, email string) (bool, error) {
+ entry := plan[email]
updates := map[string]any{}
if entry.applyExpiry {
updates["expiry_time"] = entry.newExpiry
@@ -557,35 +575,87 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
if entry.applyTotal {
updates["total"] = entry.newTotal
}
- if len(updates) > 0 {
- if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
- if _, already := skippedReasons[email]; !already {
- skippedReasons[email] = err.Error()
- }
- continue
+ if len(updates) > 0 && (scope == nil || !scope.committedAdjustments[email]) {
+ if err := tx.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
+ return false, err
}
}
if adjustHwid {
- if err := s.setClientLimitHwidByEmail(email, *limitHwid); err != nil {
- if _, already := skippedReasons[email]; !already {
- skippedReasons[email] = err.Error()
- }
- continue
+ var err error
+ if scope == nil {
+ err = s.setClientLimitHwidByEmail(email, *limitHwid)
+ } else {
+ err = s.setClientLimitHwidByEmailTx(tx, email, *limitHwid)
+ }
+ if err != nil {
+ return false, err
}
}
if adjustAdTag && adTagHonored[email] {
- if err := db.Model(&model.ClientRecord{}).Where("email = ?", email).UpdateColumn("ad_tag", wantAdTag).Error; err != nil {
+ q := tx.Model(&model.ClientRecord{}).Where("email = ?", email)
+ if scope != nil {
+ q = q.Where("id = ?", entry.record.Id)
+ }
+ if err := q.UpdateColumn("ad_tag", wantAdTag).Error; err != nil {
+ return false, err
+ }
+ }
+ return len(updates) > 0 || flowHonored[email] || adTagHonored[email] || adjustHwid, nil
+ }
+ var candidates []string
+ for email := range plan {
+ if !execFailed[email] && (scope == nil || !scope.committedAdjustments[email] || adjustHwid || adTagHonored[email]) {
+ candidates = append(candidates, email)
+ }
+ }
+ if scope == nil {
+ for _, email := range candidates {
+ changed, err := apply(db, email)
+ if err != nil {
if _, already := skippedReasons[email]; !already {
skippedReasons[email] = err.Error()
}
+ } else if changed {
+ adjusted[email] = struct{}{}
+ }
+ }
+ } else {
+ slices.SortFunc(candidates, func(a, b string) int { return cmp.Compare(scope.ids[a], scope.ids[b]) })
+ for _, batch := range chunkStrings(candidates, sqlInChunk) {
+ var changed []string
+ err := runSerializedTx(func(tx *gorm.DB) error {
+ records, err := scope.records(tx, batch, true)
+ if err != nil {
+ return err
+ }
+ for _, email := range batch {
+ if records[email] == nil {
+ skippedReasons[email] = scope.skipReason()
+ continue
+ }
+ applied, err := apply(tx, email)
+ if err != nil {
+ return err
+ }
+ if applied {
+ changed = append(changed, email)
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ for _, email := range batch {
+ skippedReasons[email] = err.Error()
+ }
continue
}
- }
- // Counted when expiry/total changed, flow was honored, adTag was honored, or limitHwid was adjusted.
- if len(updates) > 0 || flowHonored[email] || adTagHonored[email] || adjustHwid {
- adjusted[email] = struct{}{}
+ for _, email := range changed {
+ adjusted[email] = struct{}{}
+ scope.committedAdjustments[email] = true
+ }
}
}
+
result.Adjusted = len(adjusted)
for email, reason := range skippedReasons {
@@ -632,12 +702,18 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
}
reEnable := make([]string, 0, len(wasDisabledDepleted))
for e := range wasDisabledDepleted {
- if _, still := stillDepleted[e]; !still {
+ _, wasAdjusted := adjusted[e]
+ if _, still := stillDepleted[e]; !still && (scope == nil || wasAdjusted) {
reEnable = append(reEnable, e)
}
}
if len(reEnable) > 0 {
- _, nr, err := s.BulkSetEnable(inboundSvc, reEnable, true)
+ reenabled, nr, err := s.bulkSetEnable(inboundSvc, reEnable, scope, true)
+ for _, skip := range reenabled.Skipped {
+ if scope != nil {
+ result.Skipped = append(result.Skipped, BulkAdjustReport(skip))
+ }
+ }
if err != nil {
return result, needRestart, err
}
@@ -651,8 +727,9 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
}
type bulkInboundAdjustResult struct {
- perEmailSkipped map[string]string
- flowHonored map[string]bool
+ perEmailSkipped map[string]string
+ disabledDepleted []string
+ flowHonored map[string]bool
// flowIneligible is tracked apart from perEmailSkipped: a flow directive
// that an inbound cannot carry must not suppress the expiry/total write for
// the same client (which would diverge the inbound JSON / ClientRecord from
@@ -674,6 +751,7 @@ func (s *ClientService) bulkAdjustInboundClients(
inboundId int,
emails []string,
plan map[string]*bulkAdjustEntry,
+ scope *GroupBulkScope,
flow string,
adTag string,
) bulkInboundAdjustResult {
@@ -822,7 +900,27 @@ func (s *ClientService) bulkAdjustInboundClients(
// Serialize against the traffic poll to avoid the cross-transaction
// lock-order deadlock on inbounds/client_records (runSerializedTx).
- txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error {
+ var limited, previouslyDepleted []string
+ txErr := mutation.commitThen(oldInbound, nodeClientDelta, func(tx *gorm.DB) error {
+ records, err := scope.inboundRecords(tx, inboundId, emails)
+ if err != nil {
+ return err
+ }
+ for email, current := range records {
+ entry := plan[email]
+ total, expiry := entry.record.TotalGB, entry.record.ExpiryTime
+ if scope.committedAdjustments[email] {
+ if entry.applyTotal {
+ total = entry.newTotal
+ }
+ if entry.applyExpiry {
+ expiry = entry.newExpiry
+ }
+ }
+ if (entry.applyTotal && current.TotalGB != total) || (entry.applyExpiry && current.ExpiryTime != expiry) {
+ return errGroupAdjustLimitsChanged
+ }
+ }
if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil {
return err
}
@@ -833,16 +931,47 @@ func (s *ClientService) bulkAdjustInboundClients(
if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
return err
}
- return nil
+ if scope == nil {
+ return nil
+ }
+ for email := range foundEmails {
+ entry := plan[email]
+ if !scope.committedAdjustments[email] && (entry.applyExpiry || entry.applyTotal) {
+ limited = append(limited, email)
+ }
+ }
+ if len(limited) == 0 {
+ return nil
+ }
+ // Commit enforcement limits before delivering any runtime changes.
+ cond, args := depletedCond(tx)
+ previouslyDepleted, err = bulkAdjustDisabledDepleted(tx, limited, cond, args)
+ if err != nil {
+ return err
+ }
+ return writeBulkAdjustTrafficLimits(tx, limited, plan)
+ }, func() {
+ if scope == nil || scope.committedAdjustments == nil {
+ return
+ }
+ for email := range foundEmails {
+ entry := plan[email]
+ if entry.applyExpiry || entry.applyTotal || res.flowHonored[email] || res.adTagHonored[email] {
+ scope.committedAdjustments[email] = true
+ }
+ }
})
if txErr != nil {
- s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
+ if !errors.Is(txErr, errGroupSelectionStale) && !errors.Is(txErr, errGroupAdjustLimitsChanged) {
+ s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
+ }
for email := range foundEmails {
if _, skip := res.perEmailSkipped[email]; !skip {
res.perEmailSkipped[email] = txErr.Error()
}
}
} else {
+ res.disabledDepleted = previouslyDepleted
if adTagChanged && oldInbound.Protocol == model.MTProto && oldInbound.NodeID == nil {
inboundSvc.applyLocalMtproto(oldInbound.Id)
}
@@ -887,8 +1016,9 @@ func (s *ClientService) bulkAdjustInboundClients(
// skip reasons when an email could not be processed.
type BulkDeleteResult struct {
ClientNodeApplyResponse
- Deleted int `json:"deleted"`
- Skipped []BulkDeleteReport `json:"skipped,omitempty"`
+ SkippedCount int `json:"skippedCount,omitempty" example:"0"`
+ Deleted int `json:"deleted"`
+ Skipped []BulkDeleteReport `json:"skipped,omitempty"`
}
type BulkDeleteReport struct {
@@ -904,6 +1034,14 @@ type BulkDeleteReport struct {
// IN-clause queries at the end. Errors on a particular email are recorded
// in the Skipped list and processing continues for the rest.
func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, keepTraffic bool) (BulkDeleteResult, bool, error) {
+ return s.bulkDelete(inboundSvc, emails, nil, keepTraffic)
+}
+
+func (s *ClientService) BulkDeleteGroup(inboundSvc *InboundService, scope *GroupBulkScope, keepTraffic bool) (BulkDeleteResult, bool, error) {
+ return s.bulkDelete(inboundSvc, scope.emails, scope, keepTraffic)
+}
+
+func (s *ClientService) bulkDelete(inboundSvc *InboundService, emails []string, scope *GroupBulkScope, keepTraffic bool) (BulkDeleteResult, bool, error) {
result := BulkDeleteResult{}
cleanEmails := trimmedUniqueEmails(emails)
@@ -913,22 +1051,35 @@ func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string,
db := database.GetDB()
- recordsByEmail, err := clientRecordsByEmail(db, cleanEmails)
- if err != nil {
+ var recordsByEmail map[string]*model.ClientRecord
+ var tombstoneEmails []string
+ planDelete := func(tx *gorm.DB) error {
+ var err error
+ recordsByEmail, err = scope.records(tx, cleanEmails, scope != nil)
+ if err != nil {
+ return err
+ }
+ for _, email := range cleanEmails {
+ if recordsByEmail[email] != nil {
+ tombstoneEmails = append(tombstoneEmails, email)
+ }
+ }
+ tombstoneClientEmails(tombstoneEmails)
+ return nil
+ }
+ if scope == nil {
+ if err := planDelete(db); err != nil {
+ return result, false, err
+ }
+ } else if err := runSerializedTx(planDelete); err != nil {
+ withdrawClientTombstones(tombstoneEmails...)
return result, false, err
}
- tombstoneEmails := make([]string, 0, len(recordsByEmail))
- for _, email := range cleanEmails {
- if recordsByEmail[email] != nil {
- tombstoneEmails = append(tombstoneEmails, email)
- }
- }
- tombstoneClientEmails(tombstoneEmails)
skippedReasons := map[string]string{}
for _, email := range cleanEmails {
if _, ok := recordsByEmail[email]; !ok {
- skippedReasons[email] = "client not found"
+ skippedReasons[email] = scope.skipReason()
}
}
@@ -961,7 +1112,7 @@ func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string,
needRestart := false
delIds := sortedInboundIds(emailsByInbound)
delResults, delPanics := fanoutClientInboundResults(delIds, inboundFanoutConcurrency, func(i int) bulkInboundDeleteResult {
- return s.bulkDelInboundClients(inboundSvc, delIds[i], emailsByInbound[delIds[i]], recordsByEmail, keepTraffic)
+ return s.bulkDelInboundClients(inboundSvc, delIds[i], emailsByInbound[delIds[i]], recordsByEmail, scope, keepTraffic)
})
for i, ibResult := range delResults {
if delPanics[i] != nil {
@@ -996,12 +1147,38 @@ func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string,
successIds = append(successIds, rec.Id)
successSubIDs = append(successSubIDs, rec.SubID)
}
- withdrawClientTombstones(failedEmails...)
-
if len(successIds) > 0 {
// Serialize the row cleanup against the traffic poll to avoid the
// cross-transaction lock-order deadlock on client_traffics/inbounds.
if err := runSerializedTx(func(tx *gorm.DB) error {
+ if scope != nil {
+ current, err := scope.records(tx, successEmails, true)
+ if err != nil {
+ return err
+ }
+ linked, err := linkedGroupBulkClients(tx, successIds)
+ if err != nil {
+ return err
+ }
+ // Fanout detached the original links. Do not delete clients with a new link.
+ var eligibleEmails []string
+ successIds, successSubIDs = nil, nil
+ for _, email := range successEmails {
+ rec := current[email]
+ if rec == nil || linked[rec.Id] {
+ skippedReasons[email] = scope.skipReason()
+ failedEmails = append(failedEmails, email)
+ continue
+ }
+ eligibleEmails = append(eligibleEmails, email)
+ successIds = append(successIds, rec.Id)
+ successSubIDs = append(successSubIDs, rec.SubID)
+ }
+ successEmails = eligibleEmails
+ }
+ if len(successIds) == 0 {
+ return nil
+ }
if e := adjustGroupBaselinesForRemovedTraffic(tx, successEmails); e != nil {
return e
}
@@ -1033,11 +1210,12 @@ func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string,
}
return nil
}); err != nil {
- withdrawClientTombstones(successEmails...)
+ withdrawClientTombstones(tombstoneEmails...)
return result, needRestart, err
}
}
+ withdrawClientTombstones(failedEmails...)
result.Deleted = len(successEmails)
for email, reason := range skippedReasons {
result.Skipped = append(result.Skipped, BulkDeleteReport{Email: email, Reason: reason})
@@ -1060,6 +1238,7 @@ func (s *ClientService) bulkDelInboundClients(
inboundId int,
emails []string,
records map[string]*model.ClientRecord,
+ scope *GroupBulkScope,
keepTraffic bool,
) bulkInboundDeleteResult {
res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}}
@@ -1161,7 +1340,7 @@ func (s *ClientService) bulkDelInboundClients(
}
var sharedSet map[string]bool
- if !keepTraffic {
+ if !keepTraffic && scope == nil {
var sharedErr error
sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(db, foundList, inboundId)
if sharedErr != nil {
@@ -1171,7 +1350,7 @@ func (s *ClientService) bulkDelInboundClients(
return res
}
}
- if !keepTraffic {
+ if !keepTraffic && scope == nil {
purge := make([]string, 0, len(foundEmails))
for email := range foundEmails {
if !sharedSet[strings.ToLower(strings.TrimSpace(email))] {
@@ -1211,6 +1390,9 @@ func (s *ClientService) bulkDelInboundClients(
}
var pending []model.NodePendingClientDelete
txErr := mutation.commit(oldInbound, nodeFullClientDelete, func(tx *gorm.DB) error {
+ if _, err := scope.inboundRecords(tx, inboundId, emails); err != nil {
+ return err
+ }
if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil {
return err
}
@@ -1225,7 +1407,9 @@ func (s *ClientService) bulkDelInboundClients(
return err
})
if txErr != nil {
- s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
+ if !errors.Is(txErr, errGroupSelectionStale) {
+ s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
+ }
for email := range wantedEmails {
if _, skip := res.perEmailSkipped[email]; !skip {
res.perEmailSkipped[email] = txErr.Error()
@@ -1296,10 +1480,51 @@ type BulkCreateReport struct {
}
func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) {
+ if slices.ContainsFunc(payloads, func(payload ClientCreatePayload) bool {
+ return payload.SubIDPrefix != ""
+ }) {
+ var err error
+ payloads, err = allocateBulkSubIDs(payloads)
+ if err != nil {
+ return BulkCreateResult{}, false, err
+ }
+ }
result, _, needRestart, err := s.bulkCreate(inboundSvc, payloads)
return result, needRestart, err
}
+func allocateBulkSubIDs(payloads []ClientCreatePayload) ([]ClientCreatePayload, error) {
+ payloads = slices.Clone(payloads)
+ taken := make(map[string]bool, len(payloads))
+ for _, item := range payloads {
+ if item.Client.SubID != "" {
+ if item.SubIDPrefix != "" {
+ return nil, common.NewError("subId and subIdPrefix cannot both be set")
+ }
+ taken[item.Client.SubID] = true
+ }
+ }
+ for i := range payloads {
+ prefix := payloads[i].SubIDPrefix
+ if prefix == "" {
+ continue
+ }
+ if err := validateClientSubID(prefix); err != nil {
+ return nil, err
+ }
+ for {
+ // The prefix is public. Each subscription gets independent secret entropy.
+ subID := prefix + "-" + rand.Text()
+ if !taken[subID] {
+ payloads[i].Client.SubID = subID
+ taken[subID] = true
+ break
+ }
+ }
+ }
+ return payloads, nil
+}
+
// bulkCreate also returns the payload indexes that inserted a new client record;
// a Created payload whose email already existed only reused that client.
func (s *ClientService) bulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, []int, bool, error) {
@@ -1595,6 +1820,10 @@ type BulkSetEnableReport struct {
}
func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []string, enable bool) (BulkSetEnableResult, bool, error) {
+ return s.bulkSetEnable(inboundSvc, emails, nil, enable)
+}
+
+func (s *ClientService) bulkSetEnable(inboundSvc *InboundService, emails []string, scope *GroupBulkScope, enable bool) (BulkSetEnableResult, bool, error) {
result := BulkSetEnableResult{}
cleanEmails := trimmedUniqueEmails(emails)
@@ -1605,7 +1834,7 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin
db := database.GetDB()
- recordsByEmail, err := clientRecordsByEmail(db, cleanEmails)
+ recordsByEmail, err := scope.records(db, cleanEmails, false)
if err != nil {
return result, false, err
}
@@ -1613,7 +1842,7 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin
skippedReasons := map[string]string{}
for _, email := range cleanEmails {
if _, ok := recordsByEmail[email]; !ok {
- skippedReasons[email] = "client not found"
+ skippedReasons[email] = scope.skipReason()
}
}
@@ -1646,7 +1875,7 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin
needRestart := false
enableIds := sortedInboundIds(emailsByInbound)
enableResults, enablePanics := fanoutClientInboundResults(enableIds, inboundFanoutConcurrency, func(i int) bulkSetEnableInboundResult {
- return s.bulkSetEnableInboundClients(inboundSvc, enableIds[i], emailsByInbound[enableIds[i]], enable)
+ return s.bulkSetEnableInboundClients(inboundSvc, enableIds[i], emailsByInbound[enableIds[i]], scope, enable)
})
for i, ibRes := range enableResults {
if enablePanics[i] != nil {
@@ -1680,6 +1909,19 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin
if len(successEmails) > 0 {
now := time.Now().UnixMilli()
trafficErr = runSerializedTx(func(tx *gorm.DB) error {
+ if scope != nil {
+ current, err := scope.records(tx, successEmails, true)
+ if err != nil {
+ return err
+ }
+ successEmails = slices.DeleteFunc(successEmails, func(email string) bool {
+ if current[email] != nil {
+ return false
+ }
+ skippedReasons[email] = scope.skipReason()
+ return true
+ })
+ }
for _, batch := range chunkStrings(successEmails, sqlInChunk) {
if e := tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("enable", enable).Error; e != nil {
return e
@@ -1728,7 +1970,7 @@ func applyBulkSidecar(inboundSvc *InboundService, inboundId int, protocol model.
}
}
-func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, enable bool) bulkSetEnableInboundResult {
+func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, scope *GroupBulkScope, enable bool) bulkSetEnableInboundResult {
res := bulkSetEnableInboundResult{perEmailSkipped: map[string]string{}}
mutation := beginInboundClientMutation(inboundId)
@@ -1833,6 +2075,9 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService,
}
txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error {
+ if _, err := scope.inboundRecords(tx, inboundId, emails); err != nil {
+ return err
+ }
if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil {
return e
}
@@ -1846,7 +2091,9 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService,
return nil
})
if txErr != nil {
- s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
+ if !errors.Is(txErr, errGroupSelectionStale) {
+ s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
+ }
for _, ch := range changed {
res.perEmailSkipped[ch.email] = txErr.Error()
}
@@ -1896,3 +2143,47 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService,
return res
}
+
+func bulkAdjustDisabledDepleted(tx *gorm.DB, emails []string, cond string, condArgs []any) ([]string, error) {
+ var disabled []string
+ for _, batch := range chunkStrings(emails, sqlInChunk) {
+ var rows []string
+ if err := tx.Model(xray.ClientTraffic{}).
+ Where(cond+" AND enable = ? AND email IN ?", append(append([]any{}, condArgs...), false, batch)...).
+ Pluck("email", &rows).Error; err != nil {
+ return nil, err
+ }
+ disabled = append(disabled, rows...)
+ }
+ return disabled, nil
+}
+
+// Lock the relevant clients before calling this. The email uniquely identifies the traffic row.
+func writeBulkAdjustTrafficLimits(tx *gorm.DB, emails []string, plan map[string]*bulkAdjustEntry) error {
+ for _, batch := range chunkStrings(emails, sqlInChunk/3) {
+ var expiryArgs, totalArgs []any
+ var expiryCases, totalCases strings.Builder
+ for _, email := range batch {
+ entry := plan[email]
+ if entry.applyExpiry {
+ expiryCases.WriteString(" WHEN ? THEN CAST(? AS BIGINT)")
+ expiryArgs = append(expiryArgs, email, entry.newExpiry)
+ }
+ if entry.applyTotal {
+ totalCases.WriteString(" WHEN ? THEN CAST(? AS BIGINT)")
+ totalArgs = append(totalArgs, email, entry.newTotal)
+ }
+ }
+ values := make(map[string]any, 2)
+ if len(expiryArgs) != 0 {
+ values["expiry_time"] = gorm.Expr("CASE email"+expiryCases.String()+" ELSE expiry_time END", expiryArgs...)
+ }
+ if len(totalArgs) != 0 {
+ values["total"] = gorm.Expr("CASE email"+totalCases.String()+" ELSE total END", totalArgs...)
+ }
+ if err := tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).UpdateColumns(values).Error; err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/web/service/client_bulk_external_link.go b/internal/web/service/client_bulk_external_link.go
index 754c9090d..63a636f36 100644
--- a/internal/web/service/client_bulk_external_link.go
+++ b/internal/web/service/client_bulk_external_link.go
@@ -20,6 +20,14 @@ type BulkExternalLinksResult struct {
// BulkAppendExternalLinks appends panel-local subscription entries atomically.
// Client row locks serialize concurrent appends; no runtime configuration changes.
func (s *ClientService) BulkAppendExternalLinks(emails []string, inputs []ExternalLinkInput) (BulkAdjustResult, error) {
+ return s.bulkAppendExternalLinks(emails, nil, inputs)
+}
+
+func (s *ClientService) BulkAppendGroupExternalLinks(scope *GroupBulkScope, inputs []ExternalLinkInput) (BulkAdjustResult, error) {
+ return s.bulkAppendExternalLinks(scope.emails, scope, inputs)
+}
+
+func (s *ClientService) bulkAppendExternalLinks(emails []string, scope *GroupBulkScope, inputs []ExternalLinkInput) (BulkAdjustResult, error) {
result := BulkAdjustResult{ExternalLinks: &BulkExternalLinksResult{}}
rows, err := normalizeExternalLinks(inputs)
if err != nil {
@@ -33,8 +41,14 @@ func (s *ClientService) BulkAppendExternalLinks(emails []string, inputs []Extern
return result, common.NewError("client emails are required")
}
sort.Strings(cleanEmails)
- err = database.GetDB().Transaction(func(tx *gorm.DB) error {
- records, err := clientRecordsByEmail(tx.Clauses(clause.Locking{Strength: "UPDATE"}).Order("id ASC"), cleanEmails)
+ write := func(tx *gorm.DB) error {
+ var records map[string]*model.ClientRecord
+ var err error
+ if scope == nil {
+ records, err = clientRecordsByEmail(tx.Clauses(clause.Locking{Strength: "UPDATE"}).Order("id ASC"), cleanEmails)
+ } else {
+ records, err = scope.records(tx, cleanEmails, true)
+ }
if err != nil {
return err
}
@@ -43,7 +57,7 @@ func (s *ClientService) BulkAppendExternalLinks(emails []string, inputs []Extern
if rec := records[email]; rec != nil {
ids = append(ids, rec.Id)
} else {
- result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "client not found"})
+ result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: scope.skipReason()})
result.ExternalLinks.Errors++
}
}
@@ -94,7 +108,12 @@ func (s *ClientService) BulkAppendExternalLinks(emails []string, inputs []Extern
}
result.ExternalLinks.Added = len(pending)
return nil
- })
+ }
+ if scope == nil {
+ err = database.GetDB().Transaction(write)
+ } else {
+ err = runSerializedTx(write)
+ }
if err != nil {
return BulkAdjustResult{ExternalLinks: &BulkExternalLinksResult{}}, err
}
diff --git a/internal/web/service/client_bulk_subid_test.go b/internal/web/service/client_bulk_subid_test.go
new file mode 100644
index 000000000..7b711677c
--- /dev/null
+++ b/internal/web/service/client_bulk_subid_test.go
@@ -0,0 +1,212 @@
+package service
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+func TestBulkCreateAllocatesIndependentSubscriptionIDsAlongsideCreate(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ db := database.GetDB()
+ const prefix = "test_%!"
+ for i, suffix := range []int{1, 3} {
+ row := model.ClientRecord{Email: fmt.Sprintf("existing-%d@example.test", i), SubID: fmt.Sprintf("%s-%d", prefix, suffix)}
+ if err := db.Create(&row).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ inbounds := []*model.Inbound{
+ mkInbound(t, 27601, model.VLESS, `{"clients":[]}`),
+ mkInbound(t, 27602, model.VLESS, `{"clients":[]}`),
+ }
+ single := mkInbound(t, 27603, model.VLESS, `{"clients":[]}`)
+ start := make(chan struct{})
+ done := make(chan error, len(inbounds)+1)
+ go func() {
+ <-start
+ _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
+ Client: model.Client{Email: "single@example.test", SubID: prefix + "-2", Enable: true},
+ InboundIds: []int{single.Id},
+ })
+ done <- err
+ }()
+ for i, inbound := range inbounds {
+ go func() {
+ items := make([]ClientCreatePayload, 2)
+ for j := range items {
+ items[j] = ClientCreatePayload{
+ Client: model.Client{Email: fmt.Sprintf("batch-%d-%d@example.test", i, j), Enable: true},
+ InboundIds: []int{inbound.Id},
+ SubIDPrefix: prefix,
+ }
+ }
+ <-start
+ result, _, err := (&ClientService{}).BulkCreate(&InboundService{}, items)
+ if err == nil && (result.Created != len(items) || len(result.Skipped) != 0) {
+ err = fmt.Errorf("created %d, skipped %v", result.Created, result.Skipped)
+ }
+ done <- err
+ }()
+ }
+ close(start)
+ for range len(inbounds) + 1 {
+ if err := <-done; err != nil {
+ t.Error(err)
+ }
+ }
+ if t.Failed() {
+ return
+ }
+ var got []string
+ if err := db.Model(&model.ClientRecord{}).Where("email LIKE ?", "batch-%").Pluck("sub_id", &got).Error; err != nil {
+ t.Fatal(err)
+ }
+ seen := make(map[string]bool)
+ for _, id := range got {
+ suffix, ok := strings.CutPrefix(id, prefix+"-")
+ if !ok || len(suffix) < 26 || seen[id] {
+ t.Fatal("bulk allocation did not create an independent random subscription ID")
+ }
+ seen[id] = true
+ }
+ if len(seen) != 4 || lookupClientRecord(t, "single@example.test").SubID != prefix+"-2" {
+ t.Fatal("concurrent BulkCreate and Create did not retain distinct IDs")
+ }
+}
+
+func TestBulkCreateSubscriptionPrefixRequest(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ inbound := mkInbound(t, 27604, model.VLESS, `{"clients":[]}`)
+ var request []ClientCreatePayload
+ err := json.Unmarshal([]byte(`[
+ {"client":{"email":"allocated@example.test"},"subIdPrefix":"label","inboundIds":[1]},
+ {"client":{"email":"explicit@example.test","subId":"label-1"},"inboundIds":[1]}
+ ]`), &request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := range request {
+ request[i].InboundIds = []int{inbound.Id}
+ }
+ svc := &ClientService{}
+ result, _, err := svc.BulkCreate(&InboundService{}, request)
+ if err != nil || result.Created != 2 || request[0].Client.SubID != "" {
+ t.Fatalf("bulk create: created=%d, error=%v", result.Created, err)
+ }
+ if lookupClientRecord(t, "explicit@example.test").SubID != "label-1" {
+ t.Fatal("explicit subscription ID changed")
+ }
+ request[0].Client.SubID = "conflicting"
+ if _, _, err := svc.BulkCreate(&InboundService{}, request); err == nil {
+ t.Fatal("expected a request with both an explicit ID and a prefix to be rejected")
+ }
+}
+
+func TestBulkCreateDoesNotReissueDeletedSubscriptionID(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ inbound := mkInbound(t, 27605, model.VLESS, `{"clients":[]}`)
+ svc, inboundSvc := &ClientService{}, &InboundService{}
+ create := func(email string) string {
+ t.Helper()
+ result, _, err := svc.BulkCreate(inboundSvc, []ClientCreatePayload{{
+ Client: model.Client{Email: email, Enable: true},
+ InboundIds: []int{inbound.Id},
+ SubIDPrefix: "label",
+ }})
+ if err != nil || result.Created != 1 {
+ t.Fatalf("bulk create: created=%d, error=%v", result.Created, err)
+ }
+ return lookupClientRecord(t, email).SubID
+ }
+ deleted := create("deleted@example.test")
+ if _, err := svc.DeleteByEmail(inboundSvc, "deleted@example.test", false); err != nil {
+ t.Fatal(err)
+ }
+ if next := create("replacement@example.test"); next == deleted {
+ t.Fatal("the deleted subscription ID was issued to a different client")
+ }
+ var owners int64
+ if err := database.GetDB().Model(&model.ClientRecord{}).Where("sub_id = ?", deleted).Count(&owners).Error; err != nil || owners != 0 {
+ t.Fatalf("deleted subscription still has an owner: %d, %v", owners, err)
+ }
+}
+
+func TestBulkCreatePrefixedBatchDoesNotWaitForUnrelatedNode(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ useTestRuntimeManager(t)
+ peer := &groupedCreatePeer{tags: map[string]int{}, settings: map[int]string{}}
+ entered, release := make(chan struct{}, 1), make(chan struct{})
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodPost {
+ select {
+ case entered <- struct{}{}:
+ default:
+ }
+ select {
+ case <-release:
+ _, _ = w.Write([]byte(`{"success":true}`))
+ case <-r.Context().Done():
+ }
+ return
+ }
+ peer.serve(w, r)
+ }))
+ defer server.Close()
+ slow := realNodeInbound(t, &fakeNodeHTTP{srv: server, tags: peer.tags}, 27606, nil)
+ local := mkInbound(t, 27607, model.VLESS, `{"clients":[]}`)
+ bulk := func(email, prefix string, inbound int) error {
+ result, _, err := (&ClientService{}).BulkCreate(&InboundService{}, []ClientCreatePayload{{
+ Client: model.Client{Email: email, Enable: true}, InboundIds: []int{inbound}, SubIDPrefix: prefix,
+ }})
+ if err == nil && result.Created != 1 {
+ err = fmt.Errorf("created %d clients", result.Created)
+ }
+ return err
+ }
+ slowDone := make(chan struct{})
+ var localDone chan struct{}
+ var slowErr error
+ go func() {
+ defer close(slowDone)
+ slowErr = bulk("slow@example.test", "slow", slow.Id)
+ }()
+ defer func() {
+ close(release)
+ <-slowDone
+ if localDone != nil {
+ <-localDone
+ }
+ if slowErr != nil {
+ t.Error(slowErr)
+ }
+ }()
+ select {
+ case <-entered:
+ case <-slowDone:
+ t.Fatalf("bulk create finished before the remote apply: %v", slowErr)
+ case <-time.After(5 * time.Second):
+ t.Fatal("bulk create did not reach the remote apply")
+ }
+ localDone = make(chan struct{})
+ var localErr error
+ go func() {
+ defer close(localDone)
+ localErr = bulk("local@example.test", "local", local.Id)
+ }()
+ select {
+ case <-localDone:
+ if localErr != nil {
+ t.Fatal(localErr)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("the local prefixed batch waited for the unrelated remote apply")
+ }
+}
diff --git a/internal/web/service/client_create_dispatch.go b/internal/web/service/client_create_dispatch.go
new file mode 100644
index 000000000..47ec3db5c
--- /dev/null
+++ b/internal/web/service/client_create_dispatch.go
@@ -0,0 +1,193 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "runtime/debug"
+ "sync"
+ "time"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/logger"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
+)
+
+type queuedClientCreate struct {
+ turn *nodeConfigTurn
+ remote *runtime.Remote
+ tag string
+ client string
+ advance func()
+ queuedAt time.Time
+}
+
+func (q *queuedClientCreate) prepare(turn *nodeConfigTurn, remote *runtime.Remote, previous, inbound *model.Inbound, client string, prunedOrphans bool) {
+ q.turn, q.remote, q.tag, q.client = turn, remote, inbound.Tag, client
+ q.queuedAt = time.Now()
+ if !prunedOrphans {
+ q.advance = remote.PreparePushedInboundAdvance(previous, inbound)
+ }
+}
+
+func (s *ClientService) pushClientCreates(parent context.Context, pushes []queuedClientCreate) (bool, error) {
+ ctx, cancel := context.WithTimeout(parent, nodeClientPushTimeout)
+ defer cancel()
+ byNode := make(map[int][]*queuedClientCreate)
+ var nodeOrder []int
+ for i := range pushes {
+ push := &pushes[i]
+ if push.turn == nil {
+ continue
+ }
+ nodeID := push.turn.nodeID
+ if len(byNode[nodeID]) == 0 {
+ nodeOrder = append(nodeOrder, nodeID)
+ }
+ byNode[nodeID] = append(byNode[nodeID], push)
+ }
+
+ applies := make([]inboundApply, 0, len(byNode))
+ // Reserve one delivery slot per admitted node. Extra groups use spare capacity.
+ spare := make(chan struct{}, max(0, inboundFanoutConcurrency-len(byNode)))
+ for _, nodeID := range nodeOrder {
+ group := byNode[nodeID]
+ applies = append(applies, inboundApply{id: group[0].turn.inboundID, nodeID: &nodeID, run: func() (bool, error) {
+ s.pushClientCreatesOnNode(ctx, spare, group)
+ return false, nil
+ }})
+ }
+ return fanoutInboundApplies(applies)
+}
+
+func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, spare chan struct{}, pending []*queuedClientCreate) {
+ queue := pending[0].turn.queue
+ nodeID := pending[0].turn.nodeID
+ defer func() {
+ for _, push := range pending {
+ push.turn.release()
+ }
+ }()
+ var workers sync.WaitGroup
+ defer workers.Wait()
+ primary := make(chan struct{}, 1)
+ for len(pending) > 0 {
+ if err := ctx.Err(); err != nil {
+ s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err)
+ return
+ }
+ changed := queue.changes()
+ type batchKey struct {
+ remote *runtime.Remote
+ client string
+ }
+ var batches [][]*queuedClientCreate
+ positions := make(map[batchKey]int)
+ var waiting []*queuedClientCreate
+ for _, push := range pending {
+ select {
+ case <-push.turn.ready:
+ key := batchKey{remote: push.remote, client: push.client}
+ i, found := positions[key]
+ if !found {
+ i = len(batches)
+ positions[key] = i
+ batches = append(batches, nil)
+ }
+ batches[i] = append(batches[i], push)
+ default:
+ waiting = append(waiting, push)
+ }
+ }
+ if len(batches) == 0 {
+ select {
+ case <-changed:
+ case <-ctx.Done():
+ }
+ continue
+ }
+ // Release ready lanes before waiting for lanes behind a node-wide turn.
+ for _, batch := range batches {
+ slot := reserveClientCreateSlot(ctx, primary, spare)
+ if slot == nil {
+ s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, ctx.Err())
+ return
+ }
+ run := func() {
+ defer func() { <-slot }()
+ defer func() {
+ for _, push := range batch {
+ push.turn.release()
+ }
+ }()
+ s.applyClientCreateBatch(ctx, nodeID, queue, batch)
+ }
+ if len(batches) == 1 && len(waiting) == 0 {
+ run()
+ } else {
+ workers.Go(run)
+ }
+ }
+ pending = waiting
+ }
+}
+
+func reserveClientCreateSlot(ctx context.Context, primary, spare chan struct{}) chan struct{} {
+ select {
+ case primary <- struct{}{}:
+ return primary
+ default:
+ }
+ select {
+ case primary <- struct{}{}:
+ return primary
+ case spare <- struct{}{}:
+ return spare
+ case <-ctx.Done():
+ return nil
+ }
+}
+
+func (s *ClientService) applyClientCreateBatch(ctx context.Context, nodeID int, queue *nodeConfigQueue, batch []*queuedClientCreate) {
+ if err := ctx.Err(); err != nil {
+ s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err)
+ return
+ }
+ if !queue.acquireLive() {
+ s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy)
+ return
+ }
+ defer queue.releaseLive()
+ defer func() {
+ if panicValue := recover(); panicValue != nil {
+ for _, push := range batch {
+ push.remote.ForgetPushedInbound(push.tag)
+ }
+ err := fmt.Errorf("panic applying grouped client create: %v", panicValue)
+ s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err)
+ logger.Errorf("%v for node %d\n%s", err, nodeID, debug.Stack())
+ }
+ }()
+ tags := make([]string, len(batch))
+ for i, push := range batch {
+ tags[i] = push.tag
+ }
+ remote := batch[0].remote
+ started := time.Now()
+ result, acknowledged, err := remote.AddClientGroup(ctx, tags, json.RawMessage(batch[0].client))
+ if err != nil {
+ s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err)
+ logger.Warning("Error applying clients on", remote.Name(), ":", err)
+ }
+ for i, push := range batch {
+ if i >= len(acknowledged) || !acknowledged[i] || push.advance == nil {
+ remote.ForgetPushedInbound(push.tag)
+ s.recordClientNodePush(nodeID, i < len(acknowledged) && acknowledged[i] && result.DownstreamPending, result, nil)
+ continue
+ }
+ push.advance()
+ s.recordClientNodePush(nodeID, true, result, nil)
+ }
+ logger.Debugf("client create node apply: node_id=%d inbounds=%d queue_wait_ms=%d rpc_ms=%d",
+ nodeID, len(tags), started.Sub(batch[0].queuedAt).Milliseconds(), time.Since(started).Milliseconds())
+}
diff --git a/internal/web/service/client_create_fanout_test.go b/internal/web/service/client_create_fanout_test.go
index 4b8ada29c..940ca93e4 100644
--- a/internal/web/service/client_create_fanout_test.go
+++ b/internal/web/service/client_create_fanout_test.go
@@ -56,6 +56,248 @@ func TestCreateAcrossManyInboundsUsesOneEmailSnapshot(t *testing.T) {
}
}
+func TestCreateGroupsCompatibleInboundsOnOneRemote(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ useTestRuntimeManager(t)
+ fake := newFakeNodeHTTP(t)
+ first := realNodeInbound(t, fake, 40301, nil)
+ ids := []int{first.Id}
+ remoteIDs := []int{101}
+ for i := 1; i < 11; i++ {
+ ib := nodeInbound(t, *first.NodeID, 40301+i, nil)
+ ids = append(ids, ib.Id)
+ remoteIDs = append(remoteIDs, 101+i)
+ fake.tags[ib.Tag] = 101 + i
+ }
+
+ svc := (&ClientService{}).TrackNodeApplies()
+ const email = "grouped@x"
+ const uuid = "bbbbbbbb-1111-2222-3333-555555555555"
+ for range 2 {
+ _, err := svc.Create(&InboundService{}, &ClientCreatePayload{
+ Client: model.Client{Email: email, ID: uuid, SubID: "sub-grouped", Enable: true}, InboundIds: ids,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ fake.mu.Lock()
+ pushes := slices.Clone(fake.clientAdds)
+ fake.mu.Unlock()
+ if len(pushes) != 1 {
+ t.Fatalf("client add RPCs = %d, want one for all 11 inbounds and none on retry", len(pushes))
+ }
+ slices.Sort(pushes[0].InboundIds)
+ if !slices.Equal(pushes[0].InboundIds, remoteIDs) || pushes[0].Client.ID != uuid {
+ t.Fatalf("node received wrong IDs or credentials: %+v", pushes[0])
+ }
+ rec := lookupClientRecord(t, email)
+ attached, err := svc.GetInboundIdsForRecord(rec.Id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ slices.Sort(attached)
+ if !slices.Equal(attached, ids) {
+ t.Fatalf("local attachments = %v, want %v", attached, ids)
+ }
+ if r := svc.NodeApplyResponse(); r == nil || r.NodePending || !slices.Equal(r.NodeResults, []ClientNodeApplyOutcome{
+ {NodeID: *first.NodeID, Status: "applied"},
+ }) {
+ t.Fatalf("node outcome = %+v, want applied", r)
+ }
+}
+
+func TestCreateSplitsFlowAndSendsResolvedInbounds(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ useTestRuntimeManager(t)
+ fake := newFakeNodeHTTP(t)
+ raw := realNodeInbound(t, fake, 40321, nil)
+ tls := nodeInbound(t, *raw.NodeID, 40322, nil)
+ missing := nodeInbound(t, *raw.NodeID, 40323, nil)
+ if err := database.GetDB().Model(tls).Update("stream_settings", `{"network":"tcp","security":"tls"}`).Error; err != nil {
+ t.Fatal(err)
+ }
+ fake.tags[tls.Tag] = 122
+
+ svc := (&ClientService{}).TrackNodeApplies()
+ const flow = "xtls-rprx-vision"
+ _, err := svc.Create(&InboundService{}, &ClientCreatePayload{
+ Client: model.Client{Email: "split@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Flow: flow, Enable: true},
+ InboundIds: []int{raw.Id, tls.Id, missing.Id},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ fake.mu.Lock()
+ pushes := slices.Clone(fake.clientAdds)
+ fake.mu.Unlock()
+ slices.SortFunc(pushes, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] })
+ if len(pushes) != 2 || !slices.Equal(pushes[0].InboundIds, []int{121}) || !slices.Equal(pushes[1].InboundIds, []int{122}) ||
+ pushes[0].Client.Flow != "" || pushes[1].Client.Flow != flow {
+ t.Fatalf("wrong delivery for mixed flow and missing tag: %+v", pushes)
+ }
+ res := svc.NodeApplyResponse()
+ want := []ClientNodeApplyOutcome{{NodeID: *raw.NodeID, Status: "pending", Reason: "push_failed"}}
+ if res == nil || !res.NodePending || !slices.Equal(res.NodeResults, want) {
+ t.Fatalf("node outcome = %+v, want %v", res, want)
+ }
+ _, _, dirty, _, err := (&NodeService{}).NodeSyncState(*raw.NodeID)
+ if err != nil || !dirty {
+ t.Fatalf("missing inbound must leave a durable reconcile: dirty=%t err=%v", dirty, err)
+ }
+}
+
+func TestCreateUsesEffectiveAllowedIPsOnRemote(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ useTestRuntimeManager(t)
+ fake := newFakeNodeHTTP(t)
+ wg := realNodeInbound(t, fake, 40331, nil)
+ awg := nodeInbound(t, *wg.NodeID, 40332, nil)
+ for _, inbound := range []struct {
+ id int
+ protocol model.Protocol
+ settings string
+ }{
+ {id: wg.Id, protocol: model.WireGuard, settings: wgServerSettings()},
+ {id: awg.Id, protocol: model.AmneziaWG, settings: amneziawgClientTestSettings},
+ } {
+ if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", inbound.id).
+ Updates(map[string]any{"protocol": inbound.protocol, "settings": inbound.settings}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ fake.tags[awg.Tag] = 132
+
+ _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
+ Client: model.Client{
+ Email: "split-tunnel@x", Enable: true,
+ AllowedIPsByInbound: map[int][]string{wg.Id: {"10.0.0.9/32"}, awg.Id: {"10.8.1.9/32"}},
+ },
+ InboundIds: []int{wg.Id, awg.Id},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ fake.mu.Lock()
+ pushes := slices.Clone(fake.clientAdds)
+ fake.mu.Unlock()
+ slices.SortFunc(pushes, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] })
+ if len(pushes) != 2 {
+ t.Fatalf("node received %d add requests, want 2 distinct tunnel payloads", len(pushes))
+ }
+ for i, addr := range []string{"10.0.0.9/32", "10.8.1.9/32"} {
+ push := pushes[i]
+ if !slices.Equal(push.InboundIds, []int{131 + i}) || !slices.Equal(push.Client.AllowedIPs, []string{addr}) ||
+ len(push.Client.AllowedIPsByInbound) != 0 {
+ t.Fatalf("tunnel %d payload = %+v, want remote inbound %d and %s", i, push, 131+i, addr)
+ }
+ }
+}
+
+func TestCreateDispatchesReadyLaneBeforeBlockedLane(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ useTestRuntimeManager(t)
+ fake := newFakeNodeHTTP(t)
+ first := realNodeInbound(t, fake, 40341, nil)
+ second := nodeInbound(t, *first.NodeID, 40342, nil)
+ fake.tags[second.Tag] = 142
+ predecessor := reserveNodeConfigTurn(*first.NodeID, first.Id, nodeClientDelta)
+ defer predecessor.release()
+
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ done := make(chan struct{})
+ var saveErr error
+ go func() {
+ defer close(done)
+ _, saveErr = (&ClientService{}).CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{
+ Client: model.Client{Email: "ordered-add@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Enable: true},
+ InboundIds: []int{first.Id, second.Id},
+ })
+ }()
+ t.Cleanup(func() {
+ cancel()
+ <-done
+ })
+ wantRPC := func(remoteID int) {
+ t.Helper()
+ select {
+ case got := <-fake.clientAddEvents:
+ if !slices.Equal(got.InboundIds, []int{remoteID}) {
+ t.Fatalf("node received inbound IDs %v, want [%d]", got.InboundIds, remoteID)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatalf("ready inbound %d was not dispatched", remoteID)
+ }
+ }
+ wantRPC(142)
+ predecessor.release()
+ wantRPC(141)
+ select {
+ case <-done:
+ if saveErr != nil {
+ t.Fatal(saveErr)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("create waited after both requests were delivered")
+ }
+}
+
+func TestCreateCancellationStopsFurtherNodeWaves(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ useTestRuntimeManager(t)
+ const nodeCount = inboundFanoutConcurrency + 1
+ fakes := make([]*fakeNodeHTTP, nodeCount)
+ var ids []int
+ for i := range nodeCount {
+ fakes[i] = newFakeNodeHTTP(t)
+ fakes[i].setHold(true)
+ ids = append(ids, realNodeInbound(t, fakes[i], 40351+i, nil).Id)
+ }
+
+ svc := (&ClientService{}).TrackNodeApplies()
+ ctx, cancel := context.WithCancel(t.Context())
+ done := make(chan struct{})
+ var saveErr error
+ go func() {
+ defer close(done)
+ _, saveErr = svc.CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{
+ Client: model.Client{Email: "cancel-add@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Enable: true},
+ InboundIds: ids,
+ })
+ }()
+ t.Cleanup(func() { cancel(); <-done })
+ deadline := time.After(5 * time.Second)
+ for _, fake := range fakes[:inboundFanoutConcurrency] {
+ select {
+ case <-fake.clientAddEvents:
+ case <-deadline:
+ t.Fatal("the first wave did not reach every admitted node")
+ }
+ }
+ cancel()
+ select {
+ case <-done:
+ if saveErr != nil {
+ t.Fatal(saveErr)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("cancelled pushes held up the create")
+ }
+ if got := fakes[nodeCount-1].hitCount("/clients/add"); got != 0 {
+ t.Fatalf("queued node received %d RPCs after request cancellation", got)
+ }
+ rec := lookupClientRecord(t, "cancel-add@x")
+ links, err := svc.GetInboundIdsForRecord(rec.Id)
+ if err != nil || len(links) != nodeCount {
+ t.Fatalf("cancellation lost a committed membership: %v, err=%v", links, err)
+ }
+ if res := svc.NodeApplyResponse(); res == nil || !res.NodePending || len(res.NodeResults) != nodeCount {
+ t.Fatalf("node outcome = %+v, want all %d pending", res, nodeCount)
+ }
+}
+
func TestAttachAcrossManyInboundsUsesOneEmailSnapshot(t *testing.T) {
setupBulkDB(t)
svc := &ClientService{}
diff --git a/internal/web/service/client_create_node_reads_test.go b/internal/web/service/client_create_node_reads_test.go
new file mode 100644
index 000000000..4c0d3ed75
--- /dev/null
+++ b/internal/web/service/client_create_node_reads_test.go
@@ -0,0 +1,286 @@
+package service
+
+import (
+ "context"
+ "net/http"
+ "slices"
+ "sync"
+ "testing"
+ "time"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+func TestSlimCreateUsesLockedFlowForGroupedDelivery(t *testing.T) {
+ peer, _, inbounds, _ := setupGroupedCreatePeer(t)
+ db := database.GetDB()
+ first, second := inbounds[0], inbounds[1]
+ const tls = `{"network":"tcp","security":"tls"}`
+ const reality = `{"network":"tcp","security":"reality"}`
+ if err := db.Model(first).Update("stream_settings", tls).Error; err != nil {
+ t.Fatal(err)
+ }
+ third := nodeInbound(t, *first.NodeID, 46203, nil)
+ peer.tags[third.Tag] = 103
+ peer.settings[103] = third.Settings
+ if err := db.Model(third).Update("settings", `{"clients":[],"decryption":"mlkem768x25519plus.native.0rtt.test"}`).Error; err != nil {
+ t.Fatal(err)
+ }
+ var disableFirst, enableSecond sync.Once
+ const hook = "test:flow-changes-after-create-preparation-read"
+ query := db.Callback().Query()
+ if err := query.After("gorm:query").Register(hook, func(tx *gorm.DB) {
+ ib, ok := tx.Statement.Dest.(*model.Inbound)
+ if !ok || tx.Error != nil {
+ return
+ }
+ switch ib.Id {
+ case first.Id:
+ disableFirst.Do(func() { _ = tx.AddError(db.Model(first).Update("disable_flow", true).Error) })
+ case second.Id:
+ enableSecond.Do(func() { _ = tx.AddError(db.Model(second).Update("stream_settings", reality).Error) })
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = query.Remove(hook) })
+
+ const flow = "xtls-rprx-vision"
+ client := groupedRecoveryClient("locked-flow@x")
+ client.Flow = flow
+ if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
+ Client: client, InboundIds: []int{first.Id, second.Id, third.Id},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ peer.mu.Lock()
+ calls := slices.Clone(peer.adds)
+ peer.mu.Unlock()
+ slices.SortFunc(calls, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] })
+ if len(calls) != 2 || !slices.Equal(calls[0].InboundIds, []int{101}) || calls[0].Client.Flow != "" ||
+ !slices.Equal(calls[1].InboundIds, []int{102, 103}) || calls[1].Client.Flow != flow {
+ t.Fatalf("peer received %+v, want no flow on 101 and Vision on 102/103", calls)
+ }
+ for _, ib := range []*model.Inbound{first, second, third} {
+ want := flow
+ if ib.Id == first.Id {
+ want = ""
+ }
+ if c, ok := settingsClient(t, ib.Id, client.Email); !ok || c.Flow != want {
+ t.Fatalf("stored flow for inbound %d = %q, want %q", ib.Id, c.Flow, want)
+ }
+ }
+}
+
+func TestSlimCreateHealthyTargetsProgressWithBlockedPeer(t *testing.T) {
+ slow, node, slowTargets, _ := setupGroupedCreatePeer(t)
+ healthy := newFakeNodeHTTP(t)
+ firstHealthy := realNodeInbound(t, healthy, 46321, nil)
+ secondHealthy := nodeInbound(t, *firstHealthy.NodeID, 46322, nil)
+ healthy.tags[secondHealthy.Tag] = 122
+ for i := range 2 {
+ ib := nodeInbound(t, node.Id, 46331+i, nil)
+ slow.tags[ib.Tag] = 131 + i
+ slow.settings[131+i] = ib.Settings
+ slowTargets = append(slowTargets, ib)
+ }
+ var ids []int
+ var locks []*inboundMutationLock
+ for _, ib := range slowTargets {
+ ids = append(ids, ib.Id)
+ locks = append(locks, lockInbound(ib.Id))
+ }
+ releaseLocks := sync.OnceFunc(func() {
+ for _, lock := range locks {
+ lock.Unlock()
+ }
+ })
+ ids = append(ids, firstHealthy.Id, secondHealthy.Id)
+ healthySent := make(chan struct{})
+ releaseRPC := sync.OnceFunc(func() { close(healthySent) })
+ slow.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) {
+ select {
+ case <-healthySent:
+ case <-r.Context().Done():
+ return
+ }
+ apply(len(payload.InboundIds))
+ _, _ = w.Write([]byte(`{"success":true}`))
+ }
+ saved := make(chan int, 2)
+ db := database.GetDB()
+ const hook = "test:healthy-inbound-write-while-other-inbounds-block"
+ updates := db.Callback().Update()
+ if err := updates.After("gorm:update").Register(hook, func(tx *gorm.DB) {
+ if tx.Statement.Table == "inbounds" && len(tx.Statement.Vars) == 2 {
+ if id, ok := tx.Statement.Vars[1].(int); ok && (id == firstHealthy.Id || id == secondHealthy.Id) {
+ saved <- id
+ }
+ }
+ }); err != nil {
+ releaseLocks()
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = updates.Remove(hook) })
+ ctx, cancel := context.WithCancel(t.Context())
+ done := make(chan struct{})
+ svc := (&ClientService{}).TrackNodeApplies()
+ var createErr error
+ t.Cleanup(func() { releaseLocks(); releaseRPC(); cancel(); <-done })
+ go func() {
+ defer close(done)
+ _, createErr = svc.CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{
+ Client: groupedRecoveryClient("healthy-node@x"), InboundIds: ids,
+ })
+ }()
+ deadline := time.After(3 * time.Second)
+ seen := make(map[int]bool)
+ for range 2 {
+ select {
+ case id := <-saved:
+ seen[id] = true
+ case <-deadline:
+ t.Fatalf("healthy node's writes waited for parked lanes: %v", seen)
+ }
+ }
+ if len(seen) != 2 {
+ t.Fatalf("healthy writes seen = %v", seen)
+ }
+ if err := submitTrafficWrite(func() error { return nil }); err != nil {
+ t.Fatal(err)
+ }
+ releaseLocks()
+ select {
+ case call := <-healthy.clientAddEvents:
+ if !slices.Equal(call.InboundIds, []int{121, 122}) {
+ t.Fatalf("healthy peer received IDs %v, want 121 and 122 together", call.InboundIds)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("healthy peer waited for the slow peer's RPC")
+ }
+ releaseRPC()
+ select {
+ case <-done:
+ if createErr != nil {
+ t.Fatal(createErr)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("create did not return")
+ }
+ result := svc.NodeApplyResponse()
+ want := []ClientNodeApplyOutcome{{NodeID: node.Id, Status: "applied"}, {NodeID: *firstHealthy.NodeID, Status: "applied"}}
+ if result == nil || result.NodePending || !slices.Equal(result.NodeResults, want) {
+ t.Fatalf("node outcomes = %+v, want %v", result, want)
+ }
+}
+
+func TestSlimCreateProjectionPreservesNodeIDAndProtocolSettings(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ fake := newFakeNodeHTTP(t)
+ remote := realNodeInbound(t, fake, 46341, nil)
+ local := seedInboundSettingsReadTest(t, 46342, model.VLESS, `{"clients":[]}`)
+ mtproto := seedInboundSettingsReadTest(t, 46343, model.MTProto, `{"clients":[],"fakeTlsDomain":"front.example.test"}`)
+ for _, tc := range []struct {
+ inbound *model.Inbound
+ generate bool
+ settings string
+ }{
+ {inbound: remote},
+ {inbound: local},
+ {inbound: mtproto, generate: true, settings: mtproto.Settings},
+ {inbound: mtproto},
+ } {
+ got, err := getInboundForClientPreparation(tc.inbound.Id, tc.generate)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var nodeID, wantNodeID int
+ if got.NodeID != nil {
+ nodeID = *got.NodeID
+ }
+ if tc.inbound.NodeID != nil {
+ wantNodeID = *tc.inbound.NodeID
+ }
+ if got.Id != tc.inbound.Id || nodeID != wantNodeID || got.Protocol != tc.inbound.Protocol ||
+ got.Enable != tc.inbound.Enable || got.Listen != tc.inbound.Listen || got.Settings != tc.settings {
+ t.Fatalf("projection id=%d node=%d protocol=%s settings bytes=%d, want id=%d node=%d protocol=%s settings bytes=%d",
+ got.Id, nodeID, got.Protocol, len(got.Settings), tc.inbound.Id, wantNodeID, tc.inbound.Protocol, len(tc.settings))
+ }
+ }
+ secret := model.GenerateFakeTLSSecret("supplied.example.test")
+ const email = "preserve-supplied-secret@x"
+ if _, err := (&ClientService{}).CreateOne(&InboundService{}, mtproto.Id, model.Client{Email: email, Secret: secret}); err != nil {
+ t.Fatal(err)
+ }
+ if c, ok := settingsClient(t, mtproto.Id, email); !ok || c.Secret != secret {
+ t.Fatal("create regenerated the supplied MTProto secret")
+ }
+}
+
+func TestSlimAttachUsesLockedFlowAndPreservesRawAdd(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ db := database.GetDB()
+ inboundSvc, svc := &InboundService{}, &ClientService{}
+ client := groupedRecoveryClient("attach-flow@x")
+ client.Flow = "xtls-rprx-vision"
+ source := seedInboundSettingsReadTest(t, 46351, model.VLESS, clientsSettings(t, []model.Client{client}))
+ if err := svc.SyncInbound(nil, source.Id, []model.Client{client}); err != nil {
+ t.Fatal(err)
+ }
+ target := seedInboundSettingsReadTest(t, 46352, model.VLESS, `{"clients":[]}`)
+ if err := db.Model(target).Update("stream_settings", `{"network":"tcp","security":"tls"}`).Error; err != nil {
+ t.Fatal(err)
+ }
+ query := db.Callback().Query()
+ const hook = "test:disable-flow-after-attach-preparation-read"
+ var disable sync.Once
+ if err := query.After("gorm:query").Register(hook, func(tx *gorm.DB) {
+ if ib, ok := tx.Statement.Dest.(*model.Inbound); ok && ib.Id == target.Id && tx.Error == nil {
+ disable.Do(func() { _ = tx.AddError(db.Model(target).Update("disable_flow", true).Error) })
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = query.Remove(hook) })
+ if _, err := svc.AttachByEmail(inboundSvc, client.Email, []int{target.Id}); err != nil {
+ t.Fatal(err)
+ }
+ if c, ok := settingsClient(t, target.Id, client.Email); !ok || c.Flow != "" {
+ t.Fatalf("attach retained stale flow %q", c.Flow)
+ }
+ client.Email, client.SubID, client.ID = "legacy-add@x", "legacy-add", "aaaaaaaa-1111-2222-3333-555555555555"
+ if _, err := svc.AddInboundClient(inboundSvc, &model.Inbound{
+ Id: target.Id, Settings: clientsSettings(t, []model.Client{client}),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if c, ok := settingsClient(t, target.Id, client.Email); !ok || c.Flow != client.Flow {
+ t.Fatalf("raw AddInboundClient changed its caller-owned flow to %q", c.Flow)
+ }
+}
+
+func TestSlimUpdateRebasesConcurrentSettings(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ ib := seedRenewableNeighbour(t, 46361, nil)
+ record := lookupClientRecord(t, "x@stale")
+ current := record.ToClient()
+ current.Comment = "updated alongside renewal"
+ reads := trackInboundSettingsReads(t)
+ var editErr error
+ commitTickBetweenReadAndWrite(t, renewYTick(ib.Id), func() {
+ _, editErr = (&ClientService{}).Update(&InboundService{}, record.Id, *current, 0)
+ })
+ if editErr != nil {
+ t.Fatal(editErr)
+ }
+ if len(reads.sizes) != 4 || reads.sizes[0] != 0 || reads.sizes[1] == 0 || reads.sizes[2] == 0 || reads.sizes[3] == 0 {
+ t.Fatalf("update settings reads = %v, want empty preparation plus full locked, renewal and transactional reads", reads.sizes)
+ }
+ requireNeighbourRenewed(t, ib.Id)
+ if saved, ok := settingsClient(t, ib.Id, current.Email); !ok || saved.Comment != current.Comment {
+ t.Fatalf("update lost the edited comment: %+v", saved)
+ }
+}
diff --git a/internal/web/service/client_create_order_test.go b/internal/web/service/client_create_order_test.go
new file mode 100644
index 000000000..7e6cfb191
--- /dev/null
+++ b/internal/web/service/client_create_order_test.go
@@ -0,0 +1,308 @@
+package service
+
+import (
+ "context"
+ "net/http"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
+)
+
+func TestGroupedCreateOrdersLaterClientMutations(t *testing.T) {
+ for _, change := range []string{"update", "rename", "detach", "delete", "delete and reattach"} {
+ t.Run(change, func(t *testing.T) {
+ peer, node, ibs, _ := setupGroupedCreatePeer(t)
+ db := database.GetDB()
+ svc, inboundSvc := &ClientService{}, &InboundService{}
+ client := groupedRecoveryClient("ordered-group@x")
+ updateEmail := client.Email
+ if change == "rename" {
+ updateEmail = "renamed-group@x"
+ }
+ blocked, release := make(chan struct{}), make(chan struct{})
+ free := sync.OnceFunc(func() { close(release) })
+ var workers sync.WaitGroup
+ t.Cleanup(func() { free(); workers.Wait() })
+ var requests atomic.Int32
+ calls := make(chan string, 8)
+ peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) {
+ calls <- "add"
+ if requests.Add(1) == 1 {
+ close(blocked)
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ return
+ }
+ }
+ apply(len(payload.InboundIds))
+ _, _ = w.Write([]byte(`{"success":true}`))
+ }
+ peer.mutate = func(w http.ResponseWriter, r *http.Request) {
+ calls <- r.URL.Path
+ _, _ = w.Write([]byte(`{"success":true}`))
+ }
+ async := func(op func() (bool, error)) <-chan error {
+ done := make(chan error, 1)
+ workers.Go(func() { _, err := op(); done <- err })
+ return done
+ }
+ created := async(func() (bool, error) {
+ return svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{ibs[0].Id, ibs[1].Id}})
+ })
+ waitTrafficWriterSignal(t, blocked, "grouped create never reached the node")
+ original := lookupClientRecord(t, client.Email)
+ before := groupedDirtyGeneration(t, node.Id)
+ const callback = "test:observe-later-grouped-commit"
+ marked := make(chan struct{}, 8)
+ if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) {
+ if tx.Statement.Table == "nodes" && strings.Contains(tx.Statement.SQL.String(), "config_dirty_at") {
+ marked <- struct{}{}
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) })
+ waitCommit := func(previous int64) int64 {
+ t.Helper()
+ deadline := time.After(2 * time.Second)
+ for {
+ select {
+ case <-marked:
+ case <-deadline:
+ t.Fatal("later local mutation did not advance the dirty generation")
+ }
+ if err := submitTrafficWrite(func() error { return nil }); err != nil {
+ t.Fatal(err)
+ }
+ if generation := groupedDirtyGeneration(t, node.Id); generation > previous {
+ return generation
+ }
+ }
+ }
+ mutated := async(func() (bool, error) {
+ switch change {
+ case "update", "rename":
+ next := client
+ next.Comment, next.Email = "committed later", updateEmail
+ return svc.UpdateByEmail(inboundSvc, client.Email, next, 0, ibs[0].Id)
+ case "detach":
+ return svc.DetachByEmail(inboundSvc, ibs[0].Id, client.Email)
+ default:
+ return svc.DeleteByEmail(inboundSvc, client.Email, false)
+ }
+ })
+ after := waitCommit(before)
+ if change == "update" || change == "rename" {
+ for {
+ stored, ok := settingsClient(t, ibs[0].Id, updateEmail)
+ if ok && stored.Comment == "committed later" {
+ break
+ }
+ after = waitCommit(after)
+ }
+ }
+ if strings.HasPrefix(change, "delete") {
+ for {
+ links, err := svc.GetInboundIdsForRecord(original.Id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(links) == 0 {
+ break
+ }
+ after = waitCommit(after)
+ }
+ }
+ deletes := func() int64 {
+ t.Helper()
+ var n int64
+ if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email = ?", node.Id, client.Email).Count(&n).Error; err != nil {
+ t.Fatal(err)
+ }
+ return n
+ }
+ var reattached <-chan error
+ if strings.HasPrefix(change, "delete") && deletes() != 1 {
+ t.Fatal("queued full delete has no durable outbox entry")
+ }
+ if change == "delete and reattach" {
+ reattached = async(func() (bool, error) {
+ return svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{ibs[0].Id}})
+ })
+ waitCommit(after)
+ }
+ if err := (&NodeService{}).ClearNodeDirty(node.Id, before); err != nil {
+ t.Fatal(err)
+ }
+ groupedDirtyGeneration(t, node.Id)
+ if len(calls) != 1 {
+ t.Fatalf("later operation reached peer before grouped create acknowledgment (%d calls)", len(calls))
+ }
+ free()
+ done := []<-chan error{created, mutated}
+ if reattached != nil {
+ done = append(done, reattached)
+ }
+ for i, settled := range done {
+ if err := waitTrafficWriterErr(t, settled); err != nil {
+ t.Fatalf("operation %d failed: %v", i+1, err)
+ }
+ }
+ var got []string
+ for len(calls) > 0 {
+ got = append(got, <-calls)
+ }
+ second := "/panel/api/clients/update/" + client.Email
+ switch change {
+ case "detach":
+ second = "/panel/api/clients/" + client.Email + "/detach"
+ case "delete":
+ second = "/panel/api/clients/del/" + client.Email
+ case "delete and reattach":
+ second = "add"
+ }
+ if !slices.Equal(got, []string{"add", second}) {
+ t.Fatalf("remote order = %v, want [add %s]", got, second)
+ }
+ if deletes() != 0 {
+ t.Fatal("completed or superseded delete was retained")
+ }
+ if reattached != nil {
+ rec := lookupClientRecord(t, client.Email)
+ links, err := svc.GetInboundIdsForRecord(rec.Id)
+ if err != nil || !slices.Equal(links, []int{ibs[0].Id}) {
+ t.Fatalf("later attachment lost: %v, err=%v", links, err)
+ }
+ }
+ })
+ }
+}
+
+func TestGroupedCreateKeepsFifthNodeDurablyPendingWhenBudgetExpires(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ mgr := useTestRuntimeManager(t)
+ const nodes = inboundFanoutConcurrency + 1
+ var peers []*fakeNodeHTTP
+ var ids []int
+ var healthy *model.Inbound
+ for i := range nodes {
+ fake := newFakeNodeHTTP(t)
+ fake.setHold(i < inboundFanoutConcurrency)
+ peers = append(peers, fake)
+ healthy = realNodeInbound(t, fake, 46231+i, nil)
+ ids = append(ids, healthy.Id)
+ }
+ svc := (&ClientService{}).TrackNodeApplies()
+ inboundSvc := &InboundService{}
+ started := time.Now()
+ client := groupedRecoveryClient("fifth-destination@x")
+ if _, err := svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: ids}); err != nil {
+ t.Fatal(err)
+ }
+ elapsed := time.Since(started)
+ if elapsed >= 2*nodeClientPushTimeout {
+ t.Fatalf("create took %v, want one delivery window", elapsed)
+ }
+ status := svc.NodeApplyResponse()
+ if status == nil || !status.NodePending || len(status.NodeResults) != nodes {
+ t.Fatalf("node outcomes = %+v, want %d pending", status, nodes)
+ }
+ for i, p := range peers {
+ want := 1
+ if i == inboundFanoutConcurrency {
+ want = 0
+ }
+ if got := p.hitCount("/clients/add"); got != want {
+ t.Fatalf("peer %d received %d adds, want %d with shared timeout", i, got, want)
+ }
+ if outcome := status.NodeResults[i]; outcome.Status != "pending" || outcome.Reason != "timeout" {
+ t.Fatalf("peer %d outcome = %+v, want timeout", i, outcome)
+ }
+ }
+ inboundID := *healthy.NodeID
+ groupedDirtyGeneration(t, inboundID)
+ if got := settingsClientEmails(t, healthy.Id); !slices.Equal(got, []string{client.Email}) {
+ t.Fatalf("healthy peer membership was dropped: %v", got)
+ }
+ var node model.Node
+ if err := database.GetDB().First(&node, inboundID).Error; err != nil {
+ t.Fatal(err)
+ }
+ rt, err := mgr.RuntimeFor(&inboundID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), time.Second)
+ defer cancel()
+ if err := inboundSvc.ReconcileNode(ctx, rt.(*runtime.Remote), &node); err != nil {
+ t.Fatal(err)
+ }
+ if got := peers[nodes-1].hitCount("/inbounds/update/"); got != 1 {
+ t.Fatalf("healthy peer received %d recovery updates, want 1", got)
+ }
+ t.Logf("four slow deliveries used %v and the fifth peer converged on reconciliation", elapsed)
+}
+
+func TestGroupedCreateReconcileBarrierDrainsAfterAcknowledgment(t *testing.T) {
+ peer, node, ibs, remote := setupGroupedCreatePeer(t)
+ blocked, release := make(chan struct{}), make(chan struct{})
+ free := sync.OnceFunc(func() { close(release) })
+ var workers sync.WaitGroup
+ t.Cleanup(func() { free(); workers.Wait() })
+ peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) {
+ close(blocked)
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ return
+ }
+ apply(len(payload.InboundIds))
+ _, _ = w.Write([]byte(`{"success":true}`))
+ }
+ created, reconciled := make(chan error, 1), make(chan error, 1)
+ inboundSvc := &InboundService{}
+ workers.Go(func() {
+ _, err := (&ClientService{}).Create(inboundSvc, &ClientCreatePayload{
+ Client: groupedRecoveryClient("reconcile-barrier@x"), InboundIds: []int{ibs[0].Id, ibs[1].Id},
+ })
+ created <- err
+ })
+ waitTrafficWriterSignal(t, blocked, "grouped add never reached peer")
+ workers.Go(func() { reconciled <- inboundSvc.ReconcileNode(t.Context(), remote, node) })
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ nodeConfigDispatchMu.Lock()
+ q := nodeConfigDispatch[node.Id]
+ waiting := q != nil && q.reconciles == 1
+ nodeConfigDispatchMu.Unlock()
+ if waiting {
+ break
+ }
+ select {
+ case err := <-reconciled:
+ t.Fatalf("reconcile overtook the blocked grouped create, err=%v", err)
+ default:
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("reconciliation never reached the node-wide barrier")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ free()
+ for _, done := range []<-chan error{created, reconciled} {
+ if err := waitTrafficWriterErr(t, done); err != nil {
+ t.Fatal(err)
+ }
+ }
+ assertGroupedRecovery(t, peer, node, remote, ibs, 1, nil)
+}
diff --git a/internal/web/service/client_create_reads_test.go b/internal/web/service/client_create_reads_test.go
new file mode 100644
index 000000000..283c7cc83
--- /dev/null
+++ b/internal/web/service/client_create_reads_test.go
@@ -0,0 +1,174 @@
+package service
+
+import (
+ "encoding/hex"
+ "fmt"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+type inboundSettingsReads struct {
+ mu sync.Mutex
+ sizes []int
+}
+
+func trackInboundSettingsReads(t testing.TB) *inboundSettingsReads {
+ t.Helper()
+ reads := &inboundSettingsReads{}
+ query := database.GetDB().Callback().Query()
+ const name = "test:track_client_inbound_settings"
+ if err := query.After("gorm:query").Register(name, func(tx *gorm.DB) {
+ if tx.Statement.Table != "inbounds" || tx.Error != nil {
+ return
+ }
+ projection, _, _ := strings.Cut(tx.Statement.SQL.String(), " FROM ")
+ if !strings.Contains(projection, "settings") && !strings.Contains(projection, "*") {
+ return
+ }
+ reads.mu.Lock()
+ defer reads.mu.Unlock()
+ switch dest := tx.Statement.Dest.(type) {
+ case *model.Inbound:
+ reads.sizes = append(reads.sizes, len(dest.Settings))
+ case *[]string:
+ for _, settings := range *dest {
+ reads.sizes = append(reads.sizes, len(settings))
+ }
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := query.Remove(name); err != nil {
+ t.Error(err)
+ }
+ })
+ return reads
+}
+
+func seedInboundSettingsReadTest(t *testing.T, port int, protocol model.Protocol, settings string) *model.Inbound {
+ t.Helper()
+ ib := &model.Inbound{Tag: fmt.Sprintf("settings-reads-%d", port), Enable: true, Port: port, Protocol: protocol, Settings: settings}
+ if err := database.GetDB().Create(ib).Error; err != nil {
+ t.Fatal(err)
+ }
+ return ib
+}
+
+func TestClientCreateReadsInboundSettingsOnlyForMutation(t *testing.T) {
+ setupBulkDB(t)
+ const flow = "xtls-rprx-vision"
+ ib := seedInboundSettingsReadTest(t, 23121, model.VLESS, `{"clients":[],"decryption":"mlkem768x25519plus.native.0rtt.test"}`)
+ reads := trackInboundSettingsReads(t)
+
+ if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
+ InboundIds: []int{ib.Id},
+ Client: model.Client{Email: "create-reads@example.test", Flow: flow},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ want := []int{0, len(ib.Settings), len(ib.Settings)}
+ if !slices.Equal(reads.sizes, want) {
+ t.Fatalf("inbound settings bytes by read = %v, want %v (preparation, locked read, transaction guard)", reads.sizes, want)
+ }
+ if client, found := settingsClient(t, ib.Id, "create-reads@example.test"); !found || client.Flow != flow {
+ t.Fatalf("encrypted VLESS inbound saved flow %q, want %q", client.Flow, flow)
+ }
+}
+
+func TestClientCreateClearsFlowOnIneligibleInbound(t *testing.T) {
+ setupBulkDB(t)
+ ib := seedInboundSettingsReadTest(t, 23123, model.VLESS, `{"clients":[],"decryption":"none"}`)
+ if _, err := (&ClientService{}).CreateOne(&InboundService{}, ib.Id, model.Client{
+ Email: "create-noflow@example.test", Flow: "xtls-rprx-vision",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if client, found := settingsClient(t, ib.Id, "create-noflow@example.test"); !found || client.Flow != "" {
+ t.Fatalf("ineligible VLESS inbound has client=%v with flow %q, want client without flow", found, client.Flow)
+ }
+}
+
+func TestClientCreatePreservesSettingsBasedDefaults(t *testing.T) {
+ setupBulkDB(t)
+ const method = "2022-blake3-aes-256-gcm"
+ const domain = "front.example.test"
+ ss := seedInboundSettingsReadTest(t, 23124, model.Shadowsocks, `{"clients":[],"method":"`+method+`","password":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}`)
+ mt := seedInboundSettingsReadTest(t, 23125, model.MTProto, `{"clients":[],"fakeTlsDomain":"`+domain+`"}`)
+ const email = "create-defaults@example.test"
+ if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
+ InboundIds: []int{ss.Id, mt.Id},
+ Client: model.Client{Email: email},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if client, found := settingsClient(t, ss.Id, email); !found || !validShadowsocksClientKey(method, client.Password) {
+ t.Fatalf("Shadowsocks client found=%v, want a valid %s key", found, method)
+ }
+ if client, found := settingsClient(t, mt.Id, email); !found || !model.ValidMtprotoSecret(client.Secret) ||
+ !strings.HasSuffix(client.Secret, hex.EncodeToString([]byte(domain))) {
+ t.Fatalf("MTProto client found=%v, want a valid FakeTLS secret for %s", found, domain)
+ }
+}
+
+func TestUpdateInboundClientReadsSettingsOnceBeforeCommit(t *testing.T) {
+ setupBulkDB(t)
+ svc, inbounds := &ClientService{}, &InboundService{}
+ client := model.Client{Email: "update-reads@example.test", ID: "225452da-1385-4a1c-84ab-05481e000001", SubID: "update-reads"}
+ ib := seedInboundSettingsReadTest(t, 23122, model.VLESS, clientsSettings(t, []model.Client{client}))
+ if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
+ t.Fatal(err)
+ }
+ reads := trackInboundSettingsReads(t)
+
+ client.Comment = "changed"
+ if _, err := svc.UpdateInboundClient(inbounds, &model.Inbound{
+ Id: ib.Id, Settings: clientsSettings(t, []model.Client{client}),
+ }, client.Email); err != nil {
+ t.Fatal(err)
+ }
+ want := []int{len(ib.Settings), len(ib.Settings)}
+ if !slices.Equal(reads.sizes, want) {
+ t.Fatalf("inbound settings bytes by read = %v, want %v (locked read, transaction guard)", reads.sizes, want)
+ }
+}
+
+func BenchmarkClientCreateLargeInboundSettings(b *testing.B) {
+ setupScaleDB(b)
+ const inbounds, clientsPerInbound = 11, 4000
+ data := seedScaleDataset(b, inbounds*clientsPerInbound, inbounds)
+ svc, inboundSvc := &ClientService{}, &InboundService{}
+ reads := trackInboundSettingsReads(b)
+ var times []time.Duration
+ for b.Loop() {
+ payload := &ClientCreatePayload{
+ InboundIds: data.inboundIds,
+ Client: model.Client{Email: fmt.Sprintf("add-%d@example.test", len(times))},
+ }
+ start := time.Now()
+ if _, err := svc.Create(inboundSvc, payload); err != nil {
+ b.Fatal(err)
+ }
+ times = append(times, time.Since(start))
+ }
+ slices.Sort(times)
+ b.ReportMetric(float64(times[(95*len(times)+99)/100-1].Microseconds())/1000, "p95-ms")
+ bytes, blobs := 0, 0
+ for _, size := range reads.sizes {
+ bytes += size
+ if size > 0 {
+ blobs++
+ }
+ }
+ b.ReportMetric(float64(len(reads.sizes))/float64(b.N), "inbound-projections/op")
+ b.ReportMetric(float64(bytes)/float64(b.N), "settings-bytes/op")
+ b.ReportMetric(float64(blobs)/float64(b.N), "settings-reads/op")
+}
diff --git a/internal/web/service/client_create_reconcile_test.go b/internal/web/service/client_create_reconcile_test.go
new file mode 100644
index 000000000..e56e722fc
--- /dev/null
+++ b/internal/web/service/client_create_reconcile_test.go
@@ -0,0 +1,489 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
+)
+
+type groupedCreatePeer struct {
+ mu sync.Mutex
+ tags map[string]int
+ settings map[int]string
+ adds []ClientCreatePayload
+ updates []int
+ respond func(http.ResponseWriter, *http.Request, ClientCreatePayload, func(int))
+ mutate func(http.ResponseWriter, *http.Request)
+}
+
+func (p *groupedCreatePeer) serve(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/inbounds/catalog"), strings.HasSuffix(r.URL.Path, "/inbounds/list"):
+ p.mu.Lock()
+ catalog := make([]runtime.RemoteInboundOption, 0, len(p.tags))
+ for tag, id := range p.tags {
+ catalog = append(catalog, runtime.RemoteInboundOption{Id: id, Tag: tag})
+ }
+ p.mu.Unlock()
+ _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": catalog})
+ case strings.HasSuffix(r.URL.Path, "/clients/add"):
+ var payload ClientCreatePayload
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ p.mu.Lock()
+ p.adds = append(p.adds, payload)
+ p.mu.Unlock()
+ apply := func(count int) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ for _, id := range payload.InboundIds[:count] {
+ var settings map[string]any
+ _ = json.Unmarshal([]byte(p.settings[id]), &settings)
+ clients, _ := settings["clients"].([]any)
+ if slices.ContainsFunc(clients, func(entry any) bool {
+ _, email := clientEntryEmail(entry)
+ return email == payload.Client.Email
+ }) {
+ continue
+ }
+ settings["clients"] = append(clients, payload.Client)
+ encoded, _ := json.Marshal(settings)
+ p.settings[id] = string(encoded)
+ }
+ }
+ if p.respond != nil {
+ p.respond(w, r, payload, apply)
+ return
+ }
+ apply(len(payload.InboundIds))
+ _, _ = w.Write([]byte(`{"success":true}`))
+ case strings.Contains(r.URL.Path, "/inbounds/update/"):
+ _, suffix, _ := strings.Cut(r.URL.Path, "/inbounds/update/")
+ id, err := strconv.Atoi(suffix)
+ if err != nil || r.ParseForm() != nil || r.Form.Get("settings") == "" {
+ http.Error(w, "missing inbound ID or settings", http.StatusBadRequest)
+ return
+ }
+ p.mu.Lock()
+ p.settings[id] = r.Form.Get("settings")
+ p.updates = append(p.updates, id)
+ p.mu.Unlock()
+ _, _ = w.Write([]byte(`{"success":true}`))
+ default:
+ if p.mutate == nil {
+ http.NotFound(w, r)
+ } else {
+ p.mutate(w, r)
+ }
+ }
+}
+
+func TestGroupedCreateRecoversIndeterminateDelivery(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ reason string
+ reply func(w http.ResponseWriter, r *http.Request, apply func(int))
+ }{
+ {"partially applied HTTP error", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) {
+ apply(1)
+ http.Error(w, "second write failed", http.StatusInternalServerError)
+ }},
+ {"lost acknowledgment", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) {
+ apply(2)
+ conn, _, err := w.(http.Hijacker).Hijack()
+ if err == nil {
+ _ = conn.Close()
+ }
+ }},
+ {"deadline after persistence", "timeout", func(_ http.ResponseWriter, r *http.Request, apply func(int)) {
+ apply(2)
+ <-r.Context().Done()
+ }},
+ {"malformed acknowledgment", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) {
+ apply(1)
+ _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":"unknown"}}`))
+ }},
+ {"downstream pending", "downstream_pending", func(w http.ResponseWriter, _ *http.Request, apply func(int)) {
+ apply(2)
+ _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":true}}`))
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ peer, node, inbounds, remote := setupGroupedCreatePeer(t)
+ peer.respond = func(w http.ResponseWriter, r *http.Request, _ ClientCreatePayload, apply func(int)) {
+ tc.reply(w, r, apply)
+ }
+ client := groupedRecoveryClient("unknown-delivery@x")
+ svc := (&ClientService{}).TrackNodeApplies()
+ inboundSvc := &InboundService{}
+ payload := &ClientCreatePayload{Client: client, InboundIds: []int{inbounds[0].Id, inbounds[1].Id}}
+ if _, err := svc.Create(inboundSvc, payload); err != nil {
+ t.Fatal(err)
+ }
+ wantGroupedOutcome(t, &svc, node.Id, "pending", tc.reason)
+ dirtyAt := groupedDirtyGeneration(t, node.Id)
+ if _, err := (&ClientService{}).Create(inboundSvc, payload); err != nil {
+ t.Fatal(err)
+ }
+ if got := groupedDirtyGeneration(t, node.Id); dirtyAt != got {
+ t.Fatalf("idempotent create changed generation from %d to %d", dirtyAt, got)
+ }
+ for _, inbound := range inbounds {
+ if got := settingsClientEmails(t, inbound.Id); !slices.Equal(got, []string{client.Email}) {
+ t.Fatalf("master inbound %d lost or duplicated commits: %v", inbound.Id, got)
+ }
+ }
+ want := []int{101, 102}
+ if tc.reason == "downstream_pending" {
+ want = nil
+ }
+ assertGroupedRecovery(t, peer, node, remote, inbounds, 1, want)
+ })
+ }
+}
+
+func TestGroupedCreateDispatchesIndependentReadyPayload(t *testing.T) {
+ peer, _, inbounds, _ := setupGroupedCreatePeer(t)
+ first, second := inbounds[0], inbounds[1]
+ if err := database.GetDB().Model(first).Update("stream_settings", `{"network":"tcp","security":"reality"}`).Error; err != nil {
+ t.Fatal(err)
+ }
+ slow, healthy, release := make(chan struct{}), make(chan struct{}), make(chan struct{})
+ free := sync.OnceFunc(func() { close(release) })
+ t.Cleanup(free)
+ peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) {
+ if slices.Equal(payload.InboundIds, []int{101}) && payload.Client.Flow == "xtls-rprx-vision" {
+ close(slow)
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ return
+ }
+ } else if slices.Equal(payload.InboundIds, []int{102}) && payload.Client.Flow == "" {
+ close(healthy)
+ } else {
+ http.Error(w, "unexpected grouping", http.StatusBadRequest)
+ return
+ }
+ apply(1)
+ _, _ = w.Write([]byte(`{"success":true}`))
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
+ done := make(chan struct{})
+ var createErr error
+ t.Cleanup(func() { cancel(); free(); <-done })
+ go func() {
+ defer close(done)
+ client := groupedRecoveryClient("independent-flow@x")
+ client.Flow = "xtls-rprx-vision"
+ _, createErr = (&ClientService{}).CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{
+ Client: client, InboundIds: []int{first.Id, second.Id},
+ })
+ }()
+ for _, call := range []<-chan struct{}{slow, healthy} {
+ select {
+ case <-call:
+ case <-ctx.Done():
+ t.Fatal("independent payload waited behind the parked RPC")
+ }
+ }
+ free()
+ <-done
+ if createErr != nil {
+ t.Fatal(createErr)
+ }
+}
+
+func TestGroupedCreateRepairsDeferredTargets(t *testing.T) {
+ for _, scenario := range []string{"missing tag", "disabled client", "pruned orphan", "one rollback", "transport panic"} {
+ t.Run(scenario, func(t *testing.T) {
+ peer, node, inbounds, remote := setupGroupedCreatePeer(t)
+ first, second := inbounds[0], inbounds[1]
+ db := database.GetDB()
+ wantAdds, status, reason, want := 1, "pending", "deferred", []int{101}
+ client := groupedRecoveryClient("recover-target@x")
+ switch scenario {
+ case "missing tag":
+ delete(peer.tags, first.Tag)
+ reason = "push_failed"
+ case "disabled client":
+ client.Enable = false
+ wantAdds, want = 0, []int{101, 102}
+ case "pruned orphan":
+ first.Settings = clientsSettings(t, []model.Client{groupedRecoveryClient("removed@x")})
+ if err := db.Model(first).Update("settings", first.Settings).Error; err != nil {
+ t.Fatal(err)
+ }
+ remote.RecordAdoptedInbound(first)
+ peer.settings[101] = first.Settings
+ case "one rollback":
+ status, reason, want = "failed", "local_save_failed", nil
+ const callback = "test:grouped-create-local-rollback"
+ if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) {
+ vars := tx.Statement.Vars
+ if tx.Statement.Table == "inbounds" && len(vars) == 2 && vars[1] == first.Id {
+ _ = tx.AddError(errors.New("forced create rollback"))
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) })
+ case "transport panic":
+ wantAdds, reason, want = 0, "push_failed", []int{101, 102}
+ failing := *node
+ failing.OutboundTag = "test-egress"
+ remote = runtime.NewRemote(&failing, panickingCreateEgress{})
+ runtime.GetManager().SetRuntimeOverride(node.Id, remote)
+ for _, inbound := range inbounds {
+ remote.RecordAdoptedInbound(inbound)
+ }
+ }
+ svc := (&ClientService{}).TrackNodeApplies()
+ _, err := svc.Create(&InboundService{}, &ClientCreatePayload{Client: client, InboundIds: []int{first.Id, second.Id}})
+ if scenario == "one rollback" {
+ if err == nil || !strings.Contains(err.Error(), "forced create rollback") {
+ t.Fatalf("partial local failure = %v", err)
+ }
+ if _, ok := settingsClient(t, first.Id, client.Email); ok {
+ t.Fatal("rolled back inbound retained its client")
+ }
+ } else if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := settingsClient(t, second.Id, client.Email); !ok {
+ t.Fatal("successful inbound lost its committed client")
+ }
+ wantGroupedOutcome(t, &svc, node.Id, status, reason)
+ groupedDirtyGeneration(t, node.Id)
+ if scenario == "transport panic" {
+ nodeConfigDispatchMu.Lock()
+ leftover := nodeConfigDispatch[node.Id]
+ nodeConfigDispatchMu.Unlock()
+ if leftover != nil {
+ t.Fatal("recovered transport panic left a reserved node turn")
+ }
+ remote = runtime.NewRemote(node, nil)
+ }
+ peer.mu.Lock()
+ peer.tags[first.Tag] = 101
+ peer.mu.Unlock()
+ assertGroupedRecovery(t, peer, node, remote, inbounds, wantAdds, want)
+ })
+ }
+}
+
+type panickingCreateEgress struct{}
+
+func (panickingCreateEgress) NodeEgressProxyURL(int) string { panic("fixture egress failure") }
+
+func TestGroupedCreatePreservesProtocolCredentials(t *testing.T) {
+ for _, tc := range []struct {
+ protocol model.Protocol
+ settings string
+ check func(model.Client) bool
+ }{
+ {model.Shadowsocks, `{"clients":[],"method":"2022-blake3-aes-128-gcm"}`, func(c model.Client) bool {
+ return validShadowsocksClientKey("2022-blake3-aes-128-gcm", c.Password)
+ }},
+ {model.MTProto, `{"clients":[],"fakeTlsDomain":"example.test"}`, func(c model.Client) bool { return c.Secret != "" }},
+ {model.TUIC, `{"clients":[]}`, func(c model.Client) bool { return c.ID != "" && c.Password != "" }},
+ } {
+ t.Run(string(tc.protocol), func(t *testing.T) {
+ peer, _, inbounds, remote := setupGroupedCreatePeer(t)
+ db := database.GetDB()
+ var ids []int
+ for _, ib := range inbounds {
+ if err := db.Model(ib).Updates(map[string]any{"protocol": tc.protocol, "settings": tc.settings}).Error; err != nil {
+ t.Fatal(err)
+ }
+ ids = append(ids, ib.Id)
+ }
+ first, second := inbounds[0], inbounds[1]
+ delete(peer.tags, first.Tag)
+ peer.tags["adopted-legacy-tag"] = 101
+ remote.AdoptInboundAlias(first, runtime.RemoteInboundOption{Tag: "adopted-legacy-tag", Id: 101})
+ delete(peer.tags, second.Tag)
+ peer.tags["n"+strconv.Itoa(*second.NodeID)+"-"+second.Tag] = 102
+
+ const email = "protocol-default-create"
+ if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
+ Client: model.Client{Email: email, Enable: true}, InboundIds: ids,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ peer.mu.Lock()
+ adds := slices.Clone(peer.adds)
+ peer.mu.Unlock()
+ if len(adds) != 1 || !slices.Equal(adds[0].InboundIds, []int{101, 102}) || !tc.check(adds[0].Client) {
+ t.Fatalf("expected one acknowledged %s add with generated credentials and both mapped IDs", tc.protocol)
+ }
+ want := adds[0].Client
+ for _, ib := range inbounds {
+ local, ok := settingsClient(t, ib.Id, email)
+ if !ok || local.ID != want.ID || local.Secret != want.Secret || local.Password != want.Password {
+ t.Fatalf("grouped RPC changed the local %s credentials for inbound %d", tc.protocol, ib.Id)
+ }
+ }
+ })
+ }
+}
+
+func groupedRecoveryClient(email string) model.Client {
+ return model.Client{
+ Email: email, Enable: true, ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: email,
+ }
+}
+
+func wantGroupedOutcome(t *testing.T, svc *ClientService, nodeID int, status, reason string) {
+ t.Helper()
+ res := svc.NodeApplyResponse()
+ want := []ClientNodeApplyOutcome{{NodeID: nodeID, Status: status, Reason: reason}}
+ if res == nil || res.NodePending != (status == "pending") || !slices.Equal(res.NodeResults, want) {
+ t.Fatalf("node outcome = %+v, want %v", res, want)
+ }
+}
+
+func groupedDirtyGeneration(t *testing.T, nodeID int) int64 {
+ t.Helper()
+ _, _, dirty, generation, err := (&NodeService{}).NodeSyncState(nodeID)
+ if err != nil || !dirty || generation <= 0 {
+ t.Fatalf("node dirty=%t generation=%d err=%v", dirty, generation, err)
+ }
+ return generation
+}
+
+func assertGroupedRecovery(t *testing.T, peer *groupedCreatePeer, node *model.Node, remote *runtime.Remote, inbounds []*model.Inbound, addCount int, wantUpdates []int) {
+ t.Helper()
+ svc := &InboundService{}
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
+ defer cancel()
+ for range 2 {
+ if err := svc.ReconcileNode(ctx, remote, node); err != nil {
+ t.Fatal(err)
+ }
+ }
+ peer.mu.Lock()
+ defer peer.mu.Unlock()
+ slices.Sort(peer.updates)
+ if len(peer.adds) != addCount || !slices.Equal(peer.updates, wantUpdates) {
+ t.Fatalf("add RPCs=%d, repaired IDs=%v, want %d and %v", len(peer.adds), peer.updates, addCount, wantUpdates)
+ }
+ for _, ib := range inbounds {
+ master := settingsClientEmails(t, ib.Id)
+ var doc struct{ Clients []model.Client }
+ if err := json.Unmarshal([]byte(peer.settings[peer.tags[ib.Tag]]), &doc); err != nil {
+ t.Fatal(err)
+ }
+ if got := emailsOf(doc.Clients); !slices.Equal(got, master) {
+ t.Fatalf("node inbound %q has %v, master has %v", ib.Tag, got, master)
+ }
+ }
+}
+
+func setupGroupedCreatePeer(t *testing.T) (*groupedCreatePeer, *model.Node, []*model.Inbound, *runtime.Remote) {
+ t.Helper()
+ setupClientNodeOrderDB(t)
+ mgr := useTestRuntimeManager(t)
+ peer := &groupedCreatePeer{tags: map[string]int{}, settings: map[int]string{}}
+ srv := httptest.NewServer(http.HandlerFunc(peer.serve))
+ t.Cleanup(srv.Close)
+ nodeHTTP := &fakeNodeHTTP{srv: srv, tags: peer.tags}
+ first := realNodeInbound(t, nodeHTTP, 46201, nil)
+ second := nodeInbound(t, *first.NodeID, 46202, nil)
+ peer.tags[second.Tag] = 102
+ var node model.Node
+ if err := database.GetDB().First(&node, *first.NodeID).Error; err != nil {
+ t.Fatal(err)
+ }
+ rt, err := mgr.RuntimeFor(&node.Id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ remote, ok := rt.(*runtime.Remote)
+ if !ok {
+ t.Fatalf("runtime = %T, want actual remote", rt)
+ }
+ inbounds := []*model.Inbound{first, second}
+ for _, inbound := range inbounds {
+ remote.RecordAdoptedInbound(inbound)
+ peer.settings[peer.tags[inbound.Tag]] = inbound.Settings
+ }
+ return peer, &node, inbounds, remote
+}
+
+func TestGroupedCreateReconcilesUnsentRebasedSettings(t *testing.T) {
+ peer, node, inbounds, remote := setupGroupedCreatePeer(t)
+ svc := (&ClientService{}).TrackNodeApplies()
+ inboundSvc := &InboundService{}
+ changed := inbounds[0]
+ client := model.Client{
+ Email: "group-rebased@x", Enable: true,
+ ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: "group-rebased",
+ }
+ db := database.GetDB()
+ var inject sync.Once
+ const callback = "test:concurrent-settings-before-grouped-write"
+ if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) {
+ read, ok := tx.Statement.Dest.(*model.Inbound)
+ if ok && read.Id == changed.Id && read.Settings == changed.Settings {
+ // VLESS preparation omits settings. The first full read is under the mutation lock.
+ inject.Do(func() {
+ _ = tx.AddError(db.Model(&model.Inbound{}).Where("id = ?", changed.Id).
+ Update("settings", `{"clients":[],"decryption":"none"}`).Error)
+ })
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) })
+ _, createErr := svc.Create(inboundSvc, &ClientCreatePayload{
+ Client: client, InboundIds: []int{changed.Id, inbounds[1].Id},
+ })
+ if createErr != nil {
+ t.Fatal(createErr)
+ }
+ for _, inbound := range inbounds {
+ if c, ok := settingsClient(t, inbound.Id, client.Email); !ok || c.ID != client.ID {
+ t.Fatalf("master lost grouped client in inbound %d: %+v", inbound.Id, c)
+ }
+ }
+ stored, err := inboundSvc.GetInbound(changed.Id)
+ if err != nil || !strings.Contains(stored.Settings, `"decryption": "none"`) {
+ t.Fatalf("master lost concurrent settings change: %+v, %v", stored, err)
+ }
+ peer.mu.Lock()
+ adds := slices.Clone(peer.adds)
+ delivered := peer.settings[101]
+ peer.mu.Unlock()
+ if len(adds) != 1 || !slices.Equal(adds[0].InboundIds, []int{101, 102}) || adds[0].Client.Email != client.Email ||
+ strings.Contains(delivered, "decryption") || !strings.Contains(delivered, client.Email) {
+ t.Fatalf("grouped add was not limited to the new client: %+v, peer settings %s", adds, delivered)
+ }
+ for range 2 {
+ if err := inboundSvc.ReconcileNode(t.Context(), remote, node); err != nil {
+ t.Fatal(err)
+ }
+ }
+ peer.mu.Lock()
+ defer peer.mu.Unlock()
+ if !slices.Equal(peer.updates, []int{101}) || peer.settings[101] != stored.Settings {
+ t.Fatalf("reconcile updates=%v settings=%s, want exactly one repair of inbound 101", peer.updates, peer.settings[101])
+ }
+}
diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go
index 687f45f01..780cfcf29 100644
--- a/internal/web/service/client_crud.go
+++ b/internal/web/service/client_crud.go
@@ -1,6 +1,7 @@
package service
import (
+ "context"
"encoding/base64"
"encoding/json"
"errors"
@@ -203,6 +204,11 @@ func quotaDisabledEmails(tx *gorm.DB, within []string) ([]string, error) {
// Create applies the client to every requested inbound: one failing inbound no
// longer aborts the others, so the error can name several and needRestart holds.
func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
+ return s.CreateWithContext(context.Background(), inboundSvc, payload)
+}
+
+// CreateWithContext applies the request context to delivery after the local commits.
+func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
if payload == nil {
return false, common.NewError("empty payload")
}
@@ -289,7 +295,7 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate
// shared credentials on the first inbound and every later one reuses them.
adds := make([]*model.Inbound, 0, len(payload.InboundIds))
for _, ibId := range payload.InboundIds {
- inbound, getErr := inboundSvc.GetInbound(ibId)
+ inbound, getErr := getInboundForClientPreparation(ibId, client.Secret == "")
if getErr != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, getErr)
}
@@ -311,27 +317,42 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate
if err := validateAmneziaWGClientWrite(inbound, []model.Client{clientForInbound}, ""); err != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, err)
}
- settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}})
+ settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientForInbound}})
if mErr != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, mErr)
}
adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID})
}
- needRestart, fanoutErr := s.fanoutInboundClientAdds(inboundSvc, adds)
- if fanoutErr != nil {
- // Never on a failed create: this retrims the devices of an email that
- // already existed, and a create the panel reported as failed must not.
- return needRestart, fanoutErr
- }
- // nil means omitted and preserves the stored binding.
- if client.ClientHostRuleIds != nil {
- if err := database.GetDB().Model(&model.ClientRecord{}).
+ pushes := make([]queuedClientCreate, len(adds))
+ needRestart, saveErr := s.fanoutInboundClientAdds(inboundSvc, adds, pushes)
+ // Finish create metadata before remote delivery can overlap a later rename.
+ if saveErr == nil && client.ClientHostRuleIds != nil {
+ saveErr = database.GetDB().Model(&model.ClientRecord{}).
Where("email = ?", client.Email).
- Update("client_host_rule_ids", model.EncodeClientHostRuleIds(client.ClientHostRuleIds)).Error; err != nil {
- return needRestart, err
- }
+ Update("client_host_rule_ids", model.EncodeClientHostRuleIds(client.ClientHostRuleIds)).Error
}
- return needRestart, s.setClientLimitHwidByEmail(client.Email, payload.LimitHwid)
+ if saveErr == nil {
+ saveErr = s.setClientLimitHwidByEmail(client.Email, payload.LimitHwid)
+ }
+ remoteRestart, pushErr := s.pushClientCreates(ctx, pushes)
+ return needRestart || remoteRestart, errors.Join(saveErr, pushErr)
+}
+
+// getInboundForClientPreparation returns the settings blob only for protocols
+// that need it to prepare the client before any writes.
+func getInboundForClientPreparation(id int, generateSecret bool) (*model.Inbound, error) {
+ protocolsWithSettings := []model.Protocol{model.Shadowsocks, model.AmneziaWG}
+ if generateSecret {
+ protocolsWithSettings = append(protocolsWithSettings, model.MTProto)
+ }
+ var inbound model.Inbound
+ if err := database.GetDB().Select(
+ "id, node_id, protocol, enable, listen, CASE WHEN protocol IN ? THEN settings ELSE '' END AS settings",
+ protocolsWithSettings,
+ ).First(&inbound, id).Error; err != nil {
+ return nil, err
+ }
+ return &inbound, nil
}
// inboundFanoutConcurrency caps how many inbounds one client op applies at
@@ -384,12 +405,15 @@ func fanoutInboundApplies(applies []inboundApply) (bool, error) {
return needRestart.Load(), errors.Join(errs...)
}
-// fanoutInboundClientAdds applies one payload per inbound.
-func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) {
+func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound, pushes []queuedClientCreate) (bool, error) {
applies := make([]inboundApply, 0, len(adds))
- for _, add := range adds {
+ for i, add := range adds {
+ var queued *queuedClientCreate
+ if pushes != nil {
+ queued = &pushes[i]
+ }
applies = append(applies, inboundApply{id: add.Id, nodeID: add.NodeID, run: func() (bool, error) {
- return s.AddInboundClient(inboundSvc, add)
+ return s.addInboundClient(inboundSvc, add, true, queued)
}})
}
return fanoutInboundApplies(applies)
@@ -596,7 +620,7 @@ func mtprotoDomainFromSettings(settings string) string {
}
func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
- if ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
+ if c.Flow != "" && (ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings)) {
c.Flow = ""
}
return c
@@ -886,7 +910,18 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model
// mints the shared credentials on the first inbound, later ones reuse them.
applies := make([]inboundApply, 0, len(inboundIds))
for _, ibId := range inboundIds {
- inbound, getErr := inboundSvc.GetInbound(ibId)
+ requestedFlow := updated.Flow
+ if keepInboundFlows {
+ requestedFlow = inboundFlows[ibId]
+ }
+
+ var inbound *model.Inbound
+ var getErr error
+ if requestedFlow == "" {
+ inbound, getErr = getInboundForClientPreparation(ibId, updated.Secret == "")
+ } else {
+ inbound, getErr = inboundSvc.GetInbound(ibId)
+ }
if getErr != nil {
if errors.Is(getErr, gorm.ErrRecordNotFound) {
if err := database.GetDB().
@@ -908,9 +943,7 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model
if inbound.Protocol == model.WireGuard && tunnelCount > 1 {
clientForInbound.WireguardDevices = nil
}
- if keepInboundFlows {
- clientForInbound.Flow = inboundFlows[ibId]
- }
+ clientForInbound.Flow = requestedFlow
if ips, ok := updated.AllowedIPsByInbound[ibId]; ok {
clientForInbound.AllowedIPs = ips
} else if tunnelCount > 1 && (inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG) {
@@ -1143,6 +1176,18 @@ func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic b
}
if err := runSerializedTx(func(tx *gorm.DB) error {
+ // A later create can commit while this delete's node turn is waiting.
+ var attached []int
+ if err := tx.Table("client_inbounds").
+ Joins("JOIN clients ON clients.id = client_inbounds.client_id").
+ Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id").
+ Where("clients.id = ? OR clients.email = ?", id, existing.Email).
+ Limit(1).Pluck("client_inbounds.client_id", &attached).Error; err != nil {
+ return err
+ }
+ if len(attached) != 0 {
+ return nil
+ }
if existing.Email != "" {
if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil {
return err
@@ -1313,13 +1358,13 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []
if err := s.fillProtocolDefaults(©Client, inbound); err != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, err)
}
- settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
+ settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {copyClient}})
if mErr != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, mErr)
}
adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID})
}
- return s.fanoutInboundClientAdds(inboundSvc, adds)
+ return s.fanoutInboundClientAdds(inboundSvc, adds, nil)
}
func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
diff --git a/internal/web/service/client_detach_selection.go b/internal/web/service/client_detach_selection.go
new file mode 100644
index 000000000..1850b5690
--- /dev/null
+++ b/internal/web/service/client_detach_selection.go
@@ -0,0 +1,352 @@
+package service
+
+import (
+ "cmp"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "maps"
+ "slices"
+ "strings"
+
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/xray"
+)
+
+const (
+ detachCandidatePageSize = 100
+ DetachSelectionLimit = 100_000
+)
+
+type DetachCandidateParams struct {
+ InboundID int `form:"inboundId"`
+ Page int `form:"page"`
+ Search string `form:"search"`
+}
+
+type DetachCandidate struct {
+ ID int `json:"id"`
+ Email string `json:"email"`
+ Comment string `json:"comment"`
+ Enable bool `json:"enable"`
+ InScope bool `json:"inScope"`
+ Incarnation string `json:"-"`
+}
+
+type DetachCandidatePage struct {
+ Items []DetachCandidate `json:"items"`
+ Total int64 `json:"total"`
+ Attached int64 `json:"attached"`
+}
+
+type DetachScopeSummary struct {
+ ScopeToken string `json:"scopeToken"`
+ Total int `json:"total"`
+}
+
+type DetachSelection struct {
+ Mode string `json:"mode"`
+ ClientIDs []int `json:"clientIds"`
+ ExcludedClientIDs []int `json:"excludedClientIds"`
+ ScopeToken string `json:"scopeToken"`
+}
+
+type DetachSelectionResult struct {
+ Detached int `json:"detached"`
+ Skipped int `json:"skipped"`
+ Errors int `json:"errors"`
+ NodePending bool `json:"nodePending,omitempty"`
+}
+
+type detachMembership struct {
+ ID int
+ Incarnation string
+}
+
+type DetachScope struct {
+ inboundID int
+ generation uint64
+ members []detachMembership
+}
+
+func detachCandidates(db *gorm.DB, id int, search string) *gorm.DB {
+ return filteredAttachCandidates(
+ db.Table("client_inbounds AS ci").Joins("JOIN clients AS c ON c.id = ci.client_id").
+ Where("ci.inbound_id = ? AND c.email <> ''", id),
+ id, search, "",
+ )
+}
+
+func (s *DetachScope) matches(id int) bool {
+ return s != nil && s.inboundID == id && s.generation == database.ConnectionGeneration()
+}
+
+func (s *DetachScope) has(id int, incarnation string) bool {
+ n, found := slices.BinarySearchFunc(s.members, id, func(m detachMembership, id int) int {
+ return cmp.Compare(m.ID, id)
+ })
+ return found && s.members[n].Incarnation == incarnation
+}
+
+func (s *ClientService) ListDetachCandidates(ctx context.Context, p DetachCandidateParams, scope *DetachScope) (*DetachCandidatePage, error) {
+ if p.InboundID <= 0 || p.Page < 0 || p.Page > 1_000_000 || len(p.Search) > 256 {
+ return nil, errors.New("invalid client detachment page")
+ }
+ if scope != nil && !scope.matches(p.InboundID) {
+ return nil, errors.New("client detachment selection expired")
+ }
+ db := database.GetDB().WithContext(ctx)
+ if _, err := attachScope(db, p.InboundID, nil); err != nil {
+ return nil, err
+ }
+ resp := &DetachCandidatePage{Items: []DetachCandidate{}}
+ q := detachCandidates(db, p.InboundID, p.Search)
+ if err := q.Count(&resp.Total).Error; err != nil {
+ return nil, err
+ }
+ resp.Attached = resp.Total
+ if strings.TrimSpace(p.Search) != "" {
+ if err := detachCandidates(db, p.InboundID, "").Count(&resp.Attached).Error; err != nil {
+ return nil, err
+ }
+ }
+ if err := q.Select("c.id, c.email, c.comment, c.enable, ci.incarnation").
+ Order("c.id").Offset(max(0, p.Page-1) * detachCandidatePageSize).
+ Limit(detachCandidatePageSize).Scan(&resp.Items).Error; err != nil {
+ return nil, err
+ }
+ for i := range resp.Items {
+ row := &resp.Items[i]
+ row.InScope = scope != nil && scope.has(row.ID, row.Incarnation)
+ }
+ return resp, nil
+}
+
+func (s *ClientService) FreezeDetachScope(ctx context.Context, inboundID int) (*DetachScope, int, error) {
+ if inboundID <= 0 {
+ return nil, 0, errors.New("invalid source inbound")
+ }
+ generation := database.ConnectionGeneration()
+ db := database.GetDB().WithContext(ctx)
+ if _, err := attachScope(db, inboundID, nil); err != nil {
+ return nil, 0, err
+ }
+ var members []detachMembership
+ err := detachCandidates(db, inboundID, "").Select("c.id, ci.incarnation").
+ Order("c.id").Limit(DetachSelectionLimit + 1).Scan(&members).Error
+ if err != nil {
+ return nil, 0, err
+ }
+ if len(members) == 0 || len(members) > DetachSelectionLimit {
+ return nil, 0, errors.New("no attached clients or detachment selection exceeds the limit")
+ }
+ return &DetachScope{inboundID: inboundID, generation: generation, members: members}, len(members), nil
+}
+
+type DetachPlan struct {
+ inboundID int
+ generation uint64
+ ids []int
+ scope *DetachScope
+}
+
+func NewDetachPlan(inboundID int, selection DetachSelection, scope *DetachScope) (*DetachPlan, error) {
+ if inboundID <= 0 || len(selection.ClientIDs) > DetachSelectionLimit || len(selection.ExcludedClientIDs) > DetachSelectionLimit {
+ return nil, errors.New("invalid client detachment selection")
+ }
+ plan := &DetachPlan{inboundID: inboundID, generation: database.ConnectionGeneration()}
+ switch selection.Mode {
+ case "explicit":
+ if len(selection.ExcludedClientIDs) != 0 || selection.ScopeToken != "" {
+ return nil, errors.New("invalid explicit client detachment selection")
+ }
+ plan.ids = uniqueInts(selection.ClientIDs)
+ for _, id := range plan.ids {
+ if id <= 0 {
+ return nil, errors.New("invalid client ID")
+ }
+ }
+ case "allMatching":
+ if len(selection.ClientIDs) != 0 || !scope.matches(inboundID) {
+ return nil, errors.New("client detachment selection expired or belongs to another inbound")
+ }
+ plan.scope = scope
+ excluded := make(map[int]struct{}, len(selection.ExcludedClientIDs))
+ for _, id := range selection.ExcludedClientIDs {
+ excluded[id] = struct{}{}
+ }
+ for _, m := range scope.members {
+ if _, skip := excluded[m.ID]; skip {
+ delete(excluded, m.ID)
+ } else {
+ plan.ids = append(plan.ids, m.ID)
+ }
+ }
+ if len(excluded) != 0 {
+ return nil, errors.New("excluded client is outside the frozen selection")
+ }
+ default:
+ return nil, errors.New("invalid client detachment selection mode")
+ }
+ if len(plan.ids) == 0 {
+ return nil, errors.New("no clients selected for detachment")
+ }
+ return plan, nil
+}
+
+func (p *DetachPlan) Total() int { return len(p.ids) }
+
+// ApplyDetachPlan updates the source settings once, even for a large selection.
+// SQL lookup/delta batches are bounded and commit with the same membership check.
+func (s *ClientService) ApplyDetachPlan(ctx context.Context, p *DetachPlan, progress func(int)) (*DetachSelectionResult, error) {
+ defer lockInbound(p.inboundID).Unlock()
+ result := &DetachSelectionResult{}
+ var previous, inbound model.Inbound
+ var detachedEmails []string
+ err := runSerializedTx(func(tx *gorm.DB) error {
+ if p.generation != database.ConnectionGeneration() || (p.scope != nil && !p.scope.matches(p.inboundID)) {
+ return errors.New("client detachment selection expired")
+ }
+ tx = tx.WithContext(context.WithValue(ctx, serializedTxContextKey{}, serializedTxOf(tx)))
+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&inbound, p.inboundID).Error; err != nil {
+ return err
+ }
+ if _, err := attachScope(tx, p.inboundID, nil); err != nil {
+ return err
+ }
+ emails := make(map[string]struct{})
+ processed := 0
+ for _, ids := range chunkInts(p.ids, sqlInChunk) {
+ var rows []DetachCandidate
+ err := detachCandidates(tx, p.inboundID, "").Where("c.id IN ?", ids).
+ Select("c.id, c.email, ci.incarnation").Scan(&rows).Error
+ if err != nil {
+ return err
+ }
+ for _, row := range rows {
+ if p.scope == nil || p.scope.has(row.ID, row.Incarnation) {
+ emails[row.Email] = struct{}{}
+ }
+ }
+ processed += len(ids)
+ if progress != nil {
+ progress(processed)
+ }
+ }
+ result.Detached, result.Skipped = len(emails), p.Total()-len(emails)
+ if len(emails) == 0 {
+ return nil
+ }
+ settings, err := detachClientSettings(inbound.Settings, emails)
+ if err != nil {
+ return err
+ }
+ previous = inbound
+ // The running core can have users that are missing or disabled in settings.
+ detachedEmails = slices.Collect(maps.Keys(emails))
+ if settings != inbound.Settings {
+ if err := tx.Model(&inbound).Update("settings", settings).Error; err != nil {
+ return err
+ }
+ }
+ if err := s.ApplyInboundClientDelta(tx, inbound.Id, nil, detachedEmails); err != nil {
+ return err
+ }
+ if inbound.NodeID != nil {
+ result.NodePending = true
+ return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
+ }
+ return nil
+ })
+ if err != nil {
+ return &DetachSelectionResult{Skipped: result.Skipped, Errors: p.Total() - result.Skipped}, err
+ }
+ if result.Detached > 0 {
+ InvalidateSubData()
+ }
+ if inbound.NodeID == nil && inbound.Enable && len(detachedEmails) > 0 {
+ if err := applyLocalScopedDetach(ctx, &previous, &inbound, detachedEmails); err != nil {
+ (&XrayService{}).SetToNeedReconcile()
+ return result, fmt.Errorf("memberships detached, but the local runtime has not applied the change: %w", err)
+ }
+ }
+ return result, nil
+}
+
+// Apply runtime changes after commit so the traffic writer stays free during RPC.
+func applyLocalScopedDetach(ctx context.Context, previous, inbound *model.Inbound, emails []string) error {
+ inbounds := &InboundService{}
+ core := &XrayService{}
+ rt, err := inbounds.runtimeFor(inbound)
+ if servedOutsideXray(inbound.Protocol) {
+ if err != nil {
+ return err
+ }
+ next, err := inbounds.buildInboundForLocalRuntime(database.GetDB(), inbound)
+ if err != nil {
+ return err
+ }
+ return rt.UpdateInbound(ctx, previous, next)
+ }
+
+ dropSessions := removalLeavesXraySessions(inbound) && restartAfterClientRemoval()
+ if err == nil && len(emails) <= nodeBulkPushThreshold && inbound.Protocol != model.WireGuard {
+ for _, email := range emails {
+ err = rt.RemoveUser(ctx, inbound, email)
+ if err != nil && !xray.IsMissingUserErr(err) {
+ break
+ }
+ err = nil
+ }
+ if err == nil && !dropSessions {
+ return nil
+ }
+ }
+ if !core.IsXrayRunning() {
+ return nil
+ }
+ // Large selections and failed live removals reconcile before the job finishes.
+ err = core.restartXrayFrom(false, XrayOriginConfigChange, "", dropSessions)
+ if err != nil && dropSessions {
+ pendingXraySessionDrop.Store(true)
+ }
+ return err
+}
+
+func detachClientSettings(raw string, emails map[string]struct{}) (string, error) {
+ var settings map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(raw), &settings); err != nil {
+ return "", err
+ }
+ var clients []json.RawMessage
+ if err := json.Unmarshal(settings["clients"], &clients); err != nil {
+ return "", fmt.Errorf("read inbound clients: %w", err)
+ }
+ kept := make([]json.RawMessage, 0, len(clients))
+ for _, client := range clients {
+ var identity struct {
+ Email string
+ }
+ err := json.Unmarshal(client, &identity)
+ email := strings.TrimSpace(identity.Email)
+ if _, remove := emails[email]; err == nil && remove {
+ continue
+ }
+ kept = append(kept, client)
+ }
+ if len(kept) == len(clients) {
+ return raw, nil
+ }
+ values, err := json.Marshal(kept)
+ if err != nil {
+ return "", err
+ }
+ settings["clients"] = values
+ out, err := json.Marshal(settings)
+ return string(out), err
+}
diff --git a/internal/web/service/client_detach_selection_test.go b/internal/web/service/client_detach_selection_test.go
new file mode 100644
index 000000000..ba8adc088
--- /dev/null
+++ b/internal/web/service/client_detach_selection_test.go
@@ -0,0 +1,290 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "testing"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/xray"
+)
+
+type scopedDetachRuntimeProbe struct {
+ fakeNodeRuntime
+ removed []string
+ updated *model.Inbound
+}
+
+func (p *scopedDetachRuntimeProbe) RemoveUser(_ context.Context, _ *model.Inbound, email string) error {
+ p.removed = append(p.removed, email)
+ return nil
+}
+
+func (p *scopedDetachRuntimeProbe) UpdateInbound(_ context.Context, _, next *model.Inbound) error {
+ p.updated = next
+ return nil
+}
+
+func TestScopedDetachAppliesLocalRuntimeBeforeReturning(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ protocol model.Protocol
+ staleJSON bool
+ omit bool
+ }{
+ {name: "vless", protocol: model.VLESS},
+ {name: "tuic", protocol: model.TUIC},
+ {name: "normalized-only vless", protocol: model.VLESS, staleJSON: true, omit: true},
+ {name: "stale-disabled vless", protocol: model.VLESS, staleJSON: true},
+ {name: "normalized-only tuic", protocol: model.TUIC, staleJSON: true, omit: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("scoped_detach_runtime")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ setupBulkDB(t)
+ probe := &scopedDetachRuntimeProbe{}
+ useTestRuntimeManager(t).SetLocalRuntimeOverride(probe)
+ clients := []model.Client{
+ {Email: "detach-live@test", ID: "c10b9d71-71ac-42b5-bc9d-a2697d9dbfa1", Enable: true},
+ {Email: "keep-live@test", ID: "c10b9d71-71ac-42b5-bc9d-a2697d9dbfa2", Enable: true},
+ }
+ inbound := mkInbound(t, 24004, tc.protocol, clientsSettings(t, clients))
+ svc := &ClientService{}
+ if err := svc.SyncInbound(nil, inbound.Id, clients); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range clients {
+ traffic := xray.ClientTraffic{Email: c.Email, InboundId: inbound.Id, Enable: true}
+ if err := database.GetDB().Create(&traffic).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ if tc.staleJSON {
+ stored := slices.Clone(clients)
+ if tc.omit {
+ stored = stored[1:]
+ } else {
+ stored[0].Enable = false
+ }
+ err := database.GetDB().Model(inbound).Update("settings", clientsSettings(t, stored)).Error
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ rec, err := svc.GetRecordByEmail(nil, clients[0].Email)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plan, err := NewDetachPlan(inbound.Id, DetachSelection{Mode: "explicit", ClientIDs: []int{rec.Id}}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result, err := svc.ApplyDetachPlan(t.Context(), plan, nil); err != nil || result.Detached != 1 {
+ t.Fatalf("detach = %+v, err %v", result, err)
+ }
+ if tc.protocol == model.VLESS {
+ if !slices.Equal(probe.removed, []string{clients[0].Email}) {
+ t.Fatalf("live core removals = %v", probe.removed)
+ }
+ } else {
+ if probe.updated == nil {
+ t.Fatal("local TUIC listener still has its old config")
+ }
+ remaining, err := (&InboundService{}).GetClients(probe.updated)
+ if err != nil || !slices.Equal(emailsOf(remaining), []string{clients[1].Email}) {
+ t.Fatalf("runtime clients = %v, err %v", emailsOf(remaining), err)
+ }
+ }
+ })
+ }
+}
+
+func TestScopedDetachMembershipAndPagination(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("scoped_detach")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ setupBulkDB(t)
+ db := database.GetDB()
+ svc := &ClientService{}
+ inboundSvc := &InboundService{}
+ ctx := t.Context()
+ clients := make([]model.Client, 125)
+ for i := range clients {
+ clients[i] = model.Client{Email: fmt.Sprintf("detach-%03d@test", i), ID: fmt.Sprintf("uuid-%d", i), Comment: "client", SubID: fmt.Sprintf("sub-%d", i)}
+ }
+ clients[123].Comment = "Special_% Name"
+ source := mkInbound(t, 24001, model.VLESS, clientsSettings(t, clients))
+ other := mkInbound(t, 24002, model.VLESS, clientsSettings(t, clients[:1]))
+ if err := svc.SyncInbound(nil, source.Id, clients); err != nil {
+ t.Fatal(err)
+ }
+ if err := svc.SyncInbound(nil, other.Id, clients[:1]); err != nil {
+ t.Fatal(err)
+ }
+ traffic := xray.ClientTraffic{Email: clients[0].Email, InboundId: other.Id, Up: 42, Down: 19, Total: 1000, ExpiryTime: 9999999999999}
+ if err := db.Create(&traffic).Error; err != nil {
+ t.Fatal(err)
+ }
+
+ p := DetachCandidateParams{InboundID: source.Id, Page: 1}
+ first, err := svc.ListDetachCandidates(ctx, p, nil)
+ if err != nil || len(first.Items) != 100 || first.Total != 125 || first.Attached != 125 {
+ t.Fatalf("first page: %+v, error %v", first, err)
+ }
+ p.Page = 2
+ second, err := svc.ListDetachCandidates(ctx, p, nil)
+ if err != nil || len(second.Items) != 25 || first.Items[99].ID >= second.Items[0].ID {
+ t.Fatalf("second page: %+v, error %v", second, err)
+ }
+ search, err := svc.ListDetachCandidates(ctx, DetachCandidateParams{InboundID: source.Id, Search: "special_%"}, nil)
+ if err != nil || search.Total != 1 || search.Attached != 125 || len(search.Items) != 1 || search.Items[0].Email != clients[123].Email {
+ t.Fatalf("literal comment search: %+v, error %v", search, err)
+ }
+ scope, total, err := svc.FreezeDetachScope(ctx, source.Id)
+ if err != nil || total != 125 {
+ t.Fatalf("freeze count %d, error %v", total, err)
+ }
+ excluded := second.Items[0]
+ selection := DetachSelection{Mode: "allMatching", ScopeToken: "test-token", ExcludedClientIDs: []int{excluded.ID, excluded.ID}}
+ if _, err := NewDetachPlan(other.Id, selection, scope); err == nil {
+ t.Fatal("a frozen scope was accepted for another inbound")
+ }
+ if _, err := NewDetachPlan(source.Id, DetachSelection{Mode: "explicit"}, nil); err == nil {
+ t.Fatal("an empty explicit selection was accepted")
+ }
+
+ // One old member is removed, one is reattached, and a new one is added.
+ if res, _, err := svc.BulkDetach(inboundSvc, []string{clients[1].Email, clients[1].Email}, []int{source.Id}); err != nil ||
+ len(res.Detached) != 1 || len(res.Errors) != 0 {
+ t.Fatalf("legacy duplicate-email detach = %+v, error %v", res, err)
+ }
+ relinked := &model.ClientInbound{InboundId: source.Id, ClientId: first.Items[2].ID}
+ var oldLink model.ClientInbound
+ if err := db.Where(relinked).First(&oldLink).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Where(relinked).Delete(&model.ClientInbound{}).Error; err != nil {
+ t.Fatal(err)
+ }
+ newClient := model.Client{Email: "late@test", ID: "late-id", SubID: "late"}
+ if err := db.Delete(&model.ClientRecord{}, first.Items[3].ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ current := append(slices.Clone(clients[:1]), clients[2])
+ current = append(current, clients[4:]...)
+ current = append(current, newClient)
+ if err := db.Model(source).Update("settings", clientsSettings(t, current)).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := svc.SyncInbound(nil, source.Id, current); err != nil {
+ t.Fatal(err)
+ }
+ // Force the same millisecond so a timestamp comparison cannot distinguish the reattach.
+ if err := db.Model(&model.ClientInbound{}).Where(relinked).Update("created_at", oldLink.CreatedAt).Error; err != nil {
+ t.Fatal(err)
+ }
+ replacement, err := svc.ListDetachCandidates(ctx, DetachCandidateParams{InboundID: source.Id, Search: clients[2].Email}, scope)
+ if err != nil || len(replacement.Items) != 1 || replacement.Items[0].InScope {
+ t.Fatalf("reattached membership shown as selected: %+v, error %v", replacement, err)
+ }
+ late, err := svc.ListDetachCandidates(ctx, DetachCandidateParams{InboundID: source.Id, Search: "late@test"}, scope)
+ if err != nil || len(late.Items) != 1 || late.Items[0].InScope {
+ t.Fatalf("late attachment shown as selected: %+v, error %v", late, err)
+ }
+ plan, err := NewDetachPlan(source.Id, selection, scope)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var processed int
+ result, err := svc.ApplyDetachPlan(ctx, plan, func(n int) { processed = n })
+ if err != nil || result.Detached != 121 || result.Skipped != 3 || result.Errors != 0 || processed != 124 {
+ t.Fatalf("scoped apply: %+v, processed %d, error %v", result, processed, err)
+ }
+ remaining, err := svc.ListForInbound(nil, source.Id)
+ want := []string{excluded.Email, clients[2].Email, newClient.Email}
+ slices.Sort(want)
+ if err != nil || !slices.Equal(sortedEmails(remaining), want) {
+ t.Fatalf("source memberships = %v, want %v, err %v", sortedEmails(remaining), want, err)
+ }
+ stored, err := inboundSvc.GetInbound(source.Id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ settingsClients, err := inboundSvc.GetClients(stored)
+ if err != nil || !slices.Equal(sortedEmails(settingsClients), want) {
+ t.Fatalf("source settings clients = %v, want %v, err %v", sortedEmails(settingsClients), want, err)
+ }
+ otherClients, err := svc.ListForInbound(nil, other.Id)
+ if err != nil || len(otherClients) != 1 || otherClients[0].Email != clients[0].Email {
+ t.Fatalf("other inbound changed: %+v, error %v", otherClients, err)
+ }
+ if _, err := svc.GetRecordByEmail(nil, clients[0].Email); err != nil {
+ t.Fatal(err)
+ }
+ var gotTraffic xray.ClientTraffic
+ if err := db.First(&gotTraffic, traffic.Id).Error; err != nil || gotTraffic.Up != traffic.Up ||
+ gotTraffic.Down != traffic.Down || gotTraffic.Total != traffic.Total || gotTraffic.ExpiryTime != traffic.ExpiryTime {
+ t.Fatalf("traffic changed: %+v, error %v", gotTraffic, err)
+ }
+}
+
+func TestScopedDetachQueuesOfflineNodeAndRollsBackInvalidSettings(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("scoped_detach_node")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ setupBulkDB(t)
+ db := database.GetDB()
+ svc := &ClientService{}
+ client := model.Client{Email: "node-detach@test", ID: "client-id", SubID: "sub"}
+ source := mkInbound(t, 24003, model.VLESS, clientsSettings(t, []model.Client{client}))
+ node := model.Node{Name: "detached-offline-node", Status: "offline"}
+ if err := db.Create(&node).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Model(source).Update("node_id", node.Id).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := svc.SyncInbound(nil, source.Id, []model.Client{client}); err != nil {
+ t.Fatal(err)
+ }
+ record, err := svc.GetRecordByEmail(nil, client.Email)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plan, err := NewDetachPlan(source.Id, DetachSelection{Mode: "explicit", ClientIDs: []int{record.Id, record.Id}}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ validSettings := source.Settings
+ if err := db.Model(source).Update("settings", "{}").Error; err != nil {
+ t.Fatal(err)
+ }
+ failed, err := svc.ApplyDetachPlan(t.Context(), plan, nil)
+ if err == nil || failed.Detached != 0 || failed.Errors != 1 {
+ t.Fatalf("malformed settings should fail atomically: %+v, error %v", failed, err)
+ }
+ if err := db.Model(source).Update("settings", validSettings).Error; err != nil {
+ t.Fatal(err)
+ }
+ res, err := svc.ApplyDetachPlan(t.Context(), plan, nil)
+ if err != nil || res.Detached != 1 || !res.NodePending {
+ t.Fatalf("offline detach result: %+v, error %v", res, err)
+ }
+ if err := db.First(&node, node.Id).Error; err != nil || !node.ConfigDirty {
+ t.Fatalf("node was not queued for reconciliation: %+v, error %v", node, err)
+ }
+ retry, err := svc.ApplyDetachPlan(t.Context(), plan, nil)
+ if err != nil || retry.Detached != 0 || retry.Skipped != 1 {
+ t.Fatalf("retry = %+v, error %v", retry, err)
+ }
+}
diff --git a/internal/web/service/client_group_bulk_scope.go b/internal/web/service/client_group_bulk_scope.go
new file mode 100644
index 000000000..cedb30a78
--- /dev/null
+++ b/internal/web/service/client_group_bulk_scope.go
@@ -0,0 +1,145 @@
+package service
+
+import (
+ "context"
+ "slices"
+
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+type groupClientIdentity struct {
+ ID int
+ Email string
+}
+
+type GroupBulkScope struct {
+ group string
+ emails []string
+ ids map[string]int
+ // Only the adjustment's serialized writer publishes completed inbound mutations.
+ committedAdjustments map[string]bool
+}
+
+func groupClientEmails(rows []groupClientIdentity) []string {
+ emails := make([]string, 0, len(rows))
+ for _, row := range rows {
+ emails = append(emails, row.Email)
+ }
+ return emails
+}
+
+func ResolveGroupBulkScope(ctx context.Context, group, token string) (*GroupBulkScope, error) {
+ db := database.GetDB().WithContext(ctx)
+ scope, err := findGroupClientScope(db, group, "remove")
+ if err != nil {
+ return nil, err
+ }
+ q := scope.candidates(db)
+ var rows []groupClientIdentity
+ if token != "" {
+ rows, err = scope.frozenClients(q, GroupClientSelection{ScopeToken: token})
+ } else {
+ err = q.Select("c.id, c.email").Order("c.id").Scan(&rows).Error
+ }
+ if err != nil {
+ return nil, err
+ }
+ targets := &GroupBulkScope{group: scope.name, emails: groupClientEmails(rows), ids: make(map[string]int, len(rows))}
+ for _, row := range rows {
+ targets.ids[row.Email] = row.ID
+ }
+ return targets, nil
+}
+
+func (scope *GroupBulkScope) records(db *gorm.DB, emails []string, lock bool) (map[string]*model.ClientRecord, error) {
+ if scope == nil {
+ return clientRecordsByEmail(db, emails)
+ }
+ ids := make([]int, 0, len(emails))
+ for _, email := range emails {
+ if id, ok := scope.ids[email]; ok {
+ ids = append(ids, id)
+ }
+ }
+ slices.Sort(ids)
+ matches := make(map[string]*model.ClientRecord, len(ids))
+ for _, batch := range chunkInts(ids, sqlInChunk) {
+ q := db.Where("id IN ?", batch).Order("id")
+ if scope.committedAdjustments == nil {
+ q = q.Where("group_name = ?", scope.group)
+ }
+ if lock && db.Name() == database.DialectPostgres {
+ q = q.Clauses(clause.Locking{Strength: "UPDATE"})
+ }
+ var rows []model.ClientRecord
+ if err := q.Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ for i := range rows {
+ if scope.ids[rows[i].Email] == rows[i].Id && (rows[i].Group == scope.group || scope.committedAdjustments[rows[i].Email]) {
+ matches[rows[i].Email] = &rows[i]
+ }
+ }
+ }
+ return matches, nil
+}
+
+// Lock the original records and check the link used to plan this inbound write.
+func (scope *GroupBulkScope) inboundRecords(tx *gorm.DB, inboundID int, emails []string) (map[string]*model.ClientRecord, error) {
+ if scope == nil {
+ return nil, nil
+ }
+ records, err := scope.records(tx, emails, true)
+ if err != nil {
+ return nil, err
+ }
+ if len(records) != len(emails) {
+ return nil, errGroupSelectionStale
+ }
+ ids := make([]int, 0, len(records))
+ for _, rec := range records {
+ ids = append(ids, rec.Id)
+ }
+ slices.Sort(ids)
+ for _, batch := range chunkInts(ids, sqlInChunk) {
+ var linked []int
+ q := tx.Model(&model.ClientInbound{}).
+ Where("inbound_id = ? AND client_id IN ?", inboundID, batch).Order("client_id")
+ if tx.Name() == database.DialectPostgres {
+ q = q.Clauses(clause.Locking{Strength: "UPDATE"})
+ }
+ if err := q.Pluck("client_id", &linked).Error; err != nil {
+ return nil, err
+ }
+ if len(linked) != len(batch) {
+ return nil, errGroupSelectionStale
+ }
+ }
+ return records, nil
+}
+
+func (scope *GroupBulkScope) skipReason() string {
+ if scope == nil {
+ return "client not found"
+ }
+ return errGroupSelectionStale.Error()
+}
+
+func linkedGroupBulkClients(tx *gorm.DB, ids []int) (map[int]bool, error) {
+ matches := make(map[int]bool)
+ for _, batch := range chunkInts(ids, sqlInChunk) {
+ var linked []int
+ err := tx.Model(&model.ClientInbound{}).Where("client_id IN ?", batch).Distinct().Pluck("client_id", &linked).Error
+ if err != nil {
+ return nil, err
+ }
+ for _, id := range linked {
+ matches[id] = true
+ }
+ }
+ return matches, nil
+}
diff --git a/internal/web/service/client_group_bulk_scope_test.go b/internal/web/service/client_group_bulk_scope_test.go
new file mode 100644
index 000000000..b39b44e91
--- /dev/null
+++ b/internal/web/service/client_group_bulk_scope_test.go
@@ -0,0 +1,314 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
+)
+
+func setupFrozenGroupBulkDB(t *testing.T) {
+ t.Helper()
+ cleanup, err := testpg.IsolatePackage("frozen_group_bulk")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ setupBulkDB(t)
+}
+
+func TestFrozenGroupBulkRejectsIdentityAndMembershipChanges(t *testing.T) {
+ for _, operation := range []string{"adjust", "delete"} {
+ for _, change := range []string{"replace", "move"} {
+ t.Run(operation+"/"+change, func(t *testing.T) {
+ setupFrozenGroupBulkDB(t)
+ db := database.GetDB()
+ svc, inboundSvc := &ClientService{}, &InboundService{}
+ client := model.Client{Email: "frozen@example.test", Group: "staff", ID: "11111111-1111-1111-1111-111111111111", TotalGB: 1024, Enable: true}
+ ib := mkInbound(t, 41001, model.VLESS, clientsSettings(t, []model.Client{client}))
+ if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
+ t.Fatal(err)
+ }
+ mkTraffic(t, ib.Id, client.Email, 1, 0, 1024, 0, true)
+ before, err := svc.GetRecordByEmail(nil, client.Email)
+ if err != nil {
+ t.Fatal(err)
+ }
+ page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: "staff", Mode: "remove", Freeze: true})
+ if err != nil || page.Total != 1 {
+ t.Fatalf("freeze: %+v, %v", page, err)
+ }
+ scope, err := ResolveGroupBulkScope(t.Context(), "staff", page.ScopeToken)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // The operation can only proceed once the other writer has committed.
+ done := make(chan error, 1)
+ wantID := before.Id
+ go func() {
+ done <- runSerializedTx(func(tx *gorm.DB) error {
+ if change == "move" {
+ return tx.Model(before).Update("group_name", "outside").Error
+ }
+ if err := tx.Where("client_id = ?", before.Id).Delete(&model.ClientInbound{}).Error; err != nil {
+ return err
+ }
+ if err := tx.Delete(before).Error; err != nil {
+ return err
+ }
+ next := *before
+ next.Id = 0
+ if err := tx.Create(&next).Error; err != nil {
+ return err
+ }
+ if next.Id <= page.MaxID {
+ return fmt.Errorf("replacement %d is within cutoff %d", next.Id, page.MaxID)
+ }
+ wantID = next.Id
+ return tx.Create(&model.ClientInbound{ClientId: next.Id, InboundId: ib.Id}).Error
+ })
+ }()
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+
+ if operation == "adjust" {
+ res, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 0, 1024, "", nil, "")
+ if err != nil || res.Adjusted != 0 || len(res.Skipped) != 1 || res.Skipped[0].Reason != scope.skipReason() {
+ t.Fatalf("adjust: %+v, %v", res, err)
+ }
+ // Also exercise the guard with a plan made before the other writer.
+ plan := map[string]*bulkAdjustEntry{client.Email: {record: before, applyTotal: true, newTotal: 2048}}
+ part := svc.bulkAdjustInboundClients(inboundSvc, ib.Id, []string{client.Email}, plan, scope, "", "")
+ if part.perEmailSkipped[client.Email] != scope.skipReason() {
+ t.Fatalf("stale inbound adjust: %+v", part)
+ }
+ } else {
+ res, _, err := svc.BulkDeleteGroup(inboundSvc, scope, false)
+ if err != nil || res.Deleted != 0 || len(res.Skipped) != 1 || res.Skipped[0].Reason != scope.skipReason() {
+ t.Fatalf("delete: %+v, %v", res, err)
+ }
+ part := svc.bulkDelInboundClients(inboundSvc, ib.Id, []string{client.Email}, map[string]*model.ClientRecord{client.Email: before}, scope, false)
+ if part.perEmailSkipped[client.Email] != scope.skipReason() || isClientEmailTombstoned(client.Email) {
+ t.Fatalf("stale inbound delete: %+v", part)
+ }
+ }
+ got, err := svc.GetRecordByEmail(nil, client.Email)
+ if err != nil || got.Id != wantID || got.TotalGB != 1024 {
+ t.Fatalf("protected record: %+v, %v", got, err)
+ }
+ if got := trafficOf(t, client.Email); got.Total != 1024 || got.Up != 1 {
+ t.Fatalf("protected traffic: %+v", got)
+ }
+ var settings string
+ if err := db.Model(ib).Select("settings").Find(&settings).Error; err != nil || settings != ib.Settings {
+ t.Fatalf("protected settings changed: %s (%v)", settings, err)
+ }
+ })
+ }
+ }
+}
+
+func TestFrozenGroupBulkAppliesLinkedTargets(t *testing.T) {
+ setupFrozenGroupBulkDB(t)
+ svc, inboundSvc := &ClientService{}, &InboundService{}
+ client := model.Client{Email: "linked-group@example.test", Group: "staff", ID: "11111111-1111-1111-1111-111111111111", TotalGB: 1024, Enable: true}
+ ib := mkInbound(t, 41001, model.VLESS, clientsSettings(t, []model.Client{client}))
+ if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
+ t.Fatal(err)
+ }
+ mkTraffic(t, ib.Id, client.Email, 1, 0, 1024, 0, true)
+ page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: "staff", Mode: "remove", Freeze: true})
+ if err != nil || page.Total != 1 {
+ t.Fatalf("freeze: %+v, %v", page, err)
+ }
+ scope, err := ResolveGroupBulkScope(t.Context(), "staff", page.ScopeToken)
+ if err != nil {
+ t.Fatal(err)
+ }
+ adjust, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 0, 1024, "", nil, "")
+ if err != nil || adjust.Adjusted != 1 || len(adjust.Skipped) != 0 {
+ t.Fatalf("adjust: %+v, %v", adjust, err)
+ }
+ if got := trafficOf(t, client.Email); got.Total != 2048 {
+ t.Fatalf("adjusted traffic: %+v", got)
+ }
+ del, _, err := svc.BulkDeleteGroup(inboundSvc, scope, false)
+ if err != nil || del.Deleted != 1 || len(del.Skipped) != 0 {
+ t.Fatalf("delete: %+v, %v", del, err)
+ }
+ var rows int64
+ if err := database.GetDB().Model(&model.ClientRecord{}).Where("email = ?", client.Email).Count(&rows).Error; err != nil || rows != 0 {
+ t.Fatalf("deleted client still present: %d (%v)", rows, err)
+ }
+}
+
+type groupAdjustBarrierRuntime struct {
+ fakeNodeRuntime
+ entered chan struct{}
+ release chan struct{}
+}
+
+func (r *groupAdjustBarrierRuntime) UpdateUser(ctx context.Context, _ *model.Inbound, _ string, _ model.Client) (runtime.ClientApplyResult, error) {
+ select {
+ case r.entered <- struct{}{}:
+ default:
+ }
+ select {
+ case <-r.release:
+ return runtime.ClientApplyResult{}, nil
+ case <-ctx.Done():
+ return runtime.ClientApplyResult{}, ctx.Err()
+ }
+}
+
+func TestFrozenGroupBulkAdjustSurvivesMembershipMoveAfterCommit(t *testing.T) {
+ setupClientNodeOrderDB(t)
+ nodeID, _ := setupNodeRuntime(t)
+ barrier := &groupAdjustBarrierRuntime{entered: make(chan struct{}, 1), release: make(chan struct{})}
+ runtime.GetManager().SetRuntimeOverride(nodeID, barrier)
+
+ const originalTotal = 1024
+ const newTotal = 2048
+ oldExpiry := time.Now().Add(48 * time.Hour).UnixMilli()
+ newExpiry := oldExpiry + reenableDay
+ client := model.Client{
+ Email: "moving@example.test",
+ Group: "staff",
+ ID: "11111111-1111-1111-1111-111111111111",
+ TotalGB: originalTotal,
+ ExpiryTime: oldExpiry,
+ }
+ svc, inboundSvc := &ClientService{}, &InboundService{}
+ remote := nodeInbound(t, nodeID, 41001, []model.Client{client})
+ local := mkInbound(t, 41002, model.VLESS, clientsSettings(t, []model.Client{client}))
+ if err := svc.SyncInbound(nil, local.Id, []model.Client{client}); err != nil {
+ t.Fatal(err)
+ }
+ mkTraffic(t, remote.Id, client.Email, originalTotal, 0, originalTotal, oldExpiry, false)
+ page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: "staff", Mode: "remove", Freeze: true})
+ if err != nil || page.Total != 1 {
+ t.Fatalf("freeze: %+v, %v", page, err)
+ }
+ scope, err := ResolveGroupBulkScope(t.Context(), "staff", page.ScopeToken)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ siblingLock := lockInbound(local.Id)
+ unlockSibling := sync.OnceFunc(siblingLock.Unlock)
+ releaseNode := sync.OnceFunc(func() { close(barrier.release) })
+ type outcome struct {
+ result BulkAdjustResult
+ err error
+ }
+ done := make(chan outcome, 1)
+ var operation sync.WaitGroup
+ t.Cleanup(func() {
+ unlockSibling()
+ releaseNode()
+ operation.Wait()
+ })
+ operation.Go(func() {
+ res, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 1, newTotal-originalTotal, "", nil, "")
+ done <- outcome{res, err}
+ })
+ select {
+ case <-barrier.entered:
+ case <-time.After(nodeClientPushTimeout):
+ t.Fatal("adjustment never reached post-commit node delivery")
+ }
+
+ if got := trafficOf(t, client.Email); got.Total != newTotal || got.ExpiryTime != newExpiry {
+ t.Errorf("traffic limits at the post-commit barrier: %+v", got)
+ }
+ if moved, err := svc.AddToGroup([]string{client.Email}, "new-group"); err != nil || moved != 1 {
+ t.Fatalf("move while node apply waits: %d (%v)", moved, err)
+ }
+ unlockSibling()
+ releaseNode()
+
+ applied := <-done
+ if got := trafficOf(t, client.Email); got.Total != newTotal || got.ExpiryTime != newExpiry || got.Up != originalTotal || !got.Enable {
+ t.Errorf("traffic after committed adjust and group move: %+v", got)
+ }
+ record, err := svc.GetRecordByEmail(nil, client.Email)
+ if err != nil || record.Group != "new-group" || record.TotalGB != newTotal || record.ExpiryTime != newExpiry || !record.Enable {
+ t.Errorf("record after committed adjust and group move: %+v (%v)", record, err)
+ }
+ for _, attached := range []*model.Inbound{remote, local} {
+ inbound, err := inboundSvc.GetInbound(attached.Id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ list, err := inboundSvc.GetClients(inbound)
+ if err != nil || len(list) != 1 || list[0].Group != "new-group" || list[0].TotalGB != newTotal || list[0].ExpiryTime != newExpiry || !list[0].Enable {
+ t.Errorf("inbound %d after committed adjust and group move: %+v (%v)", attached.Id, list, err)
+ }
+ }
+ if applied.err != nil || applied.result.Adjusted != 1 || len(applied.result.Skipped) != 0 {
+ t.Errorf("adjust result: %+v (%v)", applied.result, applied.err)
+ }
+}
+
+func TestFrozenGroupBulkAdjustRollsBackWhenTrafficWriteFails(t *testing.T) {
+ setupFrozenGroupBulkDB(t)
+ db := database.GetDB()
+ svc, inboundSvc := &ClientService{}, &InboundService{}
+ client := model.Client{
+ Email: "rollback@example.test",
+ Group: "rollback-group",
+ ID: "11111111-1111-1111-1111-111111111111",
+ TotalGB: 1024,
+ Enable: true,
+ }
+ inbound := mkInbound(t, 41003, model.VLESS, clientsSettings(t, []model.Client{client}))
+ if err := svc.SyncInbound(nil, inbound.Id, []model.Client{client}); err != nil {
+ t.Fatal(err)
+ }
+ mkTraffic(t, inbound.Id, client.Email, 1, 0, 1024, 0, true)
+ page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: client.Group, Mode: "remove", Freeze: true})
+ if err != nil || page.Total != 1 {
+ t.Fatalf("freeze: %+v, %v", page, err)
+ }
+ scope, err := ResolveGroupBulkScope(t.Context(), client.Group, page.ScopeToken)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const callback = "test:fail_adjust_traffic_write"
+ writeErr := errors.New("injected client traffic write failure")
+ if err := db.Callback().Update().Before("gorm:update").Register(callback, func(tx *gorm.DB) {
+ if tx.Statement.Table == "client_traffics" {
+ _ = tx.AddError(writeErr)
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) })
+
+ result, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 0, 1024, "", nil, "")
+ if err != nil || result.Adjusted != 0 || len(result.Skipped) != 1 || result.Skipped[0].Reason != writeErr.Error() {
+ t.Fatalf("expected a rolled-back adjust, got %+v (%v)", result, err)
+ }
+ record, err := svc.GetRecordByEmail(nil, client.Email)
+ if err != nil || record.TotalGB != 1024 {
+ t.Errorf("normalized quota after rollback: %+v (%v)", record, err)
+ }
+ current, err := inboundSvc.GetInbound(inbound.Id)
+ if err != nil || current.Settings != inbound.Settings {
+ t.Errorf("inbound settings after rollback: %+v (%v)", current, err)
+ }
+ if got := trafficOf(t, client.Email); got.Total != 1024 || got.Up != 1 {
+ t.Errorf("traffic after rollback: %+v", got)
+ }
+}
diff --git a/internal/web/service/client_group_scope.go b/internal/web/service/client_group_scope.go
new file mode 100644
index 000000000..95cd8bafc
--- /dev/null
+++ b/internal/web/service/client_group_scope.go
@@ -0,0 +1,337 @@
+package service
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "hash"
+ "strconv"
+ "strings"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+const (
+ groupClientPageSize = 100
+ maxGroupSelectionExclusions = 1000
+)
+
+var errGroupSelectionStale = errors.New("client group selection changed. Reopen the action or select clients again.")
+
+type GroupClientPageParams struct {
+ Group string `form:"group"`
+ Mode string `form:"mode"`
+ Page int `form:"page"`
+ Search string `form:"search"`
+ Freeze bool `form:"freeze"`
+ ScopeSearch string `form:"scopeSearch"`
+ MaxID *int `form:"maxId"`
+}
+
+type GroupClientRow struct {
+ ID int `json:"id" example:"1"`
+ Email string `json:"email" example:"alice"`
+ Comment string `json:"comment" example:"Example client"`
+ Group string `json:"group" example:"staff"`
+ Enable bool `json:"enable" example:"true"`
+ SubID string `json:"subId" example:"example-sub-id"`
+ InScope bool `json:"inScope" example:"true"`
+}
+
+type GroupClientPage struct {
+ Items []GroupClientRow `json:"items"`
+ Total int64 `json:"total" example:"120"`
+ ScopeToken string `json:"scopeToken,omitempty"`
+ MaxID int `json:"maxId,omitempty"`
+}
+
+type GroupClientSelection struct {
+ Mode string `json:"mode" example:"allMatching"`
+ ClientIDs []int `json:"clientIds,omitempty"`
+ ExcludedClientIDs []int `json:"excludedClientIds,omitempty"`
+ ScopeToken string `json:"scopeToken,omitempty"`
+ Search string `json:"search,omitempty"`
+}
+
+type groupClientScope struct {
+ name string
+ mode string
+}
+
+func (scope groupClientScope) candidates(db *gorm.DB) *gorm.DB {
+ q := attachCandidates(db, 0)
+ if scope.mode == "add" {
+ return q.Where("COALESCE(c.group_name, '') <> ?", scope.name)
+ }
+ q = q.Where("c.group_name = ?", scope.name)
+ if scope.mode == "links" {
+ q = q.Where("c.sub_id <> ''")
+ }
+ return q
+}
+
+func findGroupClientScope(db *gorm.DB, group, mode string) (groupClientScope, error) {
+ group = strings.TrimSpace(group)
+ if group == "" || (mode != "add" && mode != "remove" && mode != "links") {
+ return groupClientScope{}, fmt.Errorf("invalid client group scope")
+ }
+ if mode != "add" {
+ return groupClientScope{name: group, mode: mode}, nil
+ }
+ var stored model.ClientGroup
+ err := db.Where("LOWER(name) = LOWER(?)", group).Order("id").Take(&stored).Error
+ if err == nil {
+ return groupClientScope{name: stored.Name, mode: mode}, nil
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return groupClientScope{}, err
+ }
+ var derived model.ClientRecord
+ err = db.Table("clients").Where("group_name = ?", group).Select("id").Take(&derived).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return groupClientScope{}, fmt.Errorf("client group no longer exists")
+ }
+ return groupClientScope{name: group, mode: mode}, err
+}
+
+func groupSearchCond(needle string) (string, []any) {
+ parts, args := clientTextSearch(caseVariants(needle), []string{"c.email", "c.comment", "c.group_name"})
+ return "(" + strings.Join(parts, " OR ") + ")", args
+}
+
+func groupClientSearch(q *gorm.DB, search string) *gorm.DB {
+ if needle := strings.TrimSpace(search); needle != "" {
+ filter, args := groupSearchCond(needle)
+ return q.Where(filter, args...)
+ }
+ return q
+}
+
+func (scope groupClientScope) digest(search string) hash.Hash {
+ h := sha256.New()
+ for _, part := range []string{"group-client-scope", scope.mode, scope.name, strings.TrimSpace(search)} {
+ writeClientScopeID(h, len(part))
+ _, _ = h.Write([]byte(part))
+ }
+ return h
+}
+
+func groupClientToken(h hash.Hash, maxID int) string {
+ writeClientScopeID(h, maxID)
+ return strconv.Itoa(maxID) + "." + hex.EncodeToString(h.Sum(nil))
+}
+
+func (s *ClientService) ListGroupClients(ctx context.Context, p GroupClientPageParams) (*GroupClientPage, error) {
+ if p.Page < 0 || p.Page > 1_000_000 || len(p.Search) > 1024 || len(p.ScopeSearch) > 1024 ||
+ (p.MaxID != nil && *p.MaxID < 1) || (p.Freeze && p.Mode == "links") {
+ return nil, fmt.Errorf("invalid client group page")
+ }
+ db := database.GetDB().WithContext(ctx)
+ scope, err := findGroupClientScope(db, p.Group, p.Mode)
+ if err != nil {
+ return nil, err
+ }
+ page := &GroupClientPage{Items: []GroupClientRow{}}
+ q := groupClientSearch(scope.candidates(db), p.Search)
+ if p.Freeze {
+ rows, err := q.Select("c.id").Order("c.id").Rows()
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ h := scope.digest(p.Search)
+ for rows.Next() {
+ if err := rows.Scan(&page.MaxID); err != nil {
+ return nil, err
+ }
+ writeClientScopeID(h, page.MaxID)
+ page.Total++
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ page.ScopeToken = groupClientToken(h, page.MaxID)
+ return page, nil
+ }
+
+ if err := q.Session(&gorm.Session{}).Count(&page.Total).Error; err != nil {
+ return nil, err
+ }
+ const fields = "c.id, c.email, COALESCE(c.comment, '') AS comment, COALESCE(c.group_name, '') AS \"group\", COALESCE(c.enable, false) AS enable, COALESCE(c.sub_id, '') AS sub_id, "
+ inScope := "true"
+ var args []any
+ if p.MaxID != nil {
+ inScope = "(c.id <= ?)"
+ args = append(args, *p.MaxID)
+ if needle := strings.TrimSpace(p.ScopeSearch); needle != "" {
+ filter, filterArgs := groupSearchCond(needle)
+ inScope = "(" + inScope + " AND COALESCE(" + filter + ", false))"
+ args = append(args, filterArgs...)
+ }
+ }
+ order := "c.id"
+ if p.Mode == "links" {
+ order = "c.email, c.id"
+ }
+ err = q.Select(fields+inScope+" AS in_scope", args...).Order(order).
+ Offset(max(0, p.Page-1) * groupClientPageSize).Limit(groupClientPageSize).Scan(&page.Items).Error
+ return page, err
+}
+
+func (scope groupClientScope) selectionEmails(db *gorm.DB, selection GroupClientSelection) ([]string, error) {
+ q := scope.candidates(db)
+ switch selection.Mode {
+ case "explicit":
+ if len(selection.ClientIDs) == 0 || len(selection.ClientIDs) > 50_000 || selection.ScopeToken != "" ||
+ len(selection.ExcludedClientIDs) != 0 || selection.Search != "" {
+ return nil, fmt.Errorf("invalid explicit client group selection")
+ }
+ ids := uniqueInts(selection.ClientIDs)
+ var emails []string
+ for _, chunk := range chunkInts(ids, sqlInChunk) {
+ var part []string
+ if err := q.Session(&gorm.Session{}).Where("c.id IN ?", chunk).Pluck("c.email", &part).Error; err != nil {
+ return nil, err
+ }
+ if len(part) != len(chunk) {
+ return nil, errGroupSelectionStale
+ }
+ emails = append(emails, part...)
+ }
+ return emails, nil
+ case "allMatching":
+ rows, err := scope.frozenClients(q, selection)
+ return groupClientEmails(rows), err
+ default:
+ return nil, fmt.Errorf("invalid client group selection mode")
+ }
+}
+
+func (scope groupClientScope) frozenClients(q *gorm.DB, selection GroupClientSelection) ([]groupClientIdentity, error) {
+ cutoff, digest, ok := strings.Cut(selection.ScopeToken, ".")
+ maxID, parseErr := strconv.Atoi(cutoff)
+ if !ok || parseErr != nil || maxID < 0 || len(digest) != sha256.Size*2 || len(selection.ClientIDs) != 0 ||
+ len(selection.ExcludedClientIDs) > maxGroupSelectionExclusions || len(selection.Search) > 1024 {
+ return nil, fmt.Errorf("invalid frozen client group selection")
+ }
+ excluded := make(map[int]struct{}, len(selection.ExcludedClientIDs))
+ for _, id := range selection.ExcludedClientIDs {
+ excluded[id] = struct{}{}
+ }
+ rows, err := groupClientSearch(q, selection.Search).Where("c.id <= ?", maxID).
+ Select("c.id, c.email").Order("c.id").Rows()
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ h := scope.digest(selection.Search)
+ var clients []groupClientIdentity
+ for rows.Next() {
+ var id int
+ var email string
+ if err := rows.Scan(&id, &email); err != nil {
+ return nil, err
+ }
+ writeClientScopeID(h, id)
+ if _, skip := excluded[id]; skip {
+ delete(excluded, id)
+ } else {
+ clients = append(clients, groupClientIdentity{ID: id, Email: email})
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ if len(excluded) != 0 || groupClientToken(h, maxID) != selection.ScopeToken {
+ return nil, errGroupSelectionStale
+ }
+ return clients, nil
+}
+
+func (s *ClientService) ChangeGroupSelection(ctx context.Context, group, mode string, selection GroupClientSelection) (int, error) {
+ if mode != "add" && mode != "remove" {
+ return 0, fmt.Errorf("invalid client group action")
+ }
+ var affected int
+ err := runSerializedTx(func(tx *gorm.DB) error {
+ tx = tx.WithContext(ctx)
+ scope, err := findGroupClientScope(tx, group, mode)
+ if err != nil {
+ return err
+ }
+ emails, err := scope.selectionEmails(tx, selection)
+ if err != nil {
+ return err
+ }
+ target := ""
+ if mode == "add" && len(emails) != 0 {
+ record, err := database.EnsureClientGroup(tx, scope.name)
+ if err != nil {
+ return err
+ }
+ target = record.Name
+ }
+ affected, err = applyClientGroup(tx, emails, target)
+ return err
+ })
+ return affected, err
+}
+
+func (s *ClientService) AddInboundToGroup(ctx context.Context, inboundID int, group string) (int, error) {
+ if inboundID <= 0 {
+ return 0, fmt.Errorf("invalid source inbound ID")
+ }
+ var affected int
+ err := runSerializedTx(func(tx *gorm.DB) error {
+ tx = tx.WithContext(ctx)
+ var inbound model.Inbound
+ if err := tx.Select("id").First(&inbound, inboundID).Error; err != nil {
+ return err
+ }
+ var emails []string
+ if err := attachCandidates(tx, inbound.Id).Pluck("c.email", &emails).Error; err != nil {
+ return err
+ }
+ if len(emails) == 0 {
+ return nil
+ }
+ target, err := database.EnsureClientGroup(tx, group)
+ if err != nil {
+ return err
+ }
+ if target == nil {
+ return fmt.Errorf("group name is required")
+ }
+ affected, err = applyClientGroup(tx, emails, target.Name)
+ return err
+ })
+ return affected, err
+}
+
+func (s *ClientService) WalkGroupSubscriptionClients(ctx context.Context, group string, visit func(email, subID string) error) error {
+ db := database.GetDB().WithContext(ctx)
+ scope, err := findGroupClientScope(db, group, "links")
+ if err != nil {
+ return err
+ }
+ rows, err := scope.candidates(db).Select("c.email, c.sub_id").Order("c.email, c.id").Rows()
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var email, subID string
+ if err := rows.Scan(&email, &subID); err != nil {
+ return err
+ }
+ if err := visit(email, subID); err != nil {
+ return err
+ }
+ }
+ return rows.Err()
+}
diff --git a/internal/web/service/client_groups.go b/internal/web/service/client_groups.go
index 5bee1cd68..052c908cd 100644
--- a/internal/web/service/client_groups.go
+++ b/internal/web/service/client_groups.go
@@ -340,129 +340,132 @@ func (s *ClientService) AddToGroup(emails []string, group string) (int, error) {
if len(emails) == 0 {
return 0, nil
}
- db := database.GetDB()
-
- if group != "" {
- record, err := database.EnsureClientGroup(db, group)
- if err != nil {
- return 0, err
+ var affected int
+ err := runSerializedTx(func(tx *gorm.DB) error {
+ if group != "" {
+ record, err := database.EnsureClientGroup(tx, group)
+ if err != nil {
+ return err
+ }
+ group = record.Name
}
- group = record.Name
- }
+ var err error
+ affected, err = applyClientGroup(tx, emails, group)
+ return err
+ })
+ return affected, err
+}
- var records []model.ClientRecord
- for _, batch := range chunkStrings(emails, sqlInChunk) {
- var rows []model.ClientRecord
- if err := db.Where("email IN ?", batch).
- Where("group_name IS NULL OR group_name <> ?", group).
- Find(&rows).Error; err != nil {
- return 0, err
- }
- records = append(records, rows...)
- }
- if len(records) == 0 {
- return 0, nil
- }
- affectedEmails := make([]string, 0, len(records))
- for _, r := range records {
- affectedEmails = append(affectedEmails, r.Email)
- }
-
- tx := db.Begin()
+func applyClientGroup(tx *gorm.DB, emails []string, group string) (int, error) {
+ var affectedEmails []string
var affected int64
- for _, batch := range chunkStrings(affectedEmails, sqlInChunk) {
- result := tx.Model(&model.ClientRecord{}).
- Where("email IN ?", batch).
- Where("group_name IS NULL OR group_name <> ?", group).
- UpdateColumn("group_name", group)
+ inboundIDs := make(map[int]struct{})
+ for _, batch := range chunkStrings(emails, sqlInChunk) {
+ var changed []string
+ if err := tx.Model(&model.ClientRecord{}).
+ Where("email IN ? AND (group_name IS NULL OR group_name <> ?)", batch, group).
+ Pluck("email", &changed).Error; err != nil {
+ return 0, err
+ }
+ if len(changed) == 0 {
+ continue
+ }
+ result := tx.Model(&model.ClientRecord{}).Where("email IN ?", changed).UpdateColumn("group_name", group)
if result.Error != nil {
- tx.Rollback()
return 0, result.Error
}
affected += result.RowsAffected
- }
+ affectedEmails = append(affectedEmails, changed...)
- var inboundIDs []int
- inboundIDSeen := make(map[int]struct{})
- for _, batch := range chunkStrings(affectedEmails, sqlInChunk) {
var ids []int
if err := tx.Table("client_inbounds").
Joins("JOIN clients ON clients.id = client_inbounds.client_id").
- Where("clients.email IN ?", batch).
+ Where("clients.email IN ?", changed).
Distinct("client_inbounds.inbound_id").
Pluck("inbound_id", &ids).Error; err != nil {
- tx.Rollback()
return 0, err
}
for _, id := range ids {
- if _, ok := inboundIDSeen[id]; !ok {
- inboundIDSeen[id] = struct{}{}
- inboundIDs = append(inboundIDs, id)
- }
+ inboundIDs[id] = struct{}{}
}
}
-
emailSet := make(map[string]struct{}, len(affectedEmails))
- for _, e := range affectedEmails {
- emailSet[e] = struct{}{}
+ for _, email := range affectedEmails {
+ emailSet[email] = struct{}{}
}
-
- for _, ibID := range inboundIDs {
+ dirtyNodes := make(map[int]struct{})
+ for _, id := range sortedInboundIds(inboundIDs) {
var ib model.Inbound
- if err := tx.First(&ib, ibID).Error; err != nil {
- tx.Rollback()
+ if err := tx.Select("id", "settings", "node_id").First(&ib, id).Error; err != nil {
return 0, err
}
- var settings map[string]any
- if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
- continue
+ settings, changed, err := patchInboundClientGroup(ib.Settings, emailSet, group)
+ if err != nil {
+ return 0, err
}
- clients, ok := settings["clients"].([]any)
- if !ok {
- continue
- }
- modified := false
- for i := range clients {
- cm, ok := clients[i].(map[string]any)
- if !ok {
- continue
- }
- email, _ := cm["email"].(string)
- if _, hit := emailSet[email]; !hit {
- continue
- }
- if group == "" {
- delete(cm, "group")
- } else {
- cm["group"] = group
- }
- clients[i] = cm
- modified = true
- }
- if modified {
- settings["clients"] = clients
- newSettings, err := json.Marshal(settings)
- if err != nil {
- continue
- }
- ib.Settings = string(newSettings)
- if err := tx.Save(&ib).Error; err != nil {
- tx.Rollback()
+ if changed {
+ if err := tx.Model(&ib).UpdateColumn("settings", settings).Error; err != nil {
return 0, err
}
+ if ib.NodeID != nil {
+ dirtyNodes[*ib.NodeID] = struct{}{}
+ }
}
}
-
- if err := tx.Commit().Error; err != nil {
- return 0, err
+ for _, id := range sortedInboundIds(dirtyNodes) {
+ if err := (&NodeService{}).MarkNodeDirtyTx(tx, id); err != nil {
+ return 0, err
+ }
}
return int(affected), nil
}
+func patchInboundClientGroup(raw string, emails map[string]struct{}, group string) (string, bool, error) {
+ settings, entries, ok := splitSettingsClients(raw)
+ if !ok {
+ return "", false, common.NewError("invalid inbound client settings")
+ }
+ groupValue, err := json.Marshal(group)
+ if err != nil {
+ return "", false, err
+ }
+ changed := false
+ for i, entry := range entries {
+ client, ok := readSettingsClient(entry)
+ if !ok {
+ continue
+ }
+ if _, match := emails[client.Email]; !match {
+ continue
+ }
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(entry, &fields); err != nil {
+ return "", false, err
+ }
+ if group == "" {
+ delete(fields, "group")
+ } else {
+ fields["group"] = groupValue
+ }
+ entries[i], err = json.Marshal(fields)
+ if err != nil {
+ return "", false, err
+ }
+ changed = true
+ }
+ if !changed {
+ return raw, false, nil
+ }
+ out, ok := joinSettingsClients(raw, settings, entries)
+ if !ok {
+ return "", false, common.NewError("invalid inbound client settings")
+ }
+ return out, true, nil
+}
+
func (s *ClientService) replaceGroupValue(oldName, newName string, hostGroupIDs *[]string) (int, error) {
- db := database.GetDB()
affected := 0
- err := db.Transaction(func(tx *gorm.DB) error {
+ err := runSerializedTx(func(tx *gorm.DB) error {
var hostGroupValues []string
if hostGroupIDs != nil {
hostGroupValues = normalizeHostGroupIDs(*hostGroupIDs)
diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go
index ca0746a39..05816df51 100644
--- a/internal/web/service/client_inbound_apply.go
+++ b/internal/web/service/client_inbound_apply.go
@@ -25,13 +25,18 @@ import (
// endDroppedClientSessions is what restartXrayOnClientDisable asks for once the API removed a
// client: it drops the credential only, so the restart is queued here, not left to a config diff.
func endDroppedClientSessions(inbound *model.Inbound) bool {
+ on := restartAfterClientRemoval()
+ if on && removalLeavesXraySessions(inbound) {
+ pendingXraySessionDrop.Store(true)
+ }
+ return on
+}
+
+func restartAfterClientRemoval() bool {
on, err := (&SettingService{}).GetRestartXrayOnClientDisable()
if err != nil {
logger.Warning("get RestartXrayOnClientDisable failed:", err)
}
- if on && removalLeavesXraySessions(inbound) {
- pendingXraySessionDrop.Store(true)
- }
return on
}
@@ -397,6 +402,10 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c
}
func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (restartNeeded bool, saveErr error) {
+ return s.addInboundClient(inboundSvc, data, false, nil)
+}
+
+func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, gateFlow bool, queued *queuedClientCreate) (restartNeeded bool, saveErr error) {
defer InvalidateSubData()
mutation := beginInboundClientMutation(data.Id)
defer mutation.close()
@@ -408,15 +417,15 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
if err := validateClientsRenewal(clients); err != nil {
return false, err
}
- inbound, err := inboundSvc.GetInbound(data.Id)
+ oldInbound, err := inboundSvc.GetInbound(data.Id)
if err != nil {
return false, err
}
- existingClients, err := inboundSvc.GetClients(inbound)
+ existingClients, err := inboundSvc.GetClients(oldInbound)
if err != nil {
return false, err
}
- if err := validateClientsKeepAliveAgainstExisting(inbound.Protocol, clients, existingClients); err != nil {
+ if err := validateClientsKeepAliveAgainstExisting(oldInbound.Protocol, clients, existingClients); err != nil {
return false, err
}
@@ -430,6 +439,11 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
nowTs := time.Now().Unix() * 1000
for i := range interfaceClients {
if cm, ok := interfaceClients[i].(map[string]any); ok {
+ // Create and attach filter flow against the locked inbound snapshot.
+ if gateFlow && clients[i].Flow != "" && clientWithInboundFlow(clients[i], oldInbound).Flow == "" {
+ clients[i].Flow = ""
+ delete(cm, "flow")
+ }
if _, ok2 := cm["created_at"]; !ok2 {
cm["created_at"] = nowTs
}
@@ -449,10 +463,6 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
return false, common.NewError("Duplicate email:", existEmail)
}
- oldInbound, err := inboundSvc.GetInbound(data.Id)
- if err != nil {
- return false, err
- }
defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr)
if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil {
return false, err
@@ -712,6 +722,29 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
}
}
} else if push && len(clients) <= nodeBulkPushThreshold {
+ if remote, ok := rt.(*runtime.Remote); ok && queued != nil && len(clients) == 1 {
+ if mutation.turn == nil || !clients[0].Enable {
+ s.recordClientNodeDeferred(oldInbound.NodeID)
+ } else {
+ mutation.unlock()
+ client := clients[0]
+ // Create already selected the effective addresses for this inbound.
+ client.AllowedIPsByInbound = nil
+ raw, err := json.Marshal(client)
+ if err != nil {
+ s.recordClientNodePush(*oldInbound.NodeID, true, runtime.ClientApplyResult{}, err)
+ return needRestart, nil
+ }
+ previous := *oldInbound
+ previous.Settings = prevSettings
+ pushed := *oldInbound
+ // The add RPC omits unrelated settings merged by the write transaction.
+ pushed.Settings = string(newSettings)
+ queued.prepare(mutation.turn, remote, &previous, &pushed, string(raw), prunedOrphans)
+ mutation.turn = nil
+ }
+ return needRestart, nil
+ }
mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool {
for _, client := range clients {
// Older nodes coerce enable=true. Reconcile the rest of this batch.
@@ -747,7 +780,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
if err := validateClientsRenewal(clients); err != nil {
return false, err
}
- inbound, err := inboundSvc.GetInbound(data.Id)
+ oldInbound, err := inboundSvc.GetInbound(data.Id)
if err != nil {
return false, err
}
@@ -759,10 +792,6 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
interfaceClients := settings["clients"].([]any)
- oldInbound, err := inboundSvc.GetInbound(data.Id)
- if err != nil {
- return false, err
- }
defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr)
if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil {
return false, err
@@ -777,7 +806,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
if i == 0 {
identityEmail = oldEmail
}
- if err := validateClientKeepAliveAgainstExisting(inbound.Protocol, client, oldClients, identityEmail); err != nil {
+ if err := validateClientKeepAliveAgainstExisting(oldInbound.Protocol, client, oldClients, identityEmail); err != nil {
return false, fmt.Errorf("client %q: %w", client.Email, err)
}
}
diff --git a/internal/web/service/client_node_dispatch.go b/internal/web/service/client_node_dispatch.go
index fc3aae0aa..9e400f4e1 100644
--- a/internal/web/service/client_node_dispatch.go
+++ b/internal/web/service/client_node_dispatch.go
@@ -22,6 +22,7 @@ type nodeConfigQueue struct {
groups list.List
reconciles int
live int
+ changed chan struct{}
}
// Inbounds in the same group can push concurrently. A node-wide operation
@@ -109,6 +110,10 @@ func (t *nodeConfigTurn) release() {
return
}
q, group := t.queue, t.group
+ if q.changed != nil {
+ close(q.changed)
+ q.changed = nil
+ }
lane := group.inbounds[t.inboundID]
wasReady := q.groups.Front() == group.position && lane.Front() == t.position
lane.Remove(t.position)
@@ -136,6 +141,31 @@ func (t *nodeConfigTurn) release() {
}
}
+func (q *nodeConfigQueue) changes() <-chan struct{} {
+ nodeConfigDispatchMu.Lock()
+ defer nodeConfigDispatchMu.Unlock()
+ if q.changed == nil {
+ q.changed = make(chan struct{})
+ }
+ return q.changed
+}
+
+func (q *nodeConfigQueue) acquireLive() bool {
+ nodeConfigDispatchMu.Lock()
+ defer nodeConfigDispatchMu.Unlock()
+ if q.live >= inboundFanoutConcurrency {
+ return false
+ }
+ q.live++
+ return true
+}
+
+func (q *nodeConfigQueue) releaseLive() {
+ nodeConfigDispatchMu.Lock()
+ defer nodeConfigDispatchMu.Unlock()
+ q.live--
+}
+
type inboundClientMutation struct {
lock *inboundMutationLock
turn *nodeConfigTurn
@@ -160,8 +190,12 @@ func (m *inboundClientMutation) close() {
}
func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWork, write func(*gorm.DB) error) error {
+ return m.commitThen(inbound, work, write, nil)
+}
+
+func (m *inboundClientMutation) commitThen(inbound *model.Inbound, work nodeConfigWork, write func(*gorm.DB) error, afterCommit func()) error {
if inbound.NodeID == nil {
- return runSerializedTx(write)
+ return runSerializedTxThen(write, afterCommit)
}
nodeID := *inbound.NodeID
queuedAt := time.Now()
@@ -174,6 +208,9 @@ func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWo
return (&NodeService{}).MarkNodeDirtyTx(tx, nodeID)
}, func() {
m.turn = reserveNodeConfigTurn(nodeID, inbound.Id, work)
+ if afterCommit != nil {
+ afterCommit()
+ }
})
if !startedAt.IsZero() {
logger.Debugf("client node save: node_id=%d writer_wait_ms=%d tx_ms=%d success=%t", nodeID,
@@ -211,19 +248,11 @@ func (m *inboundClientMutation) push(s *ClientService, rt runtime.Runtime, inbou
return
}
// Conflicting turns wait without consuming a live slot.
- nodeConfigDispatchMu.Lock()
- if m.turn.queue.live >= inboundFanoutConcurrency {
- nodeConfigDispatchMu.Unlock()
+ if !m.turn.queue.acquireLive() {
s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy)
return
}
- m.turn.queue.live++
- nodeConfigDispatchMu.Unlock()
- defer func() {
- nodeConfigDispatchMu.Lock()
- m.turn.queue.live--
- nodeConfigDispatchMu.Unlock()
- }()
+ defer m.turn.queue.releaseLive()
ctx, cancel := nodePushContext()
defer cancel()
complete := false
diff --git a/internal/web/service/client_paging.go b/internal/web/service/client_paging.go
index 8c3c0e55f..98814826d 100644
--- a/internal/web/service/client_paging.go
+++ b/internal/web/service/client_paging.go
@@ -140,10 +140,17 @@ func caseVariants(s string) []string {
// clientSearchCond builds the search predicate for the given needle variants
// (lowered first) and returns its arguments.
func clientSearchCond(variants []string) (string, []any) {
+ parts, args := clientTextSearch(variants, clientSearchCols)
+ parts = append(parts, "(COALESCE(c.tg_id, 0) <> 0 AND CAST(c.tg_id AS TEXT) LIKE ? ESCAPE '\\')")
+ args = append(args, "%"+escapeLikeLiteral(variants[0])+"%")
+ return "(" + strings.Join(parts, " OR ") + ")", args
+}
+
+func clientTextSearch(variants, columns []string) ([]string, []any) {
var parts []string
var args []any
like := func(v string) string { return "%" + escapeLikeLiteral(v) + "%" }
- for _, col := range clientSearchCols {
+ for _, col := range columns {
parts = append(parts, "LOWER("+col+") LIKE ? ESCAPE '\\'")
args = append(args, like(variants[0]))
for _, v := range variants {
@@ -151,9 +158,7 @@ func clientSearchCond(variants []string) (string, []any) {
args = append(args, like(v))
}
}
- parts = append(parts, "(COALESCE(c.tg_id, 0) <> 0 AND CAST(c.tg_id AS TEXT) LIKE ? ESCAPE '\\')")
- args = append(args, like(variants[0]))
- return "(" + strings.Join(parts, " OR ") + ")", args
+ return parts, args
}
// clientQuery builds the statements behind the clients page: a clients row
diff --git a/internal/web/service/client_user_suggestions.go b/internal/web/service/client_user_suggestions.go
new file mode 100644
index 000000000..978b96965
--- /dev/null
+++ b/internal/web/service/client_user_suggestions.go
@@ -0,0 +1,33 @@
+package service
+
+import (
+ "context"
+ "strings"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+const clientEmailSuggestionLimit = 50
+
+type ClientEmailSuggestions struct {
+ Emails []string `json:"emails" example:"[\"alice@example.com\",\"bob@example.com\"]"`
+}
+
+func (s *ClientService) ListUserSuggestions(ctx context.Context, search string) (ClientEmailSuggestions, error) {
+ query := database.GetDB().WithContext(ctx).Model(&model.ClientRecord{}).Where("email <> ''")
+ if search = strings.TrimSpace(search); search != "" {
+ like := func(value string) string { return "%" + escapeLikeLiteral(value) + "%" }
+ variants := caseVariants(search)
+ conditions := []string{"LOWER(email) LIKE ? ESCAPE '\\'"}
+ args := []any{like(variants[0])}
+ for _, variant := range variants {
+ conditions = append(conditions, "email LIKE ? ESCAPE '\\'")
+ args = append(args, like(variant))
+ }
+ query = query.Where("("+strings.Join(conditions, " OR ")+")", args...)
+ }
+ result := ClientEmailSuggestions{Emails: make([]string, 0, clientEmailSuggestionLimit)}
+ err := query.Order("email").Limit(clientEmailSuggestionLimit).Pluck("email", &result.Emails).Error
+ return result, err
+}
diff --git a/internal/web/service/database_maintenance.go b/internal/web/service/database_maintenance.go
new file mode 100644
index 000000000..a3fedf3d2
--- /dev/null
+++ b/internal/web/service/database_maintenance.go
@@ -0,0 +1,106 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "sync"
+ "time"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/logger"
+)
+
+var ErrDatabaseRestoring = errors.New("database restore in progress")
+
+var databaseWork struct {
+ sync.Mutex
+ active int
+ writers int
+ drained chan struct{}
+}
+
+// BeginDatabaseWork admits work that must finish before a restore replaces the pool.
+func BeginDatabaseWork() (func(), bool) {
+ return beginDatabaseWork(false)
+}
+
+func beginDatabaseWork(writer bool) (func(), bool) {
+ databaseWork.Lock()
+ defer databaseWork.Unlock()
+ if databaseWork.drained != nil || !database.RuntimeMaintenanceAvailable() {
+ return nil, false
+ }
+ databaseWork.active++
+ if writer {
+ databaseWork.writers++
+ }
+ return func() {
+ databaseWork.Lock()
+ defer databaseWork.Unlock()
+ databaseWork.active--
+ if writer {
+ databaseWork.writers--
+ }
+ if databaseWork.active == 0 && databaseWork.drained != nil {
+ close(databaseWork.drained)
+ }
+ }, true
+}
+
+func resumeDatabaseWork() {
+ databaseWork.Lock()
+ databaseWork.drained = nil
+ databaseWork.Unlock()
+}
+
+func pauseDatabaseWork(ctx context.Context) error {
+ databaseWork.Lock()
+ if databaseWork.drained != nil || !database.RuntimeMaintenanceAvailable() {
+ databaseWork.Unlock()
+ return ErrDatabaseRestoring
+ }
+ drained := make(chan struct{})
+ databaseWork.drained = drained
+ active, writers := databaseWork.active, databaseWork.writers
+ if active == 0 {
+ close(drained)
+ }
+ databaseWork.Unlock()
+
+ started := time.Now()
+ select {
+ case <-drained:
+ logger.Infof("database restore drained: pid=%d active_operations=%d admitted_writers=%d wait_ms=%d", os.Getpid(), active, writers, time.Since(started).Milliseconds())
+ return nil
+ case <-ctx.Done():
+ resumeDatabaseWork()
+ return fmt.Errorf("drain database activity: %w", ctx.Err())
+ }
+}
+
+func beginDatabaseRestore() (*database.MaintenanceLease, func() error, error) {
+ // An in-progress node poll already has its own network deadlines.
+ drain, cancelDrain := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancelDrain()
+ if err := pauseDatabaseWork(drain); err != nil {
+ return nil, nil, err
+ }
+ lock, cancelLock := context.WithTimeout(context.Background(), database.MaintenanceWait)
+ defer cancelLock()
+ lease, release, err := database.AcquireRestoreMaintenance(lock)
+ if err != nil {
+ resumeDatabaseWork()
+ return nil, nil, err
+ }
+ started := time.Now()
+ return lease, sync.OnceValue(func() error {
+ err := release()
+ logger.Infof("database restore maintenance: duration_ms=%d released=%t", time.Since(started).Milliseconds(), err == nil)
+ if err == nil {
+ resumeDatabaseWork()
+ }
+ return err
+ }), nil
+}
diff --git a/internal/web/service/database_maintenance_test.go b/internal/web/service/database_maintenance_test.go
new file mode 100644
index 000000000..3c10d1b9e
--- /dev/null
+++ b/internal/web/service/database_maintenance_test.go
@@ -0,0 +1,84 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestRestoreDrainsAdmittedTrafficWrites(t *testing.T) {
+ StartTrafficWriter()
+ t.Cleanup(StopTrafficWriter)
+ started, unblock := make(chan struct{}), make(chan struct{})
+ releaseWriter := sync.OnceFunc(func() { close(unblock) })
+ t.Cleanup(releaseWriter)
+ firstDone, queuedDone := make(chan error, 1), make(chan error, 1)
+ go func() {
+ firstDone <- submitTrafficWrite(func() error {
+ close(started)
+ <-unblock
+ return nil
+ })
+ }()
+ select {
+ case <-started:
+ case <-time.After(2 * time.Second):
+ t.Fatal("writer did not start")
+ }
+ go func() { queuedDone <- submitTrafficWriteBackground(func() error { return nil }) }()
+ waitForMaintenanceTest(t, func() bool { return trafficWriterQueueLen() == 1 })
+
+ drain, cancel := context.WithTimeout(t.Context(), 5*time.Second)
+ defer cancel()
+ drained := make(chan error, 1)
+ go func() { drained <- pauseDatabaseWork(drain) }()
+ t.Cleanup(resumeDatabaseWork)
+ waitForMaintenanceTest(t, func() bool {
+ end, ok := BeginDatabaseWork()
+ if ok {
+ end()
+ }
+ return !ok
+ })
+ if err := submitTrafficWrite(func() error { return nil }); !errors.Is(err, ErrDatabaseRestoring) {
+ t.Fatalf("new write during restore: %v, want restore error", err)
+ }
+ select {
+ case err := <-drained:
+ t.Fatalf("restore drained before the writer completed: %v", err)
+ default:
+ }
+
+ releaseWriter()
+ for _, result := range []<-chan error{firstDone, queuedDone, drained} {
+ select {
+ case err := <-result:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-drain.Done():
+ t.Fatal("writer or restore drain did not finish")
+ }
+ }
+ resumeDatabaseWork()
+ if err := submitTrafficWrite(func() error { return nil }); err != nil {
+ t.Fatalf("write after restore: %v", err)
+ }
+}
+
+func waitForMaintenanceTest(t *testing.T, ready func() bool) {
+ t.Helper()
+ timer := time.NewTimer(2 * time.Second)
+ defer timer.Stop()
+ ticker := time.NewTicker(time.Millisecond)
+ defer ticker.Stop()
+ for !ready() {
+ select {
+ case <-ticker.C:
+ case <-timer.C:
+ t.Fatal("timed out waiting for database work")
+ }
+ }
+}
diff --git a/internal/web/service/discord/gateway.go b/internal/web/service/discord/gateway.go
index 8306514d9..d4ca36f4a 100644
--- a/internal/web/service/discord/gateway.go
+++ b/internal/web/service/discord/gateway.go
@@ -389,6 +389,11 @@ func (g *GatewayClient) handleMessage(ctx context.Context, msg MessageCreateData
if msg.Author.Bot {
return
}
+ end, ok := service.BeginDatabaseWork()
+ if !ok {
+ return
+ }
+ defer end()
channelID, err := g.settingService.GetDiscordChannelId()
if err != nil || strings.TrimSpace(channelID) == "" {
return
diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go
index 9097b5664..03fe9cd14 100644
--- a/internal/web/service/inbound.go
+++ b/internal/web/service/inbound.go
@@ -271,8 +271,7 @@ func (s *InboundService) annotateLocalOriginGuid(inbounds []*model.Inbound) {
// for the edit/info/qr/export/clone flows that need it.
func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
db := database.GetDB()
- var inbounds []*model.Inbound
- err := db.Model(model.Inbound{}).Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error
+ inbounds, err := loadSlimInboundRows(db, userId)
if err == nil {
err = attachClientStats(db, inbounds)
}
@@ -283,14 +282,11 @@ func (s *InboundService) GetInboundsSlim(userId int) ([]*model.Inbound, error) {
s.annotateLocalOriginGuid(inbounds)
// Top up stats rows owned by sibling inbounds (multi-attached clients)
// so the list's depleted/expiring badges see every client; the UUID/SubId
- // enrichment stays skipped. Must run before slimming strips the settings.
+ // enrichment stays skipped.
s.backfillClientStats(db, inbounds)
// Slim feeds the panel UI only (masters poll the full list), so the badge
// math may see the cross-panel totals a master pushed.
s.overlayInboundsClientStats(db, inbounds)
- for _, ib := range inbounds {
- ib.Settings = slimSettingsClients(ib.Settings)
- }
return inbounds, nil
}
@@ -404,6 +400,17 @@ type InboundOption struct {
ShareAddrStrategy string `json:"shareAddrStrategy,omitempty"`
}
+// GetInboundCatalog selects the fields needed for remote inbound lookup and reconciliation.
+func (s *InboundService) GetInboundCatalog(userID int) ([]runtime.RemoteInboundOption, error) {
+ catalog := make([]runtime.RemoteInboundOption, 0)
+ err := database.GetDB().Model(&model.Inbound{}).
+ Select("id", "tag", "remark", "listen", "protocol", "port").
+ Where("user_id = ?", userID).
+ Order("id ASC").
+ Find(&catalog).Error
+ return catalog, err
+}
+
func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error) {
db := database.GetDB()
var rows []struct {
diff --git a/internal/web/service/inbound_info.go b/internal/web/service/inbound_info.go
new file mode 100644
index 000000000..51c500dcc
--- /dev/null
+++ b/internal/web/service/inbound_info.go
@@ -0,0 +1,275 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/xray"
+)
+
+const inboundPeerPageSize = 50
+
+type InboundInfoPage struct {
+ Inbound *model.Inbound `json:"inbound"`
+ TotalPeers int `json:"totalPeers" example:"120"`
+ PeerOffset int `json:"peerOffset" example:"50"`
+}
+
+type inboundInfoCollection struct {
+ raw string
+ size int
+}
+
+type inboundInfoSnapshot struct {
+ inbound model.Inbound
+ fields map[string]json.RawMessage
+ source string
+ collection inboundInfoCollection
+ tunnel bool
+}
+
+func readInboundInfoSnapshot(ctx context.Context, db *gorm.DB, userID, id int) (inboundInfoSnapshot, error) {
+ var snap inboundInfoSnapshot
+ if err := db.WithContext(ctx).Where("user_id = ?", userID).First(&snap.inbound, id).Error; err != nil {
+ return snap, err
+ }
+ fields, collections, err := splitInboundInfoSettings(ctx, snap.inbound.Settings)
+ if err != nil {
+ if ctx.Err() != nil {
+ return snap, ctx.Err()
+ }
+ fields = make(map[string]json.RawMessage)
+ }
+ snap.fields = fields
+ snap.inbound.Settings = ""
+ snap.source = "clients"
+ snap.tunnel = snap.inbound.Protocol == model.WireGuard || snap.inbound.Protocol == model.AmneziaWG
+ if snap.inbound.Protocol == model.WireGuard && collections["clients"].size == 0 {
+ snap.source = "peers"
+ }
+ snap.collection = collections[snap.source]
+ return snap, nil
+}
+
+func splitInboundInfoSettings(ctx context.Context, settings string) (map[string]json.RawMessage, map[string]inboundInfoCollection, error) {
+ settings = strings.TrimSpace(settings)
+ if strings.HasPrefix(settings, `"`) {
+ var decoded string
+ if err := json.Unmarshal([]byte(settings), &decoded); err != nil {
+ return nil, nil, err
+ }
+ settings = decoded
+ }
+ metadata := make(map[string]json.RawMessage)
+ collections := make(map[string]inboundInfoCollection)
+ dec := json.NewDecoder(strings.NewReader(settings))
+ opening, err := dec.Token()
+ if err != nil || opening != json.Delim('{') {
+ return nil, nil, fmt.Errorf("invalid inbound settings")
+ }
+ for dec.More() {
+ key, err := dec.Token()
+ if err != nil {
+ return nil, nil, err
+ }
+ name, ok := key.(string)
+ if !ok {
+ return nil, nil, fmt.Errorf("invalid inbound settings field")
+ }
+ if name == "clients" || name == "peers" {
+ // Keep the stored array span and its count without decoding a full peer slice.
+ value := strings.TrimLeft(settings[dec.InputOffset():], ": \t\r\n")
+ if strings.HasPrefix(value, "[") {
+ start := len(settings) - len(value)
+ if _, err := dec.Token(); err != nil {
+ return nil, nil, err
+ }
+ count := 0
+ var row json.RawMessage
+ for dec.More() {
+ if err := ctx.Err(); err != nil {
+ return nil, nil, err
+ }
+ if err := dec.Decode(&row); err != nil {
+ return nil, nil, err
+ }
+ if len(row) > 0 && row[0] == '{' {
+ count++
+ }
+ }
+ if _, err := dec.Token(); err != nil {
+ return nil, nil, err
+ }
+ collections[name] = inboundInfoCollection{raw: settings[start:dec.InputOffset()], size: count}
+ continue
+ }
+ delete(collections, name)
+ var discarded json.RawMessage
+ if err := dec.Decode(&discarded); err != nil {
+ return nil, nil, err
+ }
+ continue
+ }
+ var field json.RawMessage
+ if err := dec.Decode(&field); err != nil {
+ return nil, nil, err
+ }
+ metadata[name] = field
+ }
+ if _, err := dec.Token(); err != nil {
+ return nil, nil, err
+ }
+ if _, err := dec.Token(); !errors.Is(err, io.EOF) {
+ return nil, nil, fmt.Errorf("unexpected data after inbound settings")
+ }
+ return metadata, collections, nil
+}
+
+func (c inboundInfoCollection) walk(ctx context.Context, visit func(json.RawMessage) bool) error {
+ if c.raw == "" {
+ return nil
+ }
+ d := json.NewDecoder(strings.NewReader(c.raw))
+ if _, err := d.Token(); err != nil {
+ return err
+ }
+ var row json.RawMessage
+ for d.More() {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if err := d.Decode(&row); err != nil {
+ return err
+ }
+ if len(row) > 0 && row[0] == '{' && !visit(row) {
+ return nil
+ }
+ }
+ return nil
+}
+
+func (s inboundInfoSnapshot) page(rows []json.RawMessage, offset int) (*InboundInfoPage, error) {
+ // Only the chosen source array is added back, so generators see the proper representation.
+ for _, name := range []string{"clients", "peers"} {
+ delete(s.fields, name)
+ }
+ if rows != nil {
+ selected, err := json.Marshal(rows)
+ if err != nil {
+ return nil, err
+ }
+ s.fields[s.source] = selected
+ }
+ raw, err := json.Marshal(s.fields)
+ if err != nil {
+ return nil, err
+ }
+ inbound := s.inbound
+ inbound.Settings = string(raw)
+ total := 0
+ if s.tunnel {
+ total = s.collection.size
+ }
+ return &InboundInfoPage{Inbound: &inbound, TotalPeers: total, PeerOffset: offset}, nil
+}
+
+func (s *InboundService) GetInboundInfo(ctx context.Context, userID, id, page int) (*InboundInfoPage, error) {
+ if id < 1 || page < 1 || page > 1_000_000 {
+ return nil, fmt.Errorf("invalid inbound info page")
+ }
+ db := database.GetDB().WithContext(ctx)
+ snap, err := readInboundInfoSnapshot(ctx, db, userID, id)
+ if err != nil {
+ return nil, err
+ }
+ start, limit := 0, 1
+ if snap.tunnel {
+ start, limit = (page-1)*inboundPeerPageSize, inboundPeerPageSize
+ }
+ rows := make([]json.RawMessage, 0, min(limit, max(0, snap.collection.size-start)))
+ if start < snap.collection.size {
+ index := 0
+ err = snap.collection.walk(ctx, func(row json.RawMessage) bool {
+ if index >= start {
+ rows = append(rows, append(json.RawMessage(nil), row...))
+ }
+ index++
+ return len(rows) < limit
+ })
+ if err != nil {
+ return nil, err
+ }
+ }
+ info, err := snap.page(rows, start)
+ if err != nil {
+ return nil, err
+ }
+ if snap.source == "clients" && len(rows) > 0 {
+ var identity struct{ Email string }
+ if json.Unmarshal(rows[0], &identity) == nil && identity.Email != "" {
+ var stats xray.ClientTraffic
+ err := db.Where("email = ?", identity.Email).Take(&stats).Error
+ if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, err
+ }
+ if err == nil {
+ info.Inbound.ClientStats = []xray.ClientTraffic{stats}
+ s.overlayInboundsClientStats(db, []*model.Inbound{info.Inbound})
+ }
+ }
+ }
+ return info, nil
+}
+
+func (s *InboundService) WalkInboundPeerPages(ctx context.Context, userID, id int, visit func(*InboundInfoPage) error) error {
+ if id < 1 {
+ return fmt.Errorf("invalid inbound ID")
+ }
+ snap, err := readInboundInfoSnapshot(ctx, database.GetDB(), userID, id)
+ if err != nil {
+ return err
+ }
+ if !snap.tunnel || snap.collection.size == 0 {
+ return fmt.Errorf("inbound has no tunnel peers to export")
+ }
+ offset := 0
+ rows := make([]json.RawMessage, 0, inboundPeerPageSize)
+ emit := func() error {
+ page, err := snap.page(rows, offset)
+ if err != nil {
+ return err
+ }
+ if err = visit(page); err != nil {
+ return err
+ }
+ offset += len(rows)
+ rows = rows[:0]
+ return nil
+ }
+ var writeErr error
+ err = snap.collection.walk(ctx, func(row json.RawMessage) bool {
+ rows = append(rows, append(json.RawMessage(nil), row...))
+ if len(rows) == inboundPeerPageSize {
+ writeErr = emit()
+ }
+ return writeErr == nil
+ })
+ if writeErr != nil {
+ return writeErr
+ }
+ if err != nil {
+ return err
+ }
+ if len(rows) > 0 {
+ return emit()
+ }
+ return nil
+}
diff --git a/internal/web/service/inbound_migration.go b/internal/web/service/inbound_migration.go
index e3e96e192..4148b3472 100644
--- a/internal/web/service/inbound_migration.go
+++ b/internal/web/service/inbound_migration.go
@@ -13,11 +13,17 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
+ "github.com/jackc/pgx/v5/pgconn"
"gorm.io/gorm"
)
func (s *InboundService) MigrationRemoveOrphanedTraffics() {
- db := database.GetDB()
+ if err := removeOrphanedMigrationTraffics(database.GetDB()); err != nil {
+ logger.Warning("MigrationRemoveOrphanedTraffics failed:", err)
+ }
+}
+
+func removeOrphanedMigrationTraffics(db *gorm.DB) error {
query := fmt.Sprintf(
"DELETE FROM client_traffics WHERE email NOT IN (SELECT email FROM clients) AND email NOT IN (SELECT %s %s)",
database.JSONFieldText("client.value", "email"),
@@ -25,39 +31,106 @@ func (s *InboundService) MigrationRemoveOrphanedTraffics() {
)
result := db.Exec(query)
if result.Error != nil {
- logger.Warning("MigrationRemoveOrphanedTraffics failed:", result.Error)
- return
+ return result.Error
}
if result.RowsAffected > 0 {
logger.Infof("MigrationRemoveOrphanedTraffics: removed %d orphaned client_traffics row(s)", result.RowsAffected)
}
+ return nil
}
-func (s *InboundService) MigrationRequirements() (err error) {
- db := database.GetDB()
- tx := db.Begin()
- defer func() {
- if err == nil {
- if commitErr := tx.Commit().Error; commitErr != nil {
- err = commitErr
- return
- }
- if !database.IsPostgres() {
- if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
- logger.Warningf("VACUUM failed: %v", dbErr)
- }
- }
- } else {
- tx.Rollback()
- }
- }()
+var errInboundMigrationBusy = errors.New("database is busy; retry the inbound migration after active database work has stopped")
- if tx.Migrator().HasColumn(&model.Inbound{}, "all_time") {
+func runInboundMigration(db *gorm.DB, repairSchema bool, migrate func(*gorm.DB) error) error {
+ started := time.Now()
+ err := db.Transaction(func(tx *gorm.DB) error {
+ if tx.Name() == database.DialectPostgres {
+ if err := preparePostgresInboundMigration(tx, repairSchema); err != nil {
+ return err
+ }
+ }
+ return migrate(tx)
+ })
+ logger.Debugf("inbound migration: tx_ms=%d committed=%t", time.Since(started).Milliseconds(), err == nil)
+ if err == nil && db.Name() == database.DialectSQLite {
+ if vacuumErr := db.Exec(`VACUUM "main"`).Error; vacuumErr != nil {
+ logger.Warningf("VACUUM failed: %v", vacuumErr)
+ }
+ }
+ return err
+}
+
+func lockInboundMigrationTables(tx *gorm.DB, tables, mode string) error {
+ err := tx.Exec("LOCK TABLE " + tables + " IN " + mode + " MODE NOWAIT").Error
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) && pgErr.Code == "55P03" {
+ return fmt.Errorf("%w: %w", errInboundMigrationBusy, err)
+ }
+ if err != nil {
+ return fmt.Errorf("lock inbound migration tables: %w", err)
+ }
+ return nil
+}
+
+func preparePostgresInboundMigration(tx *gorm.DB, repairSchema bool) error {
+ // EXCLUSIVE admits plain SELECTs and excludes writes and SELECT FOR UPDATE.
+ // Acquire the complete write set before DDL or DML, without waiting behind a live writer.
+ if err := lockInboundMigrationTables(tx, "inbounds, client_traffics, clients, client_inbounds, client_groups", "EXCLUSIVE"); err != nil || !repairSchema {
+ return err
+ }
+
+ var changes []struct{ TableName, ColumnName string }
+ if err := tx.Raw(`
+ SELECT legacy.table_name, legacy.column_name
+ FROM (VALUES
+ ('inbounds', 'all_time'), ('client_traffics', 'all_time'),
+ ('inbounds', 'enable'), ('client_traffics', 'enable'),
+ ('clients', 'enable'), ('nodes', 'enable'),
+ ('api_tokens', 'enabled'), ('outbound_subscriptions', 'enabled')
+ ) AS legacy(table_name, column_name)
+ JOIN pg_catalog.pg_attribute AS a
+ ON a.attrelid = pg_catalog.to_regclass(legacy.table_name)
+ AND a.attname = legacy.column_name AND a.attnum > 0 AND NOT a.attisdropped
+ WHERE legacy.column_name = 'all_time' OR a.atttypid <> 'pg_catalog.bool'::regtype
+ ORDER BY legacy.table_name, legacy.column_name`).Scan(&changes).Error; err != nil {
+ return fmt.Errorf("inspect legacy inbound migration columns: %w", err)
+ }
+ var tables []string
+ for _, change := range changes {
+ if len(tables) == 0 || tables[len(tables)-1] != change.TableName {
+ tables = append(tables, change.TableName)
+ }
+ }
+ if len(tables) > 0 {
+ // ALTER TABLE needs ACCESS EXCLUSIVE, but upgraded schemas need no DDL.
+ if err := lockInboundMigrationTables(tx, strings.Join(tables, ", "), "ACCESS EXCLUSIVE"); err != nil {
+ return err
+ }
+ }
+ for _, change := range changes {
+ table, col := change.TableName, change.ColumnName
+ stmt := fmt.Sprintf("ALTER TABLE %s DROP COLUMN %s", table, col)
+ if col != "all_time" {
+ stmt = fmt.Sprintf("ALTER TABLE %s ALTER COLUMN %s TYPE boolean USING (CASE WHEN %s::text IN ('1','true','t','yes') THEN true ELSE false END)", table, col, col)
+ }
+ if err := tx.Exec(stmt).Error; err != nil {
+ return fmt.Errorf("normalize legacy column %s.%s: %w", table, col, err)
+ }
+ }
+ return nil
+}
+
+func (s *InboundService) MigrationRequirements() error {
+ return runInboundMigration(database.GetDB(), true, s.migrationRequirements)
+}
+
+func (s *InboundService) migrationRequirements(tx *gorm.DB) (err error) {
+ if tx.Name() == database.DialectSQLite && tx.Migrator().HasColumn(&model.Inbound{}, "all_time") {
if err = tx.Migrator().DropColumn(&model.Inbound{}, "all_time"); err != nil {
return
}
}
- if tx.Migrator().HasColumn(&xray.ClientTraffic{}, "all_time") {
+ if tx.Name() == database.DialectSQLite && tx.Migrator().HasColumn(&xray.ClientTraffic{}, "all_time") {
if err = tx.Migrator().DropColumn(&xray.ClientTraffic{}, "all_time"); err != nil {
return
}
@@ -66,39 +139,6 @@ func (s *InboundService) MigrationRequirements() (err error) {
return
}
- // Normalize "enable" columns to boolean on Postgres. Legacy SQLite data
- // (0/1 integers), partial migrations, or mixed write paths (public API
- // inbound updates that flow through UpdateClientStat + client syncs, plus
- // node traffic merge deltas) can leave the column as integer or with mixed
- // interpretation. This (combined with the dialect-aware
- // ClientTrafficEnableMergeExpr) prevents type problems in the node traffic
- // sync merge (SetRemoteTraffic) and makes the sync robust even when
- // inbounds are updated via the public API (incl. ones carrying
- // externalProxy in streamSettings). The same expression is also safe on
- // SQLite (no PG :: casts).
- if database.IsPostgres() {
- // Use DO block so it is idempotent and doesn't fail if already boolean.
- normalizeBool := func(table, col string) error {
- return tx.Exec(fmt.Sprintf(`
- DO $$
- BEGIN
- IF EXISTS (
- SELECT 1 FROM information_schema.columns
- WHERE table_name = '%s' AND column_name = '%s'
- AND data_type <> 'boolean'
- ) THEN
- ALTER TABLE %s ALTER COLUMN %s
- TYPE boolean USING (CASE WHEN %s::text IN ('1','true','t','yes') THEN true ELSE false END);
- END IF;
- END $$;`, table, col, table, col, col)).Error
- }
- for _, column := range [][2]string{{"inbounds", "enable"}, {"client_traffics", "enable"}, {"nodes", "enable"}, {"clients", "enable"}, {"api_tokens", "enabled"}, {"outbound_subscriptions", "enabled"}} {
- if err = normalizeBool(column[0], column[1]); err != nil {
- return
- }
- }
- }
-
// Fix inbounds based problems
var inbounds []*model.Inbound
err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan", "shadowsocks", "hysteria"}).Find(&inbounds).Error
@@ -286,12 +326,21 @@ func (s *InboundService) MigrationRequirements() (err error) {
return err
}
-func (s *InboundService) MigrateDB() {
- if err := s.MigrationRequirements(); err != nil {
- logger.Errorf("MigrationRequirements failed: %v", err)
- }
- s.MigrationRemoveOrphanedTraffics()
- s.MigrationRestoreVisionFlow()
+func (s *InboundService) MigrateDB() error {
+ return s.MigrateDBOn(database.GetDB())
+}
+
+// MigrateDBOn runs inbound repair through the caller's database connection.
+func (s *InboundService) MigrateDBOn(db *gorm.DB) error {
+ return runInboundMigration(db, true, func(tx *gorm.DB) error {
+ if err := s.migrationRequirements(tx); err != nil {
+ return fmt.Errorf("inbound migration requirements: %w", err)
+ }
+ if err := removeOrphanedMigrationTraffics(tx); err != nil {
+ return fmt.Errorf("remove orphaned traffic during migration: %w", err)
+ }
+ return s.migrationRestoreVisionFlow(tx)
+ })
}
// MigrationRestoreVisionFlow repairs VLESS inbounds whose clients lost their
@@ -302,37 +351,36 @@ func (s *InboundService) MigrateDB() {
// Vision. Idempotent: once a client carries the flow it is skipped, so this is a
// no-op on healthy installs and on subsequent boots.
func (s *InboundService) MigrationRestoreVisionFlow() {
- db := database.GetDB()
+ if err := runInboundMigration(database.GetDB(), false, s.migrationRestoreVisionFlow); err != nil {
+ logger.Warning("MigrationRestoreVisionFlow failed:", err)
+ }
+}
+
+func (s *InboundService) migrationRestoreVisionFlow(tx *gorm.DB) error {
var inbounds []*model.Inbound
- if err := db.Model(&model.Inbound{}).
+ if err := tx.Model(&model.Inbound{}).
Where("protocol = ?", model.VLESS).
Find(&inbounds).Error; err != nil {
- logger.Warning("MigrationRestoreVisionFlow: load inbounds failed:", err)
- return
+ return fmt.Errorf("load VLESS inbounds for flow migration: %w", err)
}
for _, ib := range inbounds {
if ib.DisableFlow {
continue
}
- restored, changed := s.restoreVisionFlowForEligibleInbound(nil, ib.Settings, ib.StreamSettings, ib.Protocol)
+ restored, changed := s.restoreVisionFlowForEligibleInbound(tx, ib.Settings, ib.StreamSettings, ib.Protocol)
if !changed {
continue
}
clients, err := s.GetClients(&model.Inbound{Settings: restored})
if err != nil {
- logger.Warning("MigrationRestoreVisionFlow: parse clients for inbound", ib.Id, "failed:", err)
- continue
+ return fmt.Errorf("parse clients for inbound %d during flow migration: %w", ib.Id, err)
}
- err = db.Transaction(func(tx *gorm.DB) error {
- if e := tx.Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("settings", restored).Error; e != nil {
- return e
- }
- return s.clientService.SyncInbound(tx, ib.Id, clients)
- })
- if err != nil {
- logger.Warning("MigrationRestoreVisionFlow: update inbound", ib.Id, "failed:", err)
- continue
+ if err := tx.Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("settings", restored).Error; err != nil {
+ return fmt.Errorf("update inbound %d during flow migration: %w", ib.Id, err)
+ }
+ if err := s.clientService.SyncInbound(tx, ib.Id, clients); err != nil {
+ return fmt.Errorf("sync inbound %d during flow migration: %w", ib.Id, err)
}
- logger.Info("MigrationRestoreVisionFlow: restored XTLS Vision flow on inbound", ib.Id)
}
+ return nil
}
diff --git a/internal/web/service/inbound_migration_contention_test.go b/internal/web/service/inbound_migration_contention_test.go
new file mode 100644
index 000000000..a49aea7e0
--- /dev/null
+++ b/internal/web/service/inbound_migration_contention_test.go
@@ -0,0 +1,214 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgconn"
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/config"
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
+ "github.com/mhsanaei/3x-ui/v3/internal/xray"
+)
+
+func TestInboundMigrationAllowsPostgresReaders(t *testing.T) {
+ if config.GetDBKind() != database.DialectPostgres {
+ t.Skip("requires PostgreSQL table locks")
+ }
+ db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "migration-reader.db"))
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ reader := db.WithContext(ctx).Begin()
+ if reader.Error != nil {
+ t.Fatal(reader.Error)
+ }
+ defer reader.Rollback()
+ if err := reader.Exec("SELECT id FROM inbounds").Error; err != nil {
+ t.Fatal(err)
+ }
+
+ if err := runInboundMigration(db, true, func(tx *gorm.DB) error {
+ if err := db.WithContext(ctx).Exec("SELECT id FROM inbounds").Error; err != nil {
+ return fmt.Errorf("reader during migration: %w", err)
+ }
+ return tx.Exec("UPDATE inbounds SET remark = remark").Error
+ }); err != nil {
+ t.Fatalf("a pre-existing or new reader blocked the migration: %v", err)
+ }
+ if err := reader.Rollback().Error; err != nil {
+ t.Fatal(err)
+ }
+
+ if err := db.Exec("ALTER TABLE inbounds ADD COLUMN all_time bigint").Error; err != nil {
+ t.Fatal(err)
+ }
+ reader = db.WithContext(ctx).Begin()
+ if reader.Error != nil {
+ t.Fatal(reader.Error)
+ }
+ defer reader.Rollback()
+ if err := reader.Exec("SELECT id FROM inbounds").Error; err != nil {
+ t.Fatal(err)
+ }
+ svc := &InboundService{}
+ if err := svc.MigrationRequirements(); !errors.Is(err, errInboundMigrationBusy) {
+ t.Fatalf("legacy DDL with a reader: %v, want immediate lock-conflict error", err)
+ }
+ if err := reader.Rollback().Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := svc.MigrationRequirements(); err != nil || db.Migrator().HasColumn(&model.Inbound{}, "all_time") {
+ t.Fatalf("legacy column not removed after reader finished: %v", err)
+ }
+}
+
+func TestMigrationRequirementsRejectsLiveNodeMergePostgres(t *testing.T) {
+ if config.GetDBKind() != database.DialectPostgres {
+ t.Skip("requires PostgreSQL table locks")
+ }
+ db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "migration.db"))
+ node := &model.Node{Name: "migration-contention", Enable: true}
+ seedNodeRow(t, db, node)
+ svc := &InboundService{}
+ const email = "migration-client@example.test"
+ snapshot := func(up, quota int64) *runtime.TrafficSnapshot {
+ settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true,"totalGB":%d}]}`, email, quota)
+ snap := snapshotWithClients(t, "migration-contention", settings, xray.ClientTraffic{
+ Email: email, Up: up, Total: quota, Enable: true,
+ })
+ snap.Inbounds[0].Up = up
+ snap.Inbounds[0].Protocol = model.VLESS
+ return snap
+ }
+ if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil {
+ t.Fatal(err)
+ }
+
+ locked, unblock := make(chan struct{}), make(chan struct{})
+ var hold, release sync.Once
+ finishMerge := func() { release.Do(func() { close(unblock) }) }
+ if err := db.Callback().Update().After("gorm:update").Register("test:hold_node_merge", func(tx *gorm.DB) {
+ if tx.Statement.Table == "inbounds" && tx.Error == nil {
+ hold.Do(func() {
+ close(locked)
+ <-unblock
+ })
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ report := snapshot(130, 2000)
+ mergeDone := make(chan struct{})
+ var mergeErr error
+ go func() {
+ defer close(mergeDone)
+ _, mergeErr = svc.SetRemoteTraffic(node.Id, report, false, false)
+ }()
+ t.Cleanup(func() {
+ finishMerge()
+ <-mergeDone
+ })
+ select {
+ case <-locked:
+ case <-time.After(5 * time.Second):
+ t.Fatal("fixture merge never acquired write locks")
+ }
+
+ ctx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond)
+ defer cancel()
+ lease, err := database.TryConfiguredMaintenance(ctx, true)
+ if lease != nil {
+ _ = lease.Close()
+ }
+ if !errors.Is(err, database.ErrMaintenanceBusy) {
+ t.Fatalf("migration lease while node transaction is active: %v, want busy", err)
+ }
+
+ migrationDone := make(chan struct{})
+ var migrationErr error
+ go func() {
+ defer close(migrationDone)
+ migrationErr = svc.MigrationRequirements()
+ }()
+ t.Cleanup(func() {
+ finishMerge()
+ <-migrationDone
+ })
+ select {
+ case <-migrationDone:
+ var pgErr *pgconn.PgError
+ if !errors.As(migrationErr, &pgErr) || pgErr.Code != "55P03" {
+ t.Fatalf("concurrent migration error=%v, want lock not available", migrationErr)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("migration waited behind the merge instead of refusing to start")
+ }
+
+ finishMerge()
+ <-mergeDone
+ if mergeErr != nil {
+ t.Fatal(mergeErr)
+ }
+ if err := svc.MigrateDB(); err != nil {
+ t.Fatalf("retry after merge committed: %v", err)
+ }
+ if row := readTraffic(t, db, email); row.Up != 130 || row.Total != 2000 {
+ t.Fatalf("merge or migration lost traffic counters: %+v", row)
+ }
+ if record := lookupClientRecord(t, email); record.TotalGB != 2000 || linkCount(t, db, email) != 1 {
+ t.Fatalf("merge or migration lost the updated client or its membership: %+v", record)
+ }
+}
+
+func TestMigrateDBRollsBackRequirementsWhenTrafficCleanupFails(t *testing.T) {
+ if config.GetDBKind() == database.DialectPostgres {
+ t.Skip("uses a SQLite trigger to fail orphan cleanup")
+ }
+ db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "migration-rollback.db"))
+ ib := model.Inbound{
+ UserId: 1, Tag: "migration-rollback", Port: 24443, Protocol: model.VLESS,
+ Settings: `{"clients":[]}`, StreamSettings: `{"network":"tcp"}`,
+ ShareAddrStrategy: "custom", ShareAddr: " example.test ",
+ }
+ if err := db.Create(&ib).Error; err != nil {
+ t.Fatal(err)
+ }
+ orphan := xray.ClientTraffic{InboundId: ib.Id, Email: "orphan@x"}
+ if err := db.Create(&orphan).Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := db.Exec(`CREATE TRIGGER reject_orphan_cleanup BEFORE DELETE ON client_traffics
+ WHEN OLD.email = 'orphan@x' BEGIN SELECT RAISE(ABORT, 'injected orphan cleanup failure'); END`).Error; err != nil {
+ t.Fatal(err)
+ }
+ svc := &InboundService{}
+ if err := svc.MigrateDB(); err == nil || !strings.Contains(err.Error(), "injected orphan cleanup failure") {
+ t.Fatalf("migration error=%v, want the orphan cleanup failure", err)
+ }
+ var stored model.Inbound
+ if err := db.First(&stored, ib.Id).Error; err != nil || stored.ShareAddr != ib.ShareAddr {
+ t.Fatalf("requirements leaked from rolled back migration: share_addr=%q err=%v", stored.ShareAddr, err)
+ }
+ if err := db.Exec("DROP TRIGGER reject_orphan_cleanup").Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := svc.MigrateDB(); err != nil {
+ t.Fatal(err)
+ }
+ if err := db.First(&stored, ib.Id).Error; err != nil || stored.ShareAddr != "example.test" {
+ t.Fatalf("retried migration did not normalize the inbound: share_addr=%q err=%v", stored.ShareAddr, err)
+ }
+ var remaining int64
+ if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", orphan.Email).Count(&remaining).Error; err != nil || remaining != 0 {
+ t.Fatalf("retried migration left %d orphaned stats: %v", remaining, err)
+ }
+}
diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go
index 269a2450e..0a66b8150 100644
--- a/internal/web/service/inbound_node.go
+++ b/internal/web/service/inbound_node.go
@@ -854,6 +854,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
logger.Debugf("node traffic transaction: node_id=%d tx_ms=%d committed=false", nodeID, time.Since(txStarted).Milliseconds())
}
}()
+ if err := database.LockPostgresWriter(tx); err != nil {
+ return false, err
+ }
claims := &nodeClientClaims{}
rawSettings := make(map[*model.Inbound]string, len(snap.Inbounds))
@@ -1675,15 +1678,18 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
attached, err := nodeAttachedEmails(db, nodeID)
if err != nil {
logger.Warningf("setRemoteTraffic: load the clients of node %d failed, dropping its online report: %v", nodeID, err)
+ snap.OnlineTree = nil
+ snap.OnlineEmails = nil
+ } else {
+ keepAttachedOnlineEmails(snap, attached)
}
- keepAttachedOnlineEmails(snap, attached)
}
if process := currentXrayProcess(); process != nil {
hostedGuids := activeInboundGuidKeys(snap.Inbounds, tagToCentral, originGuidFor)
tree := snap.OnlineTree
switch {
- case len(tree) == 0 && len(snap.OnlineEmails) > 0:
+ case tree == nil && snap.OnlineEmails != nil:
// Old-build node (no GUID tree): key its flat online list under its
// own effective identity so attribution still works for that branch.
tree = map[string][]string{selfKey: snap.OnlineEmails}
@@ -1707,6 +1713,12 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
if len(activeTree) > 0 {
activeTree = filterGuidTreeKeys(activeTree, hostedGuids)
}
+ if _, hosted := hostedGuids[selfKey]; hosted && snap.LegacyInboundActivity {
+ if activeTree == nil {
+ activeTree = make(map[string][]string)
+ }
+ activeTree[selfKey] = nil
+ }
process.SetNodeActiveInboundTree(nodeID, activeTree)
}
@@ -1778,7 +1790,7 @@ func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
return map[string][]string{}
}
out := process.GetMergedNodeTrees()
- if local := process.GetLocalOnlineClients(); len(local) > 0 {
+ if local, _ := process.LocalOnlineSnapshot(time.Now().UnixMilli(), onlineGracePeriodMs); local != nil {
if guid := s.panelGuid(); guid != "" {
out[guid] = mergeEmails(out[guid], local)
}
@@ -1788,16 +1800,17 @@ func (s *InboundService) GetOnlineClientsByGuid() map[string][]string {
// GetActiveInboundsByGuid returns the inbound tags that carried traffic within
// the grace window, keyed by the panelGuid of the node that physically hosts
-// each inbound. A GUID missing from the map means "don't gate" for that node's
-// inbounds (old-build node or no active-inbound signal).
+// each inbound. An absent GUID means the node did not supply usable activity
+// data; an empty slice means idle and nil denotes a confirmed legacy node.
+// The reserved NUL tag marks a partial report: unlisted inbounds remain unknown.
func (s *InboundService) GetActiveInboundsByGuid() map[string][]string {
process := currentXrayProcess()
if process == nil {
return map[string][]string{}
}
out := process.GetMergedActiveInboundTrees()
- active := process.GetLocalActiveInbounds()
- if len(active) == 0 {
+ _, active := process.LocalOnlineSnapshot(time.Now().UnixMilli(), onlineGracePeriodMs)
+ if active == nil {
return out
}
guid := s.panelGuid()
@@ -1890,7 +1903,9 @@ func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]st
if guid == from {
guid = to
}
- remapped[guid] = mergeEmails(remapped[guid], values)
+ if prior, exists := remapped[guid]; !exists || values != nil {
+ remapped[guid] = mergeEmails(prior, values)
+ }
}
return remapped
}
@@ -1927,12 +1942,25 @@ func keepAttachedOnlineEmails(snap *runtime.TrafficSnapshot, attached map[string
}
return kept
}
- snap.OnlineEmails = keep(snap.OnlineEmails)
+ if snap.OnlineEmails != nil {
+ snap.OnlineEmails = keep(snap.OnlineEmails)
+ if snap.OnlineEmails == nil {
+ snap.OnlineEmails = []string{}
+ }
+ }
+ if snap.OnlineTree == nil {
+ return
+ }
tree := make(map[string][]string, len(snap.OnlineTree))
for guid, emails := range snap.OnlineTree {
- if kept := keep(emails); len(kept) > 0 {
- tree[guid] = kept
+ if emails == nil {
+ continue
}
+ kept := keep(emails)
+ if kept == nil {
+ kept = []string{}
+ }
+ tree[guid] = kept
}
snap.OnlineTree = tree
}
@@ -1943,15 +1971,20 @@ func normalizeActiveInboundTreeTags(tree map[string][]string, tagToCentral map[s
}
out := make(map[string][]string, len(tree))
for guid, tags := range tree {
- if guid == "" || len(tags) == 0 {
+ if guid == "" {
continue
}
+ if tags == nil {
+ out[guid] = nil
+ continue
+ }
+ out[guid] = []string{}
seen := make(map[string]struct{}, len(tags))
for _, tag := range tags {
if tag == "" {
continue
}
- if central, ok := tagToCentral[tag]; ok && central != nil && central.Tag != "" {
+ if central, ok := tagToCentral[tag]; tag != xray.PartialInboundActivityTag && ok && central != nil && central.Tag != "" {
tag = central.Tag
}
if _, dup := seen[tag]; dup {
@@ -1992,9 +2025,7 @@ func filterGuidTreeKeys(tree map[string][]string, allowed map[string]struct{}) m
if _, ok := allowed[guid]; !ok {
continue
}
- if len(values) > 0 {
- out[guid] = values
- }
+ out[guid] = values
}
if len(out) == 0 {
return nil
@@ -2019,17 +2050,27 @@ func clientsLastOnline(db *gorm.DB) (map[string]int64, error) {
return result, nil
}
-// RefreshLocalOnlineClients folds the emails and inbound tags active on this
-// panel's own xray this poll into the local online/active sets, applying the
-// grace window and pruning stale entries. Pass nil to only prune. See
-// xray.Process for why the local sets are kept separate from the shared
-// last_online column.
+// HasFreshXrayOnlineSample reports freshness independently of sidecar observations.
+func (*InboundService) HasFreshXrayOnlineSample() bool {
+ process := currentXrayProcess()
+ return process != nil && process.HasFreshXrayOnlineSample(time.Now().UnixMilli(), onlineGracePeriodMs)
+}
+
+// RefreshLocalOnlineClients adds sidecar activity or prunes the local window
+// without treating it as a successful Xray poll. Pass nil slices to only prune.
func (s *InboundService) RefreshLocalOnlineClients(activeEmails, activeInboundTags []string) {
if process := currentXrayProcess(); process != nil {
process.RefreshLocalOnline(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
}
}
+// PublishXrayOnlineClients records a successful poll on the current running core.
+func (s *InboundService) PublishXrayOnlineClients(process *xray.Process, activeEmails, activeInboundTags []string) {
+ if process != nil && process == currentXrayProcess() && process.IsRunning() {
+ process.RecordXrayOnlineSample(activeEmails, activeInboundTags, time.Now().UnixMilli(), onlineGracePeriodMs)
+ }
+}
+
func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
db := database.GetDB()
diff --git a/internal/web/service/inbound_node_reconcile_test.go b/internal/web/service/inbound_node_reconcile_test.go
index 2075f1fc1..0e62543da 100644
--- a/internal/web/service/inbound_node_reconcile_test.go
+++ b/internal/web/service/inbound_node_reconcile_test.go
@@ -12,6 +12,7 @@ import (
"strconv"
"strings"
"sync"
+ "sync/atomic"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
@@ -263,7 +264,7 @@ func TestReconcileNode_AdoptsCompatibleOriginInboundWithoutRemoteMutation(t *tes
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "msg": "", "obj": obj})
}
mux := http.NewServeMux()
- mux.HandleFunc("/panel/api/inbounds/list", func(w http.ResponseWriter, _ *http.Request) {
+ mux.HandleFunc("/panel/api/inbounds/catalog", func(w http.ResponseWriter, _ *http.Request) {
writeOK(w, []map[string]any{{"id": 41, "tag": "already-deployed", "listen": "", "port": 8443, "protocol": "vless"}})
})
mux.HandleFunc("/panel/api/inbounds/", func(w http.ResponseWriter, _ *http.Request) {
@@ -301,6 +302,45 @@ func TestReconcileNode_AdoptsCompatibleOriginInboundWithoutRemoteMutation(t *tes
}
}
+func TestReconcileNodeUsesOneCatalogForUpdatesCreatesAndDeletes(t *testing.T) {
+ setupConflictDB(t)
+ var reads, fullLists, adds, updates, deletes atomic.Int32
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch req.URL.Path {
+ case "/panel/api/inbounds/catalog", "/panel/api/inbounds/list":
+ if req.URL.Path == "/panel/api/inbounds/catalog" {
+ reads.Add(1)
+ } else {
+ fullLists.Add(1)
+ }
+ fmt.Fprint(w, `{"success":true,"obj":[{"id":7,"tag":"existing"},{"id":6,"tag":"removed"}]}`)
+ case "/panel/api/inbounds/add":
+ adds.Add(1)
+ fmt.Fprint(w, `{"success":true}`)
+ case "/panel/api/inbounds/update/7":
+ updates.Add(1)
+ fmt.Fprint(w, `{"success":true}`)
+ case "/panel/api/inbounds/del/6":
+ deletes.Add(1)
+ fmt.Fprint(w, `{"success":true}`)
+ default:
+ http.NotFound(w, req)
+ }
+ }))
+ t.Cleanup(ts.Close)
+ node := reconcileTestNode(t, ts, "catalog-node", "all", nil)
+ for i, tag := range []string{"existing", "missing-a", "missing-b"} {
+ seedInboundConflictNode(t, tag, "", 12000+i, model.VLESS, `{"network":"tcp"}`, `{"clients":[]}`, &node.Id)
+ }
+ svc := InboundService{}
+ if err := svc.ReconcileNode(context.Background(), runtime.NewRemote(node, nil), node); err != nil {
+ t.Fatal(err)
+ }
+ if reads.Load() != 1 || fullLists.Load() != 0 || adds.Load() != 2 || updates.Load() != 1 || deletes.Load() != 1 {
+ t.Fatalf("catalog=%d full list=%d adds=%d updates=%d deletes=%d", reads.Load(), fullLists.Load(), adds.Load(), updates.Load(), deletes.Load())
+ }
+}
+
func TestReconcileNode_AmbiguousCompatibleInboundsAreNotSwept(t *testing.T) {
setupConflictDB(t)
diff --git a/internal/web/service/inbound_online_availability_test.go b/internal/web/service/inbound_online_availability_test.go
new file mode 100644
index 000000000..5ac8be17c
--- /dev/null
+++ b/internal/web/service/inbound_online_availability_test.go
@@ -0,0 +1,86 @@
+package service
+
+import (
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/xray"
+)
+
+func TestInboundOnlineAvailabilityDistinguishesEmptyFromMissing(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("online_availability")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ setupConflictDB(t)
+ process := useOnlineTestProcess(t)
+ svc := &InboundService{}
+ guid := svc.panelGuid()
+ if guid == "" {
+ t.Fatal("test panel has no GUID")
+ }
+
+ process.RefreshLocalOnline(nil, nil, time.Now().UnixMilli(), onlineGracePeriodMs)
+ if _, ok := svc.GetActiveInboundsByGuid()[guid]; ok {
+ t.Fatal("pruning before a local poll must not publish a known-empty result")
+ }
+ process = xray.NewTestProcess(nil, "")
+ xrayState.replace(process)
+ svc.RefreshLocalOnlineClients([]string{}, []string{})
+ if _, ok := svc.GetActiveInboundsByGuid()[guid]; ok {
+ t.Fatal("an idle sidecar tick must not publish activity on a replacement core")
+ }
+ process.RecordXrayOnlineSample(nil, nil, time.Now().UnixMilli(), onlineGracePeriodMs)
+ assertEmpty := func(signal map[string][]string, key string) {
+ t.Helper()
+ values, ok := signal[key]
+ if !ok || values == nil || len(values) != 0 {
+ t.Fatalf("expected an explicit empty list for %v in %v", key, signal)
+ }
+ }
+ assertEmpty(svc.GetOnlineClientsByGuid(), guid)
+ assertEmpty(svc.GetActiveInboundsByGuid(), guid)
+
+ // A recently observed sidecar remains attributable while the Xray sample
+ // is stale. The reserved tag marks this as a partial report.
+ now := time.Now().UnixMilli()
+ process.RecordXrayOnlineSample([]string{"xray@example"}, []string{"xray"}, now-onlineGracePeriodMs, onlineGracePeriodMs)
+ svc.RefreshLocalOnlineClients([]string{"sidecar@example"}, []string{"sidecar"})
+ if got := svc.GetOnlineClientsByGuid()[guid]; !slices.Equal(got, []string{"sidecar@example"}) {
+ t.Fatalf("partial report lost the sidecar or retained expired Xray clients: %v", got)
+ }
+ tags := svc.GetActiveInboundsByGuid()[guid]
+ if len(tags) != 2 || !slices.Contains(tags, "sidecar") || !slices.Contains(tags, xray.PartialInboundActivityTag) {
+ t.Fatalf("want only the sidecar tag and the partial report marker, got %v", tags)
+ }
+ if got := svc.GetOnlineClients(); !slices.Equal(got, []string{"sidecar@example"}) {
+ t.Fatalf("combined online list lost sidecar activity: %v", got)
+ }
+ process.RefreshLocalOnline(nil, nil, now+onlineGracePeriodMs+1000, onlineGracePeriodMs)
+ if _, ok := svc.GetActiveInboundsByGuid()[guid]; ok {
+ t.Fatal("expired sidecar observations must not keep the partial report")
+ }
+
+ xrayState.replace(xray.NewTestProcess(nil, ""))
+ if _, ok := svc.GetOnlineClientsByGuid()[guid]; ok {
+ t.Fatal("replacement core has not reported online clients yet")
+ }
+ if _, ok := svc.GetActiveInboundsByGuid()[guid]; ok {
+ t.Fatal("replacement core has not reported active inbounds yet")
+ }
+
+ svc.SetNodeOnlineTree(5, map[string][]string{"remote": {}})
+ currentXrayProcess().SetNodeActiveInboundTree(5, map[string][]string{"remote": {}})
+ assertEmpty(svc.GetOnlineClientsByGuid(), "remote")
+ assertEmpty(svc.GetActiveInboundsByGuid(), "remote")
+ svc.ClearNodeOnlineClients(5)
+ if _, ok := svc.GetOnlineClientsByGuid()["remote"]; ok {
+ t.Fatal("remote timeout must remove the stale online result")
+ }
+ if _, ok := svc.GetActiveInboundsByGuid()["remote"]; ok {
+ t.Fatal("remote timeout must remove the stale active-inbound result")
+ }
+}
diff --git a/internal/web/service/inbound_slim_cache.go b/internal/web/service/inbound_slim_cache.go
new file mode 100644
index 000000000..f7cab861f
--- /dev/null
+++ b/internal/web/service/inbound_slim_cache.go
@@ -0,0 +1,120 @@
+package service
+
+import (
+ "container/list"
+ "sync"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+const (
+ slimSettingsMaxEntries = 2048
+ slimSettingsMaxBytes = 32 << 20
+)
+
+type slimSettingsKey struct {
+ db *gorm.DB
+ id int
+ revision string
+}
+
+type slimSettingsEntry struct {
+ key slimSettingsKey
+ settings string
+}
+
+var slimSettingsCache = struct {
+ sync.Mutex
+ recency list.List
+ entries map[slimSettingsKey]*list.Element
+ bytes int
+}{entries: make(map[slimSettingsKey]*list.Element)}
+
+func cachedSlimSettings(key slimSettingsKey) (string, bool) {
+ if key.revision == "" {
+ return "", false
+ }
+ c := &slimSettingsCache
+ c.Lock()
+ defer c.Unlock()
+ entry := c.entries[key]
+ if entry == nil {
+ return "", false
+ }
+ c.recency.MoveToFront(entry)
+ return entry.Value.(slimSettingsEntry).settings, true
+}
+
+func rememberSlimSettings(key slimSettingsKey, settings string) {
+ if key.revision == "" || len(settings) > slimSettingsMaxBytes {
+ return
+ }
+ c := &slimSettingsCache
+ c.Lock()
+ defer c.Unlock()
+ if entry := c.entries[key]; entry != nil {
+ c.recency.MoveToFront(entry)
+ return
+ }
+ c.entries[key] = c.recency.PushFront(slimSettingsEntry{key, settings})
+ c.bytes += len(settings)
+ for len(c.entries) > slimSettingsMaxEntries || c.bytes > slimSettingsMaxBytes {
+ oldest := c.recency.Back()
+ entry := c.recency.Remove(oldest).(slimSettingsEntry)
+ delete(c.entries, entry.key)
+ c.bytes -= len(entry.settings)
+ }
+}
+
+// Structural revision triggers invalidate settings projections even for direct SQL edits.
+// Counters and other row metadata are still read fresh on every request.
+func loadSlimInboundRows(db *gorm.DB, userID int) ([]*model.Inbound, error) {
+ var rows []*model.Inbound
+ userRows := db.Model(&model.Inbound{}).Where("user_id = ?", userID)
+ if err := userRows.Session(&gorm.Session{}).Omit("Settings").Order("id ASC").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+
+ var missing []int
+ for _, row := range rows {
+ settings, ok := cachedSlimSettings(slimSettingsKey{db, row.Id, row.SnapshotRevision})
+ if ok {
+ row.Settings = settings
+ } else {
+ missing = append(missing, row.Id)
+ }
+ }
+ if len(missing) == 0 {
+ return rows, nil
+ }
+
+ resolved := make(map[int]*model.Inbound, len(missing))
+ for _, ids := range chunkInts(missing, sqlInChunk) {
+ var full []*model.Inbound
+ if err := userRows.Session(&gorm.Session{}).Where("id IN ?", ids).Find(&full).Error; err != nil {
+ return nil, err
+ }
+ for _, row := range full {
+ row.Settings = slimSettingsClients(row.Settings)
+ rememberSlimSettings(slimSettingsKey{db, row.Id, row.SnapshotRevision}, row.Settings)
+ resolved[row.Id] = row
+ }
+ }
+
+ // A miss is replaced with the whole row from its later read, so its metadata
+ // and projection share a revision. Exclude rows removed between the reads.
+ next := rows[:0]
+ miss := 0
+ for _, row := range rows {
+ if miss < len(missing) && row.Id == missing[miss] {
+ miss++
+ row = resolved[row.Id]
+ }
+ if row != nil {
+ next = append(next, row)
+ }
+ }
+ return next, nil
+}
diff --git a/internal/web/service/inbound_slim_cache_benchmark_test.go b/internal/web/service/inbound_slim_cache_benchmark_test.go
new file mode 100644
index 000000000..6ac72119e
--- /dev/null
+++ b/internal/web/service/inbound_slim_cache_benchmark_test.go
@@ -0,0 +1,132 @@
+package service
+
+import (
+ "encoding/json"
+ "fmt"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+)
+
+// BenchmarkSlimInboundList compares the list service and its JSON encoding,
+// with dedicated SQL timing for the inbound queries.
+func BenchmarkSlimInboundList(b *testing.B) {
+ cleanup, err := testpg.IsolatePackage("slim_settings_bench")
+ if err != nil {
+ b.Fatal(err)
+ }
+ b.Cleanup(cleanup)
+ setupBulkDB(b)
+ db := database.GetDB()
+ svc := new(InboundService)
+ var sqlStart time.Time
+ var sqlElapsed time.Duration
+ if err := db.Callback().Query().Before("gorm:query").Register("bench:inboundStart", func(tx *gorm.DB) {
+ if tx.Statement.Table == "inbounds" {
+ sqlStart = time.Now()
+ }
+ }); err != nil {
+ b.Fatal(err)
+ }
+ if err := db.Callback().Query().After("gorm:query").Register("bench:inboundElapsed", func(tx *gorm.DB) {
+ if tx.Statement.Table == "inbounds" {
+ sqlElapsed += time.Since(sqlStart)
+ }
+ }); err != nil {
+ b.Fatal(err)
+ }
+
+ for _, count := range []int{1000, 10000, 20000} {
+ for _, shared := range []bool{false, true} {
+ userID := count * 2
+ if shared {
+ userID++
+ }
+ settingsBytes := 0
+ for inbound := range 2 {
+ clients := make([]map[string]any, count)
+ for i := range clients {
+ emailIndex := i
+ if !shared {
+ emailIndex += inbound * count
+ }
+ clients[i] = map[string]any{
+ "email": fmt.Sprintf("client-%d@example.test", emailIndex),
+ "enable": true, "comment": "fixture", "flow": "xtls-rprx-vision",
+ "id": strings.Repeat("a", 36), "subId": strings.Repeat("s", 16),
+ }
+ }
+ payload, err := json.Marshal(map[string]any{"clients": clients, "decryption": "none"})
+ if err != nil {
+ b.Fatal(err)
+ }
+ settingsBytes += len(payload)
+ row := &model.Inbound{UserId: userID, Port: 2096, Tag: fmt.Sprintf("bench-%d-%d", userID, inbound), Protocol: model.VLESS, Enable: true, Settings: string(payload)}
+ if err := db.Create(row).Error; err != nil {
+ b.Fatal(err)
+ }
+ }
+ baseline := func() ([]*model.Inbound, error) {
+ var rows []*model.Inbound
+ if err := db.Where("user_id = ?", userID).Order("id ASC").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ if err := attachClientStats(db, rows); err != nil {
+ return nil, err
+ }
+ svc.annotateFallbackParents(db, rows)
+ svc.annotateLocalOriginGuid(rows)
+ svc.backfillClientStats(db, rows)
+ svc.overlayInboundsClientStats(db, rows)
+ for _, row := range rows {
+ row.Settings = slimSettingsClients(row.Settings)
+ }
+ return rows, nil
+ }
+ if _, err := svc.GetInboundsSlim(userID); err != nil {
+ b.Fatal(err)
+ }
+ for _, variant := range []struct {
+ name string
+ read func() ([]*model.Inbound, error)
+ settingsBytes int
+ }{
+ {"full-read", baseline, settingsBytes},
+ {"warm-projection", func() ([]*model.Inbound, error) { return svc.GetInboundsSlim(userID) }, 0},
+ } {
+ b.Run(fmt.Sprintf("%d/shared=%t/%s", count, shared, variant.name), func(b *testing.B) {
+ var samples []time.Duration
+ var responseBytes int
+ sqlElapsed = 0
+ b.ReportAllocs()
+ for b.Loop() {
+ start := time.Now()
+ rows, err := variant.read()
+ if err != nil {
+ b.Fatal(err)
+ }
+ response, err := json.Marshal(rows)
+ if err != nil {
+ b.Fatal(err)
+ }
+ responseBytes = len(response)
+ samples = append(samples, time.Since(start))
+ }
+ slices.Sort(samples)
+ b.ReportMetric(float64(samples[(len(samples)-1)/2].Microseconds()), "p50-us")
+ b.ReportMetric(float64(samples[(len(samples)*95+99)/100-1].Microseconds()), "p95-us")
+ b.ReportMetric(float64(sqlElapsed.Microseconds())/float64(b.N), "inbound-sql-us/op")
+ b.ReportMetric(float64(variant.settingsBytes), "settings-SQL-B/op")
+ b.ReportMetric(float64(responseBytes), "response-B/op")
+ })
+ }
+ }
+ }
+}
diff --git a/internal/web/service/inbound_slim_cache_production_benchmark_test.go b/internal/web/service/inbound_slim_cache_production_benchmark_test.go
new file mode 100644
index 000000000..a44155cd4
--- /dev/null
+++ b/internal/web/service/inbound_slim_cache_production_benchmark_test.go
@@ -0,0 +1,267 @@
+package service
+
+import (
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/xray"
+)
+
+// seedSlimProductionFixture creates normalized records, shared memberships and
+// sibling-owned traffic, not merely embedded settings arrays.
+func seedSlimProductionFixture(b *testing.B, db *gorm.DB) (int, string, string) {
+ b.Helper()
+ const unique, memberships, inbounds = 7100, 115000, 30
+ clients := makeScaleClients(unique)
+ records := make([]*model.ClientRecord, unique)
+ owners := make([]int, unique)
+ expiry := time.Now().AddDate(1, 0, 0).UnixMilli()
+ for i := range clients {
+ clients[i].Comment = fmt.Sprintf("fixture-plan-%04d", i%1000)
+ clients[i].TotalGB = 100 << 30
+ clients[i].ExpiryTime = expiry
+ clients[i].Enable = i%17 != 0
+ records[i] = clients[i].ToRecord()
+ }
+ var firstID int
+ var firstSettings, changedSettings string
+ err := db.Transaction(func(tx *gorm.DB) error {
+ if err := tx.CreateInBatches(records, 250).Error; err != nil {
+ return err
+ }
+ var nodes []model.Node
+ for i := range 4 {
+ nodes = append(nodes, model.Node{Name: fmt.Sprintf("fixture-node-%d", i), Address: "node.example.test", Port: 2053, Scheme: "https", Enable: true, Guid: fmt.Sprintf("fixture-guid-%d", i)})
+ }
+ if err := tx.Create(&nodes).Error; err != nil {
+ return err
+ }
+ offset := 0
+ for i := range inbounds {
+ count := memberships / inbounds
+ if i < memberships%inbounds {
+ count++
+ }
+ subset := make([]model.Client, count)
+ links := make([]model.ClientInbound, count)
+ for j := range count {
+ index := (offset + j) % unique
+ subset[j] = clients[index]
+ links[j].ClientId = records[index].Id
+ }
+ row := model.Inbound{UserId: 1, Port: 41000 + i, Tag: fmt.Sprintf("slim-prod-%d", i), Protocol: model.VLESS, Enable: true, Settings: clientsSettings(b, subset)}
+ if i >= 14 {
+ row.NodeID = &nodes[(i-14)%len(nodes)].Id
+ row.OriginNodeGuid = nodes[(i-14)%len(nodes)].Guid
+ }
+ if err := tx.Create(&row).Error; err != nil {
+ return err
+ }
+ for j := range links {
+ index := (offset + j) % unique
+ links[j].InboundId = row.Id
+ if owners[index] == 0 {
+ owners[index] = row.Id
+ }
+ }
+ if err := tx.CreateInBatches(links, 1000).Error; err != nil {
+ return err
+ }
+ if i == 0 {
+ firstID, firstSettings = row.Id, row.Settings
+ changedSettings = strings.Replace(firstSettings, "fixture-plan-0000", "changed-plan-0000", 1)
+ }
+ offset += count
+ }
+ traffic := make([]xray.ClientTraffic, unique)
+ globals := make([]model.ClientGlobalTraffic, 0, unique/10)
+ for i, client := range clients {
+ traffic[i] = xray.ClientTraffic{InboundId: owners[i], Email: client.Email, Enable: client.Enable, Up: int64(i) * 1024, Down: int64(i) * 2048, Total: client.TotalGB, ExpiryTime: client.ExpiryTime}
+ if i%10 == 0 {
+ globals = append(globals, model.ClientGlobalTraffic{MasterGuid: "fixture-master", Email: client.Email, Up: int64(i) * 4096, Down: int64(i) * 8192, UpdatedAt: time.Now().UnixMilli()})
+ }
+ }
+ if err := tx.CreateInBatches(traffic, 500).Error; err != nil {
+ return err
+ }
+ return tx.CreateInBatches(globals, 500).Error
+ })
+ if err != nil {
+ b.Fatal(err)
+ }
+ for _, item := range []struct {
+ table string
+ want int64
+ }{{"inbounds", inbounds}, {"clients", unique}, {"client_inbounds", memberships}, {"client_traffics", unique}} {
+ var count int64
+ if err := db.Table(item.table).Count(&count).Error; err != nil || count != item.want {
+ b.Fatalf("%s: count=%d want=%d err=%v", item.table, count, item.want, err)
+ }
+ }
+ var rawBytes int64
+ if err := db.Raw("SELECT SUM(LENGTH(settings)) FROM inbounds WHERE user_id = 1").Scan(&rawBytes).Error; err != nil {
+ b.Fatal(err)
+ }
+ if firstSettings == changedSettings {
+ b.Fatal("churn fixture did not change settings")
+ }
+ if err := db.Exec("ANALYZE").Error; err != nil {
+ b.Fatal(err)
+ }
+ b.Logf("fixture: %d inbounds, %d clients, %d memberships, %d traffic rows, %d raw settings bytes", inbounds, unique, memberships, unique, rawBytes)
+ return firstID, firstSettings, changedSettings
+}
+
+// BenchmarkSlimInboundListProduction measures the service and JSON encoding,
+// including cold reads and a single concurrent structural write per churn sample.
+func BenchmarkSlimInboundListProduction(b *testing.B) {
+ cleanup, err := testpg.IsolatePackage("slim_production")
+ if err != nil {
+ b.Fatal(err)
+ }
+ b.Cleanup(cleanup)
+ setupScaleDB(b)
+ db := database.GetDB()
+ id, original, changed := seedSlimProductionFixture(b, db)
+ svc := new(InboundService)
+ baseline := func() ([]*model.Inbound, error) {
+ var rows []*model.Inbound
+ if err := db.Where("user_id = ?", 1).Order("id ASC").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ if err := attachClientStats(db, rows); err != nil {
+ return nil, err
+ }
+ svc.annotateFallbackParents(db, rows)
+ svc.annotateLocalOriginGuid(rows)
+ svc.backfillClientStats(db, rows)
+ svc.overlayInboundsClientStats(db, rows)
+ for _, row := range rows {
+ row.Settings = slimSettingsClients(row.Settings)
+ }
+ return rows, nil
+ }
+ projected := func() ([]*model.Inbound, error) { return svc.GetInboundsSlim(1) }
+ read := func(fn func() ([]*model.Inbound, error)) []byte {
+ rows, err := fn()
+ if err != nil {
+ b.Fatal(err)
+ }
+ payload, err := json.Marshal(rows)
+ if err != nil {
+ b.Fatal(err)
+ }
+ return payload
+ }
+ if sha256.Sum256(read(baseline)) != sha256.Sum256(read(projected)) {
+ b.Fatal("production fixture full/slim response mismatch")
+ }
+ var sqlStart time.Time
+ var sqlElapsed time.Duration
+ var settingsBytes, queries int64
+ const before, after = "bench:slim-production-start", "bench:slim-production-end"
+ callbacks := db.Callback().Query()
+ if err := callbacks.Before("gorm:query").Register(before, func(tx *gorm.DB) {
+ if tx.Statement.Table == "inbounds" {
+ sqlStart = time.Now()
+ }
+ }); err != nil {
+ b.Fatal(err)
+ }
+ if err := callbacks.After("gorm:query").Register(after, func(tx *gorm.DB) {
+ if tx.Statement.Table != "inbounds" {
+ return
+ }
+ sqlElapsed += time.Since(sqlStart)
+ queries++
+ if rows, ok := tx.Statement.Dest.(*[]*model.Inbound); ok {
+ for _, row := range *rows {
+ settingsBytes += int64(len(row.Settings))
+ }
+ }
+ }); err != nil {
+ b.Fatal(err)
+ }
+ b.Cleanup(func() { _ = callbacks.Remove(before); _ = callbacks.Remove(after) })
+ clear := func() {
+ c := &slimSettingsCache
+ c.Lock()
+ defer c.Unlock()
+ for key, element := range c.entries {
+ if key.db == db {
+ c.bytes -= len(element.Value.(slimSettingsEntry).settings)
+ c.recency.Remove(element)
+ delete(c.entries, key)
+ }
+ }
+ }
+ for _, mode := range []string{"warm", "cold", "churn"} {
+ for _, variant := range []struct {
+ name string
+ fn func() ([]*model.Inbound, error)
+ }{{"main", baseline}, {"pr", projected}} {
+ b.Run(mode+"/"+variant.name, func(b *testing.B) {
+ if err := db.Model(&model.Inbound{}).Where("id = ?", id).Update("settings", original).Error; err != nil {
+ b.Fatal(err)
+ }
+ clear()
+ read(variant.fn)
+ var samples []time.Duration
+ var responseBytes int
+ sqlElapsed, settingsBytes, queries = 0, 0, 0
+ b.ReportAllocs()
+ for b.Loop() {
+ if mode == "cold" {
+ b.StopTimer()
+ clear()
+ b.StartTimer()
+ }
+ var done chan error
+ if mode == "churn" {
+ next := changed
+ if len(samples)%2 == 1 {
+ next = original
+ }
+ done = make(chan error, 1)
+ go func() {
+ done <- db.Model(&model.Inbound{}).Where("id = ?", id).Update("settings", next).Error
+ }()
+ }
+ start := time.Now()
+ rows, err := variant.fn()
+ if err != nil {
+ b.Fatal(err)
+ }
+ payload, err := json.Marshal(rows)
+ if err != nil {
+ b.Fatal(err)
+ }
+ responseBytes = len(payload)
+ samples = append(samples, time.Since(start))
+ if done != nil {
+ if err := <-done; err != nil {
+ b.Fatal(err)
+ }
+ }
+ }
+ slices.Sort(samples)
+ b.ReportMetric(float64(samples[(len(samples)-1)/2].Microseconds())/1000, "p50-ms")
+ b.ReportMetric(float64(samples[(len(samples)*95+99)/100-1].Microseconds())/1000, "p95-ms")
+ b.ReportMetric(float64(sqlElapsed.Microseconds())/float64(b.N)/1000, "inbound-sql-ms/op")
+ b.ReportMetric(float64(settingsBytes)/float64(b.N), "settings-SQL-B/op")
+ b.ReportMetric(float64(queries)/float64(b.N), "inbound-queries/op")
+ b.ReportMetric(float64(responseBytes), "response-B/op")
+ })
+ }
+ }
+}
diff --git a/internal/web/service/inbound_slim_cache_test.go b/internal/web/service/inbound_slim_cache_test.go
new file mode 100644
index 000000000..c74f7407a
--- /dev/null
+++ b/internal/web/service/inbound_slim_cache_test.go
@@ -0,0 +1,88 @@
+package service
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+
+ "gorm.io/gorm"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+)
+
+func TestSlimInboundListReusesOnlyTheMatchingSettingsRevision(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("slim_settings")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ setupBulkDB(t)
+ db := database.GetDB()
+ fixtures := []string{
+ "{\"clients\":[{\"email\":\"Shared@test\",\"enable\":true,\"comment\":\"keep\",\"id\":\"discard\"}],\"decryption\":\"none\"}",
+ "{\"clients\":[null,7,{\"email\":\"Shared@test\",\"enable\":false,\"comment\":\"\"}],\"method\":\"custom\"}",
+ "{broken",
+ "{\"clients\":[]}",
+ }
+ for i, settings := range fixtures {
+ if err := db.Create(&model.Inbound{UserId: 1, Port: 30000 + i, Tag: "slim-" + string(rune('a'+i)), Protocol: model.VLESS, Settings: settings, Enable: true}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ var queries []string
+ if err := db.Callback().Query().After("gorm:query").Register("test:slim_settings", func(tx *gorm.DB) {
+ if tx.Statement.Table == "inbounds" {
+ queries = append(queries, tx.Statement.SQL.String())
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ svc := new(InboundService)
+ check := func() []*model.Inbound {
+ t.Helper()
+ rows, err := svc.GetInboundsSlim(1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := make([]string, 0, len(rows))
+ want := make([]string, 0, len(fixtures))
+ for _, row := range rows {
+ got = append(got, row.Settings)
+ }
+ for _, raw := range fixtures {
+ want = append(want, slimSettingsClients(raw))
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("slim settings = %q, want %q", got, want)
+ }
+ return rows
+ }
+ first := check()
+ queries = nil
+ check()
+ if len(queries) != 1 || strings.Contains(queries[0], "SELECT *") || strings.Contains(queries[0], "\"settings\"") || strings.Contains(queries[0], string(rune(96))+"settings"+string(rune(96))) {
+ t.Fatalf("warm slim list still reads the full settings: %v", queries)
+ }
+ if err := db.Model(&model.Inbound{}).Where("id = ?", first[0].Id).Update("up", 19).Error; err != nil {
+ t.Fatal(err)
+ }
+ queries = nil
+ if got := check()[0].Up; got != 19 || len(queries) != 1 {
+ t.Fatalf("counter change should be visible without reloading settings: up=%d, queries=%v", got, queries)
+ }
+ fixtures[0] = "{\"clients\":[{\"email\":\"changed@test\",\"enable\":true}]}"
+ if err := db.Exec("UPDATE inbounds SET settings = ? WHERE id = ?", fixtures[0], first[0].Id).Error; err != nil {
+ t.Fatal(err)
+ }
+ queries = nil
+ check()
+ if len(queries) != 2 {
+ t.Fatalf("one changed inbound should add a single batched read, got %v", queries)
+ }
+ full, err := svc.GetInbound(first[0].Id)
+ if err != nil || full.Settings != fixtures[0] {
+ t.Fatalf("full inbound lost its settings: %v", err)
+ }
+}
diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go
index bc57a7114..cfe7cee67 100644
--- a/internal/web/service/inbound_traffic.go
+++ b/internal/web/service/inbound_traffic.go
@@ -40,7 +40,12 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b
// The periodic poll takes the background lane: an operator's save or reset
// queued while a poll runs must not sit behind the next merge batch.
err = submitTrafficWriteBackground(func() error {
- if err := database.GetDB().Transaction(account); err != nil {
+ if err := database.GetDB().Transaction(func(tx *gorm.DB) error {
+ if err := database.LockPostgresWriter(tx); err != nil {
+ return err
+ }
+ return account(tx)
+ }); err != nil {
return err
}
// safeApply can recover a panic during maintenance after accounting committed.
@@ -91,6 +96,9 @@ func (s *InboundService) maintainTrafficLocked() (bool, bool, []int, []trafficIn
)
batch := newTrafficMutationBatch()
err := database.GetDB().Transaction(func(tx *gorm.DB) error {
+ if err := database.LockPostgresWriter(tx); err != nil {
+ return err
+ }
needRestart0, count, err := s.autoRenewClients(tx, batch)
if err != nil {
return fmt.Errorf("renew clients: %w", err)
diff --git a/internal/web/service/node.go b/internal/web/service/node.go
index f24b6c618..3c3d7c045 100644
--- a/internal/web/service/node.go
+++ b/internal/web/service/node.go
@@ -43,6 +43,7 @@ type HeartbeatPatch struct {
MemPct float64
UptimeSecs uint64
UnavailableMetrics []string
+ Telemetry *model.NodeTelemetry
// NetUp/NetDown are the node's current interface throughput (bytes/sec),
// summed over non-virtual interfaces, read from its status response.
NetUp uint64
@@ -139,154 +140,6 @@ func (s *NodeService) ListOperational() ([]*model.Node, error) {
return nodes, nil
}
-func (s *NodeService) populateClientCounts(db *gorm.DB, nodes []*model.Node) {
- type clientCountRow struct {
- NodeID int `gorm:"column:node_id"`
- Count int `gorm:"column:count"`
- }
- var clientCounts []clientCountRow
- if err := db.Raw(`
- SELECT inbounds.node_id AS node_id, COUNT(DISTINCT client_inbounds.client_id) AS count
- FROM inbounds
- JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
- WHERE inbounds.node_id IS NOT NULL
- GROUP BY inbounds.node_id
- `).Scan(&clientCounts).Error; err == nil {
- for _, row := range clientCounts {
- for _, n := range nodes {
- if n.Id == row.NodeID {
- n.ClientCount = row.Count
- break
- }
- }
- }
- }
-}
-
-func (s *NodeService) enrichDashboardStats(db *gorm.DB, nodes []*model.Node) {
- // Set before the early returns: a node with nothing synced still has clients online.
- onlineTotals := (&InboundService{}).GetNodeOnlineTotals()
- for _, n := range nodes {
- n.OnlineTotalCount = onlineTotals[n.Id]
- }
- type inboundRow struct {
- Id int
- NodeID int `gorm:"column:node_id"`
- }
- var inboundRows []inboundRow
- if err := db.Table("inbounds").
- Select("id, node_id").
- Where("node_id IS NOT NULL").
- Scan(&inboundRows).Error; err != nil {
- return
- }
- if len(inboundRows) == 0 {
- return
- }
- inboundsByNode := make(map[int][]int, len(nodes))
- for _, row := range inboundRows {
- inboundsByNode[row.NodeID] = append(inboundsByNode[row.NodeID], row.Id)
- }
-
- s.populateClientCounts(db, nodes)
-
- depletedByNode := make(map[int]int)
- disabledByNode := make(map[int]int)
- activeByNode := make(map[int]int)
- statuses, _ := s.nodeClientStatuses()
- seen := make(map[int]map[int]struct{}, len(nodes))
- for _, st := range statuses {
- clientsSeen := seen[st.NodeID]
- if clientsSeen == nil {
- clientsSeen = make(map[int]struct{})
- seen[st.NodeID] = clientsSeen
- }
- if _, dup := clientsSeen[st.ClientID]; dup {
- // A client attached to several inbounds of one node counts once,
- // matching the distinct ClientCount above.
- continue
- }
- clientsSeen[st.ClientID] = struct{}{}
- switch {
- case st.Depleted:
- depletedByNode[st.NodeID]++
- case st.Disabled:
- disabledByNode[st.NodeID]++
- default:
- activeByNode[st.NodeID]++
- }
- }
- onlineByGuid := s.onlineEmailsByGuid()
- selfGuid, _ := (&SettingService{}).GetPanelGuid()
- ambiguous := ambiguousNodeGuids(nodes, selfGuid)
- for _, n := range nodes {
- n.InboundCount = len(inboundsByNode[n.Id])
- n.DepletedCount = depletedByNode[n.Id]
- n.DisabledCount = disabledByNode[n.Id]
- n.ActiveCount = activeByNode[n.Id]
- // Online is attributed to the node that physically hosts the client
- // (by GUID): a client on a sub-node counts under the sub-node, not
- // the intermediate node it syncs through (#4983).
- n.OnlineCount = len(onlineByGuid[effectiveNodeGuid(n, ambiguous)])
- }
-}
-
-// nodeClientStatus is one node-hosted client's classification, carrying enough
-// identity for callers to bucket it by node id or by attribution GUID.
-type nodeClientStatus struct {
- InboundID int
- NodeID int
- ClientID int
- Depleted bool
- Disabled bool
-}
-
-// nodeClientStatuses classifies every client attached to a node-hosted inbound as
-// depleted / disabled / active, matching client_traffics by EMAIL rather than by
-// inbound_id. client_traffics.inbound_id goes stale after an inbound is
-// delete+recreated, so filtering by it silently drops most rows; the
-// client_inbounds -> clients join is the reliable client set and the email join
-// pulls each client's live counters. Precedence matches the inbound page:
-// depleted (expired/exhausted) wins over disabled.
-func (s *NodeService) nodeClientStatuses() ([]nodeClientStatus, error) {
- type row struct {
- InboundID int `gorm:"column:inbound_id"`
- NodeID int `gorm:"column:node_id"`
- ClientID int `gorm:"column:client_id"`
- Enable bool `gorm:"column:enable"`
- Total int64 `gorm:"column:total"`
- Up int64 `gorm:"column:up"`
- Down int64 `gorm:"column:down"`
- ExpiryTime int64 `gorm:"column:expiry_time"`
- }
- var rows []row
- if err := database.GetDB().Table("inbounds").
- Select("inbounds.id AS inbound_id, inbounds.node_id AS node_id, clients.id AS client_id, " +
- "clients.enable AS enable, ct.total AS total, ct.up AS up, ct.down AS down, ct.expiry_time AS expiry_time").
- Joins("JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id").
- Joins("JOIN clients ON clients.id = client_inbounds.client_id").
- Joins("LEFT JOIN client_traffics ct ON ct.email = clients.email").
- Where("inbounds.node_id IS NOT NULL").
- Scan(&rows).Error; err != nil {
- return nil, err
- }
- now := time.Now().UnixMilli()
- out := make([]nodeClientStatus, 0, len(rows))
- for _, r := range rows {
- st := nodeClientStatus{InboundID: r.InboundID, NodeID: r.NodeID, ClientID: r.ClientID}
- expired := r.ExpiryTime > 0 && r.ExpiryTime <= now
- exhausted := r.Total > 0 && r.Up+r.Down >= r.Total
- switch {
- case expired || exhausted:
- st.Depleted = true
- case !r.Enable:
- st.Disabled = true
- }
- out = append(out, st)
- }
- return out, nil
-}
-
func (s *NodeService) onlineEmailsByGuid() map[string]map[string]struct{} {
svc := InboundService{}
byGuid := svc.GetOnlineClientsByGuid()
@@ -997,8 +850,13 @@ func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
if err != nil {
return err
}
+ telemetry, err := json.Marshal(p.Telemetry)
+ if err != nil {
+ return err
+ }
updates := map[string]any{
"unavailable_metrics": string(unavailable),
+ "telemetry": string(telemetry),
"status": p.Status,
"last_heartbeat": p.LastHeartbeat,
"latency_ms": p.LatencyMs,
@@ -1024,7 +882,7 @@ func (s *NodeService) UpdateHeartbeat(id int, p HeartbeatPatch) error {
}
if p.Status == "online" {
now := time.Unix(p.LastHeartbeat, 0)
- if !slices.Contains(p.UnavailableMetrics, "cpu") {
+ if !slices.Contains(p.UnavailableMetrics, "cpu") && (p.Telemetry == nil || p.Telemetry.CpuPct != nil) {
nodeMetrics.append(nodeMetricKey(id, "cpu"), now, p.CpuPct)
}
nodeMetrics.append(nodeMetricKey(id, "mem"), now, p.MemPct)
@@ -1366,21 +1224,14 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
Success bool `json:"success"`
Msg string `json:"msg"`
Obj *struct {
- CpuPct float64 `json:"cpu"`
- UnavailableMetrics []string `json:"unavailableMetrics"`
- Mem struct {
- Current uint64 `json:"current"`
- Total uint64 `json:"total"`
- } `json:"mem"`
+ nodeStatusMetrics
Xray struct {
Version string `json:"version"`
State string `json:"state"`
ErrorMsg string `json:"errorMsg"`
} `json:"xray"`
- PanelVersion string `json:"panelVersion"`
- PanelGuid string `json:"panelGuid"`
- Uptime uint64 `json:"uptime"`
- NetIO json.RawMessage `json:"netIO"`
+ PanelVersion string `json:"panelVersion"`
+ PanelGuid string `json:"panelGuid"`
} `json:"obj"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxProbeBodyBytes)).Decode(&envelope); err != nil {
@@ -1398,10 +1249,14 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
return patch, errors.New(patch.LastError)
}
o := envelope.Obj
- patch.CpuPct = o.CpuPct
patch.UnavailableMetrics = o.UnavailableMetrics
- if o.Mem.Total > 0 {
- patch.MemPct = float64(o.Mem.Current) * 100.0 / float64(o.Mem.Total)
+ sample := o.telemetry(time.Now())
+ patch.Telemetry = sample
+ if sample.CpuPct != nil {
+ patch.CpuPct = *sample.CpuPct
+ }
+ if sample.MemTotalBytes != nil && sample.MemUsedBytes != nil {
+ patch.MemPct = float64(*sample.MemUsedBytes) * 100 / float64(*sample.MemTotalBytes)
}
patch.XrayVersion = o.Xray.Version
patch.XrayState = o.Xray.State
@@ -1412,16 +1267,15 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
return patch, errors.New(patch.LastError)
}
patch.Guid = o.PanelGuid
- patch.UptimeSecs = o.Uptime
- var network map[string]json.RawMessage
- _ = json.Unmarshal(o.NetIO, &network)
+ if sample.UptimeSecs != nil {
+ patch.UptimeSecs = *sample.UptimeSecs
+ }
for _, metric := range []struct {
- key, direction string
- value *uint64
- }{{"netUp", "up", &patch.NetUp}, {"netDown", "down", &patch.NetDown}} {
- var value *uint64
- if json.Unmarshal(network[metric.direction], &value) == nil && value != nil {
- *metric.value = *value
+ key string
+ value, measured *uint64
+ }{{"netUp", &patch.NetUp, sample.NetUp}, {"netDown", &patch.NetDown, sample.NetDown}} {
+ if metric.measured != nil {
+ *metric.value = *metric.measured
} else if !slices.Contains(patch.UnavailableMetrics, metric.key) {
patch.UnavailableMetrics = append(patch.UnavailableMetrics, metric.key)
}
diff --git a/internal/web/service/node_contract.go b/internal/web/service/node_contract.go
index 979b6f67d..763a82d25 100644
--- a/internal/web/service/node_contract.go
+++ b/internal/web/service/node_contract.go
@@ -2,6 +2,7 @@ package service
import (
"strings"
+ "time"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
@@ -10,50 +11,51 @@ import (
// NodeView is the browser/API read contract for nodes. Credentials are
// write-only: responses expose only whether a node has a token configured.
type NodeView struct {
- Id int `json:"id" example:"1"`
- Name string `json:"name" example:"edge-1"`
- Remark string `json:"remark" example:"Primary edge"`
- Scheme string `json:"scheme" example:"https"`
- Address string `json:"address" example:"node.example.com"`
- Port int `json:"port" example:"2053"`
- BasePath string `json:"basePath" example:"/"`
- HasApiToken bool `json:"hasApiToken" example:"true"`
- Enable bool `json:"enable" example:"true"`
- AllowPrivateAddress bool `json:"allowPrivateAddress" example:"false"`
- TlsVerifyMode string `json:"tlsVerifyMode" example:"verify"`
- PinnedCertSha256 string `json:"pinnedCertSha256" example:""`
- InboundSyncMode string `json:"inboundSyncMode" example:"all"`
- InboundTags []string `json:"inboundTags" example:"[\"in-443-tcp\"]"`
- OutboundTag string `json:"outboundTag" example:"direct"`
- Guid string `json:"guid" example:"node-guid"`
- Status string `json:"status" example:"online"`
- LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"`
- HeartbeatAgeMillis *int64 `json:"heartbeatAgeMillis,omitempty" example:"1250"`
- LatencyMs int `json:"latencyMs" example:"42"`
- XrayVersion string `json:"xrayVersion" example:"25.10.31"`
- PanelVersion string `json:"panelVersion" example:"v3.x.x"`
- CpuPct float64 `json:"cpuPct" example:"12.5"`
- MemPct float64 `json:"memPct" example:"45.2"`
- UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
- UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
- NetUp uint64 `json:"netUp" example:"2097152"`
- NetDown uint64 `json:"netDown" example:"1048576"`
- LastError string `json:"lastError" example:""`
- XrayState string `json:"xrayState" example:"running"`
- XrayError string `json:"xrayError" example:""`
- ConfigDirty bool `json:"configDirty" example:"false"`
- ConfigDirtyAt int64 `json:"configDirtyAt" example:"0"`
- InboundCount int `json:"inboundCount" example:"3"`
- ClientCount int `json:"clientCount" example:"25"`
- OnlineCount int `json:"onlineCount" example:"5"`
- OnlineTotalCount int `json:"onlineTotalCount" example:"9"`
- ActiveCount int `json:"activeCount" example:"20"`
- DisabledCount int `json:"disabledCount" example:"2"`
- DepletedCount int `json:"depletedCount" example:"1"`
- ParentGuid string `json:"parentGuid,omitempty" example:""`
- Transitive bool `json:"transitive,omitempty" example:"false"`
- CreatedAt int64 `json:"createdAt" example:"1700000000"`
- UpdatedAt int64 `json:"updatedAt" example:"1700003600"`
+ Id int `json:"id" example:"1"`
+ Name string `json:"name" example:"edge-1"`
+ Remark string `json:"remark" example:"Primary edge"`
+ Scheme string `json:"scheme" example:"https"`
+ Address string `json:"address" example:"node.example.com"`
+ Port int `json:"port" example:"2053"`
+ BasePath string `json:"basePath" example:"/"`
+ HasApiToken bool `json:"hasApiToken" example:"true"`
+ Enable bool `json:"enable" example:"true"`
+ AllowPrivateAddress bool `json:"allowPrivateAddress" example:"false"`
+ TlsVerifyMode string `json:"tlsVerifyMode" example:"verify"`
+ PinnedCertSha256 string `json:"pinnedCertSha256" example:""`
+ InboundSyncMode string `json:"inboundSyncMode" example:"all"`
+ InboundTags []string `json:"inboundTags" example:"[\"in-443-tcp\"]"`
+ OutboundTag string `json:"outboundTag" example:"direct"`
+ Guid string `json:"guid" example:"node-guid"`
+ Status string `json:"status" example:"online"`
+ LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"`
+ HeartbeatAgeMillis *int64 `json:"heartbeatAgeMillis,omitempty" example:"1250"`
+ LatencyMs int `json:"latencyMs" example:"42"`
+ XrayVersion string `json:"xrayVersion" example:"25.10.31"`
+ PanelVersion string `json:"panelVersion" example:"v3.x.x"`
+ CpuPct float64 `json:"cpuPct" example:"12.5"`
+ MemPct float64 `json:"memPct" example:"45.2"`
+ UptimeSecs uint64 `json:"uptimeSecs" example:"86400"`
+ UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
+ Telemetry *model.NodeTelemetry `json:"telemetry,omitempty"`
+ NetUp uint64 `json:"netUp" example:"2097152"`
+ NetDown uint64 `json:"netDown" example:"1048576"`
+ LastError string `json:"lastError" example:""`
+ XrayState string `json:"xrayState" example:"running"`
+ XrayError string `json:"xrayError" example:""`
+ ConfigDirty bool `json:"configDirty" example:"false"`
+ ConfigDirtyAt int64 `json:"configDirtyAt" example:"0"`
+ InboundCount int `json:"inboundCount" example:"3"`
+ ClientCount int `json:"clientCount" example:"25"`
+ OnlineCount int `json:"onlineCount" example:"5"`
+ OnlineTotalCount int `json:"onlineTotalCount" example:"9"`
+ ActiveCount int `json:"activeCount" example:"20"`
+ DisabledCount int `json:"disabledCount" example:"2"`
+ DepletedCount int `json:"depletedCount" example:"1"`
+ ParentGuid string `json:"parentGuid,omitempty" example:""`
+ Transitive bool `json:"transitive,omitempty" example:"false"`
+ CreatedAt int64 `json:"createdAt" example:"1700000000"`
+ UpdatedAt int64 `json:"updatedAt" example:"1700003600"`
}
func toNodeView(n *model.Node) *NodeView {
@@ -86,6 +88,7 @@ func toNodeView(n *model.Node) *NodeView {
MemPct: n.MemPct,
UptimeSecs: n.UptimeSecs,
UnavailableMetrics: n.UnavailableMetrics,
+ Telemetry: liveNodeTelemetry(n, time.Now()),
NetUp: n.NetUp,
NetDown: n.NetDown,
LastError: n.LastError,
diff --git a/internal/web/service/node_fleet.go b/internal/web/service/node_fleet.go
new file mode 100644
index 000000000..68eba94ba
--- /dev/null
+++ b/internal/web/service/node_fleet.go
@@ -0,0 +1,162 @@
+package service
+
+import (
+ "encoding/json"
+ "slices"
+ "time"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+type NodeFleetCounts struct {
+ InboundCount int `json:"inboundCount" example:"8"`
+ ClientCount int `json:"clientCount" example:"100"`
+ ActiveCount int `json:"activeCount" example:"90"`
+ DisabledCount int `json:"disabledCount" example:"8"`
+ DepletedCount int `json:"depletedCount" example:"2"`
+ OnlineCount int `json:"onlineCount" example:"20"`
+}
+
+type NodeMasterView struct {
+ Counts NodeFleetCounts `json:"counts"`
+ Telemetry *model.NodeTelemetry `json:"telemetry,omitempty"`
+ XrayVersion string `json:"xrayVersion,omitempty" example:"26.1.1"`
+ PanelVersion string `json:"panelVersion,omitempty" example:"v3.12.0"`
+ XrayState string `json:"xrayState,omitempty" example:"running"`
+ XrayError string `json:"xrayError,omitempty"`
+}
+
+type NodeOverview struct {
+ Nodes []*NodeView `json:"nodes"`
+ Master NodeMasterView `json:"master"`
+ Fleet NodeFleetCounts `json:"fleet"`
+}
+
+func (s *NodeService) GetNodeOverview(local *Status) (*NodeOverview, error) {
+ nodes, master, fleet, err := s.getNodeTreeWithCounts(true)
+ if err != nil {
+ return nil, err
+ }
+ overview := &NodeOverview{Nodes: nodeTreeViews(nodes), Master: NodeMasterView{Counts: master}, Fleet: fleet}
+ if len(nodes) > 0 && local != nil {
+ overview.Master.XrayVersion = local.Xray.Version
+ overview.Master.PanelVersion = local.PanelVersion
+ overview.Master.XrayState = string(local.Xray.State)
+ overview.Master.XrayError = local.Xray.ErrorMsg
+ // Use the same typed projection and availability checks as remote heartbeats.
+ if payload, err := json.Marshal(local); err == nil {
+ var metrics nodeStatusMetrics
+ if json.Unmarshal(payload, &metrics) == nil && !local.T.IsZero() {
+ overview.Master.Telemetry = liveNodeTelemetry(&model.Node{
+ Enable: true, Status: "online", Telemetry: metrics.telemetry(local.T),
+ }, time.Now())
+ }
+ }
+ }
+ return overview, nil
+}
+
+type nodeFleetStatsRow struct {
+ Fleet int
+ Host string
+ NodeFleetCounts
+}
+
+func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string, overview bool) (NodeFleetCounts, NodeFleetCounts, error) {
+ ambiguous := ambiguousNodeGuids(nodes, selfGUID)
+ // Always reserve the local GUID, including when an old topology advertises a loop.
+ ambiguous[selfGUID] = struct{}{}
+ ambiguous[""] = struct{}{}
+ ambiguousGUIDs := make([]string, 0, len(ambiguous))
+ for guid := range ambiguous {
+ ambiguousGUIDs = append(ambiguousGUIDs, guid)
+ }
+ slices.Sort(ambiguousGUIDs)
+ fleetClients, fleetInbounds := "", ""
+ if overview {
+ fleetClients = "UNION ALL SELECT 1, '', id FROM clients"
+ fleetInbounds = "UNION ALL SELECT 1, '', COUNT(*) FROM hosted"
+ }
+ var rows []nodeFleetStatsRow
+ err := database.GetDB().Raw(`
+ WITH hosted AS (
+ SELECT i.id, CASE
+ WHEN i.node_id IS NULL THEN ''
+ WHEN COALESCE(i.origin_node_guid, '') NOT IN ? THEN i.origin_node_guid
+ WHEN COALESCE(i.origin_node_guid, '') = '' AND COALESCE(n.guid, '') NOT IN ? THEN n.guid
+ ELSE 'node:' || CAST(i.node_id AS TEXT)
+ END AS host
+ FROM inbounds i LEFT JOIN nodes n ON n.id = i.node_id
+ WHERE (? OR i.node_id IS NOT NULL)
+ ), memberships AS (
+ SELECT DISTINCT hosted.host, ci.client_id
+ FROM hosted JOIN client_inbounds ci ON ci.inbound_id = hosted.id
+ ), scoped AS (
+ SELECT 0 AS fleet, host, client_id FROM memberships
+ `+fleetClients+`
+ ), classified AS (
+ SELECT s.fleet, s.host, CASE
+ WHEN (ct.expiry_time > 0 AND ct.expiry_time <= ?)
+ OR (ct.total > 0 AND ct.up + ct.down >= ct.total) THEN 'depleted'
+ WHEN COALESCE(c.enable, FALSE) = FALSE THEN 'disabled'
+ ELSE 'active' END AS state
+ FROM scoped s JOIN clients c ON c.id = s.client_id
+ LEFT JOIN client_traffics ct ON ct.email = c.email
+ ), clients_by_host AS (
+ SELECT fleet, host, COUNT(*) AS client_count,
+ COUNT(*) FILTER (WHERE state = 'active') AS active_count,
+ COUNT(*) FILTER (WHERE state = 'disabled') AS disabled_count,
+ COUNT(*) FILTER (WHERE state = 'depleted') AS depleted_count
+ FROM classified GROUP BY fleet, host
+ ), inbound_counts AS (
+ SELECT 0 AS fleet, host, COUNT(*) AS inbound_count FROM hosted GROUP BY host
+ `+fleetInbounds+`
+ )
+ SELECT i.fleet, i.host, i.inbound_count, c.client_count, c.active_count, c.disabled_count, c.depleted_count
+ FROM inbound_counts i LEFT JOIN clients_by_host c ON c.fleet = i.fleet AND c.host = i.host
+ `, ambiguousGUIDs, ambiguousGUIDs, overview, time.Now().UnixMilli()).Scan(&rows).Error
+ if err != nil {
+ return NodeFleetCounts{}, NodeFleetCounts{}, err
+ }
+
+ byHost := make(map[string]NodeFleetCounts, len(rows))
+ var fleet NodeFleetCounts
+ for _, row := range rows {
+ if row.Fleet == 1 {
+ fleet = row.NodeFleetCounts
+ } else {
+ byHost[row.Host] = row.NodeFleetCounts
+ }
+ }
+ master := byHost[""]
+ online := s.onlineEmailsByGuid()
+ uniqueOnline := make(map[string]struct{})
+ if overview {
+ if process := currentXrayProcess(); process != nil {
+ for _, email := range process.GetLocalOnlineClients() {
+ uniqueOnline[email] = struct{}{}
+ }
+ }
+ }
+ master.OnlineCount = len(uniqueOnline)
+ totalOnline := (&InboundService{}).GetNodeOnlineTotals()
+ for _, node := range nodes {
+ guid := effectiveNodeGuid(node, ambiguous)
+ stats := byHost[guid]
+ node.InboundCount = stats.InboundCount
+ node.ClientCount = stats.ClientCount
+ node.ActiveCount = stats.ActiveCount
+ node.DisabledCount = stats.DisabledCount
+ node.DepletedCount = stats.DepletedCount
+ node.OnlineCount = len(online[guid])
+ node.OnlineTotalCount = totalOnline[node.Id]
+ if overview {
+ for email := range online[guid] {
+ uniqueOnline[email] = struct{}{}
+ }
+ }
+ }
+ fleet.OnlineCount = len(uniqueOnline)
+ return master, fleet, nil
+}
diff --git a/internal/web/service/node_fleet_test.go b/internal/web/service/node_fleet_test.go
new file mode 100644
index 000000000..824a4d533
--- /dev/null
+++ b/internal/web/service/node_fleet_test.go
@@ -0,0 +1,343 @@
+package service
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+)
+
+func TestNodeOverviewWithoutNodesSkipsFleetReads(t *testing.T) {
+ setupConflictDB(t)
+ db := database.GetDB()
+ if err := db.Create(&model.ClientRecord{Email: "standalone@example.test"}).Error; err != nil {
+ t.Fatal(err)
+ }
+ queries := recordExecutedSQL(t, db)
+ view, err := (&NodeService{}).GetNodeOverview(&Status{T: time.Now(), CpuCores: 4, LogicalPro: 8})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(*queries) != 1 {
+ t.Fatalf("standalone overview should only read the nodes table, queried %v", *queries)
+ }
+ if view.Nodes == nil || len(view.Nodes) != 0 ||
+ view.Master != (NodeMasterView{}) || view.Fleet != (NodeFleetCounts{}) {
+ t.Fatalf("standalone overview should be empty: %+v", view)
+ }
+}
+
+func TestNodeHeartbeatPublishesTelemetry(t *testing.T) {
+ svc, node, response := availabilityNodeFixture(t, `{"success":true,"obj":{"cpu":0,"cpuCores":4,"logicalPro":8,"mem":{"current":0,"total":4294967296},"tcpCount":0,"udpCount":7,"loads":[0,0.25,1.5],"netIO":{"up":0,"down":100}}}`)
+ read := func() map[string]any {
+ t.Helper()
+ patch, err := svc.Probe(t.Context(), node)
+ if err != nil {
+ t.Fatal(err)
+ }
+ patch.Status = "online"
+ if err := svc.UpdateHeartbeat(node.Id, patch); err != nil {
+ t.Fatal(err)
+ }
+ nodes, err := svc.GetNodeTreeView()
+ if err != nil || len(nodes) != 1 {
+ t.Fatalf("views: %v, %v", nodes, err)
+ }
+ data, err := json.Marshal(nodes[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ var view struct{ Telemetry map[string]any }
+ if err := json.Unmarshal(data, &view); err != nil {
+ t.Fatal(err)
+ }
+ return view.Telemetry
+ }
+ first := read()
+ for key, want := range map[string]float64{"cpuPct": 0, "physicalCores": 4, "logicalCores": 8, "memUsedBytes": 0, "memTotalBytes": 4294967296, "tcpCount": 0, "udpCount": 7, "load1": 0, "load5": 0.25, "load15": 1.5, "netUp": 0, "netDown": 100} {
+ if got := first[key]; got != want {
+ t.Errorf("%s = %v, want %v", key, got, want)
+ }
+ }
+ response(`{"success":true,"obj":{"cpu":0,"resourceScope":"container","cpuCores":4,"logicalPro":2,"unavailableMetrics":["cpu","tcpCount"],"tcpCount":0,"loads":[1e999,-1,0]}}`)
+ partial := read()
+ for _, field := range []string{"cpuPct", "physicalCores", "tcpCount", "udpCount", "memUsedBytes", "load1", "load5", "netUp"} {
+ if got := partial[field]; got != nil {
+ t.Errorf("unavailable %s = %v", field, got)
+ }
+ }
+ if partial["logicalCores"] != float64(2) || partial["load15"] != float64(0) {
+ t.Fatalf("lost valid partial metrics: %v", partial)
+ }
+ if err := svc.UpdateHeartbeat(node.Id, HeartbeatPatch{Status: "offline", LastHeartbeat: time.Now().Unix()}); err != nil {
+ t.Fatal(err)
+ }
+ view, err := svc.GetViewById(node.Id)
+ if err != nil || view.Status != "offline" || view.Telemetry != nil {
+ t.Fatalf("offline transition: %+v, %v", view, err)
+ }
+ response(`{"success":true,"obj":{"sampleAgeMillis":31000,"cpu":5}}`)
+ if stale := read(); stale != nil {
+ t.Fatalf("stale sample treated as live: %v", stale)
+ }
+ response(`{"success":true,"obj":{"cpu":5}}`)
+ if recovered := read(); recovered["cpuPct"] != float64(5) || recovered["tcpCount"] != nil {
+ t.Fatalf("legacy node recovery: %v", recovered)
+ }
+}
+
+func TestNodeOverviewCountsHostMembershipsAndUniqueFleetClients(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("node_fleet_counts")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ dbtest.InitDB(t, filepath.Join(t.TempDir(), "fleet.db"))
+ db := database.GetDB()
+ self, err := (&SettingService{}).GetPanelGuid()
+ if err != nil {
+ t.Fatal(err)
+ }
+ nodes := []model.Node{
+ {Name: "direct", Address: "192.0.2.1", Port: 2053, Guid: "direct"},
+ {Name: "cloned", Address: "192.0.2.2", Port: 2053, Guid: self},
+ }
+ if err := db.Create(&nodes).Error; err != nil {
+ t.Fatal(err)
+ }
+ nodeDescendantsMu.Lock()
+ nodeDescendantsCache[nodes[0].Id] = []model.NodeSummary{
+ {
+ Guid: "child", ParentGuid: "direct", Name: "child", Status: "online",
+ Telemetry: &model.NodeTelemetry{SampledAt: time.Now().UnixMilli(), UDPCount: new(0)},
+ },
+ }
+ nodeDescendantsMu.Unlock()
+ t.Cleanup(func() { (&NodeService{}).PruneNodeDescendants(nil) })
+
+ createInbound := func(tag string, nodeID *int, guid string) model.Inbound {
+ t.Helper()
+ ib := model.Inbound{Tag: tag, Port: 443, NodeID: nodeID, OriginNodeGuid: guid, Settings: `{"clients":[]}`}
+ if err := db.Create(&ib).Error; err != nil {
+ t.Fatal(err)
+ }
+ return ib
+ }
+ local := createInbound("local", nil, self)
+ direct := createInbound("direct", &nodes[0].Id, "direct")
+ child := createInbound("child", &nodes[0].Id, "child")
+ clone := createInbound("clone", &nodes[1].Id, self)
+ clients := []model.ClientRecord{{Email: "shared@test"}, {Email: "child@test"}, {Email: "orphan@test"}}
+ if err := db.Create(&clients).Error; err != nil {
+ t.Fatal(err)
+ }
+ links := []model.ClientInbound{
+ {ClientId: clients[0].Id, InboundId: local.Id},
+ {ClientId: clients[0].Id, InboundId: direct.Id},
+ {ClientId: clients[0].Id, InboundId: child.Id},
+ {ClientId: clients[1].Id, InboundId: child.Id},
+ {ClientId: clients[1].Id, InboundId: clone.Id},
+ }
+ if err := db.Create(&links).Error; err != nil {
+ t.Fatal(err)
+ }
+ status := &Status{T: time.Now(), LogicalPro: 8, CpuCores: 4, Cpu: 31, Loads: []float64{1, 2, 3}}
+ status.Mem.Total, status.Mem.Current = 8<<30, 2<<30
+ overview, err := (&NodeService{}).GetNodeOverview(status)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if overview.Fleet.ClientCount != 3 || overview.Fleet.InboundCount != 4 ||
+ overview.Master.Counts.ClientCount != 1 || overview.Master.Counts.InboundCount != 1 {
+ t.Fatalf("wrong host counts: %+v", overview)
+ }
+ want := map[string]int{"direct": 1, "cloned": 1, "child": 2}
+ for _, node := range overview.Nodes {
+ if node.ClientCount != want[node.Name] || node.InboundCount != 1 {
+ t.Errorf("wrong placement for %s: %+v", node.Name, node)
+ }
+ if node.Transitive && (node.Telemetry == nil || node.Telemetry.UDPCount == nil || *node.Telemetry.UDPCount != 0) {
+ t.Fatalf("missing descendant's own sample: %+v", node)
+ }
+ delete(want, node.Name)
+ }
+ if len(want) != 0 || overview.Master.Telemetry == nil || *overview.Master.Telemetry.Load15 != 3 {
+ t.Fatalf("missing view rows or master sample: %+v, missing=%v", overview.Master, want)
+ }
+
+ queries := recordExecutedSQL(t, db)
+ tree, err := (&NodeService{}).GetNodeTree()
+ if err != nil || len(tree) != 3 {
+ t.Fatalf("unexpected node tree: %v, %v", tree, err)
+ }
+ if strings.Contains(strings.Join(*queries, "\n"), "id FROM clients") {
+ t.Fatalf("node listing should skip the fleet aggregate: %v", *queries)
+ }
+ for i, node := range tree {
+ if node.ClientCount != overview.Nodes[i].ClientCount {
+ t.Errorf("wrong list count for %s: %d", node.Name, node.ClientCount)
+ }
+ }
+}
+
+func TestNodeOverviewUsesBestDescendantObservation(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("node_fleet_descendants")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ dbtest.InitDB(t, filepath.Join(t.TempDir(), "fleet-descendants.db"))
+ db := database.GetDB()
+ svc := &NodeService{}
+ t.Cleanup(func() { svc.PruneNodeDescendants(nil) })
+
+ parents := []model.Node{
+ {Name: "parent-a", Address: "192.0.2.1", Port: 2053, Guid: "parent-a", Enable: true},
+ {Name: "parent-b", Address: "192.0.2.2", Port: 2053, Guid: "parent-b", Enable: true},
+ }
+ if err := db.Create(&parents).Error; err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range []struct {
+ name string
+ status [2]string
+ age [2]time.Duration
+ wantParent int
+ wantStatus string
+ }{
+ {"lower ID offline", [2]string{"offline", "online"}, [2]time.Duration{}, 1, "online"},
+ {"higher ID offline", [2]string{"online", "offline"}, [2]time.Duration{}, 0, "online"},
+ {"lower ID disabled", [2]string{"disabled", "online"}, [2]time.Duration{}, 1, "online"},
+ {"higher ID disabled", [2]string{"online", "disabled"}, [2]time.Duration{}, 0, "online"},
+ {"both unavailable", [2]string{"offline", "disabled"}, [2]time.Duration{}, 0, "unknown"},
+ {"first sample stale", [2]string{"online", "online"}, [2]time.Duration{time.Minute, 0}, 1, "online"},
+ {"newer sample preferred", [2]string{"online", "online"}, [2]time.Duration{time.Second, 0}, 1, "online"},
+ {"equal samples keep lower ID", [2]string{"online", "online"}, [2]time.Duration{}, 0, "online"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ now := time.Now()
+ for i, parent := range parents {
+ if err := db.Model(&parent).Updates(map[string]any{
+ "enable": tc.status[i] != "disabled", "status": tc.status[i],
+ }).Error; err != nil {
+ t.Fatal(err)
+ }
+ nodeDescendantsMu.Lock()
+ nodeDescendantsCache[parent.Id] = []model.NodeSummary{{
+ Guid: "shared-child", Name: "shared-child", ParentGuid: parent.Guid, Status: "online",
+ Telemetry: &model.NodeTelemetry{SampledAt: now.Add(-tc.age[i]).UnixMilli(), CpuPct: new(float64(20 + i))},
+ }}
+ nodeDescendantsMu.Unlock()
+ }
+ view, err := svc.GetNodeOverview(nil)
+ if err != nil || len(view.Nodes) != 3 {
+ t.Fatalf("expected two parents and one child: %+v, %v", view, err)
+ }
+ child := view.Nodes[2]
+ if !child.Transitive || child.Guid != "shared-child" || child.ParentGuid != parents[tc.wantParent].Guid || child.Status != tc.wantStatus {
+ t.Fatalf("unexpected descendant observation: %+v", child)
+ }
+ if tc.wantStatus == "unknown" {
+ if child.Telemetry != nil {
+ t.Fatalf("unavailable descendant has telemetry: %+v", child.Telemetry)
+ }
+ } else if child.Telemetry == nil || child.Telemetry.CpuPct == nil || *child.Telemetry.CpuPct != float64(20+tc.wantParent) {
+ t.Fatalf("wrong descendant telemetry: %+v", child.Telemetry)
+ }
+ })
+ }
+}
+
+func BenchmarkNodeOverviewFleetScale(b *testing.B) {
+ dbtest.InitDB(b, filepath.Join(b.TempDir(), "fleet-scale.db"))
+ db := database.GetDB()
+ statusJSON := `{"success":true,"obj":{"cpu":25,"cpuCores":4,"logicalPro":8,"mem":{"current":2147483648,"total":8589934592,"available":6442450944},"tcpCount":132,"udpCount":22,"loads":[0.2,0.3,0.4],"uptime":90000,"netIO":{"up":12582912,"down":512}}}`
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(statusJSON))
+ }))
+ b.Cleanup(server.Close)
+ u, _ := url.Parse(server.URL)
+ port, _ := strconv.Atoi(u.Port())
+ nodes := make([]model.Node, 4)
+ for i := range nodes {
+ nodes[i] = model.Node{
+ Name: fmt.Sprint("remote-", i), Guid: fmt.Sprint("remote-guid-", i),
+ Scheme: "http", Address: u.Hostname(), Port: port, AllowPrivateAddress: true,
+ }
+ }
+ if err := db.Create(&nodes).Error; err != nil {
+ b.Fatal(err)
+ }
+ inbounds := make([]model.Inbound, 40)
+ for i := range inbounds {
+ inbounds[i] = model.Inbound{Tag: fmt.Sprint("inbound-", i), Port: 2000 + i, Settings: `{"clients":[]}`}
+ if i%5 != 0 {
+ node := &nodes[i%5-1]
+ inbounds[i].NodeID, inbounds[i].OriginNodeGuid = &node.Id, node.Guid
+ }
+ }
+ if err := db.CreateInBatches(&inbounds, 40).Error; err != nil {
+ b.Fatal(err)
+ }
+ clients := make([]model.ClientRecord, 7100)
+ for i := range clients {
+ clients[i].Email = fmt.Sprintf("client-%05d@test", i)
+ }
+ if err := db.CreateInBatches(&clients, 100).Error; err != nil {
+ b.Fatal(err)
+ }
+ links := make([]model.ClientInbound, 115000)
+ for i := range links {
+ client := clients[i%len(clients)]
+ ib := inbounds[(i/len(clients)+i)%len(inbounds)]
+ links[i] = model.ClientInbound{ClientId: client.Id, InboundId: ib.Id}
+ }
+ if err := db.CreateInBatches(&links, 250).Error; err != nil {
+ b.Fatal(err)
+ }
+ svc := &NodeService{}
+ cycle := func() {
+ for i := range nodes {
+ patch, err := svc.Probe(b.Context(), &nodes[i])
+ if err != nil {
+ b.Fatal(err)
+ }
+ patch.Status = "online"
+ if err := svc.UpdateHeartbeat(nodes[i].Id, patch); err != nil {
+ b.Fatal(err)
+ }
+ }
+ }
+ cycle()
+ b.Run("FourHeartbeatProbesAndWrites", func(b *testing.B) {
+ for b.Loop() {
+ cycle()
+ }
+ b.ReportMetric(float64(4*len(statusJSON)), "status-wire-B/cycle")
+ })
+ b.Run("OverviewAndJSON", func(b *testing.B) {
+ var payload []byte
+ for b.Loop() {
+ result, err := svc.GetNodeOverview(&Status{T: time.Now(), CpuCores: 4, LogicalPro: 8})
+ if err != nil {
+ b.Fatal(err)
+ }
+ payload, err = json.Marshal(result)
+ if err != nil || result.Fleet.ClientCount != 7100 {
+ b.Fatalf("fixture: %v", err)
+ }
+ }
+ b.ReportMetric(float64(len(payload)), "overview-wire-B/op")
+ })
+}
diff --git a/internal/web/service/node_http_fake_test.go b/internal/web/service/node_http_fake_test.go
index b5ce92530..aaf1655b4 100644
--- a/internal/web/service/node_http_fake_test.go
+++ b/internal/web/service/node_http_fake_test.go
@@ -25,20 +25,25 @@ type fakeNodeHTTP struct {
hits map[string]int
caps string
pendingClientAcks int
- // hold makes every non-list request block until the master gives up.
+ clientAdds []ClientCreatePayload
+ clientAddEvents chan ClientCreatePayload
+ // hold makes requests outside inbound discovery block until the master gives up.
hold bool
release chan struct{}
}
func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP {
t.Helper()
- f := &fakeNodeHTTP{tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{})}
+ f := &fakeNodeHTTP{
+ tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{}),
+ clientAddEvents: make(chan ClientCreatePayload, 16),
+ }
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
f.mu.Lock()
w.Header().Set(wirecodec.CapsHeader, f.caps)
f.mu.Unlock()
- if strings.HasSuffix(r.URL.Path, "/inbounds/list") {
+ if strings.HasSuffix(r.URL.Path, "/inbounds/catalog") || strings.HasSuffix(r.URL.Path, "/inbounds/list") {
f.mu.Lock()
f.hits["list"]++
type ent struct {
@@ -62,6 +67,20 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP {
f.pendingClientAcks--
}
f.mu.Unlock()
+ if strings.HasSuffix(r.URL.Path, "/clients/add") {
+ var payload ClientCreatePayload
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ f.mu.Lock()
+ f.clientAdds = append(f.clientAdds, payload)
+ f.mu.Unlock()
+ select {
+ case f.clientAddEvents <- payload:
+ default:
+ }
+ }
if hold {
// Drain first: the server only notices a client disconnect once the
// body is consumed, and Close would otherwise wait on this forever.
diff --git a/internal/web/service/node_origin_guid_test.go b/internal/web/service/node_origin_guid_test.go
index c577db363..4208c9951 100644
--- a/internal/web/service/node_origin_guid_test.go
+++ b/internal/web/service/node_origin_guid_test.go
@@ -7,6 +7,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
@@ -146,6 +147,11 @@ func TestSetRemoteTraffic_RemapsClonedNodeOwnGuidOrigin(t *testing.T) {
}
func TestSetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("online_remap")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
setupConflictDB(t)
db := database.GetDB()
@@ -178,6 +184,12 @@ func TestSetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags(t *testing.T) {
}
}
+ reporter := xray.NewTestProcess(nil, "")
+ reporter.RefreshLocalOnline([]string{"online@example.test"}, []string{"shared-tag"}, 1_000, 20_000)
+ _, tags := reporter.LocalOnlineSnapshot(1_000, 20_000)
+ // Older relays discard empty active tags when normalizing and forwarding a subtree.
+ tags = slices.DeleteFunc(tags, func(tag string) bool { return tag == "" })
+
snap := &runtime.TrafficSnapshot{
Inbounds: []*model.Inbound{{
Tag: "shared-tag",
@@ -187,7 +199,7 @@ func TestSetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags(t *testing.T) {
Settings: `{"clients":[]}`,
}},
ActiveInboundTree: map[string][]string{
- "dup": {"shared-tag"},
+ "dup": tags,
},
}
@@ -197,7 +209,7 @@ func TestSetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags(t *testing.T) {
}
merged := process.GetMergedActiveInboundTrees()
- assertStringSet(t, "active node:1", merged["node:1"], []string{"n1-shared-tag"})
+ assertStringSet(t, "active node:1", merged["node:1"], []string{"n1-shared-tag", xray.PartialInboundActivityTag})
if _, ok := merged["dup"]; ok {
t.Fatalf("cloned active-inbound subtree must not stay under shared GUID: %v", merged)
}
diff --git a/internal/web/service/node_shared_guid_test.go b/internal/web/service/node_shared_guid_test.go
index 94d7d1a79..e6c82eec7 100644
--- a/internal/web/service/node_shared_guid_test.go
+++ b/internal/web/service/node_shared_guid_test.go
@@ -117,7 +117,9 @@ func TestRecountByGuid_SplitsClonedNodesWithSharedGuid(t *testing.T) {
}
nodes := []*model.Node{n1, n2, n3}
- svc.recountByGuid(nodes, selfGuid)
+ if _, _, err := svc.countNodeFleet(nodes, selfGuid, false); err != nil {
+ t.Fatal(err)
+ }
if n1.InboundCount != 1 || n2.InboundCount != 1 {
t.Errorf("cloned nodes must not share inbound counts: n1=%d n2=%d, want 1,1", n1.InboundCount, n2.InboundCount)
diff --git a/internal/web/service/node_telemetry.go b/internal/web/service/node_telemetry.go
new file mode 100644
index 000000000..402ff9257
--- /dev/null
+++ b/internal/web/service/node_telemetry.go
@@ -0,0 +1,123 @@
+package service
+
+import (
+ "encoding/json"
+ "math"
+ "slices"
+ "time"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+const nodeTelemetryFreshness = 30 * time.Second
+
+func validNodeLoad(load float64) bool {
+ return load >= 0 && !math.IsInf(load, 0)
+}
+
+type nodeStatusMetrics struct {
+ Cpu json.RawMessage `json:"cpu"`
+ CpuCores json.RawMessage `json:"cpuCores"`
+ LogicalPro json.RawMessage `json:"logicalPro"`
+ Mem json.RawMessage `json:"mem"`
+ TcpCount json.RawMessage `json:"tcpCount"`
+ UdpCount json.RawMessage `json:"udpCount"`
+ Loads json.RawMessage `json:"loads"`
+ Uptime json.RawMessage `json:"uptime"`
+ NetIO json.RawMessage `json:"netIO"`
+ ResourceScope string `json:"resourceScope"`
+ SampleAgeMillis *int64 `json:"sampleAgeMillis"`
+ UnavailableMetrics []string `json:"unavailableMetrics"`
+}
+
+type nodeMetricNumber interface {
+ int | uint64 | float64
+}
+
+func readNodeMetric[T nodeMetricNumber](raw json.RawMessage, unavailable []string, key string) *T {
+ var v *T
+ if slices.Contains(unavailable, key) || json.Unmarshal(raw, &v) != nil || v == nil || *v < 0 {
+ return nil
+ }
+ return v
+}
+
+func (m nodeStatusMetrics) telemetry(received time.Time) *model.NodeTelemetry {
+ unavailable := m.UnavailableMetrics
+ var memory struct {
+ Current json.RawMessage `json:"current"`
+ Total json.RawMessage `json:"total"`
+ Available json.RawMessage `json:"available"`
+ }
+ var network struct {
+ Up json.RawMessage `json:"up"`
+ Down json.RawMessage `json:"down"`
+ }
+ var loads [3]json.RawMessage
+ _ = json.Unmarshal(m.Mem, &memory)
+ _ = json.Unmarshal(m.NetIO, &network)
+ _ = json.Unmarshal(m.Loads, &loads)
+
+ age := int64(0)
+ if m.SampleAgeMillis != nil {
+ age = min(max(0, *m.SampleAgeMillis), nodeTelemetryFreshness.Milliseconds())
+ }
+ sample := &model.NodeTelemetry{
+ SampledAt: received.UnixMilli() - age,
+ ResourceScope: m.ResourceScope,
+ CpuPct: readNodeMetric[float64](m.Cpu, unavailable, "cpu"),
+ PhysicalCores: readNodeMetric[int](m.CpuCores, unavailable, "cpuCores"),
+ LogicalCores: readNodeMetric[int](m.LogicalPro, unavailable, "logicalPro"),
+ MemUsedBytes: readNodeMetric[uint64](memory.Current, unavailable, "mem"),
+ MemTotalBytes: readNodeMetric[uint64](memory.Total, unavailable, "mem"),
+ MemAvailableBytes: readNodeMetric[uint64](memory.Available, unavailable, "mem"),
+ TCPCount: readNodeMetric[int](m.TcpCount, unavailable, "tcpCount"),
+ UDPCount: readNodeMetric[int](m.UdpCount, unavailable, "udpCount"),
+ Load1: readNodeMetric[float64](loads[0], unavailable, "loads"),
+ Load5: readNodeMetric[float64](loads[1], unavailable, "loads"),
+ Load15: readNodeMetric[float64](loads[2], unavailable, "loads"),
+ UptimeSecs: readNodeMetric[uint64](m.Uptime, unavailable, "uptime"),
+ NetUp: readNodeMetric[uint64](network.Up, unavailable, "netUp"),
+ NetDown: readNodeMetric[uint64](network.Down, unavailable, "netDown"),
+ }
+ if sample.CpuPct != nil && *sample.CpuPct > 100 {
+ sample.CpuPct = nil
+ }
+ if sample.ResourceScope != "" || (sample.PhysicalCores != nil && *sample.PhysicalCores == 0) {
+ sample.PhysicalCores = nil
+ }
+ if sample.LogicalCores != nil && *sample.LogicalCores == 0 {
+ sample.LogicalCores = nil
+ }
+ if sample.MemTotalBytes == nil || *sample.MemTotalBytes == 0 ||
+ sample.MemUsedBytes == nil || *sample.MemUsedBytes > *sample.MemTotalBytes {
+ sample.MemUsedBytes, sample.MemTotalBytes, sample.MemAvailableBytes = nil, nil, nil
+ } else if sample.MemAvailableBytes != nil && *sample.MemAvailableBytes > *sample.MemTotalBytes {
+ sample.MemAvailableBytes = nil
+ }
+ return sample
+}
+
+func liveNodeTelemetry(node *model.Node, now time.Time) *model.NodeTelemetry {
+ sample := node.Telemetry
+ if sample == nil || !node.Enable || node.Status != "online" {
+ return nil
+ }
+ age := now.UnixMilli() - sample.SampledAt
+ if age < 0 || age >= nodeTelemetryFreshness.Milliseconds() {
+ return nil
+ }
+ view := *sample
+ view.SampleAgeMillis = &age
+ return &view
+}
+
+// StatusWithSampleAge publishes age relative to the sampler's clock.
+func StatusWithSampleAge(status *Status) *Status {
+ if status == nil {
+ return nil
+ }
+ result := *status
+ result.SampleAgeMillis = new(max(0, time.Since(status.T).Milliseconds()))
+ return &result
+}
diff --git a/internal/web/service/node_tree.go b/internal/web/service/node_tree.go
index 83210776f..82ca79a72 100644
--- a/internal/web/service/node_tree.go
+++ b/internal/web/service/node_tree.go
@@ -42,6 +42,9 @@ func (s *NodeService) LocalDescendants() ([]model.NodeSummary, error) {
XrayVersion: n.XrayVersion,
XrayState: n.XrayState,
XrayError: n.XrayError,
+ BasePath: n.BasePath,
+ Enabled: &n.Enable,
+ Telemetry: liveNodeTelemetry(n, time.Now()),
})
}
return out, nil
@@ -71,6 +74,12 @@ func (s *NodeService) RefreshDescendants(ctx context.Context, n *model.Node) {
if err != nil {
return
}
+ now := time.Now().UnixMilli()
+ for i := range summaries {
+ if sample := summaries[i].Telemetry; sample != nil && sample.SampleAgeMillis != nil {
+ sample.SampledAt = now - min(max(0, *sample.SampleAgeMillis), nodeTelemetryFreshness.Milliseconds())
+ }
+ }
nodeDescendantsMu.Lock()
if len(summaries) == 0 {
delete(nodeDescendantsCache, n.Id)
@@ -80,39 +89,74 @@ func (s *NodeService) RefreshDescendants(ctx context.Context, n *model.Node) {
nodeDescendantsMu.Unlock()
}
-// ClearDescendants drops a node's cached sub-node summaries (its probe failed).
-func (s *NodeService) ClearDescendants(nodeID int) {
+// MarkDescendantsUnreachable keeps host identities while invalidating the last observations.
+func (s *NodeService) MarkDescendantsUnreachable(nodeID int) {
nodeDescendantsMu.Lock()
- delete(nodeDescendantsCache, nodeID)
+ for i := range nodeDescendantsCache[nodeID] {
+ nodeDescendantsCache[nodeID][i] = unavailableDescendant(nodeDescendantsCache[nodeID][i])
+ }
nodeDescendantsMu.Unlock()
}
-// RetainEnabledNodeDescendants drops sub-nodes learned from nodes the heartbeat no
-// longer probes: disabled ones it skips, deleted ones missing from nodes.
-func (s *NodeService) RetainEnabledNodeDescendants(nodes []*model.Node) {
+func unavailableDescendant(summary model.NodeSummary) model.NodeSummary {
+ summary.Status = "unknown"
+ summary.Telemetry = nil
+ summary.XrayState = ""
+ summary.XrayError = ""
+ return summary
+}
+
+// PruneNodeDescendants removes deleted branches and invalidates disabled branches' samples.
+func (s *NodeService) PruneNodeDescendants(nodes []*model.Node) {
enabled := make(map[int]bool, len(nodes))
for _, n := range nodes {
enabled[n.Id] = n.Enable
}
nodeDescendantsMu.Lock()
for nodeID := range nodeDescendantsCache {
- if !enabled[nodeID] {
+ if active, registered := enabled[nodeID]; !registered {
delete(nodeDescendantsCache, nodeID)
+ } else if !active {
+ for i, summary := range nodeDescendantsCache[nodeID] {
+ nodeDescendantsCache[nodeID][i] = unavailableDescendant(summary)
+ }
}
}
nodeDescendantsMu.Unlock()
}
-func cachedDescendants() []model.NodeSummary {
+func cachedDescendants(nodes []*model.Node) []model.NodeSummary {
nodeDescendantsMu.RLock()
defer nodeDescendantsMu.RUnlock()
out := make([]model.NodeSummary, 0)
- for _, list := range nodeDescendantsCache {
- out = append(out, list...)
+ for _, parent := range nodes {
+ for _, summary := range nodeDescendantsCache[parent.Id] {
+ if !parent.Enable || parent.Status == "offline" {
+ summary = unavailableDescendant(summary)
+ }
+ out = append(out, summary)
+ }
}
return out
}
+func preferDescendantObservation(candidate, current *model.Node, now time.Time) bool {
+ next, previous := liveNodeTelemetry(candidate, now), liveNodeTelemetry(current, now)
+ if next != nil {
+ return previous == nil || next.SampledAt > previous.SampledAt
+ }
+ if previous != nil {
+ return false
+ }
+ candidateOnline := candidate.Enable && candidate.Status == "online"
+ currentOnline := current.Enable && current.Status == "online"
+ if candidateOnline != currentOnline {
+ return candidateOnline
+ }
+ // A known state is more informative than the placeholder from a lost branch.
+ return current.Status == "unknown" && candidate.Status != "unknown"
+}
+
// GetNodeTree returns the direct nodes plus any transitive sub-nodes learned
// from them, with per-GUID counts so each node shows only the inbounds/online
// it physically hosts (#4983). Direct nodes carry the master's own GUID as
@@ -120,9 +164,14 @@ func cachedDescendants() []model.NodeSummary {
// nodes are read-only projections (Id == 0). Used by the Nodes page and the
// heartbeat broadcast — never for probing/syncing, which stay on ListOperational.
func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
+ nodes, _, _, err := s.getNodeTreeWithCounts(false)
+ return nodes, err
+}
+
+func (s *NodeService) getNodeTreeWithCounts(overview bool) ([]*model.Node, NodeFleetCounts, NodeFleetCounts, error) {
nodes, err := s.ListOperational()
- if err != nil {
- return nodes, err
+ if err != nil || len(nodes) == 0 {
+ return nodes, NodeFleetCounts{}, NodeFleetCounts{}, err
}
selfGuid, _ := (&SettingService{}).GetPanelGuid()
directGuids := make(map[string]struct{}, len(nodes))
@@ -133,20 +182,17 @@ func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
}
}
- seen := make(map[string]struct{})
+ now := time.Now()
+ indexByGUID := make(map[string]int)
var transitive []*model.Node
- for _, sum := range cachedDescendants() {
- if sum.Guid == "" {
+ for _, sum := range cachedDescendants(nodes) {
+ if sum.Guid == "" || sum.Guid == selfGuid {
continue
}
if _, ok := directGuids[sum.Guid]; ok {
continue // already shown as a direct node
}
- if _, ok := seen[sum.Guid]; ok {
- continue
- }
- seen[sum.Guid] = struct{}{}
- transitive = append(transitive, &model.Node{
+ descendant := &model.Node{
Guid: sum.Guid,
ParentGuid: sum.ParentGuid,
Name: sum.Name,
@@ -161,23 +207,24 @@ func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
XrayState: sum.XrayState,
XrayError: sum.XrayError,
Transitive: true,
- })
- }
- if len(transitive) == 0 {
- if len(nodes) > 0 {
- s.enrichDashboardStats(database.GetDB(), nodes)
+ Enable: sum.Enabled == nil || *sum.Enabled,
+ BasePath: sum.BasePath,
+ Telemetry: sum.Telemetry,
}
- return nodes, nil
+ if index, ok := indexByGUID[sum.Guid]; ok {
+ // Replace in place to preserve row order. Equal observations keep
+ // the first parent (ListOperational orders parents by ascending ID).
+ if preferDescendantObservation(descendant, transitive[index], now) {
+ transitive[index] = descendant
+ }
+ continue
+ }
+ indexByGUID[sum.Guid] = len(transitive)
+ transitive = append(transitive, descendant)
}
-
- if len(nodes) > 0 {
- s.populateClientCounts(database.GetDB(), nodes)
- }
- all := make([]*model.Node, 0, len(nodes)+len(transitive))
- all = append(all, nodes...)
- all = append(all, transitive...)
- s.recountByGuid(all, selfGuid)
- return all, nil
+ all := append(nodes, transitive...)
+ master, fleet, err := s.countNodeFleet(all, selfGuid, overview)
+ return all, master, fleet, err
}
func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
@@ -185,6 +232,10 @@ func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
if err != nil {
return nil, err
}
+ return nodeTreeViews(nodes), nil
+}
+
+func nodeTreeViews(nodes []*model.Node) []*NodeView {
views := toNodeViews(nodes)
now := time.Now()
for _, view := range views {
@@ -192,91 +243,5 @@ func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
view.HeartbeatAgeMillis = new(max(0, now.Sub(time.Unix(view.LastHeartbeat, 0)).Milliseconds()))
}
}
- return views, nil
-}
-
-// recountByGuid recomputes InboundCount/OnlineCount/DepletedCount for every node
-// in the tree, keyed by the GUID that physically hosts each inbound, so a direct
-// node shows only its own inbounds and each transitive node shows its own
-// (#4983). In a flat topology the per-GUID and per-node-id counts coincide, so
-// this only changes behaviour once a transitive node exists.
-func (s *NodeService) recountByGuid(nodes []*model.Node, selfGuid string) {
- db := database.GetDB()
- type ibRow struct {
- Id int
- NodeID *int `gorm:"column:node_id"`
- OriginNodeGuid string `gorm:"column:origin_node_guid"`
- }
- var ibRows []ibRow
- if err := db.Table("inbounds").Select("id, node_id, origin_node_guid").Scan(&ibRows).Error; err != nil {
- return
- }
- ambiguous := ambiguousNodeGuids(nodes, selfGuid)
- effByInbound := make(map[int]string, len(ibRows))
- inboundCountByGuid := make(map[string]int)
- for _, r := range ibRows {
- guid := r.OriginNodeGuid
- if guid == "" {
- if r.NodeID != nil {
- guid = synthNodeGuid(*r.NodeID)
- } else {
- guid = selfGuid
- }
- } else if r.NodeID != nil {
- // Origin still holds an ambiguous GUID (cloned server / master-shared,
- // not yet re-attributed): bucket under the hosting node's unique id so
- // the clones don't merge.
- if _, bad := ambiguous[guid]; bad {
- guid = synthNodeGuid(*r.NodeID)
- }
- }
- effByInbound[r.Id] = guid
- inboundCountByGuid[guid]++
- }
-
- // Classify by EMAIL (not the stale client_traffics.inbound_id) and bucket
- // each client under its inbound's effective attribution GUID, deduping a
- // client attached to several inbounds under the same GUID.
- depletedByGuid := make(map[string]int)
- disabledByGuid := make(map[string]int)
- activeByGuid := make(map[string]int)
- if statuses, err := s.nodeClientStatuses(); err == nil {
- seen := make(map[string]map[int]struct{})
- for _, st := range statuses {
- guid, ok := effByInbound[st.InboundID]
- if !ok {
- continue
- }
- clientsSeen := seen[guid]
- if clientsSeen == nil {
- clientsSeen = make(map[int]struct{})
- seen[guid] = clientsSeen
- }
- if _, dup := clientsSeen[st.ClientID]; dup {
- continue
- }
- clientsSeen[st.ClientID] = struct{}{}
- switch {
- case st.Depleted:
- depletedByGuid[guid]++
- case st.Disabled:
- disabledByGuid[guid]++
- default:
- activeByGuid[guid]++
- }
- }
- }
-
- onlineByGuid := s.onlineEmailsByGuid()
- onlineTotals := (&InboundService{}).GetNodeOnlineTotals()
- for _, n := range nodes {
- guid := effectiveNodeGuid(n, ambiguous)
- n.InboundCount = inboundCountByGuid[guid]
- n.OnlineCount = len(onlineByGuid[guid])
- // Keyed by node id, so a transitive sub-node (id 0) never has one.
- n.OnlineTotalCount = onlineTotals[n.Id]
- n.DepletedCount = depletedByGuid[guid]
- n.DisabledCount = disabledByGuid[guid]
- n.ActiveCount = activeByGuid[guid]
- }
+ return views
}
diff --git a/internal/web/service/node_unsynced_online_test.go b/internal/web/service/node_unsynced_online_test.go
index 486c64123..f478922a8 100644
--- a/internal/web/service/node_unsynced_online_test.go
+++ b/internal/web/service/node_unsynced_online_test.go
@@ -92,6 +92,24 @@ func TestSetRemoteTrafficKeepsOnlyTheNodesOwnClientsOnline(t *testing.T) {
if got, want := svc.GetOnlineClientsByGuid(), map[string][]string{"node-guid": {"kept@x"}}; !reflect.DeepEqual(got, want) {
t.Fatalf("online by guid = %v, want %v", got, want)
}
+ for _, legacy := range []bool{true, false} {
+ snap = snapshotWithClients(t, "keep", settings, xray.ClientTraffic{Email: "kept@x", Enable: true})
+ snap.OnlineTree = map[string][]string{"node-guid": {}}
+ if legacy {
+ snap.LegacyInboundActivity = true
+ } else {
+ snap.ActiveInboundTree = map[string][]string{"node-guid": {}}
+ }
+ if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil {
+ t.Fatal(err)
+ }
+ if idle := svc.GetOnlineClientsByGuid()["node-guid"]; idle == nil || len(idle) != 0 {
+ t.Fatalf("lost explicit empty node online list: %v", idle)
+ }
+ if tags, present := svc.GetActiveInboundsByGuid()["node-guid"]; !present || (tags == nil) != legacy {
+ t.Fatalf("legacy=%t: incorrect activity report %v, present=%t", legacy, tags, present)
+ }
+ }
}
// The client-IP reports feed the IP limit and fail2ban; a node must not plant rows for
diff --git a/internal/web/service/restore_listeners_pg.go b/internal/web/service/restore_listeners_pg.go
index 17ee0f261..5a3cf0ffa 100644
--- a/internal/web/service/restore_listeners_pg.go
+++ b/internal/web/service/restore_listeners_pg.go
@@ -117,7 +117,7 @@ func inboundFromPgCopyRow(row map[string]string) (*model.Inbound, error) {
// checkPgDumpRestoreListeners runs restoreListenerConflict over a pg_dump archive:
// pg_restore writes the two tables as a data script, which needs no connection.
-func checkPgDumpRestoreListeners(bin, dumpPath string, kept hostBoundSnapshot) error {
+func checkPgDumpRestoreListeners(ctx context.Context, bin, dumpPath string, kept hostBoundSnapshot) error {
script, err := os.CreateTemp("", "x-ui-pg-preflight-*.sql")
if err != nil {
return common.NewErrorf("Error creating temporary file: %v", err)
@@ -128,7 +128,7 @@ func checkPgDumpRestoreListeners(bin, dumpPath string, kept hostBoundSnapshot) e
return common.NewErrorf("Error creating temporary file: %v", err)
}
- cmd := exec.CommandContext(context.Background(), bin,
+ cmd := exec.CommandContext(ctx, bin,
"--data-only", "--table=inbounds", "--table=settings", "--file="+scriptPath, dumpPath)
var stderr bytes.Buffer
cmd.Stderr = &stderr
diff --git a/internal/web/service/server.go b/internal/web/service/server.go
index 395dfaf74..6e286b8e5 100644
--- a/internal/web/service/server.go
+++ b/internal/web/service/server.go
@@ -52,6 +52,7 @@ import (
"github.com/shirou/gopsutil/v4/host"
"github.com/shirou/gopsutil/v4/load"
"github.com/shirou/gopsutil/v4/mem"
+ "gorm.io/gorm"
)
// ProcessState represents the current state of a system process.
@@ -71,6 +72,7 @@ type Status struct {
networkTrafficSample *networkTrafficSample `json:"-"`
ResourceScope string `json:"resourceScope,omitempty"`
UnavailableMetrics []string `json:"unavailableMetrics,omitempty"`
+ SampleAgeMillis *int64 `json:"sampleAgeMillis,omitempty" example:"125"`
T time.Time `json:"-"`
Cpu float64 `json:"cpu"`
@@ -78,8 +80,9 @@ type Status struct {
LogicalPro int `json:"logicalPro"`
CpuSpeedMhz float64 `json:"cpuSpeedMhz"`
Mem struct {
- Current uint64 `json:"current"`
- Total uint64 `json:"total"`
+ Current uint64 `json:"current"`
+ Total uint64 `json:"total"`
+ Available *uint64 `json:"available,omitempty"`
} `json:"mem"`
Swap struct {
Current uint64 `json:"current"`
@@ -675,6 +678,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
util, err := s.sampleCPUUtilization()
if err != nil {
logger.Warning("get cpu percent failed:", err)
+ status.UnavailableMetrics = append(status.UnavailableMetrics, "cpu")
} else {
status.Cpu = util
}
@@ -691,17 +695,13 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
done := make(chan struct{})
go func() {
defer close(done)
- cpuInfos, err := cpu.Info()
+ mhz, err := sys.CPUSpeedMHz()
if err != nil {
- logger.Warning("get cpu info failed:", err)
+ logger.Warning("get cpu speed failed:", err)
return
}
- if len(cpuInfos) > 0 {
- s.cachedCpuSpeedMhz = cpuInfos[0].Mhz
- status.CpuSpeedMhz = s.cachedCpuSpeedMhz
- } else {
- logger.Warning("could not find cpu info")
- }
+ s.cachedCpuSpeedMhz = mhz
+ status.CpuSpeedMhz = mhz
}()
select {
case <-done:
@@ -716,6 +716,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
upTime, err := host.Uptime()
if err != nil {
logger.Warning("get uptime failed:", err)
+ status.UnavailableMetrics = append(status.UnavailableMetrics, "uptime")
} else {
status.Uptime = upTime
}
@@ -728,6 +729,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
} else {
status.Mem.Current = memInfo.Used
status.Mem.Total = memInfo.Total
+ status.Mem.Available = new(memInfo.Available)
}
if scoped == nil {
@@ -777,7 +779,7 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
avgState, err := load.Avg()
if err != nil {
logger.Warning("get load avg failed:", err)
- } else {
+ } else if validNodeLoad(avgState.Load1) && validNodeLoad(avgState.Load5) && validNodeLoad(avgState.Load15) {
status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
}
@@ -787,11 +789,13 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
status.TcpCount, err = sys.GetTCPCount()
if err != nil {
logger.Warning("get tcp connections failed:", err)
+ status.UnavailableMetrics = append(status.UnavailableMetrics, "tcpCount")
}
status.UdpCount, err = sys.GetUDPCount()
if err != nil {
logger.Warning("get udp connections failed:", err)
+ status.UnavailableMetrics = append(status.UnavailableMetrics, "udpCount")
}
s.resolvePublicIPsInBackground()
@@ -1881,14 +1885,13 @@ func captureHostBoundSettings() hostBoundSnapshot {
}
func restoreHostBoundSettings(snap hostBoundSnapshot) {
- if !snap.taken {
+ restoreHostBoundSettingsOn(database.GetDB(), snap)
+}
+
+func restoreHostBoundSettingsOn(db *gorm.DB, snap hostBoundSnapshot) {
+ if !snap.taken || db == nil {
return
}
- db := database.GetDB()
- if db == nil {
- return
- }
- settingSvc := &SettingService{}
for _, key := range hostBoundSettingKeys {
if _, had := snap.present[key]; !had {
// Absent because it is minted on demand, not because a default applied:
@@ -1903,7 +1906,7 @@ func restoreHostBoundSettings(snap hostBoundSnapshot) {
}
// saveSetting rather than Assign(struct): GORM drops zero-valued fields from
// the assignment map, so an empty local value never overwrote the import.
- if err := settingSvc.saveSetting(key, snap.values[key]); err != nil {
+ if err := saveSettingOn(db, key, snap.values[key]); err != nil {
logger.Warningf("Import: could not restore setting %q for this machine: %v", key, err)
}
}
@@ -1919,9 +1922,20 @@ var lazilyMintedSettingKeys = map[string]bool{
"nodeMtlsClientCAPem": true,
}
+var databaseImportMu sync.Mutex
+
func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) error {
+ return s.ImportDBContext(context.Background(), file, keepHostSettings)
+}
+
+// ImportDBContext honors cancellation during PostgreSQL archive preparation.
+func (s *ServerService) ImportDBContext(ctx context.Context, file multipart.File, keepHostSettings bool) error {
+ if !databaseImportMu.TryLock() {
+ return ErrDatabaseRestoring
+ }
+ defer databaseImportMu.Unlock()
if database.IsPostgres() {
- return s.importPostgresDB(file, keepHostSettings)
+ return s.importPostgresDB(ctx, file, keepHostSettings)
}
kind, err := sniffUploadKind(file)
if err != nil {
@@ -1935,7 +1949,11 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err
return common.NewError("Invalid file: expected a SQLite database (.db) from Back Up or a SQLite migration dump (.dump)")
}
- tempPath := fmt.Sprintf("%s.temp", config.GetDBPath())
+ livePath, err := database.SQLiteDatabasePath(config.GetDBPath())
+ if err != nil {
+ return fmt.Errorf("resolve SQLite database path: %w", err)
+ }
+ tempPath := livePath + ".temp"
if _, err := os.Stat(tempPath); err == nil {
if errRemove := os.Remove(tempPath); errRemove != nil {
@@ -1969,7 +1987,7 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err
return err
}
- xrayStopped := true
+ xrayStopped := false
defer func() {
if xrayStopped {
if errR := s.restartXrayService(XrayOriginDatabaseRestore); errR != nil {
@@ -1977,12 +1995,27 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err
}
}
}()
+ _, releaseRestore, err := beginDatabaseRestore()
+ if err != nil {
+ return err
+ }
+ keepMaintenance := false
+ defer func() {
+ if !keepMaintenance {
+ if err := releaseRestore(); err != nil {
+ xrayStopped = false
+ logger.Warning("release database restore lock:", err)
+ }
+ }
+ }()
+ xrayStopped = true
if errStop := s.stopXrayService(XrayOriginDatabaseRestore); errStop != nil {
logger.Warningf("Failed to stop Xray before DB import: %v", errStop)
}
if errClose := database.CloseDB(); errClose != nil {
- logger.Warningf("Failed to close existing DB before replacement: %v", errClose)
+ keepMaintenance, xrayStopped = true, false
+ return fmt.Errorf("close database before replacement: %w", errClose)
}
// Registered after the xray-restart defer so it runs first (LIFO): every
@@ -1990,16 +2023,17 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err
// restart needs an open pool to build the xray config from it.
dbReopened := false
defer func() {
- if dbReopened {
+ if dbReopened || keepMaintenance {
return
}
- if errReopen := database.InitDB(config.GetDBPath()); errReopen != nil {
+ if errReopen := database.InitDB(livePath); errReopen != nil {
logger.Warningf("Failed to reopen the database after import error: %v", errReopen)
+ keepMaintenance, xrayStopped = true, false
}
}()
// Backup the current database for fallback
- fallbackPath := fmt.Sprintf("%s.backup", config.GetDBPath())
+ fallbackPath := livePath + ".backup"
// Remove the existing fallback file (if any)
if _, err := os.Stat(fallbackPath); err == nil {
@@ -2009,27 +2043,29 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err
}
// Move the current database to the fallback location
- if err = os.Rename(config.GetDBPath(), fallbackPath); err != nil {
+ if err = os.Rename(livePath, fallbackPath); err != nil {
return common.NewErrorf("Error backing up current db file: %v", err)
}
// Move temp to DB path
- if err = os.Rename(tempPath, config.GetDBPath()); err != nil {
+ if err = os.Rename(tempPath, livePath); err != nil {
// Restore from fallback
- if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
+ if errRename := os.Rename(fallbackPath, livePath); errRename != nil {
+ keepMaintenance, xrayStopped = true, false
return common.NewErrorf("Error moving db file and restoring fallback: %v", errRename)
}
return common.NewErrorf("Error moving db file: %v", err)
}
// Open & migrate new DB
- if err = database.InitDB(config.GetDBPath()); err != nil {
+ if err = database.InitDB(livePath); err != nil {
// A failed InitDB still holds the imported file open; close before the
// rename or Windows refuses to replace it.
if errClose := database.CloseDB(); errClose != nil {
logger.Warningf("Failed to close the imported DB before restoring fallback: %v", errClose)
}
- if errRename := os.Rename(fallbackPath, config.GetDBPath()); errRename != nil {
+ if errRename := os.Rename(fallbackPath, livePath); errRename != nil {
+ keepMaintenance, xrayStopped = true, false
return common.NewErrorf("Error migrating db and restoring fallback: %v", errRename)
}
return common.NewErrorf("Error migrating db: %v", err)
@@ -2038,8 +2074,22 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err
restoreHostBoundSettings(keptSettings)
- s.inboundService.MigrateDB()
+ if err := s.inboundService.MigrateDB(); err != nil {
+ rollbackErr := database.CloseDB()
+ if rollbackErr == nil {
+ rollbackErr = os.Rename(fallbackPath, livePath)
+ }
+ if rollbackErr != nil {
+ keepMaintenance, xrayStopped = true, false
+ return common.NewErrorf("Inbound migration failed: %v; restoring the original database also failed: %v", err, rollbackErr)
+ }
+ dbReopened = false
+ return common.NewErrorf("Inbound migration failed and the original database was restored: %v", err)
+ }
+ if err := releaseRestore(); err != nil {
+ return err
+ }
xrayStopped = false
if err = s.restartXrayService(XrayOriginDatabaseRestore); err != nil {
return common.NewErrorf("Imported DB but failed to start Xray: %v; the previous database was kept at %s", err, fallbackPath)
@@ -2103,7 +2153,8 @@ func (s *ServerService) exportPostgresDB() ([]byte, error) {
}
ctx, cancel := context.WithTimeout(context.Background(), pgDumpTimeout)
defer cancel()
- cmd := exec.CommandContext(ctx, bin, "--format=custom", "--no-owner", "--no-privileges", "--dbname", dbname)
+ cmd := exec.CommandContext(ctx, bin, "--format=custom", "--no-owner", "--no-privileges",
+ "--exclude-schema="+database.PostgresMaintenanceSchema, "--dbname", dbname)
cmd.Env = env
// Stop waiting for the output pipes shortly after pg_dump is killed.
cmd.WaitDelay = 10 * time.Second
@@ -2131,15 +2182,18 @@ var pgArchiveVersionIntroducedIn = map[string]int{
// checkPgRestoreCanRead probes the dump with pg_restore --list (reads only the
// TOC, no database connection) so an unreadable file fails before Xray is stopped.
-func checkPgRestoreCanRead(bin, dumpPath string) error {
- cmd := exec.CommandContext(context.Background(), bin, "--list", dumpPath)
+func checkPgRestoreCanRead(ctx context.Context, bin, dumpPath string) error {
+ cmd := exec.CommandContext(ctx, bin, "--list", dumpPath)
cmd.Stdout = io.Discard
var stderr bytes.Buffer
cmd.Stderr = &stderr
if cmd.Run() == nil {
return nil
}
- return pgRestoreReadFailureError(strings.TrimSpace(stderr.String()), pgRestoreVersion(bin))
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ return pgRestoreReadFailureError(strings.TrimSpace(stderr.String()), pgRestoreVersion(ctx, bin))
}
func pgRestoreReadFailureError(probeOutput, localVersion string) error {
@@ -2156,8 +2210,8 @@ func pgRestoreReadFailureError(probeOutput, localVersion string) error {
return common.NewErrorf("This backup was created by a newer pg_dump than the server's pg_restore (version %s) can read; upgrade the postgresql-client package and retry the import", localVersion)
}
-func pgRestoreVersion(bin string) string {
- out, err := exec.CommandContext(context.Background(), bin, "--version").Output()
+func pgRestoreVersion(ctx context.Context, bin string) string {
+ out, err := exec.CommandContext(ctx, bin, "--version").Output()
if err != nil {
return ""
}
@@ -2168,6 +2222,40 @@ func parsePgToolVersion(versionOutput string) string {
return pgToolVersionPattern.FindString(versionOutput)
}
+func supportsRestrictedPgRestore(version string) bool {
+ majorText, minorText, _ := strings.Cut(version, ".")
+ major, majorErr := strconv.Atoi(majorText)
+ minor, minorErr := strconv.Atoi(minorText)
+ if majorErr != nil || minorErr != nil {
+ return false
+ }
+ // Plain-format archive execution needs the corrected psql restricted mode.
+ // https://www.postgresql.org/support/security/CVE-2026-18408/
+ minimum := map[int]int{14: 24, 15: 19, 16: 15, 17: 11, 18: 6}
+ required, known := minimum[major]
+ return major > 18 || (known && minor >= required)
+}
+
+func checkRestrictedRestoreSQL(path string) error {
+ file, err := os.Open(path)
+ if err != nil {
+ return err
+ }
+ defer file.Close()
+ scanner := bufio.NewScanner(io.LimitReader(file, 8<<10))
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" || strings.HasPrefix(line, "--") {
+ continue
+ }
+ if strings.HasPrefix(line, `\restrict `) {
+ return nil
+ }
+ break
+ }
+ return errors.New("pg_restore did not produce a restricted SQL script")
+}
+
const (
importKindUnknown = iota
importKindPgDump
@@ -2203,14 +2291,19 @@ func sniffUploadKind(file multipart.File) (int, error) {
return sniffImportKind(header[:n]), nil
}
-func (s *ServerService) importPostgresDB(file multipart.File, keepHostSettings bool) error {
+var postgresImportMu sync.Mutex
+
+func (s *ServerService) importPostgresDB(ctx context.Context, file multipart.File, keepHostSettings bool) error {
+ postgresImportMu.Lock()
+ defer postgresImportMu.Unlock()
+
kind, err := sniffUploadKind(file)
if err != nil {
return common.NewErrorf("Error reading uploaded file: %v", err)
}
switch kind {
case importKindPgDump:
- return s.restorePostgresDump(file, keepHostSettings)
+ return s.restorePostgresDump(ctx, file, keepHostSettings)
case importKindSQLiteDB:
return s.migrateSQLiteIntoPostgres(file, false, keepHostSettings)
case importKindSQLiteDump:
@@ -2220,11 +2313,51 @@ func (s *ServerService) importPostgresDB(file multipart.File, keepHostSettings b
}
}
-func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSettings bool) error {
+func (s *ServerService) reopenPostgresAfterImport(lease *database.MaintenanceLease, imported bool, keptSettings hostBoundSnapshot) error {
+ var migrationErr error
+ err := lease.InitDB(config.GetDBPath(), func(db *gorm.DB) error {
+ if imported {
+ restoreHostBoundSettingsOn(db, keptSettings)
+ }
+ // Jobs and requests still see the closed pool. Another process may
+ // briefly hold locks, so retry only lock acquisition, before any writes.
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ migrationErr = s.inboundService.MigrateDBOn(db)
+ if !errors.Is(migrationErr, errInboundMigrationBusy) || time.Now().After(deadline) {
+ break
+ }
+ select {
+ case <-db.Statement.Context.Done():
+ return db.Statement.Context.Err()
+ case <-time.After(100 * time.Millisecond):
+ }
+ }
+ if migrationErr != nil {
+ return migrationErr
+ }
+ return database.ClearPostgresRestorePending(db)
+ })
+ if migrationErr != nil {
+ return fmt.Errorf("database data was imported, but inbound migration failed: %w", migrationErr)
+ }
+ if err != nil {
+ return fmt.Errorf("reopening PostgreSQL after import failed: %w", err)
+ }
+ return nil
+}
+
+func (s *ServerService) restorePostgresDump(ctx context.Context, file multipart.File, keepHostSettings bool) error {
+ prepare, cancelPrepare := context.WithTimeout(ctx, time.Hour)
+ defer cancelPrepare()
bin, err := exec.LookPath("pg_restore")
if err != nil {
return common.NewError("pg_restore not found on the server; install the postgresql-client package to restore a PostgreSQL database")
}
+ psql, err := exec.LookPath("psql")
+ if err != nil {
+ return common.NewError("psql not found on the server; install the postgresql-client package to restore a PostgreSQL database")
+ }
env, dbname, err := pgConnEnv(config.GetDBDSN())
if err != nil {
return common.NewErrorf("invalid PostgreSQL DSN: %v", err)
@@ -2244,19 +2377,52 @@ func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSetting
return common.NewErrorf("Error closing temporary dump file: %v", err)
}
- if err := checkPgRestoreCanRead(bin, tempPath); err != nil {
+ if err := checkPgRestoreCanRead(prepare, bin, tempPath); err != nil {
return err
}
+ for _, tool := range []string{bin, psql} {
+ if version := pgRestoreVersion(prepare, tool); !supportsRestrictedPgRestore(version) {
+ return fmt.Errorf("%s %s does not support safe restricted archive restore; update postgresql-client", filepath.Base(tool), version)
+ }
+ }
var keptSettings hostBoundSnapshot
if keepHostSettings {
keptSettings = captureHostBoundSettings()
}
- if err := checkPgDumpRestoreListeners(bin, tempPath, keptSettings); err != nil {
+ if err := checkPgDumpRestoreListeners(prepare, bin, tempPath, keptSettings); err != nil {
+ return err
+ }
+ sqlFile, err := os.CreateTemp("", "x-ui-pg-restore-*.sql")
+ if err != nil {
+ return fmt.Errorf("stage PostgreSQL restore: %w", err)
+ }
+ defer os.Remove(sqlFile.Name())
+ if err := sqlFile.Close(); err != nil {
+ return err
+ }
+ // Render completely before opening a transaction. If archive decoding fails,
+ // no partly emitted SQL can reach the destination.
+ render := exec.CommandContext(prepare, bin, "--clean", "--if-exists", "--no-owner", "--no-privileges",
+ "--exclude-schema="+database.PostgresMaintenanceSchema, "--file", sqlFile.Name(), tempPath)
+ var stderr bytes.Buffer
+ render.Stderr = &stderr
+ if err := render.Run(); err != nil {
+ if contextErr := prepare.Err(); contextErr != nil {
+ return fmt.Errorf("render PostgreSQL restore: %w", contextErr)
+ }
+ return fmt.Errorf("render PostgreSQL restore: %w: %s", err, strings.TrimSpace(stderr.String()))
+ }
+ if err := checkRestrictedRestoreSQL(sqlFile.Name()); err != nil {
+ return err
+ }
+ if err := prepare.Err(); err != nil {
return err
}
- xrayStopped := true
+ // Once mutation starts, finish recovery under the database lease even if
+ // the HTTP client disconnects.
+ xrayStopped := false
defer func() {
if xrayStopped {
if errR := s.restartXrayService(XrayOriginDatabaseRestore); errR != nil {
@@ -2264,34 +2430,56 @@ func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSetting
}
}
}()
+ lease, releaseRestore, err := beginDatabaseRestore()
+ if err != nil {
+ return err
+ }
+ keepMaintenance := false
+ defer func() {
+ if !keepMaintenance {
+ if err := releaseRestore(); err != nil {
+ xrayStopped = false
+ logger.Warning("release database restore lock:", err)
+ }
+ }
+ }()
+ if err := lease.WithPostgresWork(database.GetDB(), database.MarkPostgresRestorePending); err != nil {
+ return fmt.Errorf("persist PostgreSQL restore marker: %w", err)
+ }
+ xrayStopped = true
if errStop := s.stopXrayService(XrayOriginDatabaseRestore); errStop != nil {
logger.Warningf("Failed to stop Xray before DB restore: %v", errStop)
}
if errClose := database.CloseDB(); errClose != nil {
- logger.Warningf("Failed to close existing DB before restore: %v", errClose)
+ keepMaintenance, xrayStopped = true, false
+ return fmt.Errorf("close database before restore: %w", errClose)
}
- cmd := exec.CommandContext(context.Background(), bin,
- "--clean", "--if-exists", "--no-owner", "--no-privileges",
- "--single-transaction", "--dbname", dbname, tempPath,
- )
+ fence, err := lease.PostgresFence()
+ if err != nil {
+ keepMaintenance, xrayStopped = true, false
+ return err
+ }
+ cmd := exec.CommandContext(fence.Context, psql, "--no-psqlrc", "--quiet",
+ "--single-transaction", "--set=ON_ERROR_STOP=1", "--dbname", dbname,
+ "--command", fence.TransactionFenceSQL(), "--file", sqlFile.Name())
cmd.Env = env
- var stderr bytes.Buffer
+ stderr.Reset()
cmd.Stderr = &stderr
runErr := cmd.Run()
- if errInit := database.InitDB(config.GetDBPath()); errInit != nil {
- return common.NewErrorf("Restore finished but reopening the database failed: %v", errInit)
+ if err := s.reopenPostgresAfterImport(lease, runErr == nil, keptSettings); err != nil {
+ keepMaintenance, xrayStopped = true, false
+ return err
}
- restoreHostBoundSettings(keptSettings)
-
- s.inboundService.MigrateDB()
if runErr != nil {
- return common.NewErrorf("pg_restore failed (database left unchanged): %v: %s", runErr, strings.TrimSpace(stderr.String()))
+ return common.NewErrorf("PostgreSQL restore failed: %v: %s", runErr, strings.TrimSpace(stderr.String()))
+ }
+ if err := releaseRestore(); err != nil {
+ return err
}
-
xrayStopped = false
if err := s.restartXrayService(XrayOriginDatabaseRestore); err != nil {
return common.NewErrorf("Restored DB but failed to start Xray: %v", err)
@@ -2336,7 +2524,7 @@ func (s *ServerService) migrateSQLiteIntoPostgres(file multipart.File, isSQLDump
return err
}
- xrayStopped := true
+ xrayStopped := false
defer func() {
if xrayStopped {
if errR := s.restartXrayService(XrayOriginDatabaseRestore); errR != nil {
@@ -2344,28 +2532,44 @@ func (s *ServerService) migrateSQLiteIntoPostgres(file multipart.File, isSQLDump
}
}
}()
+ lease, releaseRestore, err := beginDatabaseRestore()
+ if err != nil {
+ return err
+ }
+ keepMaintenance := false
+ defer func() {
+ if !keepMaintenance {
+ if err := releaseRestore(); err != nil {
+ xrayStopped = false
+ logger.Warning("release database restore lock:", err)
+ }
+ }
+ }()
+ if err := lease.WithPostgresWork(database.GetDB(), database.MarkPostgresRestorePending); err != nil {
+ return fmt.Errorf("persist PostgreSQL restore marker: %w", err)
+ }
+ xrayStopped = true
if errStop := s.stopXrayService(XrayOriginDatabaseRestore); errStop != nil {
logger.Warningf("Failed to stop Xray before DB restore: %v", errStop)
}
if errClose := database.CloseDB(); errClose != nil {
- logger.Warningf("Failed to close existing DB before restore: %v", errClose)
+ keepMaintenance, xrayStopped = true, false
+ return fmt.Errorf("close database before restore: %w", errClose)
}
- migrateErr := database.MigrateData(dbPath, config.GetDBDSN())
+ migrateErr := lease.RestoreSQLiteData(dbPath, config.GetDBDSN())
- if errInit := database.InitDB(config.GetDBPath()); errInit != nil {
- return common.NewErrorf("Restore finished but reopening the database failed: %v", errInit)
+ if err := s.reopenPostgresAfterImport(lease, migrateErr == nil, keptSettings); err != nil {
+ keepMaintenance, xrayStopped = true, false
+ return err
}
- if migrateErr == nil {
- restoreHostBoundSettings(keptSettings)
- }
- s.inboundService.MigrateDB()
-
if migrateErr != nil {
return common.NewErrorf("Importing the SQLite data into PostgreSQL failed: %v; the import runs in a single transaction, so the database was left unchanged", migrateErr)
}
-
+ if err := releaseRestore(); err != nil {
+ return err
+ }
xrayStopped = false
if err := s.restartXrayService(XrayOriginDatabaseRestore); err != nil {
return common.NewErrorf("Restored DB but failed to start Xray: %v", err)
@@ -2443,8 +2647,8 @@ type geofileEntry struct {
var geofileAllowlist = map[string]geofileEntry{
"geoip.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat", "geoip.dat", "geoip.dat"},
"geosite.dat": {"https://github.com/Loyalsoldier/v2ray-rules-dat", "geosite.dat", "geosite.dat"},
- "geoip_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules", "geoip.dat", "geoip_IR.dat"},
- "geosite_IR.dat": {"https://github.com/chocolate4u/Iran-v2ray-rules", "geosite.dat", "geosite_IR.dat"},
+ "geoip_IR.dat": {"https://github.com/FDeghy/Iran-v2ray-rules", "geoip.dat", "geoip_IR.dat"},
+ "geosite_IR.dat": {"https://github.com/FDeghy/Iran-v2ray-rules", "geosite.dat", "geosite_IR.dat"},
"geoip_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat", "geoip.dat", "geoip_RU.dat"},
"geosite_RU.dat": {"https://github.com/runetfreedom/russia-v2ray-rules-dat", "geosite.dat", "geosite_RU.dat"},
}
diff --git a/internal/web/service/server_geofile_test.go b/internal/web/service/server_geofile_test.go
index 2b58778cb..2b32c6e85 100644
--- a/internal/web/service/server_geofile_test.go
+++ b/internal/web/service/server_geofile_test.go
@@ -15,7 +15,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
)
-// Loyalsoldier and runetfreedom write " geoip.dat"; chocolate4u writes
+// Loyalsoldier and runetfreedom write " geoip.dat"; FDeghy writes
// " release/geoip.dat", the path from its own build.
func TestParseGeofileDigest(t *testing.T) {
const digest = "0d5d2ba0c5a5c58027fd1347a6afd57c9470799b6bb3cbc274fd4657ed8de382"
@@ -393,10 +393,10 @@ func TestUpdateGeofileRejectsNameOutsideAllowlist(t *testing.T) {
func TestStandardGeodataSources(t *testing.T) {
want := []GeodataSource{
{URL: "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat", File: "geoip.dat"},
- {URL: "https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat", File: "geoip_IR.dat"},
+ {URL: "https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geoip.dat", File: "geoip_IR.dat"},
{URL: "https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat", File: "geoip_RU.dat"},
{URL: "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat", File: "geosite.dat"},
- {URL: "https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat", File: "geosite_IR.dat"},
+ {URL: "https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geosite.dat", File: "geosite_IR.dat"},
{URL: "https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat", File: "geosite_RU.dat"},
}
diff --git a/internal/web/service/server_scope_test.go b/internal/web/service/server_scope_test.go
index fb4ed7c66..1e57111c9 100644
--- a/internal/web/service/server_scope_test.go
+++ b/internal/web/service/server_scope_test.go
@@ -51,7 +51,7 @@ func TestContainerStatusOnlyOverridesCPUSwapAndUptime(t *testing.T) {
if got.ResourceScope != "container" || got.CpuCores != 2 || got.LogicalPro != 2 || got.CpuSpeedMhz != 0 || got.Swap.Total != 512<<20 || got.Swap.Current != 19357696 || got.Uptime != 52624 {
t.Fatalf("incorrect corrected resources: %+v", got)
}
- if got.Mem.Total != 2<<30 || got.Mem.Current != 128<<20 || !reflect.DeepEqual(got.Loads, []float64{1.25, 2.5, 3.75}) || got.DiskTraffic.Read != 1024 || got.DiskTraffic.Write != 2048 || got.DiskIO.Read == 0 || got.DiskIO.Write == 0 {
+ if got.Mem.Total != 2<<30 || got.Mem.Current != 128<<20 || got.Mem.Available == nil || *got.Mem.Available != 1966080<<10 || !reflect.DeepEqual(got.Loads, []float64{1.25, 2.5, 3.75}) || got.DiskTraffic.Read != 1024 || got.DiskTraffic.Write != 2048 || got.DiskIO.Read == 0 || got.DiskIO.Write == 0 {
t.Fatalf("unrelated metric path changed: %+v", got)
}
if !slices.Equal(got.UnavailableMetrics, []string{"cpu"}) {
@@ -74,7 +74,7 @@ func TestContainerStatusOnlyOverridesCPUSwapAndUptime(t *testing.T) {
t.Fatal(err)
}
native := svc.GetStatus(previous)
- if native.ResourceScope != "" || len(native.UnavailableMetrics) != 0 || native.CpuSpeedMhz != 5000 || native.Mem != got.Mem || !reflect.DeepEqual(native.Loads, got.Loads) || native.DiskTraffic != got.DiskTraffic {
+ if native.ResourceScope != "" || len(native.UnavailableMetrics) != 0 || native.CpuSpeedMhz != 5000 || !reflect.DeepEqual(native.Mem, got.Mem) || !reflect.DeepEqual(native.Loads, got.Loads) || native.DiskTraffic != got.DiskTraffic {
t.Fatalf("native regression: %+v", native)
}
}
diff --git a/internal/web/service/setting.go b/internal/web/service/setting.go
index f801e920e..ce09ba5ad 100644
--- a/internal/web/service/setting.go
+++ b/internal/web/service/setting.go
@@ -465,8 +465,12 @@ func (s *SettingService) getSetting(key string) (*model.Setting, error) {
}
func (s *SettingService) saveSetting(key string, value string) error {
- setting, err := s.getSetting(key)
- db := database.GetDB()
+ return saveSettingOn(database.GetDB(), key, value)
+}
+
+func saveSettingOn(db *gorm.DB, key string, value string) error {
+ var setting model.Setting
+ err := db.Where("key = ?", key).First(&setting).Error
if database.IsNotFound(err) {
return db.Create(&model.Setting{
Key: key,
@@ -477,7 +481,7 @@ func (s *SettingService) saveSetting(key string, value string) error {
}
setting.Key = key
setting.Value = value
- return db.Save(setting).Error
+ return db.Save(&setting).Error
}
func (s *SettingService) getString(key string) (string, error) {
@@ -2123,6 +2127,42 @@ func (s *SettingService) BuildSubURIBase(host string) string {
return fmt.Sprintf("%s://%s:%d", scheme, subDomain, subPort)
}
+type PanelSubscriptionLinks struct {
+ Enable bool
+ JSONEnable bool
+ URI string
+ JSONURI string
+}
+
+func (s *SettingService) GetPanelSubscriptionLinks(host string) (PanelSubscriptionLinks, error) {
+ var links PanelSubscriptionLinks
+ var err error
+ if links.Enable, err = s.GetSubEnable(); err != nil {
+ return links, err
+ }
+ if links.JSONEnable, err = s.GetSubJsonEnable(); err != nil {
+ return links, err
+ }
+ if links.URI, err = s.GetSubURI(); err != nil {
+ return links, err
+ }
+ if links.JSONURI, err = s.GetSubJsonURI(); err != nil {
+ return links, err
+ }
+ if (links.Enable && links.URI == "") || (links.JSONEnable && links.JSONURI == "") {
+ base := s.BuildSubURIBase(host)
+ if links.Enable && links.URI == "" {
+ path, _ := s.GetSubPath()
+ links.URI = base + path
+ }
+ if links.JSONEnable && links.JSONURI == "" {
+ path, _ := s.GetSubJsonPath()
+ links.JSONURI = base + path
+ }
+ }
+ return links, nil
+}
+
func (s *SettingService) GetDefaultSettings(host string) (any, error) {
type settingFunc func() (any, error)
settings := map[string]settingFunc{
@@ -2134,12 +2174,8 @@ func (s *SettingService) GetDefaultSettings(host string) (any, error) {
"tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() },
"subThemeDir": func() (any, error) { return s.GetSubThemeDir() },
"happLinkEnable": func() (any, error) { return s.GetHappLinkEnable() },
- "subEnable": func() (any, error) { return s.GetSubEnable() },
- "subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() },
"subClashEnable": func() (any, error) { return s.GetSubClashEnable() },
"subTitle": func() (any, error) { return s.GetSubTitle() },
- "subURI": func() (any, error) { return s.GetSubURI() },
- "subJsonURI": func() (any, error) { return s.GetSubJsonURI() },
"subClashURI": func() (any, error) { return s.GetSubClashURI() },
"datepicker": func() (any, error) { return s.GetDatepicker() },
"ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() },
@@ -2160,39 +2196,18 @@ func (s *SettingService) GetDefaultSettings(host string) (any, error) {
result[key] = value
}
- subEnable := result["subEnable"].(bool)
- subJsonEnable := false
- if v, ok := result["subJsonEnable"]; ok {
- if b, ok2 := v.(bool); ok2 {
- subJsonEnable = b
- }
+ links, err := s.GetPanelSubscriptionLinks(host)
+ if err != nil {
+ return "", err
}
- subClashEnable := false
- if v, ok := result["subClashEnable"]; ok {
- if b, ok2 := v.(bool); ok2 {
- subClashEnable = b
- }
+ result["subEnable"] = links.Enable
+ result["subJsonEnable"] = links.JSONEnable
+ result["subURI"] = links.URI
+ result["subJsonURI"] = links.JSONURI
+ if result["subClashEnable"].(bool) && result["subClashURI"].(string) == "" {
+ path, _ := s.GetSubClashPath()
+ result["subClashURI"] = s.BuildSubURIBase(host) + path
}
- if (subEnable && result["subURI"].(string) == "") || (subJsonEnable && result["subJsonURI"].(string) == "") || (subClashEnable && result["subClashURI"].(string) == "") {
- subURI := s.BuildSubURIBase(host)
- subTitle, _ := s.GetSubTitle()
- subPath, _ := s.GetSubPath()
- subJsonPath, _ := s.GetSubJsonPath()
- subClashPath, _ := s.GetSubClashPath()
- if subEnable && result["subURI"].(string) == "" {
- result["subURI"] = subURI + subPath
- }
- if result["subTitle"].(string) == "" {
- result["subTitle"] = subTitle
- }
- if subJsonEnable && result["subJsonURI"].(string) == "" {
- result["subJsonURI"] = subURI + subJsonPath
- }
- if subClashEnable && result["subClashURI"].(string) == "" {
- result["subClashURI"] = subURI + subClashPath
- }
- }
-
return result, nil
}
diff --git a/internal/web/service/tgbot/tgbot_router.go b/internal/web/service/tgbot/tgbot_router.go
index 788793124..e578f313e 100644
--- a/internal/web/service/tgbot/tgbot_router.go
+++ b/internal/web/service/tgbot/tgbot_router.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
+ "github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mymmrac/telego"
th "github.com/mymmrac/telego/telegohandler"
@@ -28,6 +29,11 @@ func runBotHandler(fn func()) {
messageWorkerPool <- struct{}{}
defer func() { <-messageWorkerPool }()
defer recoverBotPanic()
+ end, ok := service.BeginDatabaseWork()
+ if !ok {
+ return
+ }
+ defer end()
fn()
}
@@ -94,6 +100,14 @@ func (t *Tgbot) OnReceive() {
registerTerminalCallbacks(cbHome, cbCatServer, cbCatClients, cbCatTraffic, cbCatMaintenance)
refuseGroups(h, t)
+ h.Use(func(ctx *th.Context, update telego.Update) error {
+ end, ok := service.BeginDatabaseWork()
+ if !ok {
+ return service.ErrDatabaseRestoring
+ }
+ defer end()
+ return ctx.Next(update)
+ })
// A picked inline item is the user's own message, caught before the wizard
// and broadcast handlers; the predicate must not match every ":" message.
diff --git a/internal/web/service/tgbot/tgbot_send_test.go b/internal/web/service/tgbot/tgbot_send_test.go
index b86391725..b71112ae8 100644
--- a/internal/web/service/tgbot/tgbot_send_test.go
+++ b/internal/web/service/tgbot/tgbot_send_test.go
@@ -11,7 +11,6 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/logger"
- "github.com/mymmrac/telego"
tu "github.com/mymmrac/telego/telegoutil"
"github.com/nicksnyder/go-i18n/v2/i18n"
)
@@ -55,13 +54,7 @@ func TestEditMessageTgBotSkipsNotModified(t *testing.T) {
defer mock.Close()
// Point the package-level bot at the mock.
- origBot := liveBot()
- t.Cleanup(func() { setTestBot(origBot) })
- var err error
- bot, err = telego.NewBot(testBotToken, telego.WithAPIServer(mock.URL))
- if err != nil {
- t.Fatalf("NewBot: %v", err)
- }
+ swapTestBot(t, mock.URL)
// Snapshot warning count before the edit call.
before := logger.GetLogs(100, "warning")
@@ -87,13 +80,7 @@ func TestEditMessageCallbackTgBotSkipsNotModified(t *testing.T) {
}))
defer mock.Close()
- origBot := liveBot()
- t.Cleanup(func() { setTestBot(origBot) })
- var err error
- bot, err = telego.NewBot(testBotToken, telego.WithAPIServer(mock.URL))
- if err != nil {
- t.Fatalf("NewBot: %v", err)
- }
+ swapTestBot(t, mock.URL)
before := logger.GetLogs(100, "warning")
diff --git a/internal/web/service/traffic_writer.go b/internal/web/service/traffic_writer.go
index 017fc8acf..f598aa890 100644
--- a/internal/web/service/traffic_writer.go
+++ b/internal/web/service/traffic_writer.go
@@ -175,6 +175,9 @@ func runSerializedTxThen(fn func(tx *gorm.DB) error, afterCommit func()) error {
return submitTrafficWrite(func() error {
state := &serializedTx{}
err := database.GetDB().Transaction(func(tx *gorm.DB) error {
+ if err := database.LockPostgresWriter(tx); err != nil {
+ return err
+ }
ctx := context.WithValue(tx.Statement.Context, serializedTxContextKey{}, state)
return fn(tx.WithContext(ctx))
})
@@ -233,6 +236,11 @@ func submitTrafficWriteBackground(fn func() error) error {
}
func submitTrafficWriteLane(fn func() error, background bool) error {
+ end, allowed := beginDatabaseWork(true)
+ if !allowed {
+ return ErrDatabaseRestoring
+ }
+ defer end()
req := &trafficWriteRequest{apply: fn, done: make(chan error, 1)}
twMu.Lock()
diff --git a/internal/web/service/tuic_relay_isolation_test.go b/internal/web/service/tuic_relay_isolation_test.go
index bc19cfc3c..f6caa4bdd 100644
--- a/internal/web/service/tuic_relay_isolation_test.go
+++ b/internal/web/service/tuic_relay_isolation_test.go
@@ -262,6 +262,9 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T)
dependent := ordinary
dependent.Tag = "dependent-ordinary"
dependent.Port = freeLoopbackPort(t)
+ for dependent.Port == ordinary.Port {
+ dependent.Port = freeLoopbackPort(t)
+ }
updatedSecond := isolationRelay(t, second.TuicInboundID, "new-second@test")
after.InboundConfigs = []xray.InboundConfig{before.InboundConfigs[0], next, updatedSecond, ordinary, dependent}
var policy map[string]any
@@ -278,6 +281,12 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T)
if applied, err := (&XrayService{}).tryHotApply(process, &after); applied || err == nil || !strings.Contains(err.Error(), "SOCKS5 bounds") {
t.Fatalf("failed rename result = %t, %v", applied, err)
}
+ // Reserve the deferred port before the relay probes start their own listeners.
+ reservation, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", dependent.Port))
+ if err != nil {
+ t.Fatalf("new inbound started before its dependent routing was applied: %v", err)
+ }
+ t.Cleanup(func() { _ = reservation.Close() })
assertIsolationRelay(t, previous, "original@test")
assertIsolationRelay(t, second, "old-second@test")
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
@@ -294,11 +303,6 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T)
t.Fatalf("new TUIC account escaped its deferred routing policy: %v", err)
}
assertIsolationRelay(t, ordinary, "other@test")
- reservation, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", dependent.Port))
- if err != nil {
- t.Fatalf("new inbound started before its dependent routing was applied: %v", err)
- }
- _ = reservation.Close()
route, err := api.TestRoute(xray.RouteTestRequest{InboundTag: next.Tag, IP: "203.0.113.1", Port: 6697})
if err != nil || route.Matched {
t.Fatalf("routing depending on an uninstalled relay was published: route=%+v err=%v", route, err)
@@ -306,6 +310,9 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T)
if string(process.GetConfig().RouterConfig) != string(before.RouterConfig) {
t.Fatal("snapshot recorded deferred routing as applied")
}
+ if err := reservation.Close(); err != nil {
+ t.Fatal(err)
+ }
after.InboundConfigs[1] = previous
after.InboundConfigs[1].Tag = next.Tag
if applied, err := (&XrayService{}).tryHotApply(process, &after); !applied || err != nil {
diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json
index dd6b04f5f..6412be3bc 100644
--- a/internal/web/translation/ar-EG.json
+++ b/internal/web/translation/ar-EG.json
@@ -381,6 +381,8 @@
"detachClientsResult": "فُصل {detached}، تم تخطي {skipped}.",
"detachClientsResultMixed": "فُصل {detached}، تخطي {skipped}، أخطاء {errors}.",
"detachClientsSelectLabel": "العملاء للفصل",
+ "detachSelectAll": "تحديد جميع العملاء المرتبطين",
+ "detachNodePending": "ستزامن العقدة هذه التغييرات.",
"exportLinksTitle": "تصدير روابط الإدخال",
"exportSubsTitle": "تصدير روابط الاشتراك",
"exportAllLinksTitle": "تصدير كل روابط الإدخالات",
@@ -812,6 +814,7 @@
"auth": "Auth",
"noKernelTun": "TUN بدون نواة",
"keepAlive": "Keep alive",
+ "exportAllPeers": "تصدير كل الأقران",
"peerNumber": "Peer {n}",
"peerNumberConfig": "تكوين Peer {n}"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "لا يوجد عملاء آخرون للإضافة.",
"addToGroupResult": "تمت إضافة {count} عميل إلى {name}.",
"removeFromGroup": "إزالة عملاء…",
+ "selectAllMatching": "تحديد كل العملاء المطابقين",
+ "selectionLimit": "الحد الأقصى للاختيارات أو الاستثناءات هو {count}.",
"removeFromGroupTitle": "إزالة عملاء من المجموعة «{name}»",
"removeFromGroupDesc": "اختر الأعضاء لإزالتهم من هذه المجموعة. يُحفظ العملاء (استخدم «حذف عملاء المجموعة» للإزالة الكاملة).",
"removeFromGroupResult": "تمت إزالة {count} عميل من {name}.",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "ستتم إعادة تشغيل لوحة العقدة وخدمات الاشتراك وقد تتوقف مؤقتًا. يتطلب رمز API بصلاحية node-admin أو admin على العقدة.",
"addNode": "إضافة نود",
"editNode": "تحرير العقدة",
- "totalNodes": "إجمالي النودز",
- "onlineNodes": "متصل",
- "offlineNodes": "غير متصل",
- "avgLatency": "متوسط الكمون",
"onlineOnNode": "{synced} متصل على الاتصالات الواردة المستوردة إلى هذه اللوحة، و{total} متصل على العقدة إجمالاً",
"name": "الاسم",
"namePlaceholder": "مثال: de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "رمز API",
"apiTokenPlaceholder": "التوكن من صفحة إعدادات البانل البعيد",
"apiTokenHint": "البانل البعيد بيعرض توكن API بتاعه في المصادقة → توكن API.",
- "apiTokenKeepHint": "اتركه فارغًا للإبقاء على التوكن الحالي",
+ "apiTokenKeepHint": "سيبقى التوكن الحالي ما لم تدخل توكنًا بديلاً.",
+ "apiTokenReplace": "استبدال توكن API",
"allowPrivateAddress": "السماح بالعنوان الخاص",
"allowPrivateAddressHint": "التفعيل فقط للعقد على شبكة خاصة أو VPN.",
"outboundTag": "اتصال صادر",
@@ -1279,6 +1281,38 @@
"subNodeTip": "للقراءة فقط: نود تابع يتم الوصول إليه عبر {parent}. تتم إدارته من لوحة {parent} نفسها.",
"deleteConfirmTitle": "تحذف النود \"{name}\"؟",
"deleteConfirmContent": "ده هيوقّف مراقبة النود. البانل البعيد نفسه مش هيتأثر.",
+ "fleet": {
+ "allNodes": "جميع العُقد",
+ "master": "الرئيسية",
+ "thisPanel": "هذه اللوحة",
+ "fleetScope": "الرئيسية + {remotes} عُقد بعيدة",
+ "reporting": "{live} من {total} ترسل بيانات",
+ "registered": "{remotes} عقدة بعيدة · {total} إجمالاً",
+ "allStatuses": "جميع الحالات",
+ "open": "فتح",
+ "hardware": "المعالج / الذاكرة",
+ "cpuAverage": "متوسط المعالج",
+ "logicalCores": "{cores} معالج منطقي",
+ "availableMemory": "{size} متاح",
+ "remainingMemory": "{size} متبقٍ",
+ "connections": "TCP / UDP / الحمل",
+ "load": "الحمل",
+ "loadSum": "مجموع الحمل",
+ "loadWindow": "حمل النظام على مدار ١ و٥ و١٥ دقيقة",
+ "hostMetrics": "تُجمع السرعات والاتصالات لكل مضيف.",
+ "runtime": "وقت التشغيل",
+ "mixed": "إصدارات متعددة",
+ "history": "السجل",
+ "node": "العقدة",
+ "searchNodes": "البحث عن العقد…",
+ "panel": "اللوحة",
+ "uptimeShort": "مدة العمل",
+ "uptimeVaries": "تختلف مدة العمل حسب العقدة",
+ "clientRecords": "{records} سجل عميل",
+ "acrossNodes": "عبر {total} عقدة",
+ "connectionDetails": "تفاصيل الاتصال",
+ "footnote": "تُجمع القيم من العقد التي ترسل بيانات ({coverage}). الحمل في ١ و٥ و١٥ دقيقة، ويُجمع عبر العقد المبلِّغة. مرّر المؤشر فوق الحالة لعرض آخر اتصال وزمن الاستجابة."
+ },
"statusValues": {
"online": "متصل",
"offline": "غير متصل",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "فيه سكريبت توجيه متظبط في {section}، عشان كده Xray بيتجاهل القواعد دي."
},
"hosts": {
+ "addressActions": {
+ "edit": "تعديل {address}",
+ "copy": "نسخ {address}",
+ "single": "أدخل عنوانًا واحدًا.",
+ "duplicate": "هذا العنوان موجود بالفعل في القائمة."
+ },
"addHost": "إضافة مضيف",
"editHost": "تعديل المضيف",
"selectInbound": "اختر وارداً",
diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json
index 5457d21d5..72b92d1b5 100644
--- a/internal/web/translation/en-US.json
+++ b/internal/web/translation/en-US.json
@@ -381,6 +381,8 @@
"detachClientsResult": "Detached {detached}, skipped {skipped}.",
"detachClientsResultMixed": "Detached {detached}, skipped {skipped}, errors {errors}.",
"detachClientsSelectLabel": "Clients to detach",
+ "detachSelectAll": "Select all attached clients",
+ "detachNodePending": "The node will sync these changes.",
"exportLinksTitle": "Export inbound links",
"exportSubsTitle": "Export subscription links",
"exportAllLinksTitle": "Export all inbound links",
@@ -813,6 +815,7 @@
"auth": "Auth",
"noKernelTun": "No-kernel TUN",
"keepAlive": "Keep alive",
+ "exportAllPeers": "Export all peers",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Peer {n} config"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "No other clients available to add.",
"addToGroupResult": "Added {count} client(s) to {name}.",
"removeFromGroup": "Remove clients…",
+ "selectAllMatching": "Select all matching clients",
+ "selectionLimit": "Limit selections or exclusions to {count}.",
"removeFromGroupTitle": "Remove clients from group \"{name}\"",
"removeFromGroupDesc": "Select members to remove from this group. Clients themselves are kept (use \"Delete clients in group\" to remove them entirely).",
"removeFromGroupResult": "Removed {count} client(s) from {name}.",
@@ -1211,6 +1216,12 @@
"hostRulesSaved": "Host rules updated for {name}."
},
"hosts": {
+ "addressActions": {
+ "edit": "Edit {address}",
+ "copy": "Copy {address}",
+ "single": "Enter one address.",
+ "duplicate": "This address is already in the list."
+ },
"addHost": "Add Host",
"editHost": "Edit Host",
"selectInbound": "Select an inbound",
@@ -1339,10 +1350,6 @@
"restartPanelContent": "The node panel and subscription services will restart and may be temporarily unavailable. Requires a node-admin or admin API token on the node.",
"addNode": "Add Node",
"editNode": "Edit Node",
- "totalNodes": "Total Nodes",
- "onlineNodes": "Online",
- "offlineNodes": "Offline",
- "avgLatency": "Avg Latency",
"onlineOnNode": "{synced} online on inbounds imported into this panel, {total} online on the node in total",
"name": "Name",
"namePlaceholder": "e.g. de-frankfurt-1",
@@ -1355,7 +1362,8 @@
"apiToken": "API Token",
"apiTokenPlaceholder": "Token from the remote panel's Settings page",
"apiTokenHint": "The remote panel exposes its API token under Authentication → API Token.",
- "apiTokenKeepHint": "Leave blank to keep the current token",
+ "apiTokenKeepHint": "The current token will be kept unless you enter a replacement.",
+ "apiTokenReplace": "Replace API Token",
"allowPrivateAddress": "Allow private address",
"allowPrivateAddressHint": "Enable only for nodes on a private network or VPN.",
"outboundTag": "Connection outbound",
@@ -1400,6 +1408,38 @@
"subNodeTip": "Read-only: a downstream node reached through {parent}. Manage it from {parent}'s own panel.",
"deleteConfirmTitle": "Delete node \"{name}\"?",
"deleteConfirmContent": "This stops monitoring the node. The remote panel itself is unaffected.",
+ "fleet": {
+ "allNodes": "All nodes",
+ "master": "Master",
+ "thisPanel": "This panel",
+ "fleetScope": "Master + {remotes} remote nodes",
+ "reporting": "{live}/{total} reporting",
+ "registered": "{remotes} remote nodes · {total} total",
+ "allStatuses": "All statuses",
+ "open": "Open",
+ "hardware": "CPU / RAM",
+ "cpuAverage": "Avg CPU",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "{size} available",
+ "remainingMemory": "{size} remaining",
+ "connections": "TCP / UDP / Load",
+ "load": "Load",
+ "loadSum": "Load sum",
+ "loadWindow": "System load over 1, 5 and 15 minutes",
+ "hostMetrics": "Rates and connections are summed per host.",
+ "runtime": "Runtime",
+ "mixed": "Versions vary",
+ "history": "History",
+ "node": "Node",
+ "searchNodes": "Search nodes…",
+ "panel": "Panel",
+ "uptimeShort": "Up",
+ "uptimeVaries": "Uptime varies by node",
+ "clientRecords": "{records} client records",
+ "acrossNodes": "Across {total} nodes",
+ "connectionDetails": "Connection details",
+ "footnote": "Fleet totals use reporting nodes only ({coverage}). Load values are 1 / 5 / 15 min; fleet values sum the reporting nodes. Hover status for heartbeat and latency."
+ },
"statusValues": {
"online": "Online",
"offline": "Offline",
diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json
index f9591939d..0c8065bae 100644
--- a/internal/web/translation/es-ES.json
+++ b/internal/web/translation/es-ES.json
@@ -381,6 +381,8 @@
"detachClientsResult": "Desasociados {detached}, omitidos {skipped}.",
"detachClientsResultMixed": "Desasociados {detached}, omitidos {skipped}, errores {errors}.",
"detachClientsSelectLabel": "Clientes para desasociar",
+ "detachSelectAll": "Seleccionar todos los clientes vinculados",
+ "detachNodePending": "El nodo sincronizará estos cambios.",
"exportLinksTitle": "Exportar enlaces del inbound",
"exportSubsTitle": "Exportar enlaces de suscripción",
"exportAllLinksTitle": "Exportar todos los enlaces de inbound",
@@ -812,6 +814,7 @@
"auth": "Auth",
"noKernelTun": "TUN sin kernel",
"keepAlive": "Keep alive",
+ "exportAllPeers": "Exportar todos los pares",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Config Peer {n}"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "No hay otros clientes disponibles para añadir.",
"addToGroupResult": "Añadidos {count} cliente(s) a {name}.",
"removeFromGroup": "Quitar clientes…",
+ "selectAllMatching": "Seleccionar todos los clientes coincidentes",
+ "selectionLimit": "Limita la selección o las exclusiones a {count}.",
"removeFromGroupTitle": "Quitar clientes del grupo «{name}»",
"removeFromGroupDesc": "Selecciona miembros para quitar de este grupo. Los clientes se conservan (usa «Eliminar clientes del grupo» para eliminarlos por completo).",
"removeFromGroupResult": "Quitados {count} cliente(s) de {name}.",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "El panel y los servicios de suscripción del nodo se reiniciarán y podrían dejar de estar disponibles temporalmente. Requiere un token API node-admin o admin en el nodo.",
"addNode": "Agregar nodo",
"editNode": "Editar nodo",
- "totalNodes": "Total de nodos",
- "onlineNodes": "En línea",
- "offlineNodes": "Sin conexión",
- "avgLatency": "Latencia media",
"onlineOnNode": "{synced} en línea en los inbounds importados a este panel, {total} en línea en total en el nodo",
"name": "Nombre",
"namePlaceholder": "p. ej. de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "Token API",
"apiTokenPlaceholder": "Token desde la página de Configuración del panel remoto",
"apiTokenHint": "El panel remoto expone su token de API en Configuraciones de Seguridad → Token de API.",
- "apiTokenKeepHint": "Déjalo en blanco para mantener el token actual",
+ "apiTokenKeepHint": "Se conservará el token actual si no introduces uno nuevo.",
+ "apiTokenReplace": "Reemplazar token de API",
"allowPrivateAddress": "Permitir dirección privada",
"allowPrivateAddressHint": "Habilitar solo para nodos en una red privada o VPN.",
"outboundTag": "Outbound de conexión",
@@ -1279,6 +1281,38 @@
"subNodeTip": "Solo lectura: un nodo descendente al que se llega a través de {parent}. Gestiónalo desde el propio panel de {parent}.",
"deleteConfirmTitle": "¿Eliminar el nodo \"{name}\"?",
"deleteConfirmContent": "Esto detiene la monitorización del nodo. El panel remoto en sí no se ve afectado.",
+ "fleet": {
+ "allNodes": "Todos los nodos",
+ "master": "Principal",
+ "thisPanel": "Este panel",
+ "fleetScope": "Principal + {remotes} nodos remotos",
+ "reporting": "{live}/{total} con datos",
+ "registered": "{remotes} remotos · {total} en total",
+ "allStatuses": "Todos los estados",
+ "open": "Abrir",
+ "hardware": "CPU / RAM",
+ "cpuAverage": "CPU media",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "{size} disponibles",
+ "remainingMemory": "{size} restantes",
+ "connections": "TCP / UDP / Carga",
+ "load": "Carga",
+ "loadSum": "Suma de cargas",
+ "loadWindow": "Carga del sistema en 1, 5 y 15 minutos",
+ "hostMetrics": "Las tasas y conexiones se suman por servidor.",
+ "runtime": "Ejecución",
+ "mixed": "Mixto",
+ "history": "Historial",
+ "node": "Nodo",
+ "searchNodes": "Buscar nodos…",
+ "panel": "Panel",
+ "uptimeShort": "Activo",
+ "uptimeVaries": "El tiempo activo varía por nodo",
+ "clientRecords": "{records} clientes registrados",
+ "acrossNodes": "En {total} nodos",
+ "connectionDetails": "Detalles de conexión",
+ "footnote": "Los totales usan los nodos que informan ({coverage}). Las cargas son de 1, 5 y 15 min y se suman entre nodos. Pasa el cursor por el estado para ver latencia y último contacto."
+ },
"statusValues": {
"online": "En línea",
"offline": "Sin conexión",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "Hay un script de enrutamiento definido en {section}, así que Xray ignora estas reglas."
},
"hosts": {
+ "addressActions": {
+ "edit": "Editar {address}",
+ "copy": "Copiar {address}",
+ "single": "Introduce una sola dirección.",
+ "duplicate": "Esta dirección ya está en la lista."
+ },
"addHost": "Agregar host",
"editHost": "Editar host",
"selectInbound": "Selecciona un inbound",
diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json
index 32b06d5fe..1f679f89c 100644
--- a/internal/web/translation/fa-IR.json
+++ b/internal/web/translation/fa-IR.json
@@ -381,6 +381,8 @@
"detachClientsResult": "جدا شد {detached}، نادیده {skipped}.",
"detachClientsResultMixed": "جدا شد {detached}، نادیده {skipped}، خطا {errors}.",
"detachClientsSelectLabel": "کاربران برای جداسازی",
+ "detachSelectAll": "انتخاب همهٔ کلاینتهای متصل",
+ "detachNodePending": "نود این تغییرات را همگامسازی میکند.",
"exportLinksTitle": "خروجی لینکهای اینباند",
"exportSubsTitle": "خروجی لینکهای ساب",
"exportAllLinksTitle": "خروجی لینکهای همه اینباندها",
@@ -812,6 +814,7 @@
"auth": "احراز",
"noKernelTun": "TUN غیرکرنل",
"keepAlive": "Keep alive",
+ "exportAllPeers": "خروجی همهٔ همتاها",
"peerNumber": "Peer {n}",
"peerNumberConfig": "پیکربندی Peer {n}"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "کاربر دیگری برای افزودن در دسترس نیست.",
"addToGroupResult": "{count} کاربر به {name} اضافه شد.",
"removeFromGroup": "حذف کاربران…",
+ "selectAllMatching": "انتخاب همهٔ کاربران مطابق جستجو",
+ "selectionLimit": "تعداد انتخابها یا استثناها را به {count} محدود کنید.",
"removeFromGroupTitle": "حذف کاربران از گروه «{name}»",
"removeFromGroupDesc": "اعضایی را برای حذف از این گروه انتخاب کنید. خود کاربران حفظ میشوند (برای حذف کامل از «حذف کاربران گروه» استفاده کنید).",
"removeFromGroupResult": "{count} کاربر از {name} حذف شد.",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "پنل و سرویس اشتراک نود مجدداً راهاندازی میشوند و ممکن است موقتاً در دسترس نباشند. توکن API نود باید دسترسی node-admin یا admin داشته باشد.",
"addNode": "افزودن نود",
"editNode": "ویرایش نود",
- "totalNodes": "کل نودها",
- "onlineNodes": "آنلاین",
- "offlineNodes": "آفلاین",
- "avgLatency": "میانگین تاخیر",
"onlineOnNode": "{synced} آنلاین روی اینباندهای واردشده به این پنل، {total} آنلاین در کل نود",
"name": "نام",
"namePlaceholder": "مثلاً de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "توکن API",
"apiTokenPlaceholder": "توکن از صفحه تنظیمات پنل ریموت",
"apiTokenHint": "پنل ریموت توکن API خودش را در بخش احرازهویت → توکن API نمایش میدهد.",
- "apiTokenKeepHint": "برای حفظ توکن فعلی خالی بگذارید",
+ "apiTokenKeepHint": "اگر توکن جایگزین وارد نکنید، توکن فعلی حفظ میشود.",
+ "apiTokenReplace": "جایگزینی توکن API",
"allowPrivateAddress": "اجازه آدرس خصوصی",
"allowPrivateAddressHint": "فقط برای نودهای روی شبکه خصوصی یا VPN فعال شود.",
"outboundTag": "خروجی اتصال",
@@ -1279,6 +1281,38 @@
"subNodeTip": "فقطخواندنی: یک نود پاییندستی که از طریق {parent} در دسترس است. آن را از پنل خودِ {parent} مدیریت کنید.",
"deleteConfirmTitle": "نود «{name}» حذف شود؟",
"deleteConfirmContent": "نظارت روی این نود متوقف میشود. خود پنل ریموت تغییری نمیکند.",
+ "fleet": {
+ "allNodes": "همهٔ نودها",
+ "master": "مستر",
+ "thisPanel": "این پنل",
+ "fleetScope": "مستر + {remotes} نود راه دور",
+ "reporting": "{live} از {total} در حال گزارش",
+ "registered": "{remotes} نود راه دور · {total} در مجموع",
+ "allStatuses": "همهٔ وضعیتها",
+ "open": "باز کردن",
+ "hardware": "پردازنده / حافظه",
+ "cpuAverage": "میانگین CPU",
+ "logicalCores": "{cores} پردازندهٔ منطقی",
+ "availableMemory": "{size} در دسترس",
+ "remainingMemory": "{size} باقیمانده",
+ "connections": "TCP / UDP / بار",
+ "load": "بار سیستم",
+ "loadSum": "مجموع بار",
+ "loadWindow": "بار سیستم در بازههای ۱، ۵ و ۱۵ دقیقه",
+ "hostMetrics": "نرخها و اتصالها به تفکیک میزبان جمع میشوند.",
+ "runtime": "زمان اجرا",
+ "mixed": "چند نسخه",
+ "history": "تاریخچه",
+ "node": "نود",
+ "searchNodes": "جستوجوی نودها…",
+ "panel": "پنل",
+ "uptimeShort": "زمان کار",
+ "uptimeVaries": "زمان کار به نود بستگی دارد",
+ "clientRecords": "{records} کلاینت ثبتشده",
+ "acrossNodes": "در {total} نود",
+ "connectionDetails": "جزئیات اتصال",
+ "footnote": "جمع کل از نودهای در حال گزارش محاسبه میشود ({coverage}). بار در بازههای ۱، ۵ و ۱۵ دقیقه نمایش داده میشود و در نمای کل، مجموع نودهای گزارشدهنده است. برای دیدن ضربان و تأخیر روی وضعیت مکث کنید."
+ },
"statusValues": {
"online": "آنلاین",
"offline": "آفلاین",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "یک اسکریپت مسیریابی در بخش {section} تنظیم شده است، بنابراین Xray این قوانین را نادیده میگیرد."
},
"hosts": {
+ "addressActions": {
+ "edit": "ویرایش {address}",
+ "copy": "کپی {address}",
+ "single": "فقط یک نشانی وارد کنید.",
+ "duplicate": "این نشانی از قبل در فهرست است."
+ },
"addHost": "افزودن میزبان",
"editHost": "ویرایش میزبان",
"selectInbound": "یک اینباند انتخاب کنید",
diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json
index e5f93b779..cfce7deff 100644
--- a/internal/web/translation/id-ID.json
+++ b/internal/web/translation/id-ID.json
@@ -381,6 +381,8 @@
"detachClientsResult": "Dilepas {detached}, dilewati {skipped}.",
"detachClientsResultMixed": "Dilepas {detached}, dilewati {skipped}, error {errors}.",
"detachClientsSelectLabel": "Klien untuk dilepas",
+ "detachSelectAll": "Pilih semua klien terpasang",
+ "detachNodePending": "Node akan menyinkronkan perubahan ini.",
"exportLinksTitle": "Ekspor tautan inbound",
"exportSubsTitle": "Ekspor tautan langganan",
"exportAllLinksTitle": "Ekspor semua tautan inbound",
@@ -812,6 +814,7 @@
"auth": "Auth",
"noKernelTun": "TUN tanpa kernel",
"keepAlive": "Keep alive",
+ "exportAllPeers": "Ekspor semua peer",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Konfig Peer {n}"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "Tidak ada klien lain untuk ditambahkan.",
"addToGroupResult": "{count} klien ditambahkan ke {name}.",
"removeFromGroup": "Hapus klien…",
+ "selectAllMatching": "Pilih semua klien yang cocok",
+ "selectionLimit": "Batasi pilihan atau pengecualian hingga {count}.",
"removeFromGroupTitle": "Hapus klien dari grup «{name}»",
"removeFromGroupDesc": "Pilih anggota untuk dihapus dari grup ini. Klien tetap dipertahankan (gunakan «Hapus klien di grup» untuk menghapus sepenuhnya).",
"removeFromGroupResult": "{count} klien dihapus dari {name}.",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "Panel node dan layanan langganan akan dimulai ulang dan mungkin tidak tersedia sementara. Memerlukan token API node-admin atau admin pada node.",
"addNode": "Tambah Node",
"editNode": "Edit node",
- "totalNodes": "Total Node",
- "onlineNodes": "Online",
- "offlineNodes": "Offline",
- "avgLatency": "Latensi Rata-rata",
"onlineOnNode": "{synced} online pada inbound yang diimpor ke panel ini, total {total} online di node",
"name": "Nama",
"namePlaceholder": "mis. de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "Token API",
"apiTokenPlaceholder": "Token dari halaman Pengaturan panel jarak jauh",
"apiTokenHint": "Panel jarak jauh menampilkan token API-nya di Otentikasi → Token API.",
- "apiTokenKeepHint": "Biarkan kosong untuk mempertahankan token saat ini",
+ "apiTokenKeepHint": "Token saat ini akan tetap digunakan jika Anda tidak memasukkan pengganti.",
+ "apiTokenReplace": "Ganti Token API",
"allowPrivateAddress": "Izinkan alamat pribadi",
"allowPrivateAddressHint": "Aktifkan hanya untuk node di jaringan pribadi atau VPN.",
"outboundTag": "Outbound koneksi",
@@ -1279,6 +1281,38 @@
"subNodeTip": "Hanya-baca: node turunan yang dijangkau melalui {parent}. Kelola dari panel {parent} sendiri.",
"deleteConfirmTitle": "Hapus node \"{name}\"?",
"deleteConfirmContent": "Ini menghentikan pemantauan node. Panel jarak jauh itu sendiri tidak terpengaruh.",
+ "fleet": {
+ "allNodes": "Semua node",
+ "master": "Utama",
+ "thisPanel": "Panel ini",
+ "fleetScope": "Utama + {remotes} node jarak jauh",
+ "reporting": "{live}/{total} melapor",
+ "registered": "{remotes} node jarak jauh · {total} total",
+ "allStatuses": "Semua status",
+ "open": "Buka",
+ "hardware": "CPU / RAM",
+ "cpuAverage": "Rata-rata CPU",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "{size} tersedia",
+ "remainingMemory": "{size} tersisa",
+ "connections": "TCP / UDP / Beban",
+ "load": "Beban",
+ "loadSum": "Total beban",
+ "loadWindow": "Beban sistem selama 1, 5, dan 15 menit",
+ "hostMetrics": "Laju dan koneksi dijumlahkan per host.",
+ "runtime": "Runtime",
+ "mixed": "Campuran",
+ "history": "Riwayat",
+ "node": "Node",
+ "searchNodes": "Cari node…",
+ "panel": "Panel",
+ "uptimeShort": "Aktif",
+ "uptimeVaries": "Waktu aktif berbeda menurut node",
+ "clientRecords": "{records} catatan klien",
+ "acrossNodes": "Di {total} node",
+ "connectionDetails": "Detail koneksi",
+ "footnote": "Total berasal dari node yang melapor ({coverage}). Beban 1, 5, dan 15 menit dijumlahkan antar node. Arahkan ke status untuk melihat heartbeat dan latensi."
+ },
"statusValues": {
"online": "Online",
"offline": "Offline",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "Skrip routing diatur di {section}, jadi Xray mengabaikan aturan ini."
},
"hosts": {
+ "addressActions": {
+ "edit": "Edit {address}",
+ "copy": "Salin {address}",
+ "single": "Masukkan satu alamat.",
+ "duplicate": "Alamat ini sudah ada dalam daftar."
+ },
"addHost": "Tambah Host",
"editHost": "Ubah Host",
"selectInbound": "Pilih sebuah inbound",
diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json
index b7980610e..cb3d0d30a 100644
--- a/internal/web/translation/ja-JP.json
+++ b/internal/web/translation/ja-JP.json
@@ -128,7 +128,7 @@
"openMenu": "メニューを開く",
"pinSidebar": "サイドバーを固定",
"unpinSidebar": "サイドバーの固定を解除",
- "subFormats": "Sub Formats",
+ "subFormats": "サブスクリプション形式",
"themeLight": "ライト",
"themeDark": "ダーク",
"themeUltraDark": "ウルトラダーク",
@@ -381,6 +381,8 @@
"detachClientsResult": "デタッチ {detached}、スキップ {skipped}。",
"detachClientsResultMixed": "デタッチ {detached}、スキップ {skipped}、エラー {errors}。",
"detachClientsSelectLabel": "デタッチするクライアント",
+ "detachSelectAll": "関連付けられたクライアントをすべて選択",
+ "detachNodePending": "ノードがこれらの変更を同期します。",
"exportLinksTitle": "インバウンドリンクのエクスポート",
"exportSubsTitle": "サブスクリプションリンクのエクスポート",
"exportAllLinksTitle": "全インバウンドリンクのエクスポート",
@@ -812,6 +814,7 @@
"auth": "Auth",
"noKernelTun": "非カーネル TUN",
"keepAlive": "Keep alive",
+ "exportAllPeers": "すべてのピアをエクスポート",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Peer {n} 設定"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "追加可能な他のクライアントはありません。",
"addToGroupResult": "{count} クライアントを {name} に追加しました。",
"removeFromGroup": "クライアントを削除…",
+ "selectAllMatching": "一致するクライアントをすべて選択",
+ "selectionLimit": "選択または除外は {count} 件までです。",
"removeFromGroupTitle": "グループ「{name}」からクライアントを削除",
"removeFromGroupDesc": "このグループから外すメンバーを選択してください。クライアント自体は保持されます (完全に削除するには「グループのクライアントを削除」を使用)。",
"removeFromGroupResult": "{count} クライアントを {name} から外しました。",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "ノードのパネルとサブスクリプションサービスを再起動するため、一時的に利用できなくなる場合があります。ノードのnode-adminまたはadmin APIトークンが必要です。",
"addNode": "ノードを追加",
"editNode": "ノード編集",
- "totalNodes": "ノード総数",
- "onlineNodes": "オンライン",
- "offlineNodes": "オフライン",
- "avgLatency": "平均レイテンシ",
"onlineOnNode": "このパネルにインポートしたインバウンドでオンライン: {synced}、ノード全体でオンライン: {total}",
"name": "名前",
"namePlaceholder": "例: de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "API トークン",
"apiTokenPlaceholder": "リモートパネルの設定ページから取得したトークン",
"apiTokenHint": "リモートパネルでは、セキュリティ設定 → APIトークン でAPIトークンを確認できます。",
- "apiTokenKeepHint": "現在のトークンを保持するには空欄のままにします",
+ "apiTokenKeepHint": "新しいトークンを入力しない限り、現在のトークンが使用されます。",
+ "apiTokenReplace": "APIトークンを置き換える",
"allowPrivateAddress": "プライベートアドレスを許可",
"allowPrivateAddressHint": "プライベートネットワークまたはVPN上のノードにのみ有効にします。",
"outboundTag": "接続アウトバウンド",
@@ -1279,6 +1281,38 @@
"subNodeTip": "読み取り専用: {parent} を経由して到達する下位ノードです。{parent} 自身のパネルから管理してください。",
"deleteConfirmTitle": "ノード「{name}」を削除しますか?",
"deleteConfirmContent": "ノードの監視を停止します。リモートパネル自体には影響しません。",
+ "fleet": {
+ "allNodes": "全ノード",
+ "master": "マスター",
+ "thisPanel": "このパネル",
+ "fleetScope": "マスターとリモート {remotes} 台",
+ "reporting": "{live}/{total} 台が報告中",
+ "registered": "リモート {remotes} 台 · 合計 {total} 台",
+ "allStatuses": "すべての状態",
+ "open": "開く",
+ "hardware": "CPU / RAM",
+ "cpuAverage": "平均 CPU",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "{size} 利用可能",
+ "remainingMemory": "{size} 残り",
+ "connections": "TCP / UDP / 負荷",
+ "load": "負荷",
+ "loadSum": "負荷合計",
+ "loadWindow": "1 分・5 分・15 分のシステム負荷",
+ "hostMetrics": "転送速度と接続数はホストごとの値を合計しています。",
+ "runtime": "実行環境",
+ "mixed": "混在",
+ "history": "履歴",
+ "node": "ノード",
+ "searchNodes": "ノードを検索…",
+ "panel": "パネル",
+ "uptimeShort": "稼働",
+ "uptimeVaries": "稼働時間はノードによって異なります",
+ "clientRecords": "クライアント登録数 {records}",
+ "acrossNodes": "{total} 台のノード",
+ "connectionDetails": "接続の詳細",
+ "footnote": "集計対象は報告中のノードです ({coverage})。1、5、15 分の負荷は報告中のノードの合計です。状態にカーソルを合わせると最終応答と遅延を確認できます。"
+ },
"statusValues": {
"online": "オンライン",
"offline": "オフライン",
@@ -1489,8 +1523,8 @@
"subClashEnableRoutingDesc": "生成されたYAMLサブスクリプションにClash/Mihomoのグローバルルーティングルールを含めます。",
"subClashRoutingRules": "グローバルルーティングルール",
"subClashRoutingRulesDesc": "ルール/YAML、または永続的な HTTPS URL を入力します。パネルはバックグラウンドで更新し、グループ・ルールプロバイダー・ルールのみを取り込み、生成済み VPN ノードと最後の有効値を保持します。",
- "subClashRemoteDNS": "Use DNS from remote rules",
- "subClashRemoteDNSDesc": "When the global routing rules field is a URL, also take its dns and sniffer sections. Enable only for a template you trust.",
+ "subClashRemoteDNS": "リモートルールの DNS を使用",
+ "subClashRemoteDNSDesc": "グローバルルーティングルールが URL の場合、その dns と sniffer セクションも取り込みます。信頼できるテンプレートでのみ有効にしてください。",
"subListen": "監視IP",
"subListenDesc": "サブスクリプションサービスが監視するIPアドレス(空白にするとすべてのIPを監視)",
"subPort": "監視ポート",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "{section} でルーティングスクリプトが設定されているため、Xray はこれらのルールを無視します。"
},
"hosts": {
+ "addressActions": {
+ "edit": "{address} を編集",
+ "copy": "{address} をコピー",
+ "single": "アドレスを1件入力してください。",
+ "duplicate": "このアドレスはすでに一覧にあります。"
+ },
"addHost": "ホストを追加",
"editHost": "ホストを編集",
"selectInbound": "インバウンドを選択",
diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json
index 94527b479..1e0010e2e 100644
--- a/internal/web/translation/pt-BR.json
+++ b/internal/web/translation/pt-BR.json
@@ -381,6 +381,8 @@
"detachClientsResult": "Desassociados {detached}, ignorados {skipped}.",
"detachClientsResultMixed": "Desassociados {detached}, ignorados {skipped}, erros {errors}.",
"detachClientsSelectLabel": "Clientes para desassociar",
+ "detachSelectAll": "Selecionar todos os clientes vinculados",
+ "detachNodePending": "O nó sincronizará estas alterações.",
"exportLinksTitle": "Exportar links do inbound",
"exportSubsTitle": "Exportar links de assinatura",
"exportAllLinksTitle": "Exportar todos os links de inbound",
@@ -812,6 +814,7 @@
"auth": "Auth",
"noKernelTun": "TUN sem kernel",
"keepAlive": "Keep alive",
+ "exportAllPeers": "Exportar todos os pares",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Config Peer {n}"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "Não há outros clientes disponíveis para adicionar.",
"addToGroupResult": "Adicionados {count} cliente(s) a {name}.",
"removeFromGroup": "Remover clientes…",
+ "selectAllMatching": "Selecionar todos os clientes correspondentes",
+ "selectionLimit": "Limite as seleções ou exclusões a {count}.",
"removeFromGroupTitle": "Remover clientes do grupo «{name}»",
"removeFromGroupDesc": "Selecione membros para remover deste grupo. Os clientes em si são mantidos (use «Excluir clientes do grupo» para removê-los por completo).",
"removeFromGroupResult": "Removidos {count} cliente(s) de {name}.",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "O painel e os serviços de assinatura do nó serão reiniciados e poderão ficar indisponíveis temporariamente. Requer um token de API node-admin ou admin no nó.",
"addNode": "Adicionar nó",
"editNode": "Editar nó",
- "totalNodes": "Total de nós",
- "onlineNodes": "Online",
- "offlineNodes": "Offline",
- "avgLatency": "Latência média",
"onlineOnNode": "{synced} online nos inbounds importados para este painel, {total} online no nó no total",
"name": "Nome",
"namePlaceholder": "ex.: de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "Token API",
"apiTokenPlaceholder": "Token da página de Configurações do painel remoto",
"apiTokenHint": "O painel remoto exibe o token da API em Autenticação → Token da API.",
- "apiTokenKeepHint": "Deixe em branco para manter o token atual",
+ "apiTokenKeepHint": "O token atual será mantido se você não informar um novo.",
+ "apiTokenReplace": "Substituir token da API",
"allowPrivateAddress": "Permitir endereço privado",
"allowPrivateAddressHint": "Ativar apenas para nós em uma rede privada ou VPN.",
"outboundTag": "Outbound de conexão",
@@ -1279,6 +1281,38 @@
"subNodeTip": "Somente leitura: um nó descendente acessado através de {parent}. Gerencie-o pelo próprio painel de {parent}.",
"deleteConfirmTitle": "Excluir o nó \"{name}\"?",
"deleteConfirmContent": "Isso interrompe o monitoramento do nó. O painel remoto em si não é afetado.",
+ "fleet": {
+ "allNodes": "Todos os nós",
+ "master": "Principal",
+ "thisPanel": "Este painel",
+ "fleetScope": "Principal + {remotes} nós remotos",
+ "reporting": "{live}/{total} enviando dados",
+ "registered": "{remotes} remotos · {total} no total",
+ "allStatuses": "Todos os estados",
+ "open": "Abrir",
+ "hardware": "CPU / RAM",
+ "cpuAverage": "CPU média",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "{size} disponíveis",
+ "remainingMemory": "{size} restantes",
+ "connections": "TCP / UDP / Carga",
+ "load": "Carga",
+ "loadSum": "Soma das cargas",
+ "loadWindow": "Carga do sistema em 1, 5 e 15 minutos",
+ "hostMetrics": "As taxas e conexões são somadas por host.",
+ "runtime": "Execução",
+ "mixed": "Misto",
+ "history": "Histórico",
+ "node": "Nó",
+ "searchNodes": "Pesquisar nós…",
+ "panel": "Painel",
+ "uptimeShort": "Ativo",
+ "uptimeVaries": "O tempo ativo varia por nó",
+ "clientRecords": "{records} clientes registrados",
+ "acrossNodes": "Em {total} nós",
+ "connectionDetails": "Detalhes da conexão",
+ "footnote": "Os totais usam os nós que enviam dados ({coverage}). As cargas de 1, 5 e 15 min são somadas. Passe o cursor pelo status para ver latência e último contato."
+ },
"statusValues": {
"online": "Online",
"offline": "Offline",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "Há um script de roteamento definido em {section}, então o Xray ignora estas regras."
},
"hosts": {
+ "addressActions": {
+ "edit": "Editar {address}",
+ "copy": "Copiar {address}",
+ "single": "Insira um único endereço.",
+ "duplicate": "Este endereço já está na lista."
+ },
"addHost": "Adicionar Host",
"editHost": "Editar Host",
"selectInbound": "Selecione uma entrada",
diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json
index 41e5e7bdd..b1d77f605 100644
--- a/internal/web/translation/ru-RU.json
+++ b/internal/web/translation/ru-RU.json
@@ -381,6 +381,8 @@
"detachClientsResult": "Отвязано {detached}, пропущено {skipped}.",
"detachClientsResultMixed": "Отвязано {detached}, пропущено {skipped}, ошибок {errors}.",
"detachClientsSelectLabel": "Клиенты для отвязки",
+ "detachSelectAll": "Выбрать всех привязанных клиентов",
+ "detachNodePending": "Узел синхронизирует эти изменения.",
"exportLinksTitle": "Экспортировать ссылки подключения",
"exportSubsTitle": "Экспортировать ссылки подписки",
"exportAllLinksTitle": "Экспортировать все ссылки подключений",
@@ -813,6 +815,7 @@
"auth": "Auth",
"noKernelTun": "TUN без kernel",
"keepAlive": "Keep alive",
+ "exportAllPeers": "Экспортировать все пиры",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Конфиг Peer {n}"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "Нет других клиентов для добавления.",
"addToGroupResult": "Добавлено {count} клиент(ов) в {name}.",
"removeFromGroup": "Удалить клиентов…",
+ "selectAllMatching": "Выбрать всех подходящих клиентов",
+ "selectionLimit": "Ограничьте число выбранных или исключённых клиентов до {count}.",
"removeFromGroupTitle": "Удалить клиентов из группы «{name}»",
"removeFromGroupDesc": "Выберите участников для удаления из этой группы. Сами клиенты сохраняются (используйте «Удалить клиентов группы» для полного удаления).",
"removeFromGroupResult": "Удалено {count} клиент(ов) из {name}.",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "Панель узла и службы подписки будут перезапущены и могут быть временно недоступны. Требуется API-токен node-admin или admin на узле.",
"addNode": "Добавить узел",
"editNode": "Изменить узел",
- "totalNodes": "Всего узлов",
- "onlineNodes": "В сети",
- "offlineNodes": "Не в сети",
- "avgLatency": "Средняя задержка",
"onlineOnNode": "В сети на инбаундах, импортированных в эту панель: {synced}; всего в сети на узле: {total}",
"name": "Имя",
"namePlaceholder": "напр. de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "API Токен",
"apiTokenPlaceholder": "Токен со страницы Настроек удалённой панели",
"apiTokenHint": "Удалённая панель показывает свой токен API в разделе Учетная запись → Токен API.",
- "apiTokenKeepHint": "Оставьте пустым, чтобы сохранить текущий токен",
+ "apiTokenKeepHint": "Текущий токен будет сохранён, если не ввести новый.",
+ "apiTokenReplace": "Заменить токен API",
"allowPrivateAddress": "Разрешить частный адрес",
"allowPrivateAddressHint": "Включить только для узлов в частной сети или VPN.",
"outboundTag": "Исходящее подключение",
@@ -1279,6 +1281,38 @@
"subNodeTip": "Только для чтения: подчинённый узел, доступный через {parent}. Управляйте им из собственной панели {parent}.",
"deleteConfirmTitle": "Удалить узел \"{name}\"?",
"deleteConfirmContent": "Это остановит мониторинг узла. Сама удалённая панель не будет затронута.",
+ "fleet": {
+ "allNodes": "Все узлы",
+ "master": "Главный",
+ "thisPanel": "Эта панель",
+ "fleetScope": "Главный + удалённых узлов: {remotes}",
+ "reporting": "Передают данные: {live}/{total}",
+ "registered": "Удалённых: {remotes} · Всего: {total}",
+ "allStatuses": "Все статусы",
+ "open": "Открыть",
+ "hardware": "ЦП / ОЗУ",
+ "cpuAverage": "Средняя загрузка ЦП",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "Доступно {size}",
+ "remainingMemory": "Осталось {size}",
+ "connections": "TCP / UDP / Нагрузка",
+ "load": "Нагрузка",
+ "loadSum": "Суммарная нагрузка",
+ "loadWindow": "Нагрузка системы за 1, 5 и 15 минут",
+ "hostMetrics": "Скорости и соединения суммируются по хостам.",
+ "runtime": "Среда выполнения",
+ "mixed": "Разные версии",
+ "history": "История",
+ "node": "Узел",
+ "searchNodes": "Поиск узлов…",
+ "panel": "Панель",
+ "uptimeShort": "Работа",
+ "uptimeVaries": "Время работы различается по узлам",
+ "clientRecords": "Клиентских записей: {records}",
+ "acrossNodes": "На {total} узлах",
+ "connectionDetails": "Сведения о подключении",
+ "footnote": "Итоги учитывают узлы, передающие данные ({coverage}). Нагрузка за 1, 5 и 15 минут суммируется. Наведите курсор на статус, чтобы увидеть задержку и последнюю проверку."
+ },
"statusValues": {
"online": "В сети",
"offline": "Не в сети",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "В разделе «{section}» задан скрипт маршрутизации, поэтому Xray игнорирует эти правила."
},
"hosts": {
+ "addressActions": {
+ "edit": "Редактировать {address}",
+ "copy": "Скопировать {address}",
+ "single": "Введите один адрес.",
+ "duplicate": "Этот адрес уже есть в списке."
+ },
"addHost": "Добавить хост",
"editHost": "Изменить хост",
"selectInbound": "Выберите входящее",
diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json
index 15c69af56..449338527 100644
--- a/internal/web/translation/sk-SK.json
+++ b/internal/web/translation/sk-SK.json
@@ -381,6 +381,8 @@
"detachClientsResult": "Odobraté: {detached}, preskočené: {skipped}.",
"detachClientsResultMixed": "Odobraté: {detached}, preskočené: {skipped}, chyby: {errors}.",
"detachClientsSelectLabel": "Klienti na odobratie",
+ "detachSelectAll": "Vybrať všetkých pripojených klientov",
+ "detachNodePending": "Uzol tieto zmeny zosynchronizuje.",
"exportLinksTitle": "Exportovať odkazy vstupu",
"exportSubsTitle": "Exportovať odkazy na odber",
"exportAllLinksTitle": "Exportovať odkazy všetkých vstupov",
@@ -813,6 +815,7 @@
"auth": "Overenie",
"noKernelTun": "TUN v používateľskom priestore",
"keepAlive": "Udržiavanie spojenia",
+ "exportAllPeers": "Exportovať všetky uzly",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Konfigurácia peeru {n}"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "Nie sú dostupní žiadni ďalší klienti na pridanie.",
"addToGroupResult": "Pridané do skupiny {name}: {count}.",
"removeFromGroup": "Odobrať klientov…",
+ "selectAllMatching": "Vybrať všetkých zodpovedajúcich klientov",
+ "selectionLimit": "Obmedzte počet vybraných alebo vylúčených klientov na {count}.",
"removeFromGroupTitle": "Odobrať klientov zo skupiny „{name}“",
"removeFromGroupDesc": "Vyberte členov, ktorých chcete odobrať zo skupiny. Samotní klienti zostanú zachovaní. Na ich úplné odstránenie použite akciu „Odstrániť klientov v skupine“.",
"removeFromGroupResult": "Odobraté zo skupiny {name}: {count}.",
@@ -1211,6 +1216,12 @@
"hostRulesSaved": "Host rules updated for {name}."
},
"hosts": {
+ "addressActions": {
+ "edit": "Upraviť {address}",
+ "copy": "Kopírovať {address}",
+ "single": "Zadajte jednu adresu.",
+ "duplicate": "Táto adresa už je v zozname."
+ },
"addHost": "Pridať adresu servera",
"editHost": "Upraviť adresu servera",
"selectInbound": "Vyberte vstup",
@@ -1339,10 +1350,6 @@
"restartPanelContent": "Panel uzla a služby odberov sa reštartujú a môžu byť dočasne nedostupné. Vyžaduje sa API token node-admin alebo admin na uzle.",
"addNode": "Pridať server",
"editNode": "Upraviť server",
- "totalNodes": "Počet serverov",
- "onlineNodes": "Online",
- "offlineNodes": "Offline",
- "avgLatency": "Priemerná odozva",
"onlineOnNode": "{synced} online na vstupoch importovaných do tohto panela, celkovo {total} online na uzle",
"name": "Názov",
"namePlaceholder": "napr. de-frankfurt-1",
@@ -1355,7 +1362,8 @@
"apiToken": "Token API",
"apiTokenPlaceholder": "Token zo stránky Nastavenia vzdialeného panelu",
"apiTokenHint": "Token API nájdete vo vzdialenom paneli v časti Overovanie → Token API.",
- "apiTokenKeepHint": "Prázdne pole ponechá aktuálny token",
+ "apiTokenKeepHint": "Aktuálny token sa zachová, ak nezadáte nový.",
+ "apiTokenReplace": "Nahradiť token API",
"allowPrivateAddress": "Povoliť súkromnú adresu",
"allowPrivateAddressHint": "Zapnite iba pri serveroch v súkromnej sieti alebo VPN.",
"outboundTag": "Výstup na pripojenie",
@@ -1400,6 +1408,38 @@
"subNodeTip": "Iba na čítanie: podriadený server dostupný cez {parent}. Spravujte ho z panelu servera {parent}.",
"deleteConfirmTitle": "Odstrániť server „{name}“?",
"deleteConfirmContent": "Prestane sa sledovať tento server. Samotný vzdialený panel sa nezmení.",
+ "fleet": {
+ "allNodes": "Všetky uzly",
+ "master": "Hlavný uzol",
+ "thisPanel": "Tento panel",
+ "fleetScope": "Hlavný uzol + {remotes} vzdialených uzlov",
+ "reporting": "{live}/{total} hlási údaje",
+ "registered": "{remotes} vzdialených · {total} spolu",
+ "allStatuses": "Všetky stavy",
+ "open": "Otvoriť",
+ "hardware": "CPU / RAM",
+ "cpuAverage": "Priemer CPU",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "{size} dostupných",
+ "remainingMemory": "{size} zostáva",
+ "connections": "TCP / UDP / Záťaž",
+ "load": "Záťaž",
+ "loadSum": "Súčet záťaže",
+ "loadWindow": "Systémová záťaž za 1, 5 a 15 minút",
+ "hostMetrics": "Rýchlosti a spojenia sa sčítavajú za jednotlivé hostitele.",
+ "runtime": "Beh",
+ "mixed": "Rôzne verzie",
+ "history": "História",
+ "node": "Uzol",
+ "searchNodes": "Vyhľadať uzly…",
+ "panel": "Panel",
+ "uptimeShort": "Beh",
+ "uptimeVaries": "Čas prevádzky sa líši podľa uzla",
+ "clientRecords": "{records} záznamov klientov",
+ "acrossNodes": "Na {total} uzloch",
+ "connectionDetails": "Podrobnosti pripojenia",
+ "footnote": "Súčty zahŕňajú uzly, ktoré hlásia údaje ({coverage}). Záťaž za 1, 5 a 15 minút sa sčítava. Pre posledný kontakt a odozvu ukážte na stav."
+ },
"statusValues": {
"online": "Online",
"offline": "Offline",
diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json
index b52fa0f09..894f6675e 100644
--- a/internal/web/translation/tr-TR.json
+++ b/internal/web/translation/tr-TR.json
@@ -381,6 +381,8 @@
"detachClientsResult": "Çözüldü {detached}, atlandı {skipped}.",
"detachClientsResultMixed": "Çözüldü {detached}, atlandı {skipped}, hatalar {errors}.",
"detachClientsSelectLabel": "Çözülecek Kullanıcılar",
+ "detachSelectAll": "Bağlı tüm istemcileri seç",
+ "detachNodePending": "Düğüm bu değişiklikleri eşitleyecek.",
"exportLinksTitle": "Gelen bağlantı bağlantılarını dışa aktar",
"exportSubsTitle": "Abonelik bağlantılarını dışa aktar",
"exportAllLinksTitle": "Tüm gelen bağlantı bağlantılarını dışa aktar",
@@ -812,6 +814,7 @@
"auth": "Auth",
"noKernelTun": "Çekirdeksiz TUN",
"keepAlive": "Canlı tut",
+ "exportAllPeers": "Tüm eşleri dışa aktar",
"peerNumber": "Eş {n}",
"peerNumberConfig": "Peer {n} Yapılandırması"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "Eklenecek başka kullanıcı yok.",
"addToGroupResult": "{count} kullanıcı {name} grubuna eklendi.",
"removeFromGroup": "Kullanıcı Çıkar…",
+ "selectAllMatching": "Eşleşen tüm istemcileri seç",
+ "selectionLimit": "Seçimleri veya hariç tutulanları {count} ile sınırlandırın.",
"removeFromGroupTitle": "«{name}» Grubundan Kullanıcı Çıkar",
"removeFromGroupDesc": "Bu gruptan çıkarılacak üyeleri seçin. Kullanıcılar korunur (tamamen kaldırmak için «Gruptaki kullanıcıları sil» kullanın).",
"removeFromGroupResult": "{name} grubundan {count} kullanıcı çıkarıldı.",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "Düğüm paneli ve abonelik hizmetleri yeniden başlatılacak ve geçici olarak kullanılamayabilir. Düğümde node-admin veya admin API belirteci gerekir.",
"addNode": "Düğüm Ekle",
"editNode": "Düğümü Düzenle",
- "totalNodes": "Toplam Düğüm",
- "onlineNodes": "Çevrimiçi",
- "offlineNodes": "Çevrimdışı",
- "avgLatency": "Ortalama Gecikme",
"onlineOnNode": "Bu panele içe aktarılan inbound'larda {synced} çevrimiçi, düğümde toplam {total} çevrimiçi",
"name": "Ad",
"namePlaceholder": "ör. de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "API Jetonu",
"apiTokenPlaceholder": "Uzak panelin Ayarlar sayfasındaki token",
"apiTokenHint": "Uzak panel API token'ını Kimlik Doğrulama → API Token altında gösterir.",
- "apiTokenKeepHint": "Mevcut token'ı korumak için boş bırakın",
+ "apiTokenKeepHint": "Yeni bir token girmezseniz mevcut token korunur.",
+ "apiTokenReplace": "API token’ını değiştir",
"allowPrivateAddress": "Özel Adrese İzin Ver",
"allowPrivateAddressHint": "Yalnızca özel ağ veya VPN üzerindeki düğümler için etkinleştirin.",
"outboundTag": "Bağlantı gideni",
@@ -1279,6 +1281,38 @@
"subNodeTip": "Salt okunur: {parent} üzerinden erişilen bir alt düğüm. Bunu {parent} panelinden yönetin.",
"deleteConfirmTitle": "\"{name}\" düğümü silinsin mi?",
"deleteConfirmContent": "Bu işlem düğüm izlemeyi durdurur. Uzak panelin kendisi etkilenmez.",
+ "fleet": {
+ "allNodes": "Tüm düğümler",
+ "master": "Ana düğüm",
+ "thisPanel": "Bu panel",
+ "fleetScope": "Ana düğüm + {remotes} uzak düğüm",
+ "reporting": "{live}/{total} veri gönderiyor",
+ "registered": "{remotes} uzak düğüm · {total} toplam",
+ "allStatuses": "Tüm durumlar",
+ "open": "Aç",
+ "hardware": "CPU / RAM",
+ "cpuAverage": "Ort. CPU",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "{size} kullanılabilir",
+ "remainingMemory": "{size} kalan",
+ "connections": "TCP / UDP / Yük",
+ "load": "Yük",
+ "loadSum": "Toplam yük",
+ "loadWindow": "1, 5 ve 15 dakikalık sistem yükü",
+ "hostMetrics": "Hızlar ve bağlantılar ana makine bazında toplanır.",
+ "runtime": "Çalışma zamanı",
+ "mixed": "Karma",
+ "history": "Geçmiş",
+ "node": "Düğüm",
+ "searchNodes": "Düğüm ara…",
+ "panel": "Panel",
+ "uptimeShort": "Çalışma",
+ "uptimeVaries": "Çalışma süresi düğüme göre değişir",
+ "clientRecords": "{records} istemci kaydı",
+ "acrossNodes": "{total} düğümde",
+ "connectionDetails": "Bağlantı ayrıntıları",
+ "footnote": "Toplamlara veri gönderen düğümler dahildir ({coverage}). 1, 5 ve 15 dakikalık yükler toplanır. Son sinyali ve gecikmeyi görmek için durumun üzerine gelin."
+ },
"statusValues": {
"online": "Çevrimiçi",
"offline": "Çevrimdışı",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "{section} bölümünde bir yönlendirme betiği ayarlı, bu yüzden Xray bu kuralları yok sayar."
},
"hosts": {
+ "addressActions": {
+ "edit": "{address} adresini düzenle",
+ "copy": "{address} adresini kopyala",
+ "single": "Tek bir adres girin.",
+ "duplicate": "Bu adres zaten listede."
+ },
"addHost": "Host Ekle",
"editHost": "Host'u Düzenle",
"selectInbound": "Bir gelen bağlantı seçin",
diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json
index 48082a511..ef0b2a56d 100644
--- a/internal/web/translation/uk-UA.json
+++ b/internal/web/translation/uk-UA.json
@@ -381,6 +381,8 @@
"detachClientsResult": "Від'єднано {detached}, пропущено {skipped}.",
"detachClientsResultMixed": "Від'єднано {detached}, пропущено {skipped}, помилок {errors}.",
"detachClientsSelectLabel": "Клієнти для від'єднання",
+ "detachSelectAll": "Вибрати всіх прив’язаних клієнтів",
+ "detachNodePending": "Вузол синхронізує ці зміни.",
"exportLinksTitle": "Експортувати посилання вхідних",
"exportSubsTitle": "Експортувати посилання підписок",
"exportAllLinksTitle": "Експортувати всі посилання вхідних",
@@ -812,6 +814,7 @@
"auth": "Auth",
"noKernelTun": "TUN без kernel",
"keepAlive": "Keep alive",
+ "exportAllPeers": "Експортувати всіх пірів",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Конфіг Peer {n}"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "Немає інших клієнтів для додавання.",
"addToGroupResult": "Додано {count} клієнт(ів) до {name}.",
"removeFromGroup": "Видалити клієнтів…",
+ "selectAllMatching": "Вибрати всіх відповідних клієнтів",
+ "selectionLimit": "Обмежте кількість вибраних або виключених клієнтів до {count}.",
"removeFromGroupTitle": "Видалити клієнтів з групи «{name}»",
"removeFromGroupDesc": "Виберіть учасників для видалення з цієї групи. Самі клієнти зберігаються (використовуйте «Видалити клієнтів групи» для повного видалення).",
"removeFromGroupResult": "Видалено {count} клієнт(ів) з {name}.",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "Панель вузла та служби підписки буде перезапущено, і вони можуть бути тимчасово недоступні. Потрібен API-токен node-admin або admin на вузлі.",
"addNode": "Додати вузол",
"editNode": "Змінити вузол",
- "totalNodes": "Усього вузлів",
- "onlineNodes": "У мережі",
- "offlineNodes": "Не в мережі",
- "avgLatency": "Середня затримка",
"onlineOnNode": "У мережі на інбаундах, імпортованих у цю панель: {synced}; усього в мережі на вузлі: {total}",
"name": "Назва",
"namePlaceholder": "напр. de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "API Токен",
"apiTokenPlaceholder": "Токен зі сторінки Налаштувань віддаленої панелі",
"apiTokenHint": "Віддалена панель показує свій токен API в Автентифікація → Токен API.",
- "apiTokenKeepHint": "Залиште порожнім, щоб зберегти поточний токен",
+ "apiTokenKeepHint": "Поточний токен буде збережено, якщо не ввести новий.",
+ "apiTokenReplace": "Замінити токен API",
"allowPrivateAddress": "Дозволити приватну адресу",
"allowPrivateAddressHint": "Увімкнути лише для вузлів у приватній мережі або VPN.",
"outboundTag": "Вихідне з'єднання",
@@ -1279,6 +1281,38 @@
"subNodeTip": "Лише для читання: підлеглий вузол, доступний через {parent}. Керуйте ним із власної панелі {parent}.",
"deleteConfirmTitle": "Видалити вузол \"{name}\"?",
"deleteConfirmContent": "Це зупинить моніторинг вузла. Сама віддалена панель не зазнає змін.",
+ "fleet": {
+ "allNodes": "Усі вузли",
+ "master": "Головний",
+ "thisPanel": "Ця панель",
+ "fleetScope": "Головний + віддалених вузлів: {remotes}",
+ "reporting": "Передають дані: {live}/{total}",
+ "registered": "Віддалених: {remotes} · Усього: {total}",
+ "allStatuses": "Усі стани",
+ "open": "Відкрити",
+ "hardware": "ЦП / ОЗП",
+ "cpuAverage": "Середнє ЦП",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "Доступно {size}",
+ "remainingMemory": "Залишилося {size}",
+ "connections": "TCP / UDP / Навантаження",
+ "load": "Навантаження",
+ "loadSum": "Сумарне навантаження",
+ "loadWindow": "Навантаження системи за 1, 5 та 15 хвилин",
+ "hostMetrics": "Швидкості та з’єднання підсумовуються за хостами.",
+ "runtime": "Середовище виконання",
+ "mixed": "Різні версії",
+ "history": "Історія",
+ "node": "Вузол",
+ "searchNodes": "Пошук вузлів…",
+ "panel": "Панель",
+ "uptimeShort": "Робота",
+ "uptimeVaries": "Час роботи залежить від вузла",
+ "clientRecords": "Записів клієнтів: {records}",
+ "acrossNodes": "На {total} вузлах",
+ "connectionDetails": "Відомості про з’єднання",
+ "footnote": "Підсумки враховують вузли, які передають дані ({coverage}). Навантаження за 1, 5 і 15 хвилин підсумовується. Наведіть курсор на стан для відомостей про затримку й останню перевірку."
+ },
"statusValues": {
"online": "У мережі",
"offline": "Не в мережі",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "У розділі «{section}» задано скрипт маршрутизації, тому Xray ігнорує ці правила."
},
"hosts": {
+ "addressActions": {
+ "edit": "Редагувати {address}",
+ "copy": "Копіювати {address}",
+ "single": "Введіть одну адресу.",
+ "duplicate": "Ця адреса вже є у списку."
+ },
"addHost": "Додати хост",
"editHost": "Редагувати хост",
"selectInbound": "Виберіть вхідний",
diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json
index a2a7060d0..aa6104833 100644
--- a/internal/web/translation/vi-VN.json
+++ b/internal/web/translation/vi-VN.json
@@ -381,6 +381,8 @@
"detachClientsResult": "Đã tách {detached}, bỏ qua {skipped}.",
"detachClientsResultMixed": "Đã tách {detached}, bỏ qua {skipped}, lỗi {errors}.",
"detachClientsSelectLabel": "Client để tách",
+ "detachSelectAll": "Chọn tất cả máy khách đã liên kết",
+ "detachNodePending": "Nút sẽ đồng bộ các thay đổi này.",
"exportLinksTitle": "Xuất liên kết inbound",
"exportSubsTitle": "Xuất liên kết đăng ký",
"exportAllLinksTitle": "Xuất tất cả liên kết inbound",
@@ -812,6 +814,7 @@
"auth": "Auth",
"noKernelTun": "TUN không kernel",
"keepAlive": "Keep alive",
+ "exportAllPeers": "Xuất tất cả các peer",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Cấu hình Peer {n}"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "Không có client khác để thêm.",
"addToGroupResult": "Đã thêm {count} client vào {name}.",
"removeFromGroup": "Xóa client…",
+ "selectAllMatching": "Chọn tất cả máy khách phù hợp",
+ "selectionLimit": "Giới hạn lựa chọn hoặc ngoại lệ ở mức {count}.",
"removeFromGroupTitle": "Xóa client khỏi nhóm «{name}»",
"removeFromGroupDesc": "Chọn thành viên để xóa khỏi nhóm này. Bản thân client được giữ lại (dùng «Xóa client trong nhóm» để xóa hoàn toàn).",
"removeFromGroupResult": "Đã xóa {count} client khỏi {name}.",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "Bảng điều khiển và dịch vụ đăng ký của nút sẽ khởi động lại và có thể tạm thời không khả dụng. Yêu cầu mã API node-admin hoặc admin trên nút.",
"addNode": "Thêm nút",
"editNode": "Sửa node",
- "totalNodes": "Tổng số nút",
- "onlineNodes": "Trực tuyến",
- "offlineNodes": "Ngoại tuyến",
- "avgLatency": "Độ trễ trung bình",
"onlineOnNode": "{synced} trực tuyến trên các inbound đã nhập vào bảng điều khiển này, tổng cộng {total} trực tuyến trên nút",
"name": "Tên",
"namePlaceholder": "vd: de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "Token API",
"apiTokenPlaceholder": "Token từ trang Cài đặt của panel từ xa",
"apiTokenHint": "Panel từ xa hiển thị token API tại Bảo mật → Token API.",
- "apiTokenKeepHint": "Để trống để giữ token hiện tại",
+ "apiTokenKeepHint": "Token hiện tại sẽ được giữ nếu bạn không nhập token thay thế.",
+ "apiTokenReplace": "Thay thế token API",
"allowPrivateAddress": "Cho phép địa chỉ riêng",
"allowPrivateAddressHint": "Chỉ bật cho các nút trên mạng riêng hoặc VPN.",
"outboundTag": "Outbound kết nối",
@@ -1279,6 +1281,38 @@
"subNodeTip": "Chỉ đọc: một nút phía dưới được kết nối qua {parent}. Quản lý nó từ bảng điều khiển của chính {parent}.",
"deleteConfirmTitle": "Xóa nút \"{name}\"?",
"deleteConfirmContent": "Việc này dừng giám sát nút. Panel từ xa không bị ảnh hưởng.",
+ "fleet": {
+ "allNodes": "Tất cả nút",
+ "master": "Nút chính",
+ "thisPanel": "Bảng điều khiển này",
+ "fleetScope": "Nút chính + {remotes} nút từ xa",
+ "reporting": "{live}/{total} đang báo cáo",
+ "registered": "{remotes} nút từ xa · {total} tổng cộng",
+ "allStatuses": "Mọi trạng thái",
+ "open": "Mở",
+ "hardware": "CPU / RAM",
+ "cpuAverage": "CPU trung bình",
+ "logicalCores": "{cores} vCPU",
+ "availableMemory": "{size} khả dụng",
+ "remainingMemory": "Còn lại {size}",
+ "connections": "TCP / UDP / Tải",
+ "load": "Tải",
+ "loadSum": "Tổng tải",
+ "loadWindow": "Tải hệ thống trong 1, 5 và 15 phút",
+ "hostMetrics": "Tốc độ và kết nối được cộng theo từng máy chủ.",
+ "runtime": "Môi trường chạy",
+ "mixed": "Nhiều phiên bản",
+ "history": "Lịch sử",
+ "node": "Nút",
+ "searchNodes": "Tìm nút…",
+ "panel": "Bảng điều khiển",
+ "uptimeShort": "Đã chạy",
+ "uptimeVaries": "Thời gian chạy tùy theo nút",
+ "clientRecords": "{records} hồ sơ máy khách",
+ "acrossNodes": "Trên {total} nút",
+ "connectionDetails": "Chi tiết kết nối",
+ "footnote": "Tổng chỉ tính các nút đang báo cáo ({coverage}). Tải 1, 5 và 15 phút được cộng trên các nút. Di chuột qua trạng thái để xem lần liên lạc cuối và độ trễ."
+ },
"statusValues": {
"online": "Trực tuyến",
"offline": "Ngoại tuyến",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "Một script định tuyến đã được đặt trong {section}, nên Xray bỏ qua các quy tắc này."
},
"hosts": {
+ "addressActions": {
+ "edit": "Sửa {address}",
+ "copy": "Sao chép {address}",
+ "single": "Nhập một địa chỉ.",
+ "duplicate": "Địa chỉ này đã có trong danh sách."
+ },
"addHost": "Thêm Host",
"editHost": "Sửa Host",
"selectInbound": "Chọn một inbound",
diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json
index fcb7b7535..d64d1a4ba 100644
--- a/internal/web/translation/zh-CN.json
+++ b/internal/web/translation/zh-CN.json
@@ -128,7 +128,7 @@
"openMenu": "打开菜单",
"pinSidebar": "固定侧边栏",
"unpinSidebar": "取消固定侧边栏",
- "subFormats": "Sub Formats",
+ "subFormats": "订阅格式",
"themeLight": "浅色",
"themeDark": "深色",
"themeUltraDark": "极致深色",
@@ -381,6 +381,8 @@
"detachClientsResult": "已分离 {detached},已跳过 {skipped}。",
"detachClientsResultMixed": "已分离 {detached},已跳过 {skipped},错误 {errors}。",
"detachClientsSelectLabel": "要分离的客户端",
+ "detachSelectAll": "选择所有已关联的客户端",
+ "detachNodePending": "节点将同步这些更改。",
"exportLinksTitle": "导出入站链接",
"exportSubsTitle": "导出订阅链接",
"exportAllLinksTitle": "导出所有入站链接",
@@ -812,6 +814,7 @@
"auth": "认证",
"noKernelTun": "非内核 TUN",
"keepAlive": "Keep alive",
+ "exportAllPeers": "导出所有对等端",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Peer {n} 配置"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "没有其他可添加的客户端。",
"addToGroupResult": "已将 {count} 个客户端添加到 {name}。",
"removeFromGroup": "移除客户端…",
+ "selectAllMatching": "选择所有匹配的客户端",
+ "selectionLimit": "选择或排除的项目最多为 {count} 个。",
"removeFromGroupTitle": "从分组 “{name}” 移除客户端",
"removeFromGroupDesc": "选择要从此分组中移除的成员。客户端本身保留(使用 “删除分组中的客户端” 完全移除)。",
"removeFromGroupResult": "已从 {name} 移除 {count} 个客户端。",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "节点面板和订阅服务将重启,并可能暂时不可用。需要节点上的 node-admin 或 admin API 令牌。",
"addNode": "添加节点",
"editNode": "编辑节点",
- "totalNodes": "节点总数",
- "onlineNodes": "在线",
- "offlineNodes": "离线",
- "avgLatency": "平均延迟",
"onlineOnNode": "导入此面板的入站上有 {synced} 个在线,该节点上共有 {total} 个在线",
"name": "名称",
"namePlaceholder": "例如:de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "API 令牌",
"apiTokenPlaceholder": "远程面板设置页中的令牌",
"apiTokenHint": "远程面板在 安全设定 → API 令牌 中显示其 API 令牌。",
- "apiTokenKeepHint": "留空以保留当前令牌",
+ "apiTokenKeepHint": "如果未输入新令牌,将保留当前令牌。",
+ "apiTokenReplace": "替换 API 令牌",
"allowPrivateAddress": "允许私有地址",
"allowPrivateAddressHint": "仅对私有网络或 VPN 上的节点启用。",
"outboundTag": "连接出站",
@@ -1279,6 +1281,38 @@
"subNodeTip": "只读:通过 {parent} 接入的下游节点。请在 {parent} 自己的面板中管理。",
"deleteConfirmTitle": "删除节点 \"{name}\"?",
"deleteConfirmContent": "这将停止监控该节点。远程面板本身不受影响。",
+ "fleet": {
+ "allNodes": "所有节点",
+ "master": "主节点",
+ "thisPanel": "本面板",
+ "fleetScope": "主节点 + {remotes} 个远程节点",
+ "reporting": "{live}/{total} 正在上报",
+ "registered": "{remotes} 个远程节点 · 共 {total} 个",
+ "allStatuses": "所有状态",
+ "open": "打开",
+ "hardware": "CPU / 内存",
+ "cpuAverage": "平均 CPU",
+ "logicalCores": "{cores} 个逻辑核心",
+ "availableMemory": "可用 {size}",
+ "remainingMemory": "剩余 {size}",
+ "connections": "TCP / UDP / 负载",
+ "load": "负载",
+ "loadSum": "总负载",
+ "loadWindow": "1、5 和 15 分钟系统负载",
+ "hostMetrics": "速率和连接数按主机汇总。",
+ "runtime": "运行状态",
+ "mixed": "多个版本",
+ "history": "历史",
+ "node": "节点",
+ "searchNodes": "搜索节点…",
+ "panel": "面板",
+ "uptimeShort": "运行",
+ "uptimeVaries": "运行时长因节点而异",
+ "clientRecords": "{records} 条客户端记录",
+ "acrossNodes": "分布于 {total} 个节点",
+ "connectionDetails": "连接详情",
+ "footnote": "总计仅包括正在上报的节点 ({coverage})。负载按 1、5 和 15 分钟展示,并在上报节点之间求和。将鼠标悬停在状态上可查看心跳和延迟。"
+ },
"statusValues": {
"online": "在线",
"offline": "离线",
@@ -1489,8 +1523,8 @@
"subClashEnableRoutingDesc": "在生成的 YAML 订阅中包含 Clash/Mihomo 全局路由规则。",
"subClashRoutingRules": "全局路由规则",
"subClashRoutingRulesDesc": "粘贴规则/YAML 或一个固定 HTTPS URL。面板会在后台更新,仅导入代理组、规则提供者和规则,并保留面板生成的 VPN 节点及最后一个有效值。",
- "subClashRemoteDNS": "Use DNS from remote rules",
- "subClashRemoteDNSDesc": "When the global routing rules field is a URL, also take its dns and sniffer sections. Enable only for a template you trust.",
+ "subClashRemoteDNS": "使用远程规则中的 DNS",
+ "subClashRemoteDNSDesc": "当「全局路由规则」填写的是 URL 时,也会一并采用其中的 dns 与 sniffer 段。请仅在你信任该模板时才启用。",
"subListen": "监听 IP",
"subListenDesc": "订阅服务监听的 IP 地址(留空表示监听所有 IP)",
"subPort": "监听端口",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "已在“{section}”中设置路由脚本,因此 Xray 会忽略这些规则。"
},
"hosts": {
+ "addressActions": {
+ "edit": "编辑 {address}",
+ "copy": "复制 {address}",
+ "single": "请输入一个地址。",
+ "duplicate": "此地址已在列表中。"
+ },
"addHost": "添加主机",
"editHost": "编辑主机",
"selectInbound": "选择一个入站",
diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json
index 04922e8ef..cbd98f4d8 100644
--- a/internal/web/translation/zh-TW.json
+++ b/internal/web/translation/zh-TW.json
@@ -128,7 +128,7 @@
"openMenu": "開啟選單",
"pinSidebar": "固定側邊欄",
"unpinSidebar": "取消固定側邊欄",
- "subFormats": "Sub Formats",
+ "subFormats": "訂閱格式",
"themeLight": "淺色",
"themeDark": "深色",
"themeUltraDark": "極致深色",
@@ -381,6 +381,8 @@
"detachClientsResult": "已分離 {detached},已略過 {skipped}。",
"detachClientsResultMixed": "已分離 {detached},已略過 {skipped},錯誤 {errors}。",
"detachClientsSelectLabel": "要分離的客戶端",
+ "detachSelectAll": "選取所有已關聯的用戶端",
+ "detachNodePending": "節點將同步這些變更。",
"exportLinksTitle": "匯出入站連結",
"exportSubsTitle": "匯出訂閱連結",
"exportAllLinksTitle": "匯出所有入站連結",
@@ -812,6 +814,7 @@
"auth": "認證",
"noKernelTun": "非核心 TUN",
"keepAlive": "Keep alive",
+ "exportAllPeers": "匯出所有對等端",
"peerNumber": "Peer {n}",
"peerNumberConfig": "Peer {n} 設定"
},
@@ -1202,6 +1205,8 @@
"addToGroupEmpty": "沒有其他可加入的客戶端。",
"addToGroupResult": "已將 {count} 個客戶端加入 {name}。",
"removeFromGroup": "移除客戶端…",
+ "selectAllMatching": "選取所有相符的用戶端",
+ "selectionLimit": "選取或排除的項目最多為 {count} 個。",
"removeFromGroupTitle": "從群組「{name}」移除客戶端",
"removeFromGroupDesc": "選擇要從此群組移除的成員。客戶端本身保留(用「刪除群組中的客戶端」完全移除)。",
"removeFromGroupResult": "已從 {name} 移除 {count} 個客戶端。",
@@ -1218,10 +1223,6 @@
"restartPanelContent": "節點面板與訂閱服務將重新啟動,可能暫時無法使用。需要節點上的 node-admin 或 admin API 權杖。",
"addNode": "新增節點",
"editNode": "編輯節點",
- "totalNodes": "節點總數",
- "onlineNodes": "上線",
- "offlineNodes": "離線",
- "avgLatency": "平均延遲",
"onlineOnNode": "匯入此面板的入站上有 {synced} 個上線,該節點上共有 {total} 個上線",
"name": "名稱",
"namePlaceholder": "例如:de-frankfurt-1",
@@ -1234,7 +1235,8 @@
"apiToken": "API 權杖",
"apiTokenPlaceholder": "遠端面板設定頁中的權杖",
"apiTokenHint": "遠端面板在 安全設定 → API 權杖 中顯示其 API 權杖。",
- "apiTokenKeepHint": "留空以保留目前的權杖",
+ "apiTokenKeepHint": "若未輸入新權杖,將保留目前的權杖。",
+ "apiTokenReplace": "替換 API 權杖",
"allowPrivateAddress": "允許私有地址",
"allowPrivateAddressHint": "僅對私有網路或 VPN 上的節點啟用。",
"outboundTag": "連線出站",
@@ -1279,6 +1281,38 @@
"subNodeTip": "唯讀:透過 {parent} 連接的下游節點。請在 {parent} 自己的面板中管理。",
"deleteConfirmTitle": "刪除節點「{name}」?",
"deleteConfirmContent": "這將停止監控該節點。遠端面板本身不受影響。",
+ "fleet": {
+ "allNodes": "所有節點",
+ "master": "主節點",
+ "thisPanel": "本面板",
+ "fleetScope": "主節點 + {remotes} 個遠端節點",
+ "reporting": "{live}/{total} 正在回報",
+ "registered": "{remotes} 個遠端節點 · 共 {total} 個",
+ "allStatuses": "所有狀態",
+ "open": "開啟",
+ "hardware": "CPU / 記憶體",
+ "cpuAverage": "平均 CPU",
+ "logicalCores": "{cores} 個邏輯核心",
+ "availableMemory": "可用 {size}",
+ "remainingMemory": "剩餘 {size}",
+ "connections": "TCP / UDP / 負載",
+ "load": "負載",
+ "loadSum": "總負載",
+ "loadWindow": "1、5 和 15 分鐘系統負載",
+ "hostMetrics": "速率和連線數按主機加總。",
+ "runtime": "執行狀態",
+ "mixed": "多個版本",
+ "history": "歷史",
+ "node": "節點",
+ "searchNodes": "搜尋節點…",
+ "panel": "面板",
+ "uptimeShort": "運作",
+ "uptimeVaries": "運作時間依節點而異",
+ "clientRecords": "{records} 筆用戶端紀錄",
+ "acrossNodes": "分佈於 {total} 個節點",
+ "connectionDetails": "連線詳細資料",
+ "footnote": "總計僅納入回報中的節點 ({coverage})。負載以 1、5、15 分鐘表示並加總回報節點的負載。將游標停在狀態上可查看心跳和延遲。"
+ },
"statusValues": {
"online": "上線",
"offline": "離線",
@@ -1489,8 +1523,8 @@
"subClashEnableRoutingDesc": "在產生的 YAML 訂閱中包含 Clash/Mihomo 全域路由規則。",
"subClashRoutingRules": "全域路由規則",
"subClashRoutingRulesDesc": "貼上規則/YAML 或一個固定 HTTPS URL。面板會在背景更新,只匯入代理群組、規則提供者與規則,並保留面板產生的 VPN 節點及最後一個有效值。",
- "subClashRemoteDNS": "Use DNS from remote rules",
- "subClashRemoteDNSDesc": "When the global routing rules field is a URL, also take its dns and sniffer sections. Enable only for a template you trust.",
+ "subClashRemoteDNS": "使用遠端規則中的 DNS",
+ "subClashRemoteDNSDesc": "當「全域路由規則」填寫的是 URL 時,也會一併採用其中的 dns 與 sniffer 段。請僅在你信任該範本時才啟用。",
"subListen": "監聽 IP",
"subListenDesc": "訂閱服務監聽的 IP 地址(留空表示監聽所有 IP)",
"subPort": "監聽埠",
@@ -2571,6 +2605,12 @@
"routingScriptActive": "已在「{section}」中設定路由腳本,因此 Xray 會忽略這些規則。"
},
"hosts": {
+ "addressActions": {
+ "edit": "編輯 {address}",
+ "copy": "複製 {address}",
+ "single": "請輸入一個地址。",
+ "duplicate": "此地址已在清單中。"
+ },
"addHost": "新增 Host",
"editHost": "編輯 Host",
"selectInbound": "選擇一個入站",
diff --git a/internal/web/web.go b/internal/web/web.go
index f6c6f388f..26ea75223 100644
--- a/internal/web/web.go
+++ b/internal/web/web.go
@@ -165,6 +165,17 @@ func NewServer(subLinkProvider service.SubLinkProvider) *Server {
// initRouter initializes Gin, registers middleware, templates, static
// assets, controllers and returns the configured engine.
+func gateDatabaseJob(next cron.Job) cron.Job {
+ return cron.FuncJob(func() {
+ end, ok := service.BeginDatabaseWork()
+ if !ok {
+ return
+ }
+ defer end()
+ next.Run()
+ })
+}
+
func (s *Server) initRouter() (*gin.Engine, error) {
if config.IsDebug() {
gin.SetMode(gin.DebugMode)
@@ -178,6 +189,7 @@ func (s *Server) initRouter() (*gin.Engine, error) {
directHTTPS := s.settingService.DirectHTTPSConfigured()
sendHSTS := directHTTPS && !config.IsSkipHSTS()
engine.Use(middleware.SecurityHeadersMiddleware(sendHSTS))
+ engine.Use(middleware.DatabaseWork(service.BeginDatabaseWork))
// Cap request bodies on state-changing requests so a stolen session/API
// token or a buggy client can't force large allocations or long DB
@@ -207,6 +219,7 @@ func (s *Server) initRouter() (*gin.Engine, error) {
return nil, err
}
assetsBasePath := basePath + "assets/"
+ engine.Use(controller.CaptureInboundPeerExportWriter(basePath))
// The bundles are served below from a gzip copy made once per file: compressing them
// per request lets every stalled download pin its own compressor until WriteTimeout.
engine.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPaths([]string{assetsBasePath})))
@@ -349,21 +362,22 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) {
// Reconcile mtproto (mtg) sidecars and scrape their traffic
mtJob := job.NewMtprotoJob()
_, _ = s.cron.AddJob(cadenceMtproto, mtJob)
- go mtJob.Run()
+ go gateDatabaseJob(mtJob).Run()
// Reconcile embedded AmneziaWG interfaces; traffic rides Xray's own stats
awgJob := job.NewAmneziaWGJob()
_, _ = s.cron.AddJob(cadenceAmneziaWG, awgJob)
- go awgJob.Run()
+ go gateDatabaseJob(awgJob).Run()
tuicJob := job.NewTuicJob()
_, _ = s.cron.AddJob(cadenceTuic, tuicJob)
- go tuicJob.Run()
+ go gateDatabaseJob(tuicJob).Run()
// check client ips from log file every 10 sec
_, _ = s.cron.AddJob(cadenceClientIPScan, job.NewCheckClientIpJob())
- _, _ = s.cron.AddJob(cadenceNodeHeartbeat, job.NewNodeHeartbeatJob())
+ nodeHeartbeat := job.NewNodeHeartbeatJob()
+ _, _ = s.cron.AddJob(cadenceNodeHeartbeat, nodeHeartbeat)
s.nodeTrafficJob = job.NewNodeTrafficSyncJob()
_, _ = s.cron.AddJob(cadenceNodeTraffic, s.nodeTrafficJob)
@@ -377,7 +391,7 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) {
// latency-sensitive subscription request path.
remoteRoutingJob := job.NewRemoteRoutingJob()
_, _ = s.cron.AddJob(cadenceRemoteRouting, remoteRoutingJob)
- common.GoRecover("remote-routing-warm", remoteRoutingJob.Run)
+ common.GoRecover("remote-routing-warm", gateDatabaseJob(remoteRoutingJob).Run)
// check client ips from log file every day
_, _ = s.cron.AddJob("@daily", job.NewClearLogsJob())
@@ -559,6 +573,7 @@ func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
cron.WithChain(
cron.SkipIfStillRunning(cron.DiscardLogger),
cron.Recover(cron.PrintfLogger(cronPanicLogger{})),
+ gateDatabaseJob,
),
)
s.cron.Start()
diff --git a/internal/xray/online_test.go b/internal/xray/online_test.go
index a621d6c2f..d973caba6 100644
--- a/internal/xray/online_test.go
+++ b/internal/xray/online_test.go
@@ -45,16 +45,15 @@ func TestMergedNodeTreesScopesPerGuid(t *testing.T) {
}
}
-// TestMergedNodeTreesOmitsEmpty keeps the payload small: empty GUID sets don't
-// appear as keys.
-func TestMergedNodeTreesOmitsEmpty(t *testing.T) {
+// Explicit empty reports are retained for the UI; omitted reports are unknown.
+func TestMergedNodeTreesKeepsEmpty(t *testing.T) {
p := newOnlineTestProcess()
p.SetNodeOnlineTree(1, map[string][]string{
"guid-a": {"user1"},
"guid-x": {},
})
- if _, ok := p.GetMergedNodeTrees()["guid-x"]; ok {
- t.Errorf("empty GUID set should be omitted: %v", p.GetMergedNodeTrees())
+ if got := p.GetMergedNodeTrees()["guid-x"]; got == nil || len(got) != 0 {
+ t.Errorf("expected an explicit empty GUID set: %v", p.GetMergedNodeTrees())
}
}
@@ -132,8 +131,21 @@ func TestMergedActiveInboundTreesScopesPerGuid(t *testing.T) {
merged := p.GetMergedActiveInboundTrees()
assertSameSet(t, "guid-a", merged["guid-a"], []string{"in-a", "in-c"})
assertSameSet(t, "guid-b", merged["guid-b"], []string{"in-b"})
- if _, ok := merged["guid-c"]; ok {
- t.Errorf("empty active-inbound GUID set should be omitted: %v", merged)
+ if idle := merged["guid-c"]; idle == nil || len(idle) != 0 {
+ t.Errorf("expected an explicit idle report for guid-c: %v", merged)
+ }
+}
+
+func TestMergedActiveInboundTreesPreferActivityToLegacy(t *testing.T) {
+ p := newOnlineTestProcess()
+ p.SetNodeActiveInboundTree(1, map[string][]string{"reported": nil, "legacy-only": nil})
+ p.SetNodeActiveInboundTree(2, map[string][]string{"reported": {}})
+ merged := p.GetMergedActiveInboundTrees()
+ if tags, ok := merged["legacy-only"]; !ok || tags != nil {
+ t.Fatalf("lost confirmed legacy report: %v", merged)
+ }
+ if tags := merged["reported"]; tags == nil || len(tags) != 0 {
+ t.Fatalf("successful idle report should take precedence over legacy: %v", merged)
}
}
diff --git a/internal/xray/process.go b/internal/xray/process.go
index b3d836916..e270581ad 100644
--- a/internal/xray/process.go
+++ b/internal/xray/process.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "maps"
"os"
"os/exec"
"path/filepath"
@@ -145,11 +146,14 @@ type process struct {
apiPort int
// onlineClients is the set of emails active on THIS panel's own xray
- // within the online grace window. It is derived only from local xray
- // traffic polls (see RefreshLocalOnline) — never from remote-node
+ // within the online grace window. It is derived from local Xray and sidecar
+ // traffic polls, never from remote-node
// snapshots — so a client connected solely to a remote node is not
// reported online on local inbounds.
- onlineClients []string
+ onlineClients []string
+ localXraySampleAt int64
+ localSidecarLastOnline map[string]int64
+ localSidecarInboundLastActive map[string]int64
// localActiveInbounds is the set of THIS panel's inbound tags that
// carried traffic within the same grace window. Xray's user>>>email
// stat aggregates across every inbound a client is attached to, so an
@@ -470,40 +474,55 @@ func (p *Process) GetLocalOnlineClients() []string {
return out
}
-// GetMergedNodeTrees returns the union of every direct node's reported subtree,
-// keyed by the panelGuid of the node that physically hosts each client set.
-// Because each child already reports its descendants under their own GUIDs,
-// merging the direct children yields the whole tree at any depth (#4983), so a
-// client three hops down is attributed to its real node, not the intermediate
-// one. GUIDs are globally unique, but a set reported under the same GUID by more
-// than one path is deduped per key; empty sets are omitted.
+// GetMergedNodeTrees returns online emails grouped by their physical node,
+// including explicit empty results from nodes that reported a successful poll.
func (p *Process) GetMergedNodeTrees() map[string][]string {
p.onlineMu.RLock()
defer p.onlineMu.RUnlock()
- if len(p.nodeOnlineTrees) == 0 {
- return map[string][]string{}
- }
+ return mergeNodeOnlineTrees(p.nodeOnlineTrees, false)
+}
+
+func mergeNodeOnlineTrees(trees map[int]map[string][]string, inboundActivity bool) map[string][]string {
out := make(map[string][]string)
seen := make(map[string]map[string]struct{})
- for _, tree := range p.nodeOnlineTrees {
- for guid, emails := range tree {
- if guid == "" || len(emails) == 0 {
+ complete := make(map[string]struct{})
+ for _, tree := range trees {
+ for guid, values := range tree {
+ if guid == "" {
continue
}
+ if values == nil {
+ if _, known := out[guid]; inboundActivity && !known {
+ out[guid] = nil
+ }
+ continue
+ }
+ if inboundActivity && !slices.Contains(values, PartialInboundActivityTag) {
+ complete[guid] = struct{}{}
+ }
dedup := seen[guid]
if dedup == nil {
- dedup = make(map[string]struct{}, len(emails))
+ dedup = make(map[string]struct{}, len(values))
seen[guid] = dedup
+ out[guid] = make([]string, 0, len(values))
}
- for _, email := range emails {
- if _, ok := dedup[email]; ok {
+ for _, value := range values {
+ if value == "" {
continue
}
- dedup[email] = struct{}{}
- out[guid] = append(out[guid], email)
+ if _, ok := dedup[value]; ok {
+ continue
+ }
+ dedup[value] = struct{}{}
+ out[guid] = append(out[guid], value)
}
}
}
+ for guid := range complete {
+ if _, partial := seen[guid][PartialInboundActivityTag]; partial {
+ out[guid] = slices.DeleteFunc(out[guid], func(tag string) bool { return tag == PartialInboundActivityTag })
+ }
+ }
return out
}
@@ -529,76 +548,86 @@ func (p *Process) GetLocalActiveInbounds() []string {
func (p *Process) GetMergedActiveInboundTrees() map[string][]string {
p.onlineMu.RLock()
defer p.onlineMu.RUnlock()
- if len(p.nodeActiveInboundTrees) == 0 {
- return map[string][]string{}
- }
- out := make(map[string][]string)
- seen := make(map[string]map[string]struct{})
- for _, tree := range p.nodeActiveInboundTrees {
- for guid, tags := range tree {
- if guid == "" || len(tags) == 0 {
- continue
- }
- dedup := seen[guid]
- if dedup == nil {
- dedup = make(map[string]struct{}, len(tags))
- seen[guid] = dedup
- }
- for _, tag := range tags {
- if tag == "" {
- continue
- }
- if _, ok := dedup[tag]; ok {
- continue
- }
- dedup[tag] = struct{}{}
- out[guid] = append(out[guid], tag)
- }
- }
- }
- return out
+ return mergeNodeOnlineTrees(p.nodeActiveInboundTrees, true)
}
-// RefreshLocalOnline records that each email in activeEmails and each tag in
-// activeInboundTags had local xray traffic at now, then rebuilds onlineClients
-// and localActiveInbounds from every entry seen within graceMs, pruning older
-// ones. Called by the local XrayTrafficJob after each xray gRPC stats poll.
-// Pass nil/empty slices to only prune — NodeTrafficSyncJob does this so a
-// stopped local xray's clients and inbounds still age out between local polls.
+// PartialInboundActivityTag marks a report whose listed tags are known but
+// whose other inbounds are unknown. Use a reserved nonempty value so older
+// panels that drop empty tags can still forward it.
+const PartialInboundActivityTag = "\x00"
+
+// HasFreshXrayOnlineSample reports whether this core has a usable Xray sample.
+func (p *Process) HasFreshXrayOnlineSample(now, graceMs int64) bool {
+ p.onlineMu.RLock()
+ defer p.onlineMu.RUnlock()
+ return p.hasFreshXrayOnlineSample(now, graceMs)
+}
+
+func (p *Process) hasFreshXrayOnlineSample(now, graceMs int64) bool {
+ return p.localXraySampleAt != 0 && now-p.localXraySampleAt < graceMs
+}
+
+// LocalOnlineSnapshot reports the full window when Xray is fresh. Otherwise
+// only independently observed sidecar inbounds can be attributed.
+func (p *Process) LocalOnlineSnapshot(now, graceMs int64) (emails, tags []string) {
+ p.onlineMu.RLock()
+ defer p.onlineMu.RUnlock()
+ if p.hasFreshXrayOnlineSample(now, graceMs) {
+ return slices.Clone(p.onlineClients), slices.Clone(p.localActiveInbounds)
+ }
+ tags = recentOnlineObservations(p.localSidecarInboundLastActive, now, graceMs)
+ if len(tags) == 0 {
+ return nil, nil
+ }
+ emails = recentOnlineObservations(p.localSidecarLastOnline, now, graceMs)
+ return emails, append(tags, PartialInboundActivityTag)
+}
+
+// RecordXrayOnlineSample records a successful poll, including an idle one.
+func (p *Process) RecordXrayOnlineSample(activeEmails, activeInboundTags []string, now, graceMs int64) {
+ p.onlineMu.Lock()
+ defer p.onlineMu.Unlock()
+ p.localXraySampleAt = now
+ p.refreshLocalOnline(activeEmails, activeInboundTags, now, graceMs)
+}
+
+// RefreshLocalOnline merges sidecar activity or prunes old observations without
+// marking the local Xray core as polled.
func (p *Process) RefreshLocalOnline(activeEmails, activeInboundTags []string, now, graceMs int64) {
p.onlineMu.Lock()
defer p.onlineMu.Unlock()
- if p.localLastOnline == nil {
- p.localLastOnline = make(map[string]int64, len(activeEmails))
- }
- for _, email := range activeEmails {
- p.localLastOnline[email] = now
- }
- online := make([]string, 0, len(p.localLastOnline))
- for email, ts := range p.localLastOnline {
- if now-ts < graceMs {
- online = append(online, email)
- } else {
- delete(p.localLastOnline, email)
- }
- }
- p.onlineClients = online
+ refreshOnlineObservations(&p.localSidecarLastOnline, activeEmails, now, graceMs)
+ refreshOnlineObservations(&p.localSidecarInboundLastActive, activeInboundTags, now, graceMs)
+ p.refreshLocalOnline(activeEmails, activeInboundTags, now, graceMs)
+}
- if p.localInboundLastActive == nil {
- p.localInboundLastActive = make(map[string]int64, len(activeInboundTags))
+func (p *Process) refreshLocalOnline(activeEmails, activeInboundTags []string, now, graceMs int64) {
+ refreshOnlineObservations(&p.localLastOnline, activeEmails, now, graceMs)
+ refreshOnlineObservations(&p.localInboundLastActive, activeInboundTags, now, graceMs)
+ p.onlineClients = slices.AppendSeq(make([]string, 0, len(p.localLastOnline)), maps.Keys(p.localLastOnline))
+ p.localActiveInbounds = slices.AppendSeq(make([]string, 0, len(p.localInboundLastActive)), maps.Keys(p.localInboundLastActive))
+}
+
+func refreshOnlineObservations(last *map[string]int64, active []string, now, graceMs int64) {
+ if len(active) > 0 && *last == nil {
+ *last = make(map[string]int64, len(active))
}
- for _, tag := range activeInboundTags {
- p.localInboundLastActive[tag] = now
- }
- activeInbounds := make([]string, 0, len(p.localInboundLastActive))
- for tag, ts := range p.localInboundLastActive {
- if now-ts < graceMs {
- activeInbounds = append(activeInbounds, tag)
- } else {
- delete(p.localInboundLastActive, tag)
+ for _, value := range active {
+ if value != "" && value != PartialInboundActivityTag {
+ (*last)[value] = now
}
}
- p.localActiveInbounds = activeInbounds
+ maps.DeleteFunc(*last, func(_ string, ts int64) bool { return now-ts >= graceMs })
+}
+
+func recentOnlineObservations(last map[string]int64, now, graceMs int64) []string {
+ recent := make([]string, 0, len(last))
+ for value, ts := range last {
+ if now-ts < graceMs {
+ recent = append(recent, value)
+ }
+ }
+ return recent
}
// SetNodeOnlineTree records the GUID-keyed online subtree one direct remote
diff --git a/main.go b/main.go
index 0f53f15cf..857855150 100644
--- a/main.go
+++ b/main.go
@@ -17,6 +17,7 @@ import (
"runtime"
"strings"
"syscall"
+ "time"
_ "unsafe"
"github.com/mhsanaei/3x-ui/v3/internal/config"
@@ -34,6 +35,7 @@ import (
"github.com/joho/godotenv"
"github.com/op/go-logging"
+ "gorm.io/gorm"
)
// cliFallbackTokenName is the single token the CLI regenerates, so `-getApiToken`
@@ -111,19 +113,36 @@ func runWebServer() {
log.Fatalf("Error initializing node-token encryption: %v", err)
}
- err := database.InitDB(config.GetDBPath())
+ var username, password string
+ lease, err := openPanelDatabase(func(db *gorm.DB) error {
+ if err := recoverPendingPostgresRestore(db); err != nil {
+ return fmt.Errorf("finish PostgreSQL restore: %w", err)
+ }
+ // The startup log is the one place the operator reads the first login.
+ var err error
+ username, password, err = database.EnsureFirstUser()
+ return err
+ })
if err != nil {
log.Fatalf("Error initializing database: %v", err)
}
- // Created here, not in InitDB: a CLI call's output is often piped away, and
- // this log is the one place an operator reads the first login from.
- username, password, err := database.EnsureFirstUser()
- if err != nil {
- log.Fatalf("Error creating the first panel user: %v", err)
- }
+ defer closePanelDatabase(lease)
if password != "" {
log.Printf("No panel user existed, so one was generated. Username: %s Password: %s (shown once; change it in Panel Settings)", username, password)
}
+ lockCtx, cancelLock := context.WithTimeout(context.Background(), database.MaintenanceWait)
+ err = lease.SetExclusive(lockCtx, false)
+ cancelLock()
+ if err != nil {
+ log.Fatalf("Error starting database runtime lease: %v", err)
+ }
+ database.SetRuntimeMaintenanceLease(lease)
+ defer database.SetRuntimeMaintenanceLease(nil)
+ if database.IsPostgres() {
+ watch, cancelWatch := context.WithCancel(context.Background())
+ defer cancelWatch()
+ go watchPanelDatabaseLease(watch, lease)
+ }
server := web.NewServer(sub.NewLinkProvider())
global.SetWebServer(server)
@@ -161,6 +180,11 @@ func runWebServer() {
stopTunnelHealthMonitor = cancel
monitor, err := tunnelmonitor.New(monitorCfg, func(_ context.Context) error {
+ end, ok := service.BeginDatabaseWork()
+ if !ok {
+ return service.ErrDatabaseRestoring
+ }
+ defer end()
logger.Warning("Tunnel health monitor threshold reached, restarting xray-core")
return (&service.XrayService{}).RestartXrayFrom(true, service.XrayOriginTunnelHealth)
})
@@ -173,6 +197,11 @@ func runWebServer() {
for shutdown := false; !shutdown; {
switch <-sigCh {
case syscall.SIGHUP:
+ end, ok := service.BeginDatabaseWork()
+ if !ok {
+ logger.Warning("Panel restart skipped: database restore in progress")
+ continue
+ }
logger.Info("Received SIGHUP signal. Restarting servers...")
var nextWeb *web.Server
@@ -206,9 +235,16 @@ func runWebServer() {
logger.Error("Failed to restart xray-core:", err)
}
}
+ end()
case sys.SIGUSR1:
+ end, ok := service.BeginDatabaseWork()
+ if !ok {
+ logger.Warning("Xray restart skipped: database restore in progress")
+ continue
+ }
logger.Info("Received USR1 signal, restarting xray-core...")
err := server.RestartXray(service.XrayOriginSignal)
+ end()
if err != nil {
logger.Error("Failed to restart xray-core:", err)
}
@@ -232,14 +268,8 @@ func runWebServer() {
// resetSetting resets all panel settings to their default values.
func resetSetting() error {
- err := database.InitDB(config.GetDBPath())
- if err != nil {
- fmt.Println("Failed to initialize database:", err)
- return err
- }
-
settingService := service.SettingService{}
- err = settingService.ResetSettings()
+ err := settingService.ResetSettings()
if err != nil {
fmt.Println("Failed to reset settings:", err)
return err
@@ -325,12 +355,6 @@ func updateTgbotEnableSts(status bool) {
// updateTgbotSetting updates Telegram bot settings including token, chat ID, and runtime schedule.
func updateTgbotSetting(tgBotToken string, tgBotChatid string, tgBotRuntime string) {
- err := database.InitDB(config.GetDBPath())
- if err != nil {
- fmt.Println("Error initializing database:", err)
- return
- }
-
settingService := service.SettingService{}
if tgBotToken != "" {
@@ -369,11 +393,12 @@ func encryptNodeTokens() {
fmt.Println("node-token encryption init failed:", err)
os.Exit(1)
}
- if err := database.InitDB(config.GetDBPath()); err != nil {
- fmt.Println("database initialization failed:", err)
- os.Exit(1)
- }
- changed, skipped, err := (&service.NodeService{}).MigrateNodeTokensToActiveKey()
+ var changed, skipped int
+ err := withCLIWorkingDatabase(func() error {
+ var err error
+ changed, skipped, err = (&service.NodeService{}).MigrateNodeTokensToActiveKey()
+ return err
+ })
if err != nil {
fmt.Println("token migration failed:", err)
os.Exit(1)
@@ -383,12 +408,6 @@ func encryptNodeTokens() {
// updateSetting updates various panel settings including port, credentials, base path, listen IP, and two-factor authentication.
func updateSetting(port int, username string, password string, webBasePath string, listenIP string, resetTwoFactor bool) error {
- err := database.InitDB(config.GetDBPath())
- if err != nil {
- fmt.Println("Database initialization failed:", err)
- return err
- }
-
settingService := service.SettingService{}
userService := panel.UserService{}
@@ -444,15 +463,9 @@ func updateSetting(port int, username string, password string, webBasePath strin
// updateCert updates the SSL certificate files for the panel.
func updateCert(publicKey string, privateKey string) {
- err := database.InitDB(config.GetDBPath())
- if err != nil {
- fmt.Println(err)
- return
- }
-
if (privateKey != "" && publicKey != "") || (privateKey == "" && publicKey == "") {
settingService := service.SettingService{}
- err = settingService.SetCertFile(publicKey)
+ err := settingService.SetCertFile(publicKey)
if err != nil {
fmt.Println("set certificate public key failed:", err)
} else {
@@ -524,11 +537,6 @@ func GetApiToken(getApiToken bool, tokenName, tokenScope string) {
// An explicit name applies to both branches below; without one each keeps
// the name it already used, so every existing invocation is unaffected.
name := strings.TrimSpace(tokenName)
- err := database.InitDB(config.GetDBPath())
- if err != nil {
- fmt.Println("open database failed, error info:", err)
- return
- }
apiTokenService := panel.ApiTokenService{}
tokens, err := apiTokenService.List()
if err != nil {
@@ -570,12 +578,22 @@ func migrateDb() {
inboundService := service.InboundService{}
logger.InitLogger(logging.INFO)
- err := database.InitDB(config.GetDBPath())
+ fmt.Println("Start migrating database...")
+ started := time.Now()
+ lease, err := openPanelDatabase(func(db *gorm.DB) error {
+ if err := inboundService.MigrateDBOn(db); err != nil {
+ return err
+ }
+ if db.Name() == database.DialectPostgres {
+ return database.ClearPostgresRestorePending(db)
+ }
+ return nil
+ })
if err != nil {
log.Fatal(err)
}
- fmt.Println("Start migrating database...")
- inboundService.MigrateDB()
+ defer closePanelDatabase(lease)
+ logger.Infof("inbound database maintenance complete: pid=%d duration_ms=%d", os.Getpid(), time.Since(started).Milliseconds())
fmt.Println("Migration done!")
}
@@ -699,7 +717,7 @@ func main() {
}
switch {
case migrateDump != "":
- if err := database.DumpSQLite(src, migrateDump); err != nil {
+ if err := withSQLiteMaintenance(src, false, func() error { return database.DumpSQLite(src, migrateDump) }); err != nil {
fmt.Println("dump failed:", err)
os.Exit(1)
}
@@ -709,13 +727,13 @@ func main() {
fmt.Println("--out is required when using --restore: the destination .db path (must not exist)")
return
}
- if err := database.RestoreSQLite(migrateRestore, migrateOut); err != nil {
+ if err := withSQLiteMaintenance(migrateOut, true, func() error { return database.RestoreSQLite(migrateRestore, migrateOut) }); err != nil {
fmt.Println("restore failed:", err)
os.Exit(1)
}
fmt.Printf("Restored %s -> %s\n", migrateRestore, migrateOut)
case migrateDsn != "":
- if err := database.MigrateData(src, migrateDsn); err != nil {
+ if err := migrateDatabaseFile(src, migrateDsn); err != nil {
fmt.Println("migration failed:", err)
os.Exit(1)
}
@@ -733,35 +751,39 @@ func main() {
if rest := settingCmd.Args(); len(rest) > 0 {
fmt.Printf("warning: ignored %q and any flags after it; put flags before positional arguments\n", strings.Join(rest, " "))
}
- if reset {
- if err = resetSetting(); err != nil {
- return
+ err = withCLIWorkingDatabase(func() error {
+ if reset {
+ if err := resetSetting(); err != nil {
+ return err
+ }
+ } else if err := updateSetting(port, username, password, webBasePath, listenIP, resetTwoFactor); err != nil {
+ return err
}
- } else {
- if err = updateSetting(port, username, password, webBasePath, listenIP, resetTwoFactor); err != nil {
- return
+ if webCertFile != "" || webKeyFile != "" {
+ updateCert(webCertFile, webKeyFile)
}
- }
- if webCertFile != "" || webKeyFile != "" {
- updateCert(webCertFile, webKeyFile)
- }
- if show {
- showSetting(show)
- }
- if getListen {
- GetListenIP(getListen)
- }
- if getCert {
- GetCertificate(getCert)
- }
- if getApiToken {
- GetApiToken(getApiToken, tokenName, tokenScope)
- }
- if (tgbottoken != "") || (tgbotchatid != "") || (tgbotRuntime != "") {
- updateTgbotSetting(tgbottoken, tgbotchatid, tgbotRuntime)
- }
- if enabletgbot {
- updateTgbotEnableSts(enabletgbot)
+ if show {
+ showSetting(show)
+ }
+ if getListen {
+ GetListenIP(getListen)
+ }
+ if getCert {
+ GetCertificate(getCert)
+ }
+ if getApiToken {
+ GetApiToken(getApiToken, tokenName, tokenScope)
+ }
+ if tgbottoken != "" || tgbotchatid != "" || tgbotRuntime != "" {
+ updateTgbotSetting(tgbottoken, tgbotchatid, tgbotRuntime)
+ }
+ if enabletgbot {
+ updateTgbotEnableSts(enabletgbot)
+ }
+ return nil
+ })
+ if err != nil {
+ log.Fatalf("settings command failed: %v", err)
}
case "cert":
err := settingCmd.Parse(os.Args[2:])
@@ -769,10 +791,16 @@ func main() {
fmt.Println(err)
return
}
- if reset {
- updateCert("", "")
- } else {
- updateCert(webCertFile, webKeyFile)
+ err = withCLIWorkingDatabase(func() error {
+ if reset {
+ updateCert("", "")
+ } else {
+ updateCert(webCertFile, webKeyFile)
+ }
+ return nil
+ })
+ if err != nil {
+ log.Fatalf("certificate settings command failed: %v", err)
}
default:
fmt.Println("Invalid subcommands")
diff --git a/scripts_base_path_test.go b/scripts_base_path_test.go
index 13910021b..9e808afb9 100644
--- a/scripts_base_path_test.go
+++ b/scripts_base_path_test.go
@@ -31,7 +31,11 @@ func scriptFunction(t *testing.T, script, name string) string {
const settingsCLIMock = `#!/bin/bash
set -eu
state=$TEST_SETTINGS_DIR
-if [[ "$1" == migrate ]]; then exit 0; fi
+if [[ "$1" == migrate ]]; then
+ printf 'migrate\n' >> "$state/lifecycle"
+ if [[ "$TEST_READ_MODE" == migration_failure ]]; then exit 1; fi
+ exit 0
+fi
shift
case "$1" in
-show)
@@ -129,7 +133,10 @@ systemctl() { printf '%s\n' "$*" >> "$TEST_SETTINGS_DIR/restarts"; }
rc-service() { printf '%s\n' "$*" >> "$TEST_SETTINGS_DIR/restarts"; }
prompt_and_setup_ssl() {
printf '%s\n' "$*" > "$TEST_SETTINGS_DIR/ssl"
- [[ "$TEST_READ_MODE" != ssl_failure ]]
+ if [[ "$TEST_READ_MODE" == ssl_failure ]]; then
+ printf 'ssl\n' >> "$TEST_SETTINGS_DIR/lifecycle"
+ return 1
+ fi
}
write_install_result() { printf '%s\n' "$@" > "$TEST_SETTINGS_DIR/result"; }
install_postgres_local() { echo 'unexpected PostgreSQL installation' >&2; exit 97; }
@@ -154,7 +161,8 @@ fail2ban_mode=install
body := scriptFunction(t, script, parent)
startCall := function
if script == "update.sh" {
- startCall = "setup_fail2ban"
+ startCall = `echo -e "${green}Migrating database...${plain}"`
+ driver += scriptFunction(t, script, "_fail")
}
start := strings.Index(body, "\n "+startCall)
if start < 0 {
@@ -283,7 +291,7 @@ func TestScriptConfigReadFailureKeepsServiceSetup(t *testing.T) {
if err != nil || !strings.Contains(out, "Unable to read webBasePath") {
t.Errorf("service setup should continue after the settings warning: %v\n%s", err, out)
}
- wantLifecycle, wantServices := "fail2ban\nunit\n", "daemon-reload\nenable x-ui\nstart x-ui\n"
+ wantLifecycle, wantServices := "migrate\nfail2ban\nunit\n", "daemon-reload\nenable x-ui\nstart x-ui\n"
if script == "install.sh" {
wantServices = "daemon-reload\nenable x-ui\nrestart x-ui\n"
}
@@ -308,10 +316,122 @@ func TestInstallerSSLFailureKeepsServiceSetup(t *testing.T) {
t.Fatalf("SSL setup was not attempted: %v\n%s", err, out)
}
for name, want := range map[string]string{
- "lifecycle": "fail2ban\nunit\n", "restarts": "daemon-reload\nenable x-ui\nrestart x-ui\n",
+ "lifecycle": "ssl\nmigrate\nfail2ban\nunit\n", "restarts": "daemon-reload\nenable x-ui\nrestart x-ui\n",
} {
if actual := readScriptState(t, dir, name); actual != want {
t.Errorf("%s after a failed certificate = %q, want %q: the panel must still be installed and started", name, actual, want)
}
}
}
+
+func TestInstallMigrationFailurePreventsServiceStart(t *testing.T) {
+ dir, out, err := runScriptConfig(t, "install.sh", "/a/", false, "migration_failure", 1, true)
+ if err == nil || !strings.Contains(out, "Database migration failed") {
+ t.Fatalf("migration failure should abort the update: %v\n%s", err, out)
+ }
+ if got := readScriptState(t, dir, "restarts"); got != "" {
+ t.Fatalf("service started after a failed migration: %q", got)
+ }
+ if got := readScriptState(t, dir, "lifecycle"); got != "migrate\n" {
+ t.Fatalf("lifecycle after failed migration: %q", got)
+ }
+}
+
+func TestUpdateMigrationFailureKeepsServiceUnitForRetry(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("updater regression requires a POSIX environment")
+ }
+ bash, err := exec.LookPath("bash")
+ if err != nil {
+ t.Skip("bash is required for the isolated updater regression")
+ }
+ for _, distro := range []struct {
+ name, unit, stopped, started string
+ }{
+ {"ubuntu", "systemd/x-ui.service", "systemctl stop x-ui\nsystemctl disable x-ui\n", "systemctl daemon-reload\nsystemctl enable x-ui\nsystemctl start x-ui\n"},
+ {"alpine", "init.d/x-ui", "rc-service x-ui stop\nrc-update del x-ui\n", "rc-update add x-ui\nrc-service x-ui start\n"},
+ } {
+ t.Run(distro.name, func(t *testing.T) {
+ dir := t.TempDir()
+ for _, folder := range []string{"x-ui", "systemd", "init.d", "release/x-ui", "bin"} {
+ if err := os.MkdirAll(filepath.Join(dir, folder), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ const binary = `#!/bin/bash
+if [[ $1 == migrate ]]; then
+ printf 'migrate\n' >> "$TEST_ROOT/events"
+ [[ $TEST_FAIL_MIGRATION == 0 ]]
+else
+ printf 'test version\n'
+fi
+`
+ for name, value := range map[string]string{
+ distro.unit: "old unit\n", "x-ui/x-ui": binary, "release/x-ui/x-ui": binary,
+ "release/x-ui/x-ui.sh": "#!/bin/bash\n", "release/x-ui/x-ui.service": "new unit\n",
+ } {
+ if err := os.WriteFile(filepath.Join(dir, name), []byte(value), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ driver := `red= green= yellow= blue= plain=
+xui_folder="$TEST_ROOT/x-ui"
+xui_service="$TEST_ROOT/systemd"
+release="$TEST_DISTRO"
+XUI_UPDATE_TAG=test
+curl_bin=fake_curl
+load_xui_env() { :; }
+setup_fail2ban() { :; }
+config_after_update() { :; }
+_xui_service_write_paths_dropin() { :; }
+_xui_warn_unsupported_hardening() { :; }
+chown() { :; }
+pkill() { :; }
+systemctl() { printf 'systemctl %s\n' "$*" >> "$TEST_ROOT/events"; }
+rc-service() { printf 'rc-service %s\n' "$*" >> "$TEST_ROOT/events"; }
+rc-update() { printf 'rc-update %s\n' "$*" >> "$TEST_ROOT/events"; }
+fake_curl() {
+ case "$*" in
+ *.sha256) printf 404 ;;
+ */x-ui.rc) printf 'new unit\n' > "$2" ;;
+ *) tar -czf "$2" -C "$TEST_ROOT/release" x-ui ;;
+ esac
+}
+`
+ driver += scriptFunction(t, "update.sh", "_fail") + scriptFunction(t, "update.sh", "_install_xui_service_unit")
+ driver += strings.NewReplacer(
+ "/etc/init.d/x-ui", "$TEST_ROOT/init.d/x-ui",
+ "/usr/bin/x-ui", "$TEST_ROOT/bin/x-ui",
+ "/var/log/x-ui", "$TEST_ROOT/log",
+ ).Replace(scriptFunction(t, "update.sh", "update_x-ui"))
+ driver += "update_x-ui\n"
+
+ run := func(failMigration string) (string, error) {
+ t.Helper()
+ cmd := exec.Command(bash, "-c", driver)
+ cmd.Dir = dir
+ cmd.Env = append(os.Environ(), "TEST_ROOT="+dir, "TEST_DISTRO="+distro.name, "TEST_FAIL_MIGRATION="+failMigration)
+ out, err := cmd.CombinedOutput()
+ return string(out), err
+ }
+ if out, err := run("1"); err == nil || !strings.Contains(out, "Database migration failed") {
+ t.Fatalf("first update should fail in migration: %v\n%s", err, out)
+ }
+ if unit := readScriptState(t, dir, distro.unit); unit != "old unit\n" {
+ t.Fatalf("failed update changed the service unit: %q", unit)
+ }
+ if got := readScriptState(t, dir, "events"); got != distro.stopped+"migrate\n" {
+ t.Fatalf("failed update service actions: %q", got)
+ }
+ if out, err := run("0"); err != nil {
+ t.Fatalf("ordinary update retry failed: %v\n%s", err, out)
+ }
+ if unit := readScriptState(t, dir, distro.unit); unit != "new unit\n" {
+ t.Fatalf("retry did not install the replacement unit: %q", unit)
+ }
+ if got := readScriptState(t, dir, "events"); got != strings.Repeat(distro.stopped+"migrate\n", 2)+distro.started {
+ t.Fatalf("retry service actions: %q", got)
+ }
+ })
+ }
+}
diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go
index 2633d92c0..d068d308b 100644
--- a/tools/openapigen/main.go
+++ b/tools/openapigen/main.go
@@ -37,6 +37,7 @@ func run(root, outDir string) error {
"WireguardDevice",
"Client",
"ClientRecord",
+ "NodeTelemetry",
"ClientInbound",
"InboundFallback",
"Host",
@@ -97,12 +98,13 @@ func run(root, outDir string) error {
},
{
Path: resolveRel(root, "internal/web/runtime"),
- StructAllow: setOf("NodeSnapshotAttachment", "NodeSnapshotStructure", "NodeInboundTraffic", "NodeClientTraffic", "NodeTrafficSnapshotV1"),
+ StructAllow: setOf("NodeSnapshotAttachment", "NodeSnapshotStructure", "NodeInboundTraffic", "NodeClientTraffic", "NodeTrafficSnapshotV1", "RemoteInboundOption"),
},
{
Path: resolveRel(root, "internal/web/service"),
StructAllow: setOf(
"InboundOption",
+ "InboundInfoPage",
"NetworkInterfaceOption",
"NetworkInterfacesResponse",
"NetworkTrafficSelection",
@@ -114,9 +116,19 @@ func run(root, outDir string) error {
"ClientRenewalPreviewRequest",
"ClientRenewalPreview",
"ClientPageResponse",
+ "ClientEmailSuggestions",
"AttachCandidate",
"AttachCandidatePage",
+ "GroupClientPage",
+ "GroupClientRow",
+ "GroupClientSelection",
+ "BulkDeleteResult",
+ "BulkDeleteReport",
"AttachSelectionResult",
+ "DetachCandidate",
+ "DetachCandidatePage",
+ "DetachScopeSummary",
+ "DetachSelectionResult",
"BulkAdjustResult",
"BulkAdjustReport",
"BulkAttachResult",
@@ -137,6 +149,9 @@ func run(root, outDir string) error {
"MLKEM768Response",
"NodeMutationRequest",
"NodeView",
+ "NodeOverview",
+ "NodeMasterView",
+ "NodeFleetCounts",
"ProbeResultUI",
"RealityScanResult",
"RealityWatchEntry",
@@ -159,7 +174,7 @@ func run(root, outDir string) error {
},
{
Path: resolveRel(root, "internal/web/controller"),
- StructAllow: setOf("TgBotCapabilities", "AttachJobStatus"),
+ StructAllow: setOf("TgBotCapabilities", "AttachJobStatus", "DetachJobStatus"),
},
{
Path: resolveRel(root, "internal/amneziawg"),
diff --git a/update.sh b/update.sh
index 7d7e3a1ff..6c1b1299b 100755
--- a/update.sh
+++ b/update.sh
@@ -172,7 +172,6 @@ config_after_update() {
echo -e "${yellow}x-ui settings:${plain}"
${xui_folder}/x-ui setting -show true
- ${xui_folder}/x-ui migrate
# Properly detect empty cert by checking if cert: line exists and has content after it
local existing_cert=$(${xui_folder}/x-ui setting -getCert true 2> /dev/null | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
@@ -578,12 +577,12 @@ update_x-ui() {
if [[ -e ${xui_folder}/ ]]; then
echo -e "${green}Stopping x-ui...${plain}"
+ # Keep the stopped, disabled unit in place so an update can be retried
+ # if migration fails before the replacement unit is installed.
if [[ $release == "alpine" ]]; then
if [ -f "/etc/init.d/x-ui" ]; then
rc-service x-ui stop > /dev/null 2>&1
rc-update del x-ui > /dev/null 2>&1
- echo -e "${green}Removing old service unit version...${plain}"
- rm -f /etc/init.d/x-ui > /dev/null 2>&1
else
rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
_fail "ERROR: x-ui service unit not installed."
@@ -592,9 +591,6 @@ update_x-ui() {
if [ -f "${xui_service}/x-ui.service" ]; then
systemctl stop x-ui > /dev/null 2>&1
systemctl disable x-ui > /dev/null 2>&1
- echo -e "${green}Removing old systemd unit version...${plain}"
- rm ${xui_service}/x-ui.service -f > /dev/null 2>&1
- systemctl daemon-reload > /dev/null 2>&1
else
rm x-ui-linux-$(arch).tar.gz -f > /dev/null 2>&1
_fail "ERROR: x-ui systemd unit not installed."
@@ -608,10 +604,12 @@ update_x-ui() {
pkill -f 'tuic-server.*-c .*bin/tuic/tuic_[0-9]+\.json' > /dev/null 2>&1 || true
echo -e "${green}Removing old x-ui version...${plain}"
rm ${xui_folder} -f > /dev/null 2>&1
- rm ${xui_folder}/x-ui.service -f > /dev/null 2>&1
- rm ${xui_folder}/x-ui.service.debian -f > /dev/null 2>&1
- rm ${xui_folder}/x-ui.service.arch -f > /dev/null 2>&1
- rm ${xui_folder}/x-ui.service.rhel -f > /dev/null 2>&1
+ local template
+ for template in x-ui.service x-ui.service.debian x-ui.service.arch x-ui.service.rhel; do
+ if [[ ! "${xui_folder}/${template}" -ef "${xui_service}/x-ui.service" ]]; then
+ rm -f "${xui_folder}/${template}" > /dev/null 2>&1
+ fi
+ done
rm ${xui_folder}/x-ui -f > /dev/null 2>&1
rm ${xui_folder}/x-ui.sh -f > /dev/null 2>&1
echo -e "${green}Removing old mtg version...${plain}"
@@ -680,10 +678,14 @@ update_x-ui() {
chmod 640 ${xui_folder}/bin/config.json > /dev/null 2>&1
fi
- # Finish the schema/data migrations before the service starts, so the service and
- # config_after_update's CLI calls never run them on the same database at once (#6728).
+ # Finish the schema/data migrations before the service starts.
echo -e "${green}Migrating database...${plain}"
- "${xui_folder}/x-ui" migrate
+ if ! "${xui_folder}/x-ui" migrate; then
+ if [[ $release == "alpine" ]]; then
+ rm -f "${xui_rc_temp}"
+ fi
+ _fail "ERROR: Database migration failed; x-ui was not started. Fix the migration error and rerun the update."
+ fi
setup_fail2ban
if [[ $release == "alpine" ]]; then
diff --git a/x-ui.sh b/x-ui.sh
index 46cc67c50..af00030c0 100644
--- a/x-ui.sh
+++ b/x-ui.sh
@@ -1965,7 +1965,7 @@ update_geofiles() {
;;
"IR")
dat_files=(geoip_IR geosite_IR)
- dat_source="chocolate4u/Iran-v2ray-rules"
+ dat_source="FDeghy/Iran-v2ray-rules"
;;
"RU")
dat_files=(geoip_RU geosite_RU)
@@ -2030,7 +2030,7 @@ run_geo_update() {
update_geo() {
echo -e "${green}\t1.${plain} Loyalsoldier (geoip.dat, geosite.dat)"
- echo -e "${green}\t2.${plain} chocolate4u (geoip_IR.dat, geosite_IR.dat)"
+ echo -e "${green}\t2.${plain} FDeghy (geoip_IR.dat, geosite_IR.dat)"
echo -e "${green}\t3.${plain} runetfreedom (geoip_RU.dat, geosite_RU.dat)"
echo -e "${green}\t4.${plain} All"
echo -e "${green}\t0.${plain} Back to Main Menu"
@@ -2044,7 +2044,7 @@ update_geo() {
run_geo_update "Loyalsoldier datasets" update_geofiles "main"
;;
2)
- run_geo_update "chocolate4u datasets" update_geofiles "IR"
+ run_geo_update "FDeghy datasets" update_geofiles "IR"
;;
3)
run_geo_update "runetfreedom datasets" update_geofiles "RU"