Merge remote-tracking branch 'origin/main' into pr/6971

This commit is contained in:
Sanaei
2026-11-29 17:52:58 +03:30
44 changed files with 974 additions and 196 deletions
+15
View File
@@ -157,3 +157,18 @@ These have their own settings groups and pages:
Email (SMTP) notifications are also configurable (host, port, encryption,
recipients) with the same event types as the Telegram bot.
</Callout>
### External traffic notifications
The **External traffic inform interval** controls how often the panel sends the
external webhook. It defaults to 5 seconds and accepts values from 5 to 3600
seconds. Traffic accounting, quota enforcement and online updates keep their
five-second poll. Each webhook carries the deltas summed since the previous
one, per client email and per inbound or outbound tag.
The request is sent outside the accounting poll, so a slow receiver cannot
delay accounting. Each batch is sent once. If the receiver does not answer with
a 2xx status within 3 seconds, the panel drops that batch, logs one warning
with the reason, and logs again when deliveries resume. Deltas waiting for the
next send are held in memory: disabling the webhook or a panel process exit
discards them.
+20
View File
@@ -75,6 +75,10 @@
"externalTrafficInformEnable": {
"type": "boolean"
},
"externalTrafficInformInterval": {
"example": 5,
"type": "integer"
},
"externalTrafficInformURI": {
"type": "string"
},
@@ -700,6 +704,7 @@
"expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable",
"externalTrafficInformInterval",
"externalTrafficInformURI",
"happLinkEnable",
"ipLimitAllowlist",
@@ -938,6 +943,10 @@
"externalTrafficInformEnable": {
"type": "boolean"
},
"externalTrafficInformInterval": {
"example": 5,
"type": "integer"
},
"externalTrafficInformURI": {
"type": "string"
},
@@ -1593,6 +1602,7 @@
"expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable",
"externalTrafficInformInterval",
"externalTrafficInformURI",
"happLinkEnable",
"hasApiToken",
@@ -4710,6 +4720,12 @@
"example": true,
"type": "boolean"
},
"heartbeatAgeMillis": {
"example": 1250,
"format": "int64",
"nullable": true,
"type": "integer"
},
"id": {
"example": 1,
"type": "integer"
@@ -13560,6 +13576,7 @@
"enable": true,
"guid": "node-guid",
"hasApiToken": true,
"heartbeatAgeMillis": 1250,
"id": 1,
"inboundCount": 3,
"inboundSyncMode": "all",
@@ -13765,6 +13782,7 @@
"enable": true,
"guid": "node-guid",
"hasApiToken": true,
"heartbeatAgeMillis": 1250,
"id": 1,
"inboundCount": 3,
"inboundSyncMode": "all",
@@ -13919,6 +13937,7 @@
"enable": true,
"guid": "node-guid",
"hasApiToken": true,
"heartbeatAgeMillis": 1250,
"id": 1,
"inboundCount": 3,
"inboundSyncMode": "all",
@@ -19719,6 +19738,7 @@
"enable": true,
"guid": "node-guid",
"hasApiToken": true,
"heartbeatAgeMillis": 1250,
"id": 1,
"inboundCount": 3,
"inboundSyncMode": "all",
+20
View File
@@ -75,6 +75,10 @@
"externalTrafficInformEnable": {
"type": "boolean"
},
"externalTrafficInformInterval": {
"example": 5,
"type": "integer"
},
"externalTrafficInformURI": {
"type": "string"
},
@@ -700,6 +704,7 @@
"expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable",
"externalTrafficInformInterval",
"externalTrafficInformURI",
"happLinkEnable",
"ipLimitAllowlist",
@@ -938,6 +943,10 @@
"externalTrafficInformEnable": {
"type": "boolean"
},
"externalTrafficInformInterval": {
"example": 5,
"type": "integer"
},
"externalTrafficInformURI": {
"type": "string"
},
@@ -1593,6 +1602,7 @@
"expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable",
"externalTrafficInformInterval",
"externalTrafficInformURI",
"happLinkEnable",
"hasApiToken",
@@ -4710,6 +4720,12 @@
"example": true,
"type": "boolean"
},
"heartbeatAgeMillis": {
"example": 1250,
"format": "int64",
"nullable": true,
"type": "integer"
},
"id": {
"example": 1,
"type": "integer"
@@ -13560,6 +13576,7 @@
"enable": true,
"guid": "node-guid",
"hasApiToken": true,
"heartbeatAgeMillis": 1250,
"id": 1,
"inboundCount": 3,
"inboundSyncMode": "all",
@@ -13765,6 +13782,7 @@
"enable": true,
"guid": "node-guid",
"hasApiToken": true,
"heartbeatAgeMillis": 1250,
"id": 1,
"inboundCount": 3,
"inboundSyncMode": "all",
@@ -13919,6 +13937,7 @@
"enable": true,
"guid": "node-guid",
"hasApiToken": true,
"heartbeatAgeMillis": 1250,
"id": 1,
"inboundCount": 3,
"inboundSyncMode": "all",
@@ -19719,6 +19738,7 @@
"enable": true,
"guid": "node-guid",
"hasApiToken": true,
"heartbeatAgeMillis": 1250,
"id": 1,
"inboundCount": 3,
"inboundSyncMode": "all",
@@ -74,6 +74,7 @@ export function useNodesQuery() {
return {
nodes,
nodesUpdatedAt: query.dataUpdatedAt,
totals,
loading: query.isFetching,
fetched: query.data !== undefined || query.isError,
+3
View File
@@ -15,6 +15,7 @@ export const EXAMPLES: Record<string, unknown> = {
"expireDiff": 0,
"externalSubUserAgent": "",
"externalTrafficInformEnable": false,
"externalTrafficInformInterval": 5,
"externalTrafficInformURI": "",
"happLinkEnable": false,
"ipLimitAllowlist": "",
@@ -217,6 +218,7 @@ export const EXAMPLES: Record<string, unknown> = {
"expireDiff": 0,
"externalSubUserAgent": "",
"externalTrafficInformEnable": false,
"externalTrafficInformInterval": 5,
"externalTrafficInformURI": "",
"happLinkEnable": false,
"hasApiToken": false,
@@ -1213,6 +1215,7 @@ export const EXAMPLES: Record<string, unknown> = {
"enable": true,
"guid": "node-guid",
"hasApiToken": true,
"heartbeatAgeMillis": 1250,
"id": 1,
"inboundCount": 3,
"inboundSyncMode": "all",
+16
View File
@@ -49,6 +49,10 @@ export const SCHEMAS: Record<string, unknown> = {
"externalTrafficInformEnable": {
"type": "boolean"
},
"externalTrafficInformInterval": {
"example": 5,
"type": "integer"
},
"externalTrafficInformURI": {
"type": "string"
},
@@ -674,6 +678,7 @@ export const SCHEMAS: Record<string, unknown> = {
"expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable",
"externalTrafficInformInterval",
"externalTrafficInformURI",
"happLinkEnable",
"ipLimitAllowlist",
@@ -912,6 +917,10 @@ export const SCHEMAS: Record<string, unknown> = {
"externalTrafficInformEnable": {
"type": "boolean"
},
"externalTrafficInformInterval": {
"example": 5,
"type": "integer"
},
"externalTrafficInformURI": {
"type": "string"
},
@@ -1567,6 +1576,7 @@ export const SCHEMAS: Record<string, unknown> = {
"expireDiff",
"externalSubUserAgent",
"externalTrafficInformEnable",
"externalTrafficInformInterval",
"externalTrafficInformURI",
"happLinkEnable",
"hasApiToken",
@@ -4684,6 +4694,12 @@ export const SCHEMAS: Record<string, unknown> = {
"example": true,
"type": "boolean"
},
"heartbeatAgeMillis": {
"example": 1250,
"format": "int64",
"nullable": true,
"type": "integer"
},
"id": {
"example": 1,
"type": "integer"
+3
View File
@@ -20,6 +20,7 @@ export interface AllSetting {
expireDiff: number;
externalSubUserAgent: string;
externalTrafficInformEnable: boolean;
externalTrafficInformInterval: number;
externalTrafficInformURI: string;
happLinkEnable: boolean;
ipLimitAllowlist: string;
@@ -223,6 +224,7 @@ export interface AllSettingView {
expireDiff: number;
externalSubUserAgent: string;
externalTrafficInformEnable: boolean;
externalTrafficInformInterval: number;
externalTrafficInformURI: string;
happLinkEnable: boolean;
hasApiToken: boolean;
@@ -1064,6 +1066,7 @@ export interface NodeView {
enable: boolean;
guid: string;
hasApiToken: boolean;
heartbeatAgeMillis?: number | null;
id: number;
inboundCount: number;
inboundSyncMode: string;
+3
View File
@@ -30,6 +30,7 @@ export const AllSettingSchema = z.object({
expireDiff: z.number().int().min(0),
externalSubUserAgent: z.string(),
externalTrafficInformEnable: z.boolean(),
externalTrafficInformInterval: z.number().int(),
externalTrafficInformURI: z.string(),
happLinkEnable: z.boolean(),
ipLimitAllowlist: z.string(),
@@ -234,6 +235,7 @@ export const AllSettingViewSchema = z.object({
expireDiff: z.number().int().min(0),
externalSubUserAgent: z.string(),
externalTrafficInformEnable: z.boolean(),
externalTrafficInformInterval: z.number().int(),
externalTrafficInformURI: z.string(),
happLinkEnable: z.boolean(),
hasApiToken: z.boolean(),
@@ -1129,6 +1131,7 @@ export const NodeViewSchema = z.object({
enable: z.boolean(),
guid: z.string(),
hasApiToken: z.boolean(),
heartbeatAgeMillis: z.number().int().nullable().optional(),
id: z.number().int(),
inboundCount: z.number().int(),
inboundSyncMode: z.string(),
+1
View File
@@ -75,6 +75,7 @@ export class AllSetting {
subClashPath = '/clash/';
subDomain = '';
externalTrafficInformEnable = false;
externalTrafficInformInterval = 5;
externalTrafficInformURI = '';
restartXrayOnClientDisable = true;
mcpEnable = false;
+16
View File
@@ -142,3 +142,19 @@
align-items: center;
gap: 8px;
}
.node-network-speed {
display: inline-grid;
row-gap: 2px;
text-align: start;
line-height: 1.25;
}
.node-network-direction {
display: grid;
grid-template-columns: 1em auto;
column-gap: 4px;
align-items: center;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
+24 -4
View File
@@ -23,6 +23,7 @@ import {
} from '@ant-design/icons';
import NodeHistoryPanel from './NodeHistoryPanel';
import NodeNetworkSpeed from './NodeNetworkSpeed';
import type { NodeRecord } from '@/api/queries/useNodesQuery';
import { isPanelUpdateAvailable } from '@/lib/panel-version';
import { activateOnKey } from '@/utils/a11y';
@@ -30,6 +31,7 @@ import './NodeList.css';
interface NodeListProps {
nodes: NodeRecord[];
nodesUpdatedAt?: number;
loading?: boolean;
isMobile?: boolean;
latestVersion?: string;
@@ -209,6 +211,7 @@ function OnlineTag({ node, compact }: { node: NodeRecord; compact?: boolean }) {
export default function NodeList({
nodes,
nodesUpdatedAt,
loading = false,
isMobile = false,
latestVersion = '',
@@ -229,7 +232,7 @@ export default function NodeList({
const relativeTime = useRelativeTime();
const [showAddress, setShowAddress] = useState(false);
const [statsNode, setStatsNode] = useState<NodeRow | null>(null);
const [statsNodeId, setStatsNodeId] = useState<number | null>(null);
const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set());
const restartItems = useCallback(
@@ -288,6 +291,11 @@ export default function NodeList({
return ordered;
}, [nodes]);
const statsNode =
statsNodeId === null
? undefined
: dataSource.find((node) => !node.transitive && node.id === statsNodeId);
function toggleExpanded(id: number) {
setExpandedIds((prev) => {
const next = new Set(prev);
@@ -480,6 +488,13 @@ export default function NodeList({
width: 90,
render: (_value, record) => formatPct(record.memPct),
},
{
title: t('pages.nodes.networkSpeed'),
key: 'networkSpeed',
align: 'center',
width: 125,
render: (_value, record) => <NodeNetworkSpeed node={record} receivedAt={nodesUpdatedAt} />,
},
{
title: t('pages.nodes.xrayVersion'),
dataIndex: 'xrayVersion',
@@ -585,6 +600,7 @@ export default function NodeList({
showAddress,
relativeTime,
latestVersion,
nodesUpdatedAt,
onToggleEnable,
onProbe,
onEdit,
@@ -706,8 +722,8 @@ export default function NodeList({
role="button"
tabIndex={0}
aria-label={t('info')}
onClick={() => setStatsNode(record)}
onKeyDown={activateOnKey(() => setStatsNode(record))}
onClick={() => setStatsNodeId(record.id)}
onKeyDown={activateOnKey(() => setStatsNodeId(record.id))}
/>
</Tooltip>
<Switch
@@ -795,7 +811,7 @@ export default function NodeList({
width={360}
centered
title={statsNode?.name || ''}
onCancel={() => setStatsNode(null)}
onCancel={() => setStatsNodeId(null)}
>
{statsNode && (
<div className="card-stats">
@@ -860,6 +876,10 @@ export default function NodeList({
<span className="stat-label">{t('pages.nodes.mem')}</span>
<Tag>{formatPct(statsNode.memPct)}</Tag>
</div>
<div className="stat-row">
<span className="stat-label">{t('pages.nodes.networkSpeed')}</span>
<NodeNetworkSpeed node={statsNode} receivedAt={nodesUpdatedAt} />
</div>
<div className="stat-row">
<span className="stat-label">{t('pages.nodes.xrayVersion')}</span>
<Tag>{statsNode.xrayVersion || '-'}</Tag>
@@ -0,0 +1,85 @@
import { useCallback, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
import { Tooltip, theme } from 'antd';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
import type { NodeRecord } from '@/api/queries/useNodesQuery';
import { SizeFormatter } from '@/utils';
const HEARTBEAT_FRESHNESS_MS = 30_000;
export default function NodeNetworkSpeed({
node,
receivedAt,
}: {
node: NodeRecord;
receivedAt?: number;
}) {
const { t } = useTranslation();
const { token } = theme.useToken();
const expiration =
receivedAt && node.heartbeatAgeMillis != null
? receivedAt + HEARTBEAT_FRESHNESS_MS - node.heartbeatAgeMillis
: node.lastHeartbeat
? node.lastHeartbeat * 1000 + HEARTBEAT_FRESHNESS_MS
: 0;
const subscribe = useCallback(
(onChange: () => void) => {
const delay = expiration - Date.now();
const timer =
delay > 0 && delay <= HEARTBEAT_FRESHNESS_MS
? window.setTimeout(onChange, delay)
: undefined;
return () => window.clearTimeout(timer);
},
[expiration],
);
const isFresh = () => {
const delay = expiration - Date.now();
return delay > 0 && delay <= HEARTBEAT_FRESHNESS_MS;
};
const fresh = useSyncExternalStore(subscribe, isFresh);
const available = node.enable && node.status === 'online' && !node.transitive && fresh;
const directions = [
{
key: 'netDown' as const,
label: t('pages.index.download'),
Icon: ArrowDownOutlined,
color: token.colorTextTertiary,
},
{
key: 'netUp' as const,
label: t('pages.index.upload'),
Icon: ArrowUpOutlined,
color: token.colorPrimary,
},
];
return (
<span className="node-network-speed">
{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 (
<Tooltip key={key} title={label}>
<span
role="img"
aria-label={label + ' ' + value}
className="node-network-direction"
dir="ltr"
>
<Icon aria-hidden style={{ color }} />
<span aria-hidden>{value}</span>
</span>
</Tooltip>
);
})}
</span>
);
}
+2 -1
View File
@@ -77,7 +77,7 @@ export default function NodesPage() {
setMessageInstance(messageApi);
}, [messageApi]);
const { nodes, loading, fetched, fetchError, refetch, totals } = useNodesQuery();
const { nodes, nodesUpdatedAt, loading, fetched, fetchError, refetch, totals } = useNodesQuery();
const {
create,
update,
@@ -409,6 +409,7 @@ export default function NodesPage() {
<Col span={24}>
<NodeList
nodes={nodes}
nodesUpdatedAt={nodesUpdatedAt}
loading={loading}
isMobile={isMobile}
latestVersion={latestVersion}
@@ -517,6 +517,19 @@ export default function GeneralTab({ allSetting, updateSetting }: GeneralTabProp
onChange={(e) => updateSetting({ externalTrafficInformURI: e.target.value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.externalTrafficInformInterval')}
>
<InputNumber
min={5}
max={3600}
precision={0}
aria-label={t('pages.settings.externalTrafficInformInterval')}
value={allSetting.externalTrafficInformInterval}
onChange={onNumber((v) => updateSetting({ externalTrafficInformInterval: v }))}
/>
</SettingListItem>
</>
),
},
+3
View File
@@ -16,6 +16,9 @@ export const NodeRecordSchema = z
latencyMs: z.number().optional(),
cpuPct: z.number().optional(),
memPct: z.number().optional(),
netDown: z.number().optional(),
heartbeatAgeMillis: z.number().nonnegative().optional(),
netUp: z.number().optional(),
xrayVersion: z.string().optional(),
panelVersion: z.string().optional(),
uptimeSecs: z.number().optional(),
+1
View File
@@ -87,6 +87,7 @@ export const AllSettingFieldsSchema = z
subDomain: z.string().optional(),
externalTrafficInformEnable: z.boolean().optional(),
externalTrafficInformURI: z.string().optional(),
externalTrafficInformInterval: z.number().int().min(5).max(3600).optional(),
restartXrayOnClientDisable: z.boolean().optional(),
mcpEnable: z.boolean().optional(),
subCertFile: z.string().optional(),
@@ -1,6 +1,8 @@
import { fireEvent, screen, within } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { useState } from 'react';
import { act, fireEvent, screen, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import NodeList from '@/pages/nodes/NodeList';
import NodeNetworkSpeed from '@/pages/nodes/NodeNetworkSpeed';
import { NodeRecordSchema } from '@/schemas/node';
import { renderWithProviders } from './test-utils';
const noop = () => {};
@@ -73,3 +75,101 @@ describe('node metric availability', () => {
expect(cells[headers.indexOf('Uptime')].textContent).toBe('-');
});
});
describe('node network speed', () => {
const controls = {
selectedIds: [],
onSelectionChange: noop,
onAdd: noop,
onMtls: noop,
onEdit: noop,
onDelete: noop,
onProbe: noop,
onToggleEnable: noop,
onUpdateNode: noop,
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 (
<>
<button
type="button"
onClick={() =>
setRecord({ ...record, lastHeartbeat: (node.lastHeartbeat ?? 0) - 120 })
}
>
Age sample
</button>
<NodeList {...controls} nodes={[record]} isMobile={isMobile} />
</>
);
}
renderWithProviders(<Fixture />);
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.each([-120, 120])('expires throughput with %s seconds of clock skew', (skew) => {
vi.useFakeTimers();
try {
const node = NodeRecordSchema.parse({
id: 1,
name: 'edge',
enable: true,
status: 'online',
lastHeartbeat: Math.floor(Date.now() / 1000) + skew,
heartbeatAgeMillis: 250,
netDown: 2048,
netUp: 0,
});
renderWithProviders(<NodeNetworkSpeed node={node} receivedAt={Date.now()} />);
expect(screen.getByLabelText(/^download .*2\.00 KB\/s$/i).textContent).toContain('2.00 KB/s');
act(() => vi.advanceTimersByTime(30_000));
expect(screen.getByLabelText(/^download .*—$/i).textContent).toContain('—');
} finally {
vi.useRealTimers();
}
});
it('honors disabled, legacy, and transitive availability', () => {
const base = { enable: true, status: 'online', lastHeartbeat: Math.floor(Date.now() / 1000) };
renderWithProviders(
<NodeList
{...controls}
nodes={[
{
...base,
id: 1,
name: 'legacy',
unavailableMetrics: ['netUp', 'netDown'],
netDown: 0,
netUp: 0,
},
{ ...base, id: 2, name: 'disabled', enable: false, netDown: 123, netUp: 123 },
{ ...base, id: 3, name: 'descendant', transitive: true, netDown: 123, netUp: 123 },
]}
/>,
);
expect(screen.getAllByLabelText(/^download .*—$/i)).toHaveLength(3);
expect(screen.getAllByLabelText(/^upload .*—$/i)).toHaveLength(3);
});
});
+1
View File
@@ -145,6 +145,7 @@ type AllSetting struct {
SubRateLimit int `json:"subRateLimit" form:"subRateLimit" validate:"gte=1,lte=1000"`
ExternalTrafficInformEnable bool `json:"externalTrafficInformEnable" form:"externalTrafficInformEnable"`
ExternalTrafficInformURI string `json:"externalTrafficInformURI" form:"externalTrafficInformURI"`
TrafficInformInterval int `json:"externalTrafficInformInterval" form:"externalTrafficInformInterval" example:"5"`
RestartXrayOnClientDisable bool `json:"restartXrayOnClientDisable" form:"restartXrayOnClientDisable"`
SubEncrypt bool `json:"subEncrypt" form:"subEncrypt"`
SubURI string `json:"subURI" form:"subURI"`
+165
View File
@@ -0,0 +1,165 @@
package job
import (
"bytes"
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"slices"
"sync"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
const externalInformTimeout = 3 * time.Second
var externalInformClient = &http.Client{
Timeout: externalInformTimeout,
Transport: &http.Transport{DialContext: netsafe.SSRFGuardedDialContext, IdleConnTimeout: time.Minute, MaxIdleConnsPerHost: 1},
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
type informTrafficKey struct {
inbound, outbound bool
tag string
}
type trafficInformBatch struct {
clients map[string]xray.ClientTraffic
traffic map[informTrafficKey]xray.Traffic
}
func (b *trafficInformBatch) add(traffics []*xray.Traffic, clients []*xray.ClientTraffic) {
for _, row := range clients {
if row == nil {
continue
}
sum := b.clients[row.Email]
b.clients[row.Email] = xray.ClientTraffic{Email: row.Email, Up: sum.Up + row.Up, Down: sum.Down + row.Down}
}
for _, row := range traffics {
if row == nil {
continue
}
key := informTrafficKey{row.IsInbound, row.IsOutbound, row.Tag}
sum := b.traffic[key]
b.traffic[key] = xray.Traffic{IsInbound: row.IsInbound, IsOutbound: row.IsOutbound, Tag: row.Tag, Up: sum.Up + row.Up, Down: sum.Down + row.Down}
}
}
func (b *trafficInformBatch) body() ([]byte, error) {
clients := slices.SortedFunc(maps.Values(b.clients), func(x, y xray.ClientTraffic) int { return cmp.Compare(x.Email, y.Email) })
traffic := slices.SortedFunc(maps.Values(b.traffic), func(x, y xray.Traffic) int {
return cmp.Or(cmp.Compare(x.Tag, y.Tag), cmp.Compare(fmt.Sprint(x.IsInbound, x.IsOutbound), fmt.Sprint(y.IsInbound, y.IsOutbound)))
})
return json.Marshal(struct {
Clients []xray.ClientTraffic `json:"clientTraffics"`
Traffic []xray.Traffic `json:"inboundTraffics"`
}{slices.Clip(append([]xray.ClientTraffic{}, clients...)), slices.Clip(append([]xray.Traffic{}, traffic...))})
}
// externalTrafficInform sums deltas between sends and posts each batch exactly once:
// a receiver that does not deduplicate would count a repeated batch twice.
type externalTrafficInform struct {
settingService service.SettingService
mu sync.Mutex
pending *trafficInformBatch
nextSend time.Time
problem string
lost int
}
// collect adds one accounting poll's deltas and hands out the batch once its interval has passed.
// now is when the poll fired, not when its accounting finished.
func (j *externalTrafficInform) collect(now time.Time, traffics []*xray.Traffic, clients []*xray.ClientTraffic) (due *trafficInformBatch, uri string) {
cfg, err := j.settingService.GetExternalTrafficInformConfig()
j.mu.Lock()
defer j.mu.Unlock()
switch {
case err != nil:
j.noteProblem("settings", "Skipping external traffic notification: settings are unavailable: "+err.Error())
return nil, ""
case !cfg.Enabled:
j.pending, j.nextSend, j.problem, j.lost = nil, time.Time{}, "", 0
return nil, ""
case cfg.SkipReason != "":
j.noteProblem(cfg.SkipReason, "Skipping external traffic notification: "+cfg.SkipReason)
return nil, ""
}
if len(traffics) > 0 || len(clients) > 0 {
if j.pending == nil {
j.pending = &trafficInformBatch{clients: make(map[string]xray.ClientTraffic), traffic: make(map[informTrafficKey]xray.Traffic)}
}
j.pending.add(traffics, clients)
}
if j.pending == nil || now.Before(j.nextSend) {
return nil, ""
}
due, j.pending = j.pending, nil
// Polls fire on whole seconds, each a few milliseconds late: without the truncation
// the next poll lands just before nextSend and a 5s interval sends every 10s.
j.nextSend = now.Truncate(time.Second).Add(cfg.Interval)
return due, cfg.URI
}
// deliver posts one batch once. A failure is reported and the batch is dropped, as it always was.
func (j *externalTrafficInform) deliver(batch *trafficInformBatch, uri string) {
reason := postTrafficInform(batch, uri)
j.mu.Lock()
defer j.mu.Unlock()
if reason != "" {
j.noteProblem("delivery", "External traffic notification was not delivered: "+reason)
return
}
if j.lost > 0 {
logger.Infof("External traffic notifications resumed after %d undelivered batch(es)", j.lost)
}
j.problem, j.lost = "", 0
}
// noteProblem warns when a problem starts or changes, not on every batch it costs (#7261).
func (j *externalTrafficInform) noteProblem(problem, warning string) {
j.lost++
if j.problem != problem {
j.problem = problem
logger.Warning(warning)
}
}
func postTrafficInform(batch *trafficInformBatch, uri string) (failure string) {
body, err := batch.body()
if err != nil {
return err.Error()
}
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, uri, bytes.NewReader(body))
if err != nil {
return "the request could not be built"
}
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
resp, err := externalInformClient.Do(req)
if err != nil {
// url.Error repeats the full URI, which may carry a token in its query.
var wrapped *url.Error
if errors.As(err, &wrapped) {
err = wrapped.Err
}
return err.Error()
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Sprintf("the receiver answered HTTP %d", resp.StatusCode)
}
return ""
}
+241 -92
View File
@@ -1,100 +1,194 @@
package job
import (
"errors"
"context"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/valyala/fasthttp"
"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/logger"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func stallingListener(t *testing.T) (addr string, release func()) {
// routeExternalInformTo sends every notification to server, whatever public host the URI names.
func routeExternalInformTo(t *testing.T, server *httptest.Server) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
old := externalInformClient
externalInformClient = &http.Client{
Timeout: externalInformTimeout,
Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return new(net.Dialer).DialContext(ctx, "tcp", server.Listener.Addr().String())
}},
}
done := make(chan struct{})
go func() {
defer close(done)
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(c net.Conn) {
<-done
_ = c.Close()
}(conn)
go func(c net.Conn) { _, _ = io.Copy(io.Discard, c) }(conn)
t.Cleanup(func() {
externalInformClient.CloseIdleConnections()
externalInformClient = old
})
}
func enableExternalInform(t *testing.T, inform *externalTrafficInform, uri string, intervalSeconds int) {
t.Helper()
if err := inform.settingService.SetExternalTrafficInformEnable(true); err != nil {
t.Fatal(err)
}
if err := inform.settingService.SetExternalTrafficInformURI(uri); err != nil {
t.Fatal(err)
}
if intervalSeconds > 0 {
row := model.Setting{Key: "externalTrafficInformInterval", Value: strconv.Itoa(intervalSeconds)}
if err := database.GetDB().Create(&row).Error; err != nil {
t.Fatal(err)
}
}()
return ln.Addr().String(), func() {
_ = ln.Close()
<-done
}
}
func TestExternalInformClient_StalledReceiverTimesOut(t *testing.T) {
addr, release := stallingListener(t)
defer release()
// informLogLines returns what follows marker in every matching log line, oldest first.
func informLogLines(level, marker string) []string {
var lines []string
logs := logger.GetLogs(10240, level)
for i := len(logs) - 1; i >= 0; i-- {
if _, text, found := strings.Cut(logs[i], marker); found {
lines = append(lines, text)
}
}
return lines
}
request := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(request)
request.Header.SetMethod("POST")
request.Header.SetContentType("application/json; charset=UTF-8")
request.SetBody([]byte(`{"clientTraffics":[],"inboundTraffics":[]}`))
request.SetRequestURI("http://" + addr + "/inform")
request.Header.SetConnectionClose()
type informReport struct {
Clients []xray.ClientTraffic `json:"clientTraffics"`
Traffic []xray.Traffic `json:"inboundTraffics"`
}
response := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(response)
func TestExternalInformSumsDeltasUntilTheIntervalPasses(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
inform := new(externalTrafficInform)
enableExternalInform(t, inform, "http://192.0.2.1/traffic", 60)
reports := make(chan informReport, 4)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var report informReport
if err := json.NewDecoder(r.Body).Decode(&report); err != nil {
t.Error(err)
}
reports <- report
w.WriteHeader(http.StatusNoContent)
}))
t.Cleanup(server.Close)
routeExternalInformTo(t, server)
start := time.Now()
err := externalInformClient.DoTimeout(request, response, externalInformTimeout)
elapsed := time.Since(start)
first, uri := inform.collect(start, nil, []*xray.ClientTraffic{{Email: "x@test", Up: 1}})
if first == nil || uri != "http://192.0.2.1/traffic" {
t.Fatalf("the first batch was held back: batch=%v uri=%q", first, uri)
}
inform.deliver(first, uri)
<-reports
if err == nil {
t.Fatal("a receiver that never answers must produce an error, not a completed request")
for _, tick := range []struct {
after time.Duration
traffic []*xray.Traffic
clients []*xray.ClientTraffic
}{
{5 * time.Second, []*xray.Traffic{{Tag: "shared", IsInbound: true, Up: 3}}, []*xray.ClientTraffic{{Email: "x@test", Up: 8}}},
{10 * time.Second, []*xray.Traffic{{Tag: "shared", IsOutbound: true, Down: 4}}, []*xray.ClientTraffic{{Email: "x@test", Up: 6, Down: 2}, {Email: "y@test", Down: 9}}},
{59 * time.Second, []*xray.Traffic{{Tag: "shared", IsInbound: true, Up: 2}}, nil},
} {
if batch, _ := inform.collect(start.Add(tick.after), tick.traffic, tick.clients); batch != nil {
t.Fatalf("a batch was handed out %s into a 60s interval", tick.after)
}
}
if !errors.Is(err, fasthttp.ErrTimeout) {
t.Errorf("want a timeout error, got %v", err)
// An idle tick still flushes what the interval collected.
batch, uri := inform.collect(start.Add(60*time.Second), nil, nil)
if batch == nil {
t.Fatal("no batch was due once the interval had passed")
}
if elapsed > externalInformTimeout+2*time.Second {
t.Errorf("call took %v, must be bounded by %v", elapsed, externalInformTimeout)
inform.deliver(batch, uri)
got := <-reports
wantClients := []xray.ClientTraffic{{Email: "x@test", Up: 14, Down: 2}, {Email: "y@test", Down: 9}}
wantTraffic := []xray.Traffic{{Tag: "shared", IsOutbound: true, Down: 4}, {Tag: "shared", IsInbound: true, Up: 5}}
if len(got.Clients) != 2 || got.Clients[0] != wantClients[0] || got.Clients[1] != wantClients[1] {
t.Errorf("client deltas = %+v, want %+v", got.Clients, wantClients)
}
if len(got.Traffic) != 2 || got.Traffic[0] != wantTraffic[0] || got.Traffic[1] != wantTraffic[1] {
t.Errorf("tag deltas = %+v, want %+v", got.Traffic, wantTraffic)
}
if len(reports) != 0 {
t.Errorf("%d extra reports were sent", len(reports))
}
}
func TestExternalInformClient_HasDeadlines(t *testing.T) {
if externalInformClient.ReadTimeout <= 0 || externalInformClient.WriteTimeout <= 0 {
t.Fatal("the traffic-notify client must carry read and write deadlines")
}
if externalInformTimeout >= 5*time.Second {
t.Errorf("the call budget (%v) must stay under the 5s traffic poll cadence", externalInformTimeout)
func TestExternalInformKeepsPaceWithTheAccountingPoll(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
inform := new(externalTrafficInform)
enableExternalInform(t, inform, "http://192.0.2.1/traffic", 0)
// The poll fires on whole seconds, each time a few milliseconds late by a different amount.
base := time.Date(2026, 11, 29, 13, 38, 0, 0, time.UTC)
for i, lateness := range []time.Duration{12 * time.Millisecond, 9 * time.Millisecond, 4 * time.Millisecond, 30 * time.Millisecond} {
tick := base.Add(time.Duration(i)*5*time.Second + lateness)
if batch, _ := inform.collect(tick, nil, []*xray.ClientTraffic{{Email: "x@test", Up: 1}}); batch == nil {
t.Fatalf("poll %d at +%s was held back: the default interval must send on every poll", i+1, tick.Sub(base))
}
}
}
func TestInformSkippedWhenNothingToReport(t *testing.T) {
j := &XrayTrafficJob{}
done := make(chan struct{})
go func() {
defer close(done)
j.informTrafficToExternalAPI(nil, nil)
}()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("an empty payload must return before touching settings or the network")
func TestExternalInformSendsAFailedBatchOnlyOnce(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
inform := new(externalTrafficInform)
enableExternalInform(t, inform, "http://192.0.2.1/traffic?token=synthetic-secret", 0)
var bodies []string
var healthy atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
bodies = append(bodies, string(body))
if !healthy.Load() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusNoContent)
}))
t.Cleanup(server.Close)
routeExternalInformTo(t, server)
const failed, resumed = "External traffic notification was not delivered: ", "External traffic notifications resumed after "
failuresBefore, resumesBefore := len(informLogLines("WARNING", failed)), len(informLogLines("INFO", resumed))
now := time.Now()
for i, email := range []string{"first@test", "second@test", "third@test", "fourth@test"} {
healthy.Store(i == 3)
batch, uri := inform.collect(now.Add(time.Duration(i)*5*time.Second), nil, []*xray.ClientTraffic{{Email: email, Up: 1}})
if batch == nil {
t.Fatalf("batch %d was not due at the default 5s interval", i+1)
}
inform.deliver(batch, uri)
}
if len(bodies) != 4 {
t.Fatalf("the receiver saw %d requests for 4 batches, want one each", len(bodies))
}
for i, email := range []string{"first@test", "second@test", "third@test", "fourth@test"} {
var report informReport
if err := json.Unmarshal([]byte(bodies[i]), &report); err != nil {
t.Fatal(err)
}
if len(report.Clients) != 1 || report.Clients[0].Email != email || report.Clients[0].Up != 1 {
t.Errorf("request %d carried %s, want only %s: a refused batch must not be sent again", i+1, bodies[i], email)
}
}
failures := informLogLines("WARNING", failed)[failuresBefore:]
if len(failures) != 1 || failures[0] != "the receiver answered HTTP 503" {
t.Errorf("failure warnings = %q, want one naming HTTP 503", failures)
}
resumes := informLogLines("INFO", resumed)[resumesBefore:]
if len(resumes) != 1 || resumes[0] != "3 undelivered batch(es)" {
t.Errorf("recovery lines = %q, want one counting 3 undelivered batches", resumes)
}
}
@@ -105,28 +199,17 @@ func TestXrayTrafficSkipsInvalidExternalInformWithoutLosingCommittedDeltas(t *te
if err := db.Create(&client).Error; err != nil {
t.Fatal(err)
}
var dials atomic.Int32
oldClient := externalInformClient
externalInformClient = &fasthttp.Client{Dial: func(string) (net.Conn, error) {
externalInformClient = &http.Client{Transport: &http.Transport{DialContext: func(context.Context, string, string) (net.Conn, error) {
dials.Add(1)
return nil, errors.New("unexpected notification dial")
}}
return nil, net.ErrClosed
}}}
t.Cleanup(func() { externalInformClient = oldClient })
job := NewXrayTrafficJob()
const warning = "Skipping external traffic notification: "
skipWarnings := func() []string {
var reasons []string
for _, line := range logger.GetLogs(10240, "WARNING") {
if _, reason, found := strings.Cut(line, warning); found {
reasons = append(reasons, reason)
}
}
return reasons
}
countWarnings := func() int { return len(skipWarnings()) }
before := countWarnings()
const skipped = "Skipping external traffic notification: "
before := len(informLogLines("WARNING", skipped))
run := func(enabled bool, uri, sampleID string) {
t.Helper()
if err := job.settingService.SetExternalTrafficInformEnable(enabled); err != nil {
@@ -139,24 +222,23 @@ func TestXrayTrafficSkipsInvalidExternalInformWithoutLosingCommittedDeltas(t *te
job.Run()
}
run(true, "https://user:synthetic-secret@example.test:bad/traffic", "malformed")
run(true, "https://user:synthetic-secret@example.test:bad/traffic", "malformed-again")
run(true, " \t ", "whitespace")
run(true, "", "empty")
if got := countWarnings() - before; got != 1 {
t.Errorf("warnings during one invalid episode = %d, want 1", got)
}
run(false, "", "disabled")
run(true, "http://127.0.0.1/traffic", "blocked")
if got := countWarnings() - before; got != 2 {
t.Errorf("warnings across two invalid episodes = %d, want 2", got)
run(true, "", "empty-again")
want := []string{
"ExternalTrafficInformURI is not a valid http(s) URL",
"ExternalTrafficInformURI is empty",
"ExternalTrafficInformURI is empty",
}
// GetLogs returns newest first: a rejected destination must say why it was rejected.
if reasons := skipWarnings(); len(reasons) == 0 || reasons[0] != "blocked private/internal address 127.0.0.1" {
t.Errorf("blocked destination warning = %q, want the private-address reason", reasons)
got := informLogLines("WARNING", skipped)[before:]
if strings.Join(got, "|") != strings.Join(want, "|") {
t.Errorf("skip warnings = %q, want one per problem and one more after re-enabling: %q", got, want)
}
for _, line := range logger.GetLogs(32, "WARNING") {
if strings.Contains(line, "ExternalTrafficInformURI") && strings.Contains(line, "synthetic-secret") {
t.Error("external inform diagnostic disclosed the synthetic credential")
for _, line := range logger.GetLogs(10240, "WARNING") {
if strings.Contains(line, "synthetic-secret") {
t.Errorf("a warning disclosed the URI's credential: %s", line)
}
}
if got := dials.Load(); got != 0 {
@@ -165,7 +247,74 @@ func TestXrayTrafficSkipsInvalidExternalInformWithoutLosingCommittedDeltas(t *te
if err := db.First(&client, client.Id).Error; err != nil {
t.Fatal(err)
}
if client.Up != 55 || client.Down != 35 || client.LastOnline <= 0 {
t.Errorf("stored counters and activity = (%d, %d, %d), want (55, 35, positive last online)", client.Up, client.Down, client.LastOnline)
if client.Up != 66 || client.Down != 42 || client.LastOnline <= 0 {
t.Errorf("stored counters and activity = (%d, %d, %d), want (66, 42, positive last online)", client.Up, client.Down, client.LastOnline)
}
}
func TestExternalInformRefusesAPrivateDestinationAtDialTime(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
inform := new(externalTrafficInform)
enableExternalInform(t, inform, "http://"+listener.Addr().String()+"/traffic", 0)
const failed = "External traffic notification was not delivered: "
before := len(informLogLines("WARNING", failed))
batch, uri := inform.collect(time.Now(), nil, []*xray.ClientTraffic{{Email: "x@test", Up: 1}})
if batch == nil {
t.Fatal("a well-formed URI must reach the dial-time check")
}
inform.deliver(batch, uri)
reasons := informLogLines("WARNING", failed)[before:]
if len(reasons) != 1 || !strings.Contains(reasons[0], "127.0.0.1") || strings.Contains(reasons[0], "/traffic") {
t.Errorf("failure warnings = %q, want one naming the blocked address and not the URI", reasons)
}
_ = listener.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond))
if conn, err := listener.Accept(); err == nil {
_ = conn.Close()
t.Fatal("the notification dialed a loopback listener")
}
}
func TestXrayTrafficRunDoesNotWaitForAStalledReceiver(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
release := make(chan struct{})
reached := make(chan struct{}, 1)
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
reached <- struct{}{}
select {
case <-release:
case <-r.Context().Done():
}
}))
t.Cleanup(server.Close)
t.Cleanup(func() { close(release) })
routeExternalInformTo(t, server)
job := NewXrayTrafficJob()
enableExternalInform(t, &job.externalInform, "http://192.0.2.1/traffic", 0)
job.pending = &xrayTrafficSample{id: "stalled", clients: []*xray.ClientTraffic{{Email: "x@test", Up: 1}}}
started := time.Now()
job.Run()
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("the accounting tick took %s while the receiver stalled", elapsed)
}
select {
case <-reached:
case <-time.After(2 * time.Second):
t.Fatal("the report never left the panel")
}
const failed = "External traffic notification was not delivered: "
before := len(informLogLines("WARNING", failed))
deadline := time.Now().Add(externalInformTimeout + 2*time.Second)
for len(informLogLines("WARNING", failed)) == before {
if time.Now().After(deadline) {
t.Fatalf("a stalled receiver was not given up on within %s", externalInformTimeout)
}
time.Sleep(50 * time.Millisecond)
}
}
+6 -73
View File
@@ -1,19 +1,17 @@
package job
import (
"encoding/json"
"sync"
"time"
"github.com/google/uuid"
"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"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/outbound"
"github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
"github.com/valyala/fasthttp"
)
// XrayTrafficJob collects and processes traffic statistics from Xray, updating the database and optionally informing external APIs.
@@ -24,8 +22,7 @@ type XrayTrafficJob struct {
outboundService outbound.OutboundService
runMu sync.Mutex
pending *xrayTrafficSample
externalInformInvalidLogged bool
externalInform externalTrafficInform
}
type xrayTrafficSample struct {
@@ -73,15 +70,6 @@ func splitMovedClientTraffics(clientTraffics []*xray.ClientTraffic) ([]*xray.Cli
return moved, emails, active
}
const externalInformTimeout = 3 * time.Second
var externalInformClient = &fasthttp.Client{
ReadTimeout: externalInformTimeout,
WriteTimeout: externalInformTimeout,
MaxIdleConnDuration: time.Minute,
MaxConnsPerHost: 4,
}
// NewXrayTrafficJob creates a new traffic collection job instance.
func NewXrayTrafficJob() *XrayTrafficJob {
return new(XrayTrafficJob)
@@ -109,6 +97,7 @@ func (j *XrayTrafficJob) pollTraffic(collect func() ([]*xray.Traffic, []*xray.Cl
// real-time updates over WebSocket using compact delta payloads — no REST
// fallback, scales to 10k–20k+ clients per inbound.
func (j *XrayTrafficJob) Run() {
polledAt := time.Now()
j.runMu.Lock()
defer j.runMu.Unlock()
if j.pending == nil && !j.xrayService.IsXrayRunning() {
@@ -137,12 +126,9 @@ func (j *XrayTrafficJob) Run() {
if needRestart {
j.xrayService.SetToNeedRestartFrom(service.XrayOriginTrafficAccounting)
}
if enabled, err := j.settingService.GetExternalTrafficInformEnable(); err != nil {
logger.Warning("get ExternalTrafficInformEnable failed:", err)
} else if enabled {
j.informTrafficToExternalAPI(traffics, clientTraffics)
} else {
j.externalInformInvalidLogged = false
if batch, uri := j.externalInform.collect(polledAt, traffics, clientTraffics); batch != nil {
// Off the accounting tick: a slow receiver must not delay the next poll.
common.GoRecover("external-traffic-inform", func() { j.externalInform.deliver(batch, uri) })
}
// Live online statistics require a running core. The committed sample does not.
@@ -265,56 +251,3 @@ func (j *XrayTrafficJob) Run() {
logger.Warning("get all outbounds for websocket failed:", err)
}
}
// externalInformDestination never echoes a malformed URI: url.Parse errors quote it,
// credentials included. Destination checks name only the host, so those pass through.
func externalInformDestination(raw string) (destination, skipReason string) {
clean, err := service.SanitizeHTTPURL(raw)
if err != nil {
return "", "ExternalTrafficInformURI is not a valid http(s) URL"
}
if clean == "" {
return "", "ExternalTrafficInformURI is empty"
}
if clean, err = service.SanitizePublicHTTPURL(clean, false); err != nil {
return "", err.Error()
}
return clean, ""
}
func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
if len(inboundTraffics) == 0 && len(clientTraffics) == 0 {
return
}
informURL, err := j.settingService.GetExternalTrafficInformURI()
if err != nil {
logger.Warning("get ExternalTrafficInformURI failed:", err)
return
}
informURL, skipReason := externalInformDestination(informURL)
if skipReason != "" {
if !j.externalInformInvalidLogged {
logger.Warning("Skipping external traffic notification: " + skipReason)
j.externalInformInvalidLogged = true
}
return
}
j.externalInformInvalidLogged = false
requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
if err != nil {
logger.Warning("parse client/inbound traffic failed:", err)
return
}
request := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(request)
request.Header.SetMethod("POST")
request.Header.SetContentType("application/json; charset=UTF-8")
request.SetBody(requestBody)
request.SetRequestURI(informURL)
request.Header.SetConnectionClose()
response := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(response)
if err := externalInformClient.DoTimeout(request, response, externalInformTimeout); err != nil {
logger.Warning("POST ExternalTrafficInformURI failed:", err)
}
}
+14 -8
View File
@@ -14,7 +14,6 @@ import (
"testing"
"time"
"github.com/valyala/fasthttp"
stats "github.com/xtls/xray-core/app/stats/command"
"google.golang.org/grpc"
"gorm.io/gorm"
@@ -90,9 +89,9 @@ func TestXrayTrafficRunFinishesCommittedSampleWhileStopped(t *testing.T) {
}))
t.Cleanup(server.Close)
oldClient := externalInformClient
externalInformClient = &fasthttp.Client{Dial: func(string) (net.Conn, error) {
return net.DialTimeout("tcp", server.Listener.Addr().String(), time.Second)
}}
externalInformClient = &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return new(net.Dialer).DialContext(ctx, "tcp", server.Listener.Addr().String())
}}}
t.Cleanup(func() { externalInformClient = oldClient })
hub := websocket.NewHub()
@@ -144,10 +143,17 @@ func TestXrayTrafficRunFinishesCommittedSampleWhileStopped(t *testing.T) {
if !job.xrayService.IsNeedRestartAndSetFalse() {
t.Error("restart was not queued after disabling a client with Xray stopped")
}
if len(informs) != 1 {
t.Errorf("sent %d external reports, want 1", len(informs))
} else if report := <-informs; len(report.Clients) != 1 || report.Clients[0].Email != client.Email || report.Clients[0].Up != 10 {
t.Errorf("external report did not include the committed delta: %+v", report)
// The report leaves the accounting tick on its own goroutine, and the idle second run adds none.
select {
case report := <-informs:
if len(report.Clients) != 1 || report.Clients[0].Email != client.Email || report.Clients[0].Up != 10 {
t.Errorf("external report did not include the committed delta: %+v", report)
}
case <-time.After(2 * time.Second):
t.Error("the committed delta was never reported")
}
if len(informs) != 0 {
t.Errorf("sent %d extra external reports, want exactly 1", len(informs))
}
select {
case data := <-listener.Send:
@@ -0,0 +1,59 @@
package service
import (
"strconv"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
const (
externalTrafficInformIntervalKey = "externalTrafficInformInterval"
minExternalTrafficInformInterval = 5
maxExternalTrafficInformInterval = 3600
)
// ExternalTrafficInformConfig is one committed snapshot of the webhook settings.
type ExternalTrafficInformConfig struct {
Enabled bool
URI string
Interval time.Duration
// SkipReason says why an enabled webhook cannot be sent; it never quotes the stored URI.
SkipReason string
}
func (s *SettingService) GetExternalTrafficInformConfig() (ExternalTrafficInformConfig, error) {
keys := []string{"externalTrafficInformEnable", "externalTrafficInformURI", externalTrafficInformIntervalKey}
var rows []model.Setting
if err := database.GetDB().Where("key IN ?", keys).Find(&rows).Error; err != nil {
return ExternalTrafficInformConfig{}, err
}
stored := make(map[string]string, len(rows))
for _, row := range rows {
stored[row.Key] = row.Value
}
effective := func(key string) string { return effectiveSettingValue(key, stored[key]) }
if effective("externalTrafficInformEnable") != "true" {
return ExternalTrafficInformConfig{}, nil
}
seconds, err := strconv.Atoi(effective(externalTrafficInformIntervalKey))
if err != nil || !validExternalTrafficInformInterval(seconds) {
seconds = minExternalTrafficInformInterval
}
cfg := ExternalTrafficInformConfig{Enabled: true, Interval: time.Duration(seconds) * time.Second}
// A url.Parse error quotes the URI, credentials included, so it is not passed on.
switch uri, err := SanitizeHTTPURL(stored["externalTrafficInformURI"]); {
case err != nil:
cfg.SkipReason = "ExternalTrafficInformURI is not a valid http(s) URL"
case uri == "":
cfg.SkipReason = "ExternalTrafficInformURI is empty"
default:
cfg.URI = uri
}
return cfg, nil
}
func validExternalTrafficInformInterval(seconds int) bool {
return seconds >= minExternalTrafficInformInterval && seconds <= maxExternalTrafficInformInterval
}
@@ -0,0 +1,39 @@
package service
import (
"path/filepath"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
)
func TestExternalTrafficInformIntervalSurvivesLegacySave(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
service := new(SettingService)
all, err := service.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if all.TrafficInformInterval != 5 {
t.Fatalf("default interval = %d, want 5s", all.TrafficInformInterval)
}
all.ExternalTrafficInformEnable = true
all.ExternalTrafficInformURI = "https://example.test/traffic"
all.TrafficInformInterval = 60
if err := service.UpdateAllSetting(all, SecretClears{}); err != nil {
t.Fatal(err)
}
all.TrafficInformInterval = 0
if err := service.UpdateAllSetting(all, SecretClears{}); err != nil {
t.Fatal(err)
}
all.TrafficInformInterval = 3601
if err := service.UpdateAllSetting(all, SecretClears{}); err == nil || err.Error() != "external traffic inform interval must be between 5 and 3600 seconds" {
t.Fatalf("invalid interval save = %v", err)
}
cfg, err := service.GetExternalTrafficInformConfig()
if err != nil || cfg.Interval != time.Minute || cfg.URI != "https://example.test/traffic" {
t.Fatalf("effective configuration = %+v, error = %v", cfg, err)
}
}
+17 -9
View File
@@ -1379,13 +1379,10 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
State string `json:"state"`
ErrorMsg string `json:"errorMsg"`
} `json:"xray"`
PanelVersion string `json:"panelVersion"`
PanelGuid string `json:"panelGuid"`
Uptime uint64 `json:"uptime"`
NetIO struct {
Up uint64 `json:"up"`
Down uint64 `json:"down"`
} `json:"netIO"`
PanelVersion string `json:"panelVersion"`
PanelGuid string `json:"panelGuid"`
Uptime uint64 `json:"uptime"`
NetIO json.RawMessage `json:"netIO"`
} `json:"obj"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxProbeBodyBytes)).Decode(&envelope); err != nil {
@@ -1418,8 +1415,19 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
}
patch.Guid = o.PanelGuid
patch.UptimeSecs = o.Uptime
patch.NetUp = o.NetIO.Up
patch.NetDown = o.NetIO.Down
var network map[string]json.RawMessage
_ = json.Unmarshal(o.NetIO, &network)
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
} else if !slices.Contains(patch.UnavailableMetrics, metric.key) {
patch.UnavailableMetrics = append(patch.UnavailableMetrics, metric.key)
}
}
return patch, nil
}
+1
View File
@@ -28,6 +28,7 @@ type NodeView struct {
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"`
+26 -2
View File
@@ -120,8 +120,8 @@ func unavailableMetricsOf(t *testing.T, value any) []string {
}
const (
unavailableStatusBody = `{"success":true,"obj":{"cpu":0,"uptime":0,"unavailableMetrics":["cpu","uptime"],"mem":{"current":1,"total":2},"xray":{"state":"running"}}}`
zeroStatusBody = `{"success":true,"obj":{"cpu":0,"uptime":0,"mem":{"current":1,"total":2},"xray":{"state":"running"}}}`
unavailableStatusBody = `{"success":true,"obj":{"cpu":0,"uptime":0,"unavailableMetrics":["cpu","uptime"],"mem":{"current":1,"total":2},"netIO":{"up":0,"down":0},"xray":{"state":"running"}}}`
zeroStatusBody = `{"success":true,"obj":{"cpu":0,"uptime":0,"mem":{"current":1,"total":2},"netIO":{"up":0,"down":0},"xray":{"state":"running"}}}`
)
func TestProbeKeepsMetricAvailability(t *testing.T) {
@@ -230,3 +230,27 @@ func TestNodeAvailabilityColumnKeepsLegacyRows(t *testing.T) {
t.Fatalf("legacy row changed: id=%d availability=%v", stored.Id, stored.UnavailableMetrics)
}
}
func TestProbeDistinguishesMissingNetworkMetricsFromZero(t *testing.T) {
svc, n, setBody := availabilityNodeFixture(t, `{"success":true,"obj":{"panelGuid":"legacy"}}`)
patch, err := svc.Probe(context.Background(), n)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(patch.UnavailableMetrics, []string{"netUp", "netDown"}) {
t.Fatalf("legacy metric availability = %v, want missing throughput directions", patch.UnavailableMetrics)
}
setBody(`{"success":true,"obj":{"panelGuid":"legacy","netIO":{"up":0}}}`)
patch, err = svc.Probe(context.Background(), n)
if err != nil {
t.Fatal(err)
}
if patch.NetUp != 0 || !slices.Equal(patch.UnavailableMetrics, []string{"netDown"}) {
t.Fatalf("zero upload or missing download was lost: %+v", patch)
}
setBody(`{"success":true,"obj":{"panelGuid":"legacy","netIO":{"up":-1,"down":250}}}`)
patch, err = svc.Probe(context.Background(), n)
if err != nil || patch.NetDown != 250 || !slices.Equal(patch.UnavailableMetrics, []string{"netUp"}) {
t.Fatalf("one invalid rate should not hide the valid direction: %+v, %v", patch, err)
}
}
+9 -1
View File
@@ -3,6 +3,7 @@ package service
import (
"context"
"sync"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
@@ -184,7 +185,14 @@ func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
if err != nil {
return nil, err
}
return toNodeViews(nodes), nil
views := toNodeViews(nodes)
now := time.Now()
for _, view := range views {
if view.LastHeartbeat > 0 && !view.Transitive {
view.HeartbeatAgeMillis = new(max(0, now.Sub(time.Unix(view.LastHeartbeat, 0)).Milliseconds()))
}
}
return views, nil
}
// recountByGuid recomputes InboundCount/OnlineCount/DepletedCount for every node
+27
View File
@@ -2,6 +2,7 @@ package service
import (
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
@@ -80,3 +81,29 @@ func TestGetNodeTree_SurfacesTransitiveNodeNestedUnderParent(t *testing.T) {
t.Errorf("transitive Node3 should host its 1 inbound, got %d", node3.InboundCount)
}
}
func TestNodeTreeViewReportsMasterRelativeHeartbeatAge(t *testing.T) {
setupConflictDB(t)
now := time.Now()
for _, node := range []model.Node{
{Name: "sampled", Address: "10.0.0.2", Port: 2053, LastHeartbeat: now.Add(-5 * time.Second).Unix()},
{Name: "unprobed", Address: "10.0.0.3", Port: 2053},
} {
if err := database.GetDB().Create(&node).Error; err != nil {
t.Fatalf("create node: %v", err)
}
}
views, err := (&NodeService{}).GetNodeTreeView()
if err != nil || len(views) != 2 {
t.Fatalf("get node views: len=%d err=%v", len(views), err)
}
sampled, unprobed := views[0], views[1]
minAge := now.UnixMilli() - sampled.LastHeartbeat*1000
maxAge := time.Now().UnixMilli() - sampled.LastHeartbeat*1000
if age := sampled.HeartbeatAgeMillis; age == nil || *age < minAge || *age > maxAge {
t.Fatalf("sampled heartbeat age = %v, want a value in [%d, %d]", age, minAge, maxAge)
}
if unprobed.HeartbeatAgeMillis != nil {
t.Fatal("unprobed node has a heartbeat age")
}
}
+13 -4
View File
@@ -224,10 +224,13 @@ var defaultValueMap = map[string]string{
"pia": "",
"externalTrafficInformEnable": "false",
"externalTrafficInformURI": "",
"restartXrayOnClientDisable": "true",
"xrayOutboundTestUrl": "https://www.google.com/generate_204",
"panelOutbound": "",
"devChannelEnable": "false",
externalTrafficInformIntervalKey: "5",
"restartXrayOnClientDisable": "true",
"xrayOutboundTestUrl": "https://www.google.com/generate_204",
"panelOutbound": "",
"devChannelEnable": "false",
// LDAP defaults
"ldapEnable": "false",
@@ -1758,6 +1761,9 @@ type SecretClears struct {
func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears SecretClears) error {
preserveTrafficSelection := allSetting.NetworkTrafficMode == ""
if seconds := allSetting.TrafficInformInterval; seconds != 0 && !validExternalTrafficInformInterval(seconds) {
return errors.New("external traffic inform interval must be between 5 and 3600 seconds")
}
if err := validateNetworkTrafficSettings(allSetting); err != nil {
return err
}
@@ -1840,6 +1846,9 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears
if preserveTrafficSelection && (key == "networkTrafficMode" || key == "networkTrafficInterface") {
continue
}
if key == externalTrafficInformIntervalKey && allSetting.TrafficInformInterval == 0 {
continue
}
fieldV := v.FieldByName(field.Name)
value := fmt.Sprint(fieldV.Interface())
if st, ok := byKey[key]; ok {
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "الذاكرة",
"netUp": "صعود الشبكة (KB/s)",
"networkSpeed": "سرعة الشبكة",
"netDown": "نزول الشبكة (KB/s)",
"uptime": "مدة التشغيل",
"latency": "الكمون",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "إخطار واجهة API خارجية بكل تحديث لحركة المرور.",
"externalTrafficInformURI": "مسار تنبيه الترافيك الخارجي",
"externalTrafficInformURIDesc": "تحديثات الترافيك هتتبعت للمسار ده.",
"externalTrafficInformInterval": "فاصل إرسال بيانات المرور الخارجية (بالثواني)",
"restartXrayOnClientDisable": "إعادة تشغيل Xray بعد تعطيل العميل",
"restartXrayOnClientDisableDesc": "عندما يتوقف تقديم الخدمة للعميل — بتعطيل تلقائي بسبب انتهاء الصلاحية أو حد حركة المرور، أو بتعطيل أو حذف يدوي — أعد تشغيل Xray لإنهاء اتصالاته النشطة.",
"fragment": "تجزئة",
+2
View File
@@ -1376,6 +1376,7 @@
"cpu": "CPU",
"mem": "Memory",
"netUp": "Net Up (KB/s)",
"networkSpeed": "Network speed",
"netDown": "Net Down (KB/s)",
"uptime": "Uptime",
"latency": "Latency",
@@ -1643,6 +1644,7 @@
"externalTrafficInformEnableDesc": "Inform external API on every traffic update.",
"externalTrafficInformURI": "External Traffic Inform URI",
"externalTrafficInformURIDesc": "Traffic updates are sent to this URI.",
"externalTrafficInformInterval": "External traffic inform interval (seconds)",
"restartXrayOnClientDisable": "Restart Xray After Client Disable",
"restartXrayOnClientDisableDesc": "When a client stops being served - auto-disabled by expiration or traffic limit, or disabled or deleted by hand - restart Xray so its live connections end.",
"fragment": "Fragmentation",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "Memoria",
"netUp": "Subida de red (KB/s)",
"networkSpeed": "Velocidad de red",
"netDown": "Bajada de red (KB/s)",
"uptime": "Tiempo activo",
"latency": "Latencia",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "Informar a una API externa en cada actualización de tráfico.",
"externalTrafficInformURI": "URI de información de tráfico externo",
"externalTrafficInformURIDesc": "Las actualizaciones de tráfico se envían a este URI.",
"externalTrafficInformInterval": "Intervalo de aviso de tráfico externo (segundos)",
"restartXrayOnClientDisable": "Reiniciar Xray al desactivar un cliente",
"restartXrayOnClientDisableDesc": "Cuando un cliente deja de atenderse — desactivado automáticamente por vencimiento o límite de tráfico, o desactivado o eliminado a mano — reiniciar Xray para que terminen sus conexiones activas.",
"fragment": "Fragmentación",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "حافظه",
"netUp": "آپلود شبکه (KB/s)",
"networkSpeed": "سرعت شبکه",
"netDown": "دانلود شبکه (KB/s)",
"uptime": "مدت فعالیت",
"latency": "تاخیر",
@@ -1522,6 +1523,7 @@
"externalTrafficInformEnableDesc": "به API خارجی در هر به‌روزرسانی ترافیک اطلاع بده.",
"externalTrafficInformURI": "لینک اطلاع رسانی خارجی مصرف ترافیک",
"externalTrafficInformURIDesc": "ترافیک های مصرفی به این لینک هم ارسال می شود",
"externalTrafficInformInterval": "فاصلهٔ ارسال گزارش ترافیک خارجی (ثانیه)",
"restartXrayOnClientDisable": "ری‌استارت Xray پس از غیرفعال‌سازی کلاینت",
"restartXrayOnClientDisableDesc": "وقتی دیگر به کاربر سرویس داده نمی‌شود — غیرفعال شدن خودکار به‌خاطر اتمام زمان یا محدودیت ترافیک، یا غیرفعال/حذف دستی — Xray ری‌استارت شود تا اتصال‌های فعالش بسته شوند.",
"fragment": "فرگمنت",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "Memori",
"netUp": "Upload Jaringan (KB/s)",
"networkSpeed": "Kecepatan jaringan",
"netDown": "Download Jaringan (KB/s)",
"uptime": "Uptime",
"latency": "Latensi",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "Beritahu API eksternal setiap kali ada pembaruan trafik.",
"externalTrafficInformURI": "Lalu Lintas Eksternal Menginformasikan URI",
"externalTrafficInformURIDesc": "Pembaruan lalu lintas dikirim ke URI ini.",
"externalTrafficInformInterval": "Interval pemberitahuan lalu lintas eksternal (detik)",
"restartXrayOnClientDisable": "Nyalakan Ulang Xray Setelah Klien Dinonaktifkan",
"restartXrayOnClientDisableDesc": "Saat klien berhenti dilayani — dinonaktifkan otomatis karena kedaluwarsa atau batas trafik, atau dinonaktifkan maupun dihapus secara manual — mulai ulang Xray agar koneksi aktifnya berakhir.",
"fragment": "Fragmentasi",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "メモリ",
"netUp": "送信 (KB/s)",
"networkSpeed": "ネットワーク速度",
"netDown": "受信 (KB/s)",
"uptime": "稼働時間",
"latency": "レイテンシ",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "トラフィック更新ごとに外部 API に通知。",
"externalTrafficInformURI": "外部トラフィック通知 URI",
"externalTrafficInformURIDesc": "トラフィックの更新ごとに外部 API に通知します。",
"externalTrafficInformInterval": "外部トラフィック通知間隔(秒)",
"restartXrayOnClientDisable": "クライアント無効化後に Xray を再起動",
"restartXrayOnClientDisableDesc": "クライアントがサービス対象でなくなったとき(有効期限や通信量上限による自動無効化、または手動での無効化・削除)、接続を終わらせるため Xray を再起動します。",
"fragment": "フラグメント",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "Memória",
"netUp": "Subida de rede (KB/s)",
"networkSpeed": "Velocidade de rede",
"netDown": "Descida de rede (KB/s)",
"uptime": "Tempo ativo",
"latency": "Latência",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "Informar API externa a cada atualização de tráfego.",
"externalTrafficInformURI": "URI de informação de tráfego externo",
"externalTrafficInformURIDesc": "As atualizações de tráfego são enviadas para este URI.",
"externalTrafficInformInterval": "Intervalo de notificação externa de tráfego (segundos)",
"restartXrayOnClientDisable": "Reiniciar Xray Após Desativar um Cliente",
"restartXrayOnClientDisableDesc": "Quando um cliente deixa de ser atendido — desativado automaticamente por expiração ou limite de tráfego, ou desativado ou excluído manualmente — reinicie o Xray para encerrar suas conexões ativas.",
"fragment": "Fragmentação",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "Память",
"netUp": "Отдача (KB/s)",
"networkSpeed": "Скорость сети",
"netDown": "Приём (KB/s)",
"uptime": "Аптайм",
"latency": "Задержка",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "Уведомлять внешний API при каждом обновлении трафика.",
"externalTrafficInformURI": "URI информации о внешнем трафике",
"externalTrafficInformURIDesc": "Обновления трафика отправляются на этот URI",
"externalTrafficInformInterval": "Интервал внешних уведомлений о трафике (секунды)",
"restartXrayOnClientDisable": "Перезапускать Xray после отключения клиента",
"restartXrayOnClientDisableDesc": "Когда клиент перестаёт обслуживаться — автоматически (по сроку или лимиту трафика) или вручную — перезапускать Xray, чтобы его активные соединения оборвались.",
"fragment": "Фрагментация",
+2
View File
@@ -1376,6 +1376,7 @@
"cpu": "CPU",
"mem": "Pamäť",
"netUp": "Odosielanie (KB/s)",
"networkSpeed": "Rýchlosť siete",
"netDown": "Sťahovanie (KB/s)",
"uptime": "Čas prevádzky",
"latency": "Odozva",
@@ -1643,6 +1644,7 @@
"externalTrafficInformEnableDesc": "Pri každej aktualizácii spotreby informovať externé API.",
"externalTrafficInformURI": "URI externého hlásenia spotreby",
"externalTrafficInformURIDesc": "Na túto URI sa posielajú aktualizácie spotreby.",
"externalTrafficInformInterval": "Interval externých upozornení o prevádzke (sekundy)",
"restartXrayOnClientDisable": "Reštartovať Xray po vypnutí klienta",
"restartXrayOnClientDisableDesc": "Keď klient stratí prístup pre skončenú platnosť alebo vyčerpaný limit, prípadne ho správca vypne či odstráni, reštartovať Xray a ukončiť jeho existujúce spojenia.",
"fragment": "Fragmentácia",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "Bellek",
"netUp": "Ağ Yükleme (KB/s)",
"networkSpeed": "Ağ hızı",
"netDown": "Ağ İndirme (KB/s)",
"uptime": "Çalışma Süresi",
"latency": "Gecikme",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "Her trafik güncellemesinde harici API'yi bilgilendirir.",
"externalTrafficInformURI": "Harici Trafik Bilgisi URI'si",
"externalTrafficInformURIDesc": "Trafik güncellemeleri bu URI'ye gönderilir.",
"externalTrafficInformInterval": "Harici trafik bildirim aralığı (saniye)",
"restartXrayOnClientDisable": "İstemci Devre Dışı Bırakıldığında Xray'i Yeniden Başlat",
"restartXrayOnClientDisableDesc": "Bir istemci artık sunulmadığında — süre dolumu veya trafik limiti nedeniyle otomatik, ya da elle devre dışı bırakıldığında veya silindiğinde — açık bağlantıları bitsin diye Xray'i yeniden başlatır.",
"fragment": "Parçalama",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "Пам'ять",
"netUp": "Вихідний (KB/s)",
"networkSpeed": "Швидкість мережі",
"netDown": "Вхідний (KB/s)",
"uptime": "Час роботи",
"latency": "Затримка",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "Повідомляти зовнішній API про кожне оновлення трафіку.",
"externalTrafficInformURI": "Інформаційний URI зовнішнього трафіку",
"externalTrafficInformURIDesc": "Оновлення трафіку надсилаються на цей URI.",
"externalTrafficInformInterval": "Інтервал зовнішніх сповіщень про трафік (секунди)",
"restartXrayOnClientDisable": "Перезапускати Xray після вимкнення клієнта",
"restartXrayOnClientDisableDesc": "Коли клієнт перестає обслуговуватися — автоматично (через термін дії чи ліміт трафіку) або вручну — перезапускати Xray, щоб його активні з'єднання обірвалися.",
"fragment": "Фрагментація",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "Bộ nhớ",
"netUp": "Mạng lên (KB/s)",
"networkSpeed": "Tốc độ mạng",
"netDown": "Mạng xuống (KB/s)",
"uptime": "Thời gian hoạt động",
"latency": "Độ trễ",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "Thông báo API ngoài mỗi khi cập nhật lưu lượng.",
"externalTrafficInformURI": "URI thông báo lưu lượng truy cập bên ngoài",
"externalTrafficInformURIDesc": "Cập nhật lưu lượng truy cập được gửi tới URI này.",
"externalTrafficInformInterval": "Khoảng thời gian thông báo lưu lượng ra ngoài (giây)",
"restartXrayOnClientDisable": "Khởi Động Lại Xray Sau Khi Vô Hiệu Hóa Máy Khách",
"restartXrayOnClientDisableDesc": "Khi một máy khách không còn được phục vụ — bị vô hiệu hóa tự động do hết hạn hoặc giới hạn lưu lượng, hoặc bị vô hiệu hóa hay xóa thủ công — hãy khởi động lại Xray để các kết nối đang mở của nó kết thúc.",
"fragment": "Sự phân mảnh",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "内存",
"netUp": "网络上行 (KB/s)",
"networkSpeed": "网络速率",
"netDown": "网络下行 (KB/s)",
"uptime": "运行时长",
"latency": "延迟",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "每次流量更新时通知外部 API。",
"externalTrafficInformURI": "外部流量通知 URI",
"externalTrafficInformURIDesc": "流量更新将发送到此 URI",
"externalTrafficInformInterval": "外部流量通知间隔(秒)",
"restartXrayOnClientDisable": "客户端被禁用后重启 Xray",
"restartXrayOnClientDisableDesc": "当客户端不再被服务时——因到期或流量超限被自动禁用,或被手动禁用、删除——重启 Xray 以断开其活动连接。",
"fragment": "分片",
+2
View File
@@ -1255,6 +1255,7 @@
"cpu": "CPU",
"mem": "記憶體",
"netUp": "網路上行 (KB/s)",
"networkSpeed": "網路速率",
"netDown": "網路下行 (KB/s)",
"uptime": "運行時間",
"latency": "延遲",
@@ -1518,6 +1519,7 @@
"externalTrafficInformEnableDesc": "每次流量更新時通知外部 API。",
"externalTrafficInformURI": "外部流量通知 URI",
"externalTrafficInformURIDesc": "流量更新將會傳送到此 URI",
"externalTrafficInformInterval": "外部流量通知間隔(秒)",
"restartXrayOnClientDisable": "用戶被停用後重新啟動 Xray",
"restartXrayOnClientDisableDesc": "當用戶不再被服務時——因到期或流量上限被自動停用,或被手動停用、刪除——重新啟動 Xray 以中斷其作用中的連線。",
"fragment": "分片",