mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-09-04 01:17:15 +00:00
feat(sub): leastLoad member weights for subscription balancers (#6304)
* feat(model): add MemberWeights to SubBalancer Per-inbound leastLoad weights, stored with the same gorm json serializer as InboundIds so AutoMigrate adds the text column on every dialect (postgresModelSettled sees the missing column and re-runs). Absent entries mean weight 1.0; only meaningful for strategy leastLoad. * feat(sub): accept memberWeights on the sub-balancer API Parsed as one JSON form field (gin cannot bind bracket-keyed maps from urlencoded bodies). validate() rejects weights under any strategy but leastLoad — xray would silently ignore costs there, so storing them would pretend a knob exists. Non-positive weights error instead of defaulting: a zero usually means a typo'd "never pick this node". Entries for inbounds no longer selected are dropped on save. * feat(sub): emit leastLoad strategy costs from member weights costs[] is built after the tagging loop reuses the exact retagged tags (bal-N-protocol[-k]) and each member's owning inbound id. Members without a configured weight default to 1.0, but costs are omitted entirely unless at least one explicit weight survives — an all-1.0 array would bloat every subscription response for no effect. * feat(sub-balancers): leastLoad member weight inputs Weight fields render only under leastLoad and hide on strategy change without dropping their values, so an accidental toggle away and back loses nothing until save; non-leastLoad submits strip them entirely because xray would ignore costs. Weights travel as one JSON form field (gin cannot bind bracket-keyed maps) and every locale gets the three new keys in the same commit per the dead-keys rule. * docs(api): document memberWeights on sub-balancers leastLoad-only JSON form field; update notes that omitting it clears stored weights. Regenerated openapi artifacts via make gen + the docs copy/gen:api step nothing checks automatically. * fix(api-docs): use the allowed object ParamType for memberWeights * fix(sub-balancers): cap the member-weight list height Many selected inbounds pushed the modal body past the viewport. The weight rows now scroll inside a 220px viewport, mirroring the inbound picker's listHeight so both lists read the same. * fix(sub): anchor leastLoad cost matches to exact member tags Verified against xray-core: without regexp, WeightManager matches costs by substring (strings.Index), so the bare tag "bal-1-vless" also hits the deduplicated "bal-1-vless-2" and both members get the first entry's weight. Anchored ^tag$ regexps make every cost entry match only its own member. Also confirmed value<=0 makes xray derive a weight from the first digit of the matched tag — validating weights > 0 server-side was the right call. * fix(sub-balancers): keep member weights across the enabled toggle The table's toggleEnabled re-posted a full-row payload without memberWeights, and the update path treats an absent key as "erase" — flipping the switch silently dropped every configured weight. Round-trip the stored weights through the toggle payload, and prove persistence with a re-Get in the weight-validation test (the returned struct alone would stay green even if Save skipped the column). * fix(sub-balancers): address review on member weights - omitempty on MemberWeights: the panel sends null for every pre-existing and non-leastLoad balancer, which failed the hand-written zod response schema on every fetch (zod .optional() accepts undefined only; switched to .nullish() per repo convention) and drifted the generated contract. Regenerated openapi artifacts + docs copy + MDX. - Bound weights to the positive float32 range: xray decodes costs as float32, so an over-range value makes clients reject the whole subscription document and an underflow decays to the tag-digit fallback weight. Tests for both directions. - Trim six comment blocks to the 2-line cap from CLAUDE.md. --------- Co-authored-by: DIMFLIX <dimflix@users.noreply.github.com>
This commit is contained in:
@@ -4,15 +4,23 @@ import { HttpUtil } from '@/utils';
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import type { SubBalancerFormValues } from '@/schemas/subBalancer';
|
||||
|
||||
// Deliberately urlencoded (no JSON headers): the Go side binds inboundIds from
|
||||
// repeated form keys, which is exactly how HttpUtil encodes arrays.
|
||||
// Deliberately urlencoded: Go binds inboundIds from repeated form keys; weights
|
||||
// go as one JSON string — gin cannot bind bracket-keyed maps from form bodies.
|
||||
function toWirePayload(values: SubBalancerFormValues): Record<string, unknown> {
|
||||
const { memberWeights, ...rest } = values;
|
||||
if (values.strategy === 'leastLoad' && memberWeights && Object.keys(memberWeights).length > 0) {
|
||||
return { ...rest, memberWeights: JSON.stringify(memberWeights) };
|
||||
}
|
||||
return rest;
|
||||
}
|
||||
|
||||
export function useSubBalancerMutations() {
|
||||
const queryClient = useQueryClient();
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey: keys.subBalancers.root() });
|
||||
|
||||
const createMut = useMutation({
|
||||
mutationFn: (payload: SubBalancerFormValues) =>
|
||||
HttpUtil.post('/panel/api/sub-balancers', payload),
|
||||
HttpUtil.post('/panel/api/sub-balancers', toWirePayload(payload)),
|
||||
onSuccess: (msg) => {
|
||||
if (msg?.success) invalidate();
|
||||
},
|
||||
@@ -20,7 +28,7 @@ export function useSubBalancerMutations() {
|
||||
|
||||
const updateMut = useMutation({
|
||||
mutationFn: ({ id, payload }: { id: number; payload: SubBalancerFormValues }) =>
|
||||
HttpUtil.post(`/panel/api/sub-balancers/${id}`, payload),
|
||||
HttpUtil.post(`/panel/api/sub-balancers/${id}`, toWirePayload(payload)),
|
||||
onSuccess: (msg) => {
|
||||
if (msg?.success) invalidate();
|
||||
},
|
||||
|
||||
@@ -813,6 +813,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
1,
|
||||
3
|
||||
],
|
||||
"memberWeights": {},
|
||||
"remark": "auto-fastest",
|
||||
"sortOrder": 1,
|
||||
"strategy": "random",
|
||||
|
||||
@@ -3364,6 +3364,13 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"memberWeights": {
|
||||
"additionalProperties": {
|
||||
"type": "number"
|
||||
},
|
||||
"description": "inboundId -\u003e leastLoad weight; absent entries mean 1.0. Only meaningful\nwith Strategy \"leastLoad\" — xray ignores costs on every other strategy.",
|
||||
"type": "object"
|
||||
},
|
||||
"remark": {
|
||||
"example": "auto-fastest",
|
||||
"maxLength": 256,
|
||||
|
||||
@@ -768,6 +768,7 @@ export interface SubBalancer {
|
||||
enabled: boolean;
|
||||
id: number;
|
||||
inboundIds: number[];
|
||||
memberWeights?: Record<number, number>;
|
||||
remark: string;
|
||||
sortOrder: number;
|
||||
strategy: string;
|
||||
|
||||
@@ -819,6 +819,7 @@ export const SubBalancerSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
id: z.number().int(),
|
||||
inboundIds: z.array(z.number().int()),
|
||||
memberWeights: z.record(z.number().int(), z.number()).optional(),
|
||||
remark: z.string().max(256),
|
||||
sortOrder: z.number().int().min(1),
|
||||
strategy: z.enum(['leastLoad', 'leastPing', 'random', 'roundRobin']),
|
||||
|
||||
@@ -2248,6 +2248,12 @@ export const sections: readonly Section[] = [
|
||||
type: 'integer[]',
|
||||
desc: 'Repeated form keys selecting the member inbounds, e.g. inboundIds=1&inboundIds=3 (required, at least one).',
|
||||
},
|
||||
{
|
||||
name: 'memberWeights',
|
||||
in: 'body (form)',
|
||||
type: 'object',
|
||||
desc: 'leastLoad only: JSON object mapping inbound id to a static weight > 0, e.g. {"3":0.2}. Lower weight = picked more often; absent ids weigh 1. Rejected for other strategies; entries for unselected inbounds are dropped.',
|
||||
},
|
||||
{
|
||||
name: 'sortOrder',
|
||||
in: 'body (form)',
|
||||
@@ -2267,7 +2273,7 @@ export const sections: readonly Section[] = [
|
||||
method: 'POST',
|
||||
path: '/panel/api/sub-balancers/:id',
|
||||
summary:
|
||||
'Update a balancer by id. Accepts the same form fields as create (full-row update, including the enabled toggle).',
|
||||
'Update a balancer by id. Accepts the same form fields as create (full-row update, including the enabled toggle); omitting memberWeights clears stored weights.',
|
||||
params: [{ name: 'id', in: 'path', type: 'integer', desc: 'Balancer id.' }],
|
||||
responseSchema: 'SubBalancer',
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Form, Input, InputNumber, Modal, Select, Switch, message } from 'antd';
|
||||
import { FormProvider, useForm, useWatch } from 'react-hook-form';
|
||||
import { Controller, FormProvider, useForm, useWatch } from 'react-hook-form';
|
||||
|
||||
import { FormField, rhfZodValidate } from '@/components/form/rhf';
|
||||
import SelectAllClearButtons from '@/components/form/SelectAllClearButtons';
|
||||
@@ -38,6 +38,7 @@ function initialState(balancer: SubBalancer | null): SubBalancerFormValues {
|
||||
remark: balancer?.remark ?? '',
|
||||
strategy: balancer?.strategy ?? 'random',
|
||||
inboundIds: [...(balancer?.inboundIds ?? [])],
|
||||
memberWeights: balancer?.memberWeights ? { ...balancer.memberWeights } : undefined,
|
||||
sortOrder: balancer?.sortOrder ?? 1,
|
||||
enabled: balancer?.enabled ?? true,
|
||||
};
|
||||
@@ -66,6 +67,10 @@ export default function SubBalancerFormModal({
|
||||
}, [open, balancer, methods]);
|
||||
|
||||
const inboundIds = useWatch({ control: methods.control, name: 'inboundIds' });
|
||||
const strategy = useWatch({ control: methods.control, name: 'strategy' });
|
||||
// Weights only make sense for leastLoad; the fields hide but keep their
|
||||
// values so an accidental toggle away and back loses nothing until submit.
|
||||
const showWeights = strategy === 'leastLoad';
|
||||
|
||||
const { data: inboundOptionsRaw } = useInboundOptions();
|
||||
const inboundOptions = useMemo(
|
||||
@@ -82,7 +87,20 @@ export default function SubBalancerFormModal({
|
||||
);
|
||||
|
||||
function onFinish(values: SubBalancerFormValues) {
|
||||
const parsed = SubBalancerFormSchema.safeParse(values);
|
||||
const candidate: SubBalancerFormValues = { ...values };
|
||||
if (candidate.memberWeights) {
|
||||
const cleaned = Object.fromEntries(
|
||||
Object.entries(candidate.memberWeights).filter(
|
||||
([, v]) => typeof v === 'number' && Number.isFinite(v) && v > 0,
|
||||
),
|
||||
);
|
||||
candidate.memberWeights = Object.keys(cleaned).length > 0 ? cleaned : undefined;
|
||||
}
|
||||
// xray ignores costs on every strategy but leastLoad — never send them.
|
||||
if (candidate.strategy !== 'leastLoad') {
|
||||
delete candidate.memberWeights;
|
||||
}
|
||||
const parsed = SubBalancerFormSchema.safeParse(candidate);
|
||||
if (!parsed.success) {
|
||||
messageApi.error(
|
||||
t(parsed.error.issues[0]?.message ?? 'pages.settings.subBalancers.errRemarkRequired'),
|
||||
@@ -158,6 +176,59 @@ export default function SubBalancerFormModal({
|
||||
onChange={(v) => methods.setValue('inboundIds', v, { shouldDirty: true })}
|
||||
/>
|
||||
|
||||
{showWeights && (inboundIds ?? []).length > 0 && (
|
||||
<Form.Item
|
||||
className="sub-balancer-weights"
|
||||
label={t('pages.settings.subBalancers.weights')}
|
||||
tooltip={t('pages.settings.subBalancers.weightsHelp')}
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 8,
|
||||
maxHeight: 220,
|
||||
overflowY: 'auto',
|
||||
paddingRight: 4,
|
||||
}}
|
||||
>
|
||||
{(inboundIds ?? []).map((id) => {
|
||||
const option = inboundOptions.find((o) => o.value === id);
|
||||
return (
|
||||
<div key={id} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<span
|
||||
title={option?.title}
|
||||
style={{
|
||||
minWidth: 0,
|
||||
flex: 1,
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
}}
|
||||
>
|
||||
{option?.label ?? `#${id}`}
|
||||
</span>
|
||||
<Controller
|
||||
control={methods.control}
|
||||
name={`memberWeights.${id}`}
|
||||
render={({ field }) => (
|
||||
<InputNumber
|
||||
min={0.1}
|
||||
step={0.1}
|
||||
precision={1}
|
||||
style={{ width: 120 }}
|
||||
value={(field.value as number | undefined) ?? 1}
|
||||
onChange={(v) => field.onChange(typeof v === 'number' ? v : undefined)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Form.Item>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
label={t('pages.settings.subBalancers.enabled')}
|
||||
name="enabled"
|
||||
|
||||
@@ -91,6 +91,7 @@ export default function SubscriptionBalancersTab({
|
||||
remark: balancer.remark,
|
||||
strategy: balancer.strategy,
|
||||
inboundIds: balancer.inboundIds,
|
||||
memberWeights: balancer.memberWeights ?? undefined,
|
||||
sortOrder: balancer.sortOrder,
|
||||
enabled: !balancer.enabled,
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ export const SubBalancerSchema = z.object({
|
||||
remark: z.string(),
|
||||
strategy: SubBalancerStrategySchema,
|
||||
inboundIds: z.array(z.number()),
|
||||
memberWeights: z.record(z.string(), z.number()).nullish(),
|
||||
sortOrder: z.number(),
|
||||
enabled: z.boolean(),
|
||||
createdAt: z.number().optional(),
|
||||
@@ -27,6 +28,15 @@ export const SubBalancerFormSchema = z.object({
|
||||
inboundIds: z
|
||||
.array(z.number().int().positive())
|
||||
.min(1, 'pages.settings.subBalancers.errInboundsRequired'),
|
||||
// inboundId (stringified) -> leastLoad weight; absent members weigh 1.0.
|
||||
memberWeights: z
|
||||
.record(
|
||||
z.string(),
|
||||
z
|
||||
.number({ message: 'pages.settings.subBalancers.errWeightPositive' })
|
||||
.positive('pages.settings.subBalancers.errWeightPositive'),
|
||||
)
|
||||
.optional(),
|
||||
sortOrder: z
|
||||
.number({ message: 'pages.settings.subBalancers.errSortOrder' })
|
||||
.int('pages.settings.subBalancers.errSortOrder')
|
||||
|
||||
@@ -64,6 +64,26 @@ function selectInbound(optionTitle: string) {
|
||||
fireEvent.keyDown(multi, { key: 'Escape' });
|
||||
}
|
||||
|
||||
function selectStrategy(label: string) {
|
||||
const single = Array.from(document.querySelectorAll('.ant-select')).find(
|
||||
(s) => !s.classList.contains('ant-select-multiple'),
|
||||
);
|
||||
if (!single) throw new Error('Strategy select not found');
|
||||
fireEvent.mouseDown(single as HTMLElement);
|
||||
const option = Array.from(document.querySelectorAll('.ant-select-item-option')).find(
|
||||
(o) => (o.getAttribute('title') ?? o.textContent ?? '').trim() === label,
|
||||
);
|
||||
if (!option) throw new Error(`Strategy option '${label}' not found`);
|
||||
fireEvent.click(option);
|
||||
fireEvent.keyDown(single, { key: 'Escape' });
|
||||
}
|
||||
|
||||
function weightInputs(): HTMLInputElement[] {
|
||||
return Array.from(
|
||||
document.querySelectorAll<HTMLInputElement>('.sub-balancer-weights .ant-input-number-input'),
|
||||
);
|
||||
}
|
||||
|
||||
describe('SubBalancerFormModal', () => {
|
||||
it('shows no validation errors when freshly opened in add mode', () => {
|
||||
renderModal(null);
|
||||
@@ -133,4 +153,56 @@ describe('SubBalancerFormModal', () => {
|
||||
});
|
||||
expect(inboundOptionTitles()).toContain('Disabled');
|
||||
});
|
||||
|
||||
// Weights are a leastLoad-only xray knob; the inputs must not exist under
|
||||
// other strategies rather than merely being hidden.
|
||||
it('shows weight inputs for selected inbounds only under leastLoad', async () => {
|
||||
const { onConfirm } = renderModal(null);
|
||||
fireEvent.change(remarkInput(), { target: { value: 'weighted' } });
|
||||
selectInbound('First');
|
||||
selectInbound('Second');
|
||||
selectStrategy('Least load');
|
||||
await waitFor(() => expect(weightInputs()).toHaveLength(2));
|
||||
|
||||
fireEvent.change(weightInputs()[0], { target: { value: '0.5' } });
|
||||
fireEvent.click(primaryButton());
|
||||
await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));
|
||||
expect(onConfirm).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ strategy: 'leastLoad', memberWeights: { '1': 0.5 } }),
|
||||
);
|
||||
});
|
||||
|
||||
it('omits memberWeights when a non-leastLoad strategy is saved', async () => {
|
||||
const { onConfirm } = renderModal(null);
|
||||
fireEvent.change(remarkInput(), { target: { value: 'plain' } });
|
||||
selectInbound('First');
|
||||
selectStrategy('Least load');
|
||||
await waitFor(() => expect(weightInputs()).toHaveLength(1));
|
||||
fireEvent.change(weightInputs()[0], { target: { value: '0.5' } });
|
||||
selectStrategy('Random');
|
||||
await waitFor(() => expect(document.querySelector('.sub-balancer-weights')).toBeNull());
|
||||
fireEvent.click(primaryButton());
|
||||
await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));
|
||||
expect(onConfirm).toHaveBeenCalledWith({
|
||||
remark: 'plain',
|
||||
strategy: 'random',
|
||||
inboundIds: [1],
|
||||
sortOrder: 1,
|
||||
enabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('seeds weight values from the edited balancer', async () => {
|
||||
renderModal({
|
||||
id: 9,
|
||||
remark: 'existing',
|
||||
strategy: 'leastLoad',
|
||||
inboundIds: [2],
|
||||
memberWeights: { '2': 1.5 },
|
||||
sortOrder: 1,
|
||||
enabled: true,
|
||||
});
|
||||
await waitFor(() => expect(weightInputs()).toHaveLength(1));
|
||||
expect(weightInputs()[0].value).toBe('1.5');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user