mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-09-17 07:37:15 +00:00
7100fbcd08
* 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>
209 lines
7.5 KiB
TypeScript
209 lines
7.5 KiB
TypeScript
import { describe, it, expect, vi } from 'vitest';
|
|
import { fireEvent, waitFor } from '@testing-library/react';
|
|
|
|
import SubBalancerFormModal from '@/pages/settings/SubBalancerFormModal';
|
|
import type { SubBalancer } from '@/schemas/subBalancer';
|
|
import { renderWithProviders } from './test-utils';
|
|
|
|
vi.mock('@/api/queries/useInboundOptions', () => ({
|
|
useInboundOptions: () => ({
|
|
data: [
|
|
{ id: 1, tag: 'inb-vless', remark: 'First', protocol: 'vless', port: 443, enable: true },
|
|
{ id: 2, tag: 'inb-ws', remark: 'Second', protocol: 'vmess', port: 8443, enable: true },
|
|
{ id: 3, tag: 'inb-off', remark: 'Disabled', protocol: 'vless', port: 8080, enable: false },
|
|
],
|
|
isLoading: false,
|
|
}),
|
|
}));
|
|
|
|
function renderModal(balancer: SubBalancer | null, onConfirm = vi.fn()) {
|
|
renderWithProviders(
|
|
<SubBalancerFormModal open balancer={balancer} onClose={() => {}} onConfirm={onConfirm} />,
|
|
);
|
|
return { onConfirm };
|
|
}
|
|
|
|
function primaryButton(): HTMLElement {
|
|
const btn = document.querySelector('.ant-modal-footer .ant-btn-primary');
|
|
if (!btn) throw new Error('Primary button not found');
|
|
return btn as HTMLElement;
|
|
}
|
|
|
|
function erroredItemCount(): number {
|
|
return document.querySelectorAll('.ant-form-item-has-error').length;
|
|
}
|
|
|
|
function remarkInput(): HTMLInputElement {
|
|
const el = Array.from(document.querySelectorAll('.ant-modal input')).find((i) =>
|
|
(i as HTMLInputElement).placeholder.includes('Auto'),
|
|
);
|
|
if (!el) throw new Error('Remark input not found');
|
|
return el as HTMLInputElement;
|
|
}
|
|
|
|
function inboundOptionTitles(): string[] {
|
|
const multi = document.querySelector('.ant-select-multiple');
|
|
if (!multi) throw new Error('Inbound multi-select not found');
|
|
fireEvent.mouseDown(multi as HTMLElement);
|
|
return Array.from(document.querySelectorAll('.ant-select-item-option')).map((o) =>
|
|
(o.getAttribute('title') ?? o.textContent ?? '').trim(),
|
|
);
|
|
}
|
|
|
|
function selectInbound(optionTitle: string) {
|
|
const multi = document.querySelector('.ant-select-multiple');
|
|
if (!multi) throw new Error('Inbound multi-select not found');
|
|
// AntD 6 multiple selects have no .ant-select-selector; mousedown on the
|
|
// root toggles the dropdown.
|
|
fireEvent.mouseDown(multi as HTMLElement);
|
|
const option = Array.from(document.querySelectorAll('.ant-select-item-option')).find(
|
|
(o) => (o.getAttribute('title') ?? o.textContent ?? '').trim() === optionTitle,
|
|
);
|
|
if (!option) throw new Error(`Option '${optionTitle}' not found`);
|
|
fireEvent.click(option);
|
|
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);
|
|
expect(document.querySelector('.ant-modal')).toBeTruthy();
|
|
expect(erroredItemCount()).toBe(0);
|
|
expect(primaryButton().hasAttribute('disabled')).toBe(false);
|
|
});
|
|
|
|
it('reveals required-field errors after a save attempt, without confirming', async () => {
|
|
const { onConfirm } = renderModal(null);
|
|
fireEvent.click(primaryButton());
|
|
await waitFor(() => expect(erroredItemCount()).toBe(2));
|
|
expect(onConfirm).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('confirms with parsed values once remark and an inbound are set', async () => {
|
|
const { onConfirm } = renderModal(null);
|
|
fireEvent.change(remarkInput(), { target: { value: ' auto ' } });
|
|
selectInbound('First');
|
|
fireEvent.click(primaryButton());
|
|
await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));
|
|
expect(onConfirm).toHaveBeenCalledWith({
|
|
remark: 'auto',
|
|
strategy: 'random',
|
|
inboundIds: [1],
|
|
sortOrder: 1,
|
|
enabled: true,
|
|
});
|
|
});
|
|
|
|
it('seeds the form from the edited balancer', async () => {
|
|
const { onConfirm } = renderModal({
|
|
id: 7,
|
|
remark: 'existing',
|
|
strategy: 'leastPing',
|
|
inboundIds: [2],
|
|
sortOrder: 3,
|
|
enabled: false,
|
|
});
|
|
expect(remarkInput().value).toBe('existing');
|
|
fireEvent.click(primaryButton());
|
|
await waitFor(() => expect(onConfirm).toHaveBeenCalledTimes(1));
|
|
expect(onConfirm).toHaveBeenCalledWith({
|
|
remark: 'existing',
|
|
strategy: 'leastPing',
|
|
inboundIds: [2],
|
|
sortOrder: 3,
|
|
enabled: false,
|
|
});
|
|
});
|
|
|
|
// A disabled member is dropped by the sub server, so offering it here would
|
|
// silently stop the balancer document from being emitted (#5645).
|
|
it('hides disabled inbounds from the member picker', () => {
|
|
renderModal(null);
|
|
expect(inboundOptionTitles()).toEqual(['First', 'Second']);
|
|
});
|
|
|
|
it('keeps an already-selected disabled inbound visible when editing', () => {
|
|
renderModal({
|
|
id: 8,
|
|
remark: 'existing',
|
|
strategy: 'random',
|
|
inboundIds: [3],
|
|
sortOrder: 1,
|
|
enabled: true,
|
|
});
|
|
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');
|
|
});
|
|
});
|