diff --git a/docs/content/docs/en/reference/api/subscription-balancers.mdx b/docs/content/docs/en/reference/api/subscription-balancers.mdx index 1efa91574..8457b9a55 100644 --- a/docs/content/docs/en/reference/api/subscription-balancers.mdx +++ b/docs/content/docs/en/reference/api/subscription-balancers.mdx @@ -10,8 +10,9 @@ _openapi: - ./public/openapi.json toc: - depth: 2 - title: List all subscription balancers in sort order (sort_order asc, id asc). - url: '#list-all-subscription-balancers-in-sort-order-sort_order-asc-id-asc' + title: List all subscription balancers in sort order, with problems[] + advisories. + url: '#list-all-subscription-balancers-in-sort-order-with-problems-advisories' - depth: 2 title: Create a subscription balancer. It appears in the JSON subscription of every client that sits on at least one selected inbound. @@ -30,8 +31,9 @@ _openapi: url: '#delete-a-balancer-by-id-post-alias-of-delete-for-clients-that-cannot-send-delete' structuredData: headings: - - content: List all subscription balancers in sort order (sort_order asc, id asc). - id: list-all-subscription-balancers-in-sort-order-sort_order-asc-id-asc + - content: List all subscription balancers in sort order, with problems[] + advisories. + id: list-all-subscription-balancers-in-sort-order-with-problems-advisories - content: Create a subscription balancer. It appears in the JSON subscription of every client that sits on at least one selected inbound. id: create-a-subscription-balancer-it-appears-in-the-json-subscription-of-every-client-that-sits-on-at-least-one-selected-inbound @@ -44,7 +46,14 @@ _openapi: - content: Delete a balancer by id (POST alias of DELETE for clients that cannot send DELETE). id: delete-a-balancer-by-id-post-alias-of-delete-for-clients-that-cannot-send-delete - contents: [] + contents: + - content: 'Each balancer carries a problems[] array of diagnostic advisories: + unknown_inbound, disabled_inbound, json_incapable_protocol, + inbound_without_clients, hosts_excluded_from_json, no_members. + Advisories never change the emitted config — a balancer with no + resolvable member is still omitted from the JSON subscription. + sort_order asc, id asc.' + heading: list-all-subscription-balancers-in-sort-order-with-problems-advisories --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 463b0cb7b..32d2940e5 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -5636,6 +5636,112 @@ ], "type": "object" }, + "SubBalancerProblem": { + "description": "SubBalancerProblem is one reason a balancer cannot emit what an operator expects.\nAdvisories never change the emitted config, and per-client losses are out of scope.", + "properties": { + "code": { + "example": "unknown_inbound", + "type": "string" + }, + "detail": { + "example": "amneziawg", + "type": "string" + }, + "inboundIds": { + "example": [ + 7, + 9 + ], + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "code" + ], + "type": "object" + }, + "SubBalancerWithProblems": { + "description": "SubBalancerWithProblems embeds the row by value so it marshals flat; Problems is\nalways non-nil so the response shape is stable.", + "properties": { + "createdAt": { + "example": 1710000000000, + "format": "int64", + "type": "integer" + }, + "enabled": { + "description": "No gorm default:true — a bool default makes an explicit false at insert\ncollapse back to the column default (zero value is skipped).", + "example": true, + "type": "boolean" + }, + "id": { + "example": 1, + "type": "integer" + }, + "inboundIds": { + "example": [ + 1, + 3 + ], + "items": { + "type": "integer" + }, + "type": "array" + }, + "memberWeights": { + "additionalProperties": { + "type": "number" + }, + "description": "inboundId -> leastLoad weight; absent entries mean 1.0. Only meaningful\nwith Strategy \"leastLoad\" — xray ignores costs on every other strategy.", + "type": "object" + }, + "problems": { + "items": { + "$ref": "#/components/schemas/SubBalancerProblem" + }, + "type": "array" + }, + "remark": { + "example": "auto-fastest", + "maxLength": 256, + "type": "string" + }, + "sortOrder": { + "example": 1, + "minimum": 1, + "type": "integer" + }, + "strategy": { + "enum": [ + "leastLoad", + "leastPing", + "random", + "roundRobin" + ], + "example": "random", + "type": "string" + }, + "updatedAt": { + "example": 1710000000000, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "createdAt", + "enabled", + "id", + "inboundIds", + "problems", + "remark", + "sortOrder", + "strategy", + "updatedAt" + ], + "type": "object" + }, "TgBotCapabilities": { "description": "TgBotCapabilities is the browser-safe shape of the bot's own capabilities.", "properties": { @@ -17811,8 +17917,9 @@ "tags": [ "Subscription Balancers" ], - "summary": "List all subscription balancers in sort order (sort_order asc, id asc).", + "summary": "List all subscription balancers in sort order, with problems[] advisories.", "operationId": "get_panel_api_sub_balancers", + "description": "Each balancer carries a problems[] array of diagnostic advisories: unknown_inbound, disabled_inbound, json_incapable_protocol, inbound_without_clients, hosts_excluded_from_json, no_members. Advisories never change the emitted config — a balancer with no resolvable member is still omitted from the JSON subscription. sort_order asc, id asc.", "responses": { "200": { "description": "Successful response", @@ -17830,7 +17937,7 @@ "obj": { "type": "array", "items": { - "$ref": "#/components/schemas/SubBalancer" + "$ref": "#/components/schemas/SubBalancerWithProblems" } } } @@ -17847,6 +17954,16 @@ 3 ], "memberWeights": {}, + "problems": [ + { + "code": "unknown_inbound", + "detail": "amneziawg", + "inboundIds": [ + 7, + 9 + ] + } + ], "remark": "auto-fastest", "sortOrder": 1, "strategy": "random", diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 463b0cb7b..32d2940e5 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -5636,6 +5636,112 @@ ], "type": "object" }, + "SubBalancerProblem": { + "description": "SubBalancerProblem is one reason a balancer cannot emit what an operator expects.\nAdvisories never change the emitted config, and per-client losses are out of scope.", + "properties": { + "code": { + "example": "unknown_inbound", + "type": "string" + }, + "detail": { + "example": "amneziawg", + "type": "string" + }, + "inboundIds": { + "example": [ + 7, + 9 + ], + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "code" + ], + "type": "object" + }, + "SubBalancerWithProblems": { + "description": "SubBalancerWithProblems embeds the row by value so it marshals flat; Problems is\nalways non-nil so the response shape is stable.", + "properties": { + "createdAt": { + "example": 1710000000000, + "format": "int64", + "type": "integer" + }, + "enabled": { + "description": "No gorm default:true — a bool default makes an explicit false at insert\ncollapse back to the column default (zero value is skipped).", + "example": true, + "type": "boolean" + }, + "id": { + "example": 1, + "type": "integer" + }, + "inboundIds": { + "example": [ + 1, + 3 + ], + "items": { + "type": "integer" + }, + "type": "array" + }, + "memberWeights": { + "additionalProperties": { + "type": "number" + }, + "description": "inboundId -> leastLoad weight; absent entries mean 1.0. Only meaningful\nwith Strategy \"leastLoad\" — xray ignores costs on every other strategy.", + "type": "object" + }, + "problems": { + "items": { + "$ref": "#/components/schemas/SubBalancerProblem" + }, + "type": "array" + }, + "remark": { + "example": "auto-fastest", + "maxLength": 256, + "type": "string" + }, + "sortOrder": { + "example": 1, + "minimum": 1, + "type": "integer" + }, + "strategy": { + "enum": [ + "leastLoad", + "leastPing", + "random", + "roundRobin" + ], + "example": "random", + "type": "string" + }, + "updatedAt": { + "example": 1710000000000, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "createdAt", + "enabled", + "id", + "inboundIds", + "problems", + "remark", + "sortOrder", + "strategy", + "updatedAt" + ], + "type": "object" + }, "TgBotCapabilities": { "description": "TgBotCapabilities is the browser-safe shape of the bot's own capabilities.", "properties": { @@ -17811,8 +17917,9 @@ "tags": [ "Subscription Balancers" ], - "summary": "List all subscription balancers in sort order (sort_order asc, id asc).", + "summary": "List all subscription balancers in sort order, with problems[] advisories.", "operationId": "get_panel_api_sub_balancers", + "description": "Each balancer carries a problems[] array of diagnostic advisories: unknown_inbound, disabled_inbound, json_incapable_protocol, inbound_without_clients, hosts_excluded_from_json, no_members. Advisories never change the emitted config — a balancer with no resolvable member is still omitted from the JSON subscription. sort_order asc, id asc.", "responses": { "200": { "description": "Successful response", @@ -17830,7 +17937,7 @@ "obj": { "type": "array", "items": { - "$ref": "#/components/schemas/SubBalancer" + "$ref": "#/components/schemas/SubBalancerWithProblems" } } } @@ -17847,6 +17954,16 @@ 3 ], "memberWeights": {}, + "problems": [ + { + "code": "unknown_inbound", + "detail": "amneziawg", + "inboundIds": [ + 7, + 9 + ] + } + ], "remark": "auto-fastest", "sortOrder": 1, "strategy": "random", diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 93b98ec8b..5139ce603 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1444,6 +1444,38 @@ export const EXAMPLES: Record = { "strategy": "random", "updatedAt": 1710000000000 }, + "SubBalancerProblem": { + "code": "unknown_inbound", + "detail": "amneziawg", + "inboundIds": [ + 7, + 9 + ] + }, + "SubBalancerWithProblems": { + "createdAt": 1710000000000, + "enabled": true, + "id": 1, + "inboundIds": [ + 1, + 3 + ], + "memberWeights": {}, + "problems": [ + { + "code": "unknown_inbound", + "detail": "amneziawg", + "inboundIds": [ + 7, + 9 + ] + } + ], + "remark": "auto-fastest", + "sortOrder": 1, + "strategy": "random", + "updatedAt": 1710000000000 + }, "TgBotCapabilities": { "groupPrivacy": false, "inlineEnabled": true, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 4fcbe9d81..9453db3bb 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -5610,6 +5610,112 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "SubBalancerProblem": { + "description": "SubBalancerProblem is one reason a balancer cannot emit what an operator expects.\nAdvisories never change the emitted config, and per-client losses are out of scope.", + "properties": { + "code": { + "example": "unknown_inbound", + "type": "string" + }, + "detail": { + "example": "amneziawg", + "type": "string" + }, + "inboundIds": { + "example": [ + 7, + 9 + ], + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "code" + ], + "type": "object" + }, + "SubBalancerWithProblems": { + "description": "SubBalancerWithProblems embeds the row by value so it marshals flat; Problems is\nalways non-nil so the response shape is stable.", + "properties": { + "createdAt": { + "example": 1710000000000, + "format": "int64", + "type": "integer" + }, + "enabled": { + "description": "No gorm default:true — a bool default makes an explicit false at insert\ncollapse back to the column default (zero value is skipped).", + "example": true, + "type": "boolean" + }, + "id": { + "example": 1, + "type": "integer" + }, + "inboundIds": { + "example": [ + 1, + 3 + ], + "items": { + "type": "integer" + }, + "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" + }, + "problems": { + "items": { + "$ref": "#/components/schemas/SubBalancerProblem" + }, + "type": "array" + }, + "remark": { + "example": "auto-fastest", + "maxLength": 256, + "type": "string" + }, + "sortOrder": { + "example": 1, + "minimum": 1, + "type": "integer" + }, + "strategy": { + "enum": [ + "leastLoad", + "leastPing", + "random", + "roundRobin" + ], + "example": "random", + "type": "string" + }, + "updatedAt": { + "example": 1710000000000, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "createdAt", + "enabled", + "id", + "inboundIds", + "problems", + "remark", + "sortOrder", + "strategy", + "updatedAt" + ], + "type": "object" + }, "TgBotCapabilities": { "description": "TgBotCapabilities is the browser-safe shape of the bot's own capabilities.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 306252fc3..d3702f32b 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1270,6 +1270,25 @@ export interface SubBalancer { updatedAt: number; } +export interface SubBalancerProblem { + code: string; + detail?: string; + inboundIds?: number[]; +} + +export interface SubBalancerWithProblems { + createdAt: number; + enabled: boolean; + id: number; + inboundIds: number[]; + memberWeights?: Record; + problems: SubBalancerProblem[]; + remark: string; + sortOrder: number; + strategy: string; + updatedAt: number; +} + export interface TgBotCapabilities { groupPrivacy: boolean; inlineEnabled: boolean; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 50e218939..3573985b0 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -1348,6 +1348,27 @@ export const SubBalancerSchema = z.object({ }); export type SubBalancer = z.infer; +export const SubBalancerProblemSchema = z.object({ + code: z.string(), + detail: z.string().optional(), + inboundIds: z.array(z.number().int()).optional(), +}); +export type SubBalancerProblem = z.infer; + +export const SubBalancerWithProblemsSchema = z.object({ + createdAt: z.number().int(), + enabled: z.boolean(), + id: z.number().int(), + inboundIds: z.array(z.number().int()), + memberWeights: z.record(z.number().int(), z.number()).optional(), + problems: z.array(z.lazy(() => SubBalancerProblemSchema)), + remark: z.string().max(256), + sortOrder: z.number().int().min(1), + strategy: z.enum(['leastLoad', 'leastPing', 'random', 'roundRobin']), + updatedAt: z.number().int(), +}); +export type SubBalancerWithProblems = z.infer; + export const TgBotCapabilitiesSchema = z.object({ groupPrivacy: z.boolean(), inlineEnabled: z.boolean(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 64baf3b73..cc51fe8a4 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -3013,8 +3013,10 @@ export const sections: readonly Section[] = [ { method: 'GET', path: '/panel/api/sub-balancers', - summary: 'List all subscription balancers in sort order (sort_order asc, id asc).', - responseSchema: 'SubBalancer', + summary: 'List all subscription balancers in sort order, with problems[] advisories.', + description: + 'Each balancer carries a problems[] array of diagnostic advisories: unknown_inbound, disabled_inbound, json_incapable_protocol, inbound_without_clients, hosts_excluded_from_json, no_members. Advisories never change the emitted config — a balancer with no resolvable member is still omitted from the JSON subscription. sort_order asc, id asc.', + responseSchema: 'SubBalancerWithProblems', responseSchemaArray: true, }, { diff --git a/frontend/src/pages/settings/SubscriptionBalancersTab.tsx b/frontend/src/pages/settings/SubscriptionBalancersTab.tsx index 842ef1e33..4815adc32 100644 --- a/frontend/src/pages/settings/SubscriptionBalancersTab.tsx +++ b/frontend/src/pages/settings/SubscriptionBalancersTab.tsx @@ -30,7 +30,7 @@ import type { AllSetting } from '@/models/setting'; import { onNumber } from '@/utils/onNumber'; import { SettingListItem } from '@/components/ui'; import { useMediaQuery } from '@/hooks/useMediaQuery'; -import type { SubBalancer, SubBalancerFormValues } from '@/schemas/subBalancer'; +import type { SubBalancer, SubBalancerFormValues, SubBalancerProblem } from '@/schemas/subBalancer'; import { PingConfigSchema, type PingConfigObject } from '@/schemas/observatory'; import { DEFAULT_BURST_OBSERVATORY } from '@/pages/xray/balancers/balancer-helpers'; import SubBalancerFormModal from './SubBalancerFormModal'; @@ -56,6 +56,25 @@ function parsePingConfig(raw: string): PingConfigObject { } } +function ProblemTooltip({ + problems, + inboundLabels, +}: { + problems: SubBalancerProblem[]; + inboundLabels: Map; +}) { + const { t } = useTranslation(); + return ( +
+ {problems.map((p) => { + const ids = (p.inboundIds ?? []).map((id) => inboundLabels.get(id) ?? `#${id}`).join(', '); + const base = t(`pages.settings.subBalancers.problem.${p.code}`); + return
{ids ? `${base}: ${ids}` : base}
; + })} +
+ ); +} + interface SubscriptionBalancersTabProps { allSetting: AllSetting; updateSetting: (patch: Partial) => void; @@ -149,6 +168,22 @@ export default function SubscriptionBalancersTab({ ); }, }, + { + title: t('pages.settings.subBalancers.problems'), + key: 'problems', + width: 150, + render: (_: unknown, r: SubBalancer) => { + const problems = r.problems ?? []; + if (problems.length === 0) return null; + return ( + }> + + {t('pages.settings.subBalancers.problemsCount', { count: problems.length })} + + + ); + }, + }, { title: t('pages.settings.subBalancers.enabled'), dataIndex: 'enabled', diff --git a/frontend/src/schemas/subBalancer.ts b/frontend/src/schemas/subBalancer.ts index ebd5aa909..9f95d148e 100644 --- a/frontend/src/schemas/subBalancer.ts +++ b/frontend/src/schemas/subBalancer.ts @@ -3,6 +3,23 @@ import { z } from 'zod'; export const SubBalancerStrategySchema = z.enum(['leastLoad', 'leastPing', 'random', 'roundRobin']); export type SubBalancerStrategy = z.infer; +export const SubBalancerProblemCodeSchema = z.enum([ + 'unknown_inbound', + 'disabled_inbound', + 'json_incapable_protocol', + 'inbound_without_clients', + 'hosts_excluded_from_json', + 'no_members', +]); +export type SubBalancerProblemCode = z.infer; + +export const SubBalancerProblemSchema = z.object({ + code: SubBalancerProblemCodeSchema, + inboundIds: z.array(z.number()).optional(), + detail: z.string().optional(), +}); +export type SubBalancerProblem = z.infer; + export const SubBalancerSchema = z.object({ id: z.number(), remark: z.string(), @@ -11,6 +28,8 @@ export const SubBalancerSchema = z.object({ memberWeights: z.record(z.string(), z.number()).nullish(), sortOrder: z.number(), enabled: z.boolean(), + // Advisories from the list API; create/update responses omit them. + problems: z.array(SubBalancerProblemSchema).optional(), createdAt: z.number().optional(), updatedAt: z.number().optional(), }); diff --git a/internal/sub/json_service.go b/internal/sub/json_service.go index da5be71f4..bbc07766c 100644 --- a/internal/sub/json_service.go +++ b/internal/sub/json_service.go @@ -477,6 +477,36 @@ func (s *SubJsonService) hiddenMemberConfig(subReq *SubService, inbound *model.I return s.getConfig(subReq, inbound, client, host) } +// omittedBalancerWarned remembers which balancers already warned, so a subscription +// fetched once per client device does not repeat the same line on every request. +var omittedBalancerWarned = struct { + sync.Mutex + seen map[int]bool +}{seen: map[int]bool{}} + +func warnOmittedBalancer(balancer *model.SubBalancer) { + omittedBalancerWarned.Lock() + already := omittedBalancerWarned.seen[balancer.Id] + omittedBalancerWarned.seen[balancer.Id] = true + omittedBalancerWarned.Unlock() + if already { + return + } + logger.Warningf("SubJsonService: balancer %q (#%d) omitted, its inbounds are in this subscription but produced no member", + balancer.Remark, balancer.Id) +} + +// selectsPresentBalancer is true when an inbound the balancer selects is among this +// subscriber's entries: the only case where an empty member list signals a fault. +func selectsPresentBalancer(inboundIds []int, sources []subConfigEntry) bool { + for _, entry := range sources { + if entry.kind == 0 && slices.Contains(inboundIds, entry.id) { + return true + } + } + return false +} + // appendBalancerEntries appends one entry per balancer that has at least one member outbound // among the inbound entries; hidden inbounds' entries are members but never output themselves. func (s *SubJsonService) appendBalancerEntries(entries, hidden []subConfigEntry, balancers []model.SubBalancer) []subConfigEntry { @@ -500,6 +530,11 @@ func (s *SubJsonService) appendBalancerEntries(entries, hidden []subConfigEntry, for i := range balancers { config := s.buildBalancerConfig(&balancers[i], sources, entryProxies) if config == nil { + // Balancers are global, sources are this subscriber's: an empty + // intersection is normal, only a present-but-memberless one warns. + if selectsPresentBalancer(balancers[i].InboundIds, sources) { + warnOmittedBalancer(&balancers[i]) + } continue } entries = append(entries, subConfigEntry{ diff --git a/internal/web/controller/sub_balancer.go b/internal/web/controller/sub_balancer.go index a0debd244..6ecc8cf34 100644 --- a/internal/web/controller/sub_balancer.go +++ b/internal/web/controller/sub_balancer.go @@ -81,11 +81,14 @@ func (a *SubBalancerController) parseID(c *gin.Context) (int, error) { } func (a *SubBalancerController) list(c *gin.Context) { - balancers, err := a.SubBalancerService.List() + balancers, err := a.SubBalancerService.ListWithProblems() if err != nil { jsonMsg(c, I18nWeb(c, "pages.settings.subBalancers.toasts.list"), err) return } + for _, balancer := range balancers { + service.LogSubBalancerProblems(&balancer.SubBalancer, balancer.Problems) + } jsonObj(c, balancers, nil) } diff --git a/internal/web/service/sub_balancer_problems.go b/internal/web/service/sub_balancer_problems.go new file mode 100644 index 000000000..e5ef48514 --- /dev/null +++ b/internal/web/service/sub_balancer_problems.go @@ -0,0 +1,253 @@ +package service + +import ( + "slices" + "strconv" + "strings" + "sync" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/logger" +) + +// SubBalancerProblem codes. They are part of the API contract (the panel UI +// maps them to i18n keys), so treat them as stable identifiers. +const ( + // An import or a restored backup can bring back the id of a deleted inbound. + SubBalancerProblemUnknownInbound = "unknown_inbound" + SubBalancerProblemDisabledInbound = "disabled_inbound" + // The protocol renders share links and Clash proxies but has no JSON outbound. + SubBalancerProblemJSONIncapable = "json_incapable_protocol" + // No selected inbound can contribute, so the JSON subscription omits the balancer. + SubBalancerProblemNoMembers = "no_members" + // Enabled and renderable, but with no client it reaches no subscription. + SubBalancerProblemInboundWithoutClients = "inbound_without_clients" + // Every enabled host excludes the JSON format, so hostEndpoints closes the inbound. + SubBalancerProblemHostsExcluded = "hosts_excluded_from_json" +) + +// SubBalancerProblem is one reason a balancer cannot emit what an operator expects. +// Advisories never change the emitted config, and per-client losses are out of scope. +type SubBalancerProblem struct { + Code string `json:"code" example:"unknown_inbound"` + InboundIds []int `json:"inboundIds,omitempty" example:"[7,9]"` + Detail string `json:"detail,omitempty" example:"amneziawg"` +} + +// jsonIncapableProtocols mirrors the Protocol switch in internal/sub/json_service.go; +// sub_balancer_problems_parity_test.go fails when the two drift. +var jsonIncapableProtocols = map[string]struct{}{ + "amneziawg": {}, + "tuic": {}, + "mtproto": {}, +} + +// SubBalancerWithProblems embeds the row by value so it marshals flat; Problems is +// always non-nil so the response shape is stable. +type SubBalancerWithProblems struct { + model.SubBalancer + Problems []SubBalancerProblem `json:"problems"` +} + +// ListWithProblems returns every balancer with its advisories attached. +func (s *SubBalancerService) ListWithProblems() ([]*SubBalancerWithProblems, error) { + balancers, err := s.List() + if err != nil { + return nil, err + } + ids := make([]int, 0, len(balancers)) + for _, b := range balancers { + ids = append(ids, b.InboundIds...) + } + byID, clientCounts, hostsClosed, err := loadBalancerMemberInbounds(ids) + if err != nil { + return nil, err + } + out := make([]*SubBalancerWithProblems, 0, len(balancers)) + for _, b := range balancers { + problems := diagnoseSubBalancer(b, byID, clientCounts, hostsClosed) + out = append(out, &SubBalancerWithProblems{SubBalancer: *b, Problems: problems}) + } + return out, nil +} + +// loadBalancerMemberInbounds reads only the columns the diagnosis needs, plus +// grouped client and host counts that decide reachability per inbound. +func loadBalancerMemberInbounds(ids []int) (map[int]*model.Inbound, map[int]int, map[int]bool, error) { + byID := map[int]*model.Inbound{} + clients := map[int]int{} + hostsClosed := map[int]bool{} + unique := make([]int, 0, len(ids)) + for _, id := range ids { + if !slices.Contains(unique, id) { + unique = append(unique, id) + } + } + if len(unique) == 0 { + return byID, clients, hostsClosed, nil + } + var inbounds []*model.Inbound + err := database.GetDB().Model(&model.Inbound{}). + Select("id", "protocol", "enable"). + Where("id IN ?", unique).Find(&inbounds).Error + if err != nil { + return nil, nil, nil, err + } + for _, ib := range inbounds { + byID[ib.Id] = ib + } + + var counts []struct { + InboundId int + Total int + } + err = database.GetDB().Model(&model.ClientInbound{}). + Select("inbound_id, COUNT(*) AS total"). + Where("inbound_id IN ?", unique). + Group("inbound_id").Scan(&counts).Error + if err != nil { + return nil, nil, nil, err + } + for _, c := range counts { + clients[c.InboundId] = c.Total + } + + // An inbound whose enabled hosts all exclude JSON is closed by hostEndpoints, + // so its clients never render. The column is a JSON array, hence the quoted match. + var hostRows []struct { + InboundId int + Enabled int + ExcludingJSONCount int + } + err = database.GetDB().Model(&model.Host{}). + Select(`inbound_id, COUNT(*) AS enabled, `+ + `SUM(CASE WHEN exclude_from_sub_types LIKE '%"json"%' THEN 1 ELSE 0 END) AS excluding_json_count`). + Where("inbound_id IN ? AND is_disabled = ?", unique, false). + Group("inbound_id").Scan(&hostRows).Error + if err != nil { + return nil, nil, nil, err + } + for _, h := range hostRows { + if h.Enabled > 0 && h.ExcludingJSONCount == h.Enabled { + hostsClosed[h.InboundId] = true + } + } + return byID, clients, hostsClosed, nil +} + +// diagnoseSubBalancer groups per-inbound problems by code in selection order, +// then appends no_members when nothing could be emitted. +func diagnoseSubBalancer(b *model.SubBalancer, byID map[int]*model.Inbound, clientCounts map[int]int, hostsClosed map[int]bool) []SubBalancerProblem { + unknown := []int{} + disabled := []int{} + incapable := []int{} + empty := []int{} + closedHosts := []int{} + incapableDetail := "" + contributing := 0 + for _, id := range b.InboundIds { + ib, ok := byID[id] + if !ok { + unknown = append(unknown, id) + continue + } + if !ib.Enable { + disabled = append(disabled, id) + continue + } + if _, bad := jsonIncapableProtocols[string(ib.Protocol)]; bad { + incapable = append(incapable, id) + if incapableDetail == "" { + incapableDetail = string(ib.Protocol) + } + continue + } + if clientCounts[id] == 0 { + // Renderable but unreachable: with no client on it the inbound never + // enters any subscription, so the balancer drops out for everyone. + empty = append(empty, id) + continue + } + if hostsClosed[id] { + // Every enabled host excludes the JSON format, so hostEndpoints closes + // the inbound and none of its clients render. + closedHosts = append(closedHosts, id) + continue + } + contributing++ + } + problems := make([]SubBalancerProblem, 0, 6) + if len(unknown) > 0 { + problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemUnknownInbound, InboundIds: unknown}) + } + if len(disabled) > 0 { + problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemDisabledInbound, InboundIds: disabled}) + } + if len(incapable) > 0 { + problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemJSONIncapable, InboundIds: incapable, Detail: incapableDetail}) + } + if len(empty) > 0 { + problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemInboundWithoutClients, InboundIds: empty}) + } + if len(closedHosts) > 0 { + problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemHostsExcluded, InboundIds: closedHosts}) + } + if contributing == 0 { + problems = append(problems, SubBalancerProblem{Code: SubBalancerProblemNoMembers}) + } + return problems +} + +// loggedProblems remembers the last reported fingerprint per balancer, so the +// read path warns when something changes instead of on every listing. +var loggedProblems = struct { + sync.Mutex + byID map[int]string +}{byID: map[int]string{}} + +// LogSubBalancerProblems warns when a balancer's problems change. Identical listings +// stay silent, and a resolution is reported only when a problem was known before. +func LogSubBalancerProblems(b *model.SubBalancer, problems []SubBalancerProblem) { + fingerprint := problemsFingerprint(problems) + + loggedProblems.Lock() + previous, seen := loggedProblems.byID[b.Id] + if fingerprint == "" { + delete(loggedProblems.byID, b.Id) + } else { + loggedProblems.byID[b.Id] = fingerprint + } + loggedProblems.Unlock() + + if fingerprint == "" { + // Nothing to report for a balancer that never had a problem; a known one + // going quiet is a real transition worth one line. + if seen { + logger.Noticef("[SubBalancer] balancer %q (#%d) no longer has problems", b.Remark, b.Id) + } + return + } + if seen && previous == fingerprint { + return + } + logger.Warningf("[SubBalancer] balancer %q (#%d) has %d problem(s), inboundIds=%v: %+v", + b.Remark, b.Id, len(problems), b.InboundIds, problems) +} + +// problemsFingerprint renders the advisories deterministically; empty means +// healthy, which also clears the stored entry. +func problemsFingerprint(problems []SubBalancerProblem) string { + if len(problems) == 0 { + return "" + } + parts := make([]string, 0, len(problems)) + for _, p := range problems { + ids := make([]string, 0, len(p.InboundIds)) + for _, id := range p.InboundIds { + ids = append(ids, strconv.Itoa(id)) + } + parts = append(parts, p.Code+"["+strings.Join(ids, ",")+"]"+p.Detail) + } + return strings.Join(parts, ";") +} diff --git a/internal/web/service/sub_balancer_problems_parity_test.go b/internal/web/service/sub_balancer_problems_parity_test.go new file mode 100644 index 000000000..2b098ae38 --- /dev/null +++ b/internal/web/service/sub_balancer_problems_parity_test.go @@ -0,0 +1,149 @@ +package service + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "regexp" + "runtime" + "sort" + "strings" + "testing" +) + +// A protocol the JSON service never renders must not count as a working member. +// Both sides are parsed from source, so drift fails here rather than in production. +func TestJSONIncapableProtocolsMatchRenderer(t *testing.T) { + _, thisFile, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("cannot locate test file") + } + subDir := filepath.Join(filepath.Dir(thisFile), "..", "..", "sub") + + capable := rendererCapableProtocols(t, filepath.Join(subDir, "json_service.go")) + allowlist := subscriptionAllowlist(t, filepath.Join(subDir, "service.go")) + + if len(capable) == 0 || len(allowlist) == 0 { + t.Fatalf("parsed nothing meaningful (capable=%d allowlist=%d); did the sources move?", len(capable), len(allowlist)) + } + + want := make([]string, 0, len(allowlist)) + for _, protocol := range allowlist { + if !capable[protocol] { + want = append(want, protocol) + } + } + got := make([]string, 0, len(jsonIncapableProtocols)) + for protocol := range jsonIncapableProtocols { + got = append(got, protocol) + } + sort.Strings(want) + sort.Strings(got) + if strings.Join(want, ",") != strings.Join(got, ",") { + t.Fatalf("jsonIncapableProtocols = %v, want %v (allowlist minus renderer-handled protocols)", got, want) + } +} + +// rendererCapableProtocols returns the protocols whose case in the Protocol +// switch adds an outbound; a case that only continues (or is absent) cannot. +func rendererCapableProtocols(t *testing.T, path string) map[string]bool { + t.Helper() + file, err := parser.ParseFile(token.NewFileSet(), path, nil, 0) + if err != nil { + t.Fatalf("parse %s: %v", path, err) + } + capable := map[string]bool{} + ast.Inspect(file, func(n ast.Node) bool { + switchStmt, ok := n.(*ast.SwitchStmt) + if !ok { + return true + } + tag, ok := switchStmt.Tag.(*ast.SelectorExpr) + if !ok || tag.Sel.Name != "Protocol" { + return true + } + for _, stmt := range switchStmt.Body.List { + clause, ok := stmt.(*ast.CaseClause) + if !ok { + continue + } + onlyContinue := len(clause.Body) == 1 + if onlyContinue { + if branch, ok := clause.Body[0].(*ast.BranchStmt); !ok || branch.Tok != token.CONTINUE { + onlyContinue = false + } + } + if onlyContinue { + continue + } + for _, expr := range clause.List { + if lit, ok := expr.(*ast.BasicLit); ok { + capable[strings.Trim(lit.Value, `"`)] = true + } + } + } + return true + }) + return capable +} + +// subscriptionAllowlist reads the protocol list the subscription query selects, +// so a protocol added there without renderer support is caught too. +func subscriptionAllowlist(t *testing.T, path string) []string { + t.Helper() + source, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + clause := regexp.MustCompile(`inbounds\.protocol in \(([^)]*)\)`).FindSubmatch(source) + if clause == nil { + t.Fatalf("subscription protocol allowlist not found in %s", path) + } + quoted := regexp.MustCompile(`'([a-z]+)'`).FindAllSubmatch(clause[1], -1) + protocols := make([]string, 0, len(quoted)) + for _, match := range quoted { + protocols = append(protocols, string(match[1])) + } + return protocols +} + +// The form offers a fixed protocol list; the advisory must agree with it, or the +// UI hides an inbound the diagnosis calls healthy (or offers one it calls broken). +func TestJSONIncapableProtocolsMatchFormList(t *testing.T) { + _, thisFile, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("cannot locate test file") + } + formPath := filepath.Join(filepath.Dir(thisFile), "..", "..", "..", "frontend", "src", + "pages", "settings", "SubBalancerFormModal.tsx") + source, err := os.ReadFile(formPath) + if err != nil { + t.Fatalf("read %s: %v", formPath, err) + } + block := regexp.MustCompile(`MULTI_CLIENT_PROTOCOLS\s*=\s*new Set\(\[([^\]]*)\]\)`).FindSubmatch(source) + if block == nil { + t.Fatalf("MULTI_CLIENT_PROTOCOLS not found in %s", formPath) + } + offered := map[string]bool{} + for _, m := range regexp.MustCompile(`'([a-z0-9]+)'`).FindAllSubmatch(block[1], -1) { + offered[string(m[1])] = true + } + if len(offered) == 0 { + t.Fatal("parsed no protocols from the form list") + } + + allowlist := subscriptionAllowlist(t, filepath.Join(filepath.Dir(thisFile), "..", "..", "sub", "service.go")) + for _, protocol := range allowlist { + offeredByForm := offered[protocol] + listedByUs := false + if _, ok := jsonIncapableProtocols[protocol]; ok { + listedByUs = true + } + if offeredByForm == listedByUs { + t.Errorf("protocol %q: form offers=%v, advisory lists incapable=%v — they must be opposites", + protocol, offeredByForm, listedByUs) + } + } +} diff --git a/internal/web/service/sub_balancer_problems_test.go b/internal/web/service/sub_balancer_problems_test.go new file mode 100644 index 000000000..3a2276f98 --- /dev/null +++ b/internal/web/service/sub_balancer_problems_test.go @@ -0,0 +1,347 @@ +package service + +import ( + "fmt" + "strings" + "sync" + "testing" + + "github.com/op/go-logging" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger" +) + +// seedDiagInbound also links one client: a client-less inbound is its own advisory, +// separately tested, and must not leak into tests aimed at other codes. +func seedDiagInbound(t *testing.T, id int, protocol model.Protocol, enable bool) { + t.Helper() + ib := &model.Inbound{ + Id: id, UserId: 1, Tag: fmt.Sprintf("diag-%d", id), Enable: enable, + Listen: "203.0.113.9", Port: 4000 + id, Protocol: protocol, + Remark: fmt.Sprintf("diag-%d", id), Settings: `{}`, StreamSettings: `{}`, + } + if err := database.GetDB().Create(ib).Error; err != nil { + t.Fatalf("seed inbound %d: %v", id, err) + } + client := &model.ClientRecord{ + Email: fmt.Sprintf("diag-%d@test", id), SubID: fmt.Sprintf("diag%d", id), Enable: true, + } + if err := database.GetDB().Create(client).Error; err != nil { + t.Fatalf("seed client %d: %v", id, err) + } + if err := database.GetDB().Create(&model.ClientInbound{ + ClientId: client.Id, InboundId: id, + }).Error; err != nil { + t.Fatalf("link client %d: %v", id, err) + } +} + +// seedDiagInboundWithoutClients inserts only the inbound row, leaving +// client_inbounds empty for it. +func seedDiagInboundWithoutClients(t *testing.T, id int, protocol model.Protocol) { + t.Helper() + ib := &model.Inbound{ + Id: id, UserId: 1, Tag: fmt.Sprintf("diag-%d", id), Enable: true, + Listen: "203.0.113.9", Port: 4000 + id, Protocol: protocol, + Remark: fmt.Sprintf("diag-%d", id), Settings: `{}`, StreamSettings: `{}`, + } + if err := database.GetDB().Create(ib).Error; err != nil { + t.Fatalf("seed inbound %d: %v", id, err) + } +} + +// problemCodes flattens the codes so table assertions stay readable. +func problemCodes(problems []SubBalancerProblem) []string { + codes := make([]string, 0, len(problems)) + for _, p := range problems { + codes = append(codes, p.Code) + } + return codes +} + +func wantCodes(got []string, want ...string) string { + if len(got) != len(want) { + return fmt.Sprintf("codes = %v, want %v", got, want) + } + for i := range got { + if got[i] != want[i] { + return fmt.Sprintf("codes = %v, want %v", got, want) + } + } + return "" +} + +// Mixed healthy, dangling, disabled and JSON-incapable inbounds report one problem +// per class in a stable order, and no no_members while one member survives. +func TestSubBalancerProblemsMixedClasses(t *testing.T) { + setupSubBalancerDB(t) + seedDiagInbound(t, 1, model.VLESS, true) + seedDiagInbound(t, 2, model.VLESS, false) + seedDiagInbound(t, 3, model.AmneziaWG, true) + + svc := &SubBalancerService{} + if _, err := svc.Create(&model.SubBalancer{ + Remark: "mixed", Strategy: "random", InboundIds: []int{1, 2, 3, 99}, SortOrder: 1, Enabled: true, + }); err != nil { + t.Fatalf("create: %v", err) + } + + list, err := svc.ListWithProblems() + if err != nil { + t.Fatalf("ListWithProblems: %v", err) + } + if len(list) != 1 { + t.Fatalf("len = %d, want 1", len(list)) + } + got := problemCodes(list[0].Problems) + if diff := wantCodes(got, SubBalancerProblemUnknownInbound, SubBalancerProblemDisabledInbound, SubBalancerProblemJSONIncapable); diff != "" { + t.Fatal(diff) + } + if ids := list[0].Problems[0].InboundIds; len(ids) != 1 || ids[0] != 99 { + t.Fatalf("unknown ids = %v, want [99]", ids) + } + if ids := list[0].Problems[1].InboundIds; len(ids) != 1 || ids[0] != 2 { + t.Fatalf("disabled ids = %v, want [2]", ids) + } + if detail := list[0].Problems[2].Detail; detail != "amneziawg" { + t.Fatalf("detail = %q, want amneziawg", detail) + } +} + +// Every selected inbound unusable means the balancer is omitted at render +// time; the advisory says so once, without per-inbound codes meaning nothing. +func TestSubBalancerProblemsNoMembers(t *testing.T) { + setupSubBalancerDB(t) + seedDiagInbound(t, 1, model.TUIC, true) + + svc := &SubBalancerService{} + if _, err := svc.Create(&model.SubBalancer{ + Remark: "dead", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true, + }); err != nil { + t.Fatalf("create: %v", err) + } + + list, err := svc.ListWithProblems() + if err != nil { + t.Fatalf("ListWithProblems: %v", err) + } + got := problemCodes(list[0].Problems) + if diff := wantCodes(got, SubBalancerProblemJSONIncapable, SubBalancerProblemNoMembers); diff != "" { + t.Fatal(diff) + } +} + +// A purely healthy balancer carries an empty, non-nil slice so the JSON shape +// stays "problems": [] rather than dropping the field. +func TestSubBalancerProblemsHealthyIsEmpty(t *testing.T) { + setupSubBalancerDB(t) + seedDiagInbound(t, 1, model.VLESS, true) + + svc := &SubBalancerService{} + if _, err := svc.Create(&model.SubBalancer{ + Remark: "fine", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true, + }); err != nil { + t.Fatalf("create: %v", err) + } + + list, err := svc.ListWithProblems() + if err != nil { + t.Fatalf("ListWithProblems: %v", err) + } + if list[0].Problems == nil { + t.Fatal("Problems = nil, want non-nil empty slice") + } + if len(list[0].Problems) != 0 { + t.Fatalf("Problems = %v, want empty", list[0].Problems) + } +} + +// diagnoseSubBalancer is pure; unknown ids keep selection order and no_members +// is never reported while one member contributes. +func TestDiagnoseSubBalancerOrderAndNoMembers(t *testing.T) { + byID := map[int]*model.Inbound{ + 1: {Id: 1, Protocol: model.VLESS, Enable: true}, + 2: {Id: 2, Protocol: model.VLESS, Enable: false}, + } + // Inbound 1 has a client, so it still contributes and no_members stays away. + clientCounts := map[int]int{1: 3} + bal := &model.SubBalancer{Id: 7, Remark: "pure", InboundIds: []int{42, 2, 1, 41}} + problems := diagnoseSubBalancer(bal, byID, clientCounts, nil) + if diff := wantCodes(problemCodes(problems), SubBalancerProblemUnknownInbound, SubBalancerProblemDisabledInbound); diff != "" { + t.Fatal(diff) + } + if ids := problems[0].InboundIds; len(ids) != 2 || ids[0] != 42 || ids[1] != 41 { + t.Fatalf("unknown ids = %v, want [42 41] in selection order", ids) + } + + allDisabled := &model.SubBalancer{Id: 8, Remark: "off", InboundIds: []int{2}} + problems = diagnoseSubBalancer(allDisabled, byID, clientCounts, nil) + if diff := wantCodes(problemCodes(problems), SubBalancerProblemDisabledInbound, SubBalancerProblemNoMembers); diff != "" { + t.Fatal(diff) + } +} + +// A renderable inbound nobody sits on reaches no subscription, so the balancer +// drops out for everyone — the silence this feature exists to explain. +func TestSubBalancerProblemsInboundWithoutClients(t *testing.T) { + setupSubBalancerDB(t) + // Seeding only the inbound leaves client_inbounds empty. + seedDiagInboundWithoutClients(t, 1, model.VLESS) + + svc := &SubBalancerService{} + if _, err := svc.Create(&model.SubBalancer{ + Remark: "empty", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true, + }); err != nil { + t.Fatalf("create: %v", err) + } + + list, err := svc.ListWithProblems() + if err != nil { + t.Fatalf("ListWithProblems: %v", err) + } + got := problemCodes(list[0].Problems) + if diff := wantCodes(got, SubBalancerProblemInboundWithoutClients, SubBalancerProblemNoMembers); diff != "" { + t.Fatal(diff) + } +} + +// The log is the contract, not the fingerprint map: assert on what was written. +func TestLogSubBalancerProblemsDeduplicates(t *testing.T) { + xuilogger.InitLogger(logging.DEBUG) + bal := &model.SubBalancer{Id: 9001, Remark: "dedup-9001", InboundIds: []int{5}} + problem := []SubBalancerProblem{{Code: SubBalancerProblemUnknownInbound, InboundIds: []int{5}}} + + before := len(logLines()) + LogSubBalancerProblems(bal, problem) + if got := logLinesSince(before); countContaining(got, "dedup-9001") != 1 { + t.Fatalf("first listing: want exactly one line, got %v", got) + } + + // Same problem set again: the journal must not repeat itself. + before = len(logLines()) + LogSubBalancerProblems(bal, problem) + if got := logLinesSince(before); countContaining(got, "dedup-9001") != 0 { + t.Fatalf("repeat listing: want no line, got %v", got) + } + + // A known problem going quiet is a real transition: exactly one notice. + before = len(logLines()) + LogSubBalancerProblems(bal, nil) + lines := logLinesSince(before) + if countContaining(lines, "no longer has problems") != 1 { + t.Fatalf("resolution: want one notice, got %v", lines) + } + + // A balancer that never had a problem must stay silent on every listing. + healthy := &model.SubBalancer{Id: 9002, Remark: "healthy-9002", InboundIds: []int{6}} + for i := 0; i < 3; i++ { + before = len(logLines()) + LogSubBalancerProblems(healthy, nil) + if got := logLinesSince(before); countContaining(got, "healthy-9002") != 0 { + t.Fatalf("healthy listing %d: want silence, got %v", i, got) + } + } +} + +// GetLogs returns newest first and caps at c, so read a large window and take a +// snapshot before each call instead of trusting absolute indices. +func logLines() []string { return xuilogger.GetLogs(1_000_000, "DEBUG") } + +func logLinesSince(n int) []string { + all := logLines() + if len(all) <= n { + return nil + } + return all[:len(all)-n] +} + +func countContaining(lines []string, substr string) int { + count := 0 + for _, line := range lines { + if strings.Contains(line, substr) { + count++ + } + } + return count +} + +// The map is shared across concurrent listings (settings tab + refetches). +func TestLogSubBalancerProblemsConcurrent(t *testing.T) { + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func(id int) { + defer wg.Done() + bal := &model.SubBalancer{Id: 9100 + id, Remark: "race", InboundIds: []int{id}} + problems := []SubBalancerProblem{ + {Code: SubBalancerProblemUnknownInbound, InboundIds: []int{id}}, + } + LogSubBalancerProblems(bal, problems) + }(i) + } + wg.Wait() +} + +// An inbound whose every enabled host excludes the JSON format is closed by +// hostEndpoints: its clients never render, so the balancer emits nothing. +func TestSubBalancerProblemsAllHostsExcludedFromJSON(t *testing.T) { + setupSubBalancerDB(t) + seedDiagInbound(t, 1, model.VLESS, true) // also links one client + for i, types := range [][]string{{"json"}, {"json", "clash"}} { + host := &model.Host{ + InboundId: 1, Remark: fmt.Sprintf("host-%d", i), + Address: "cdn.example.com", Port: 443, ExcludeFromSubTypes: types, + } + if err := database.GetDB().Create(host).Error; err != nil { + t.Fatalf("seed host %d: %v", i, err) + } + } + + svc := &SubBalancerService{} + if _, err := svc.Create(&model.SubBalancer{ + Remark: "closed", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true, + }); err != nil { + t.Fatalf("create: %v", err) + } + + list, err := svc.ListWithProblems() + if err != nil { + t.Fatalf("ListWithProblems: %v", err) + } + got := problemCodes(list[0].Problems) + if diff := wantCodes(got, SubBalancerProblemHostsExcluded, SubBalancerProblemNoMembers); diff != "" { + t.Fatal(diff) + } +} + +// One host still serving JSON keeps the inbound usable, so no advisory appears. +func TestSubBalancerProblemsPartiallyExcludedHostsAreHealthy(t *testing.T) { + setupSubBalancerDB(t) + seedDiagInbound(t, 1, model.VLESS, true) + hosts := []*model.Host{ + {InboundId: 1, Remark: "closed", Address: "a.example.com", Port: 443, ExcludeFromSubTypes: []string{"json"}}, + {InboundId: 1, Remark: "open", Address: "b.example.com", Port: 443}, + } + for _, h := range hosts { + if err := database.GetDB().Create(h).Error; err != nil { + t.Fatalf("seed host: %v", err) + } + } + + svc := &SubBalancerService{} + if _, err := svc.Create(&model.SubBalancer{ + Remark: "partial", Strategy: "random", InboundIds: []int{1}, SortOrder: 1, Enabled: true, + }); err != nil { + t.Fatalf("create: %v", err) + } + + list, err := svc.ListWithProblems() + if err != nil { + t.Fatalf("ListWithProblems: %v", err) + } + if len(list[0].Problems) != 0 { + t.Fatalf("Problems = %v, want none", problemCodes(list[0].Problems)) + } +} diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 45d43e7c7..9cd51ef38 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "الموضع في قائمة الاشتراك، متداخل مع ترتيب الإينبوندات؛ عند تساوي الرقم يأتي الموزّع بعد الإينباند.", "inbounds": "الإينبوندات", "inboundsCount": "{count} الإينبوندات", + "problems": "المشكلات", + "problemsCount": "{count} مشكلة", + "problem": { + "unknown_inbound": "الإنباند لم يعد موجودًا", + "disabled_inbound": "الإنباند معطّل", + "json_incapable_protocol": "البروتوكول لا يحتوي على خروج JSON، لذا لا يمكن أن يكون عضوًا", + "no_members": "لا يوجد عضو قابل للاستخدام: يتم استبعاد الموزّع من اشتراك JSON", + "inbound_without_clients": "الإنباند ليس لديه عملاء، لذا لا يصل إلى أي اشتراك", + "hosts_excluded_from_json": "جميع المضيفين المفعّلين لهذا الإنباند مستبعدون من تنسيق JSON" + }, "weights": "أوزان الأعضاء", "weightsHelp": "لـ LeastLoad فقط: الوزن الأقل يُختار أكثر؛ العضو بدون قيمة وزنه 1.", "enabled": "مُفعّل", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 3ec9b24f4..0f0c9b635 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -1857,6 +1857,16 @@ "sortOrderHelp": "Position in the subscription list, interleaved with the inbounds' own order; on equal numbers the balancer comes after the inbound.", "inbounds": "Inbounds", "inboundsCount": "{count} Inbounds", + "problems": "Problems", + "problemsCount": "{count} problem(s)", + "problem": { + "unknown_inbound": "Inbound no longer exists", + "disabled_inbound": "Inbound is disabled", + "json_incapable_protocol": "Protocol has no JSON outbound, so it cannot be a member", + "no_members": "No usable member: the balancer is omitted from the JSON subscription", + "inbound_without_clients": "Inbound has no clients, so it reaches no subscription", + "hosts_excluded_from_json": "All enabled hosts of this inbound are excluded from the JSON format" + }, "weights": "Member weights", "weightsHelp": "Only for LeastLoad: a lower weight is picked more often; members without a value weigh 1.", "enabled": "Enabled", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 3aa34b093..9c35c6660 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "Posición en la lista de la suscripción, intercalada con el orden de los inbounds; con el mismo número, el balanceador va después del inbound.", "inbounds": "Inbounds", "inboundsCount": "{count} Inbounds", + "problems": "Problemas", + "problemsCount": "{count} problema(s)", + "problem": { + "unknown_inbound": "El inbound ya no existe", + "disabled_inbound": "El inbound está deshabilitado", + "json_incapable_protocol": "El protocolo no tiene outbound JSON, así que no puede ser miembro", + "no_members": "Ningún miembro utilizable: el balanceador se omite de la suscripción JSON", + "inbound_without_clients": "El inbound no tiene clientes, así que no llega a ninguna suscripción", + "hosts_excluded_from_json": "Todos los hosts habilitados de este inbound están excluidos del formato JSON" + }, "weights": "Pesos de miembros", "weightsHelp": "Solo para LeastLoad: un peso más bajo se elige con más frecuencia; los miembros sin valor pesan 1.", "enabled": "Activado", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 75a333c7b..b883d8847 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "جایگاه در فهرست اشتراک، درهم‌تنیده با ترتیب اینباند‌ها؛ با شمارهٔ برابر، موزان‌کننده بعد از اینباند می‌آید.", "inbounds": "اینباند‌ها", "inboundsCount": "{count} اینباند‌ها", + "problems": "مشکلات", + "problemsCount": "{count} مشکل", + "problem": { + "unknown_inbound": "اینباند دیگر وجود ندارد", + "disabled_inbound": "اینباند غیرفعال است", + "json_incapable_protocol": "پروتکل خروجی JSON ندارد، بنابراین نمیتواند عضو باشد", + "no_members": "عضو قابل استفاده‌ای نیست: متعادل‌کننده از اشتراک JSON حذف شد", + "inbound_without_clients": "اینباند هیچ کلاینتی ندارد، بنابراین به هیچ اشتراکی نمیرسد", + "hosts_excluded_from_json": "همهٔ هاست‌های فعال این اینباند از قالب JSON حذف شده‌اند" + }, "weights": "وزن اعضا", "weightsHelp": "فقط برای LeastLoad: وزن کمتر بیشتر انتخاب می‌شود؛ عضوی که مقداری نداشته باشد وزن ۱ دارد.", "enabled": "فعال", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 17da9277d..70da620f3 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "Posisi dalam daftar langganan, berselang-seling dengan urutan inbound; jika sama, penyeimbang berada setelah inbound.", "inbounds": "Inbound", "inboundsCount": "{count} Inbound", + "problems": "Masalah", + "problemsCount": "{count} masalah", + "problem": { + "unknown_inbound": "Inbound tidak ada lagi", + "disabled_inbound": "Inbound dinonaktifkan", + "json_incapable_protocol": "Protokol tidak memiliki outbound JSON, jadi tidak bisa menjadi anggota", + "no_members": "Tidak ada anggota yang dapat digunakan: penyeimbang dihilangkan dari langganan JSON", + "inbound_without_clients": "Inbound tidak memiliki klien, sehingga tidak masuk ke langganan mana pun", + "hosts_excluded_from_json": "Semua host yang aktif pada inbound ini dikecualikan dari format JSON" + }, "weights": "Bobot anggota", "weightsHelp": "Hanya untuk LeastLoad: bobot lebih rendah lebih sering dipilih; anggota tanpa nilai berbobot 1.", "enabled": "Aktif", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 7ee8cc998..bfe2e9543 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "サブスクリプション一覧内の位置。インバウンドの順序と交互に並び、同番号の場合はインバウンドの後ろになります。", "inbounds": "インバウンド", "inboundsCount": "{count} インバウンド", + "problems": "問題", + "problemsCount": "{count} 件の問題", + "problem": { + "unknown_inbound": "インバウンドは存在しません", + "disabled_inbound": "インバウンドは無効です", + "json_incapable_protocol": "プロトコルに JSON アウトバウンドがないため、メンバーにできません", + "no_members": "使用可能なメンバーがありません: バランサーは JSON サブスクリプションから除外されます", + "inbound_without_clients": "インバウンドにクライアントがないため、どのサブスクリプションにも届きません", + "hosts_excluded_from_json": "このインバウンドの有効なホストはすべて JSON 形式から除外されています" + }, "weights": "メンバーの重み", "weightsHelp": "LeastLoad のみ:値が小さいほど選ばれやすくなります。未指定のメンバーは重み 1 です。", "enabled": "有効", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index aa3c22d9b..d0967122d 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "Posição na lista da assinatura, intercalada com a ordem dos inbounds; em caso de empate, o balanceador vem depois do inbound.", "inbounds": "Inbounds", "inboundsCount": "{count} Inbounds", + "problems": "Problemas", + "problemsCount": "{count} problema(s)", + "problem": { + "unknown_inbound": "O inbound não existe mais", + "disabled_inbound": "O inbound está desativado", + "json_incapable_protocol": "O protocolo não tem outbound JSON, então não pode ser membro", + "no_members": "Nenhum membro utilizável: o balanceador é omitido da assinatura JSON", + "inbound_without_clients": "O inbound não tem clientes, então não chega a nenhuma assinatura", + "hosts_excluded_from_json": "Todos os hosts habilitados deste inbound estão excluídos do formato JSON" + }, "weights": "Pesos dos membros", "weightsHelp": "Apenas para LeastLoad: peso menor é escolhido com mais frequência; membros sem valor têm peso 1.", "enabled": "Ativado", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 4eb0c8208..a9af6b490 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "Позиция в списке подписки, чередуется с порядком инбаундов; при равных номерах балансировщик идёт после инбаунда.", "inbounds": "Инбаунды", "inboundsCount": "{count} Инбаунды", + "problems": "Проблемы", + "problemsCount": "Проблем: {count}", + "problem": { + "unknown_inbound": "Инбаунд больше не существует", + "disabled_inbound": "Инбаунд выключен", + "json_incapable_protocol": "У протокола нет JSON-аутбаунда, участником он быть не может", + "no_members": "Нет рабочего участника: балансер исключается из JSON-подписки", + "inbound_without_clients": "У инбаунда нет клиентов, поэтому он не попадает ни в одну подписку", + "hosts_excluded_from_json": "Все включённые хосты этого инбаунда исключены из JSON-формата" + }, "weights": "Веса участников", "weightsHelp": "Только для LeastLoad: чем меньше вес, тем чаще выбирается участник; без значения вес равен 1.", "enabled": "Включён", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index f1f0503f0..9d1887047 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -1857,6 +1857,16 @@ "sortOrderHelp": "Pozícia v zozname odberu, spoločne s poradím vstupov. Pri rovnakom čísle nasleduje vyvažovanie po vstupe.", "inbounds": "Vstupy", "inboundsCount": "Počet vstupov: {count}", + "problems": "Problémy", + "problemsCount": "{count} problém(ov)", + "problem": { + "unknown_inbound": "Inbound už neexistuje", + "disabled_inbound": "Inbound je vypnutý", + "json_incapable_protocol": "Protokol nemá JSON outbound, preto nemôže byť členom", + "no_members": "Žiadny použiteľný člen: balancer je vynechaný z JSON odberu", + "inbound_without_clients": "Inbound nemá žiadnych klientov, preto sa nedostane do žiadneho odberu", + "hosts_excluded_from_json": "Všetky povolené hosty tohto inboundu sú vylúčené z formátu JSON" + }, "weights": "Váhy členov", "weightsHelp": "Iba pre LeastLoad: nižšia váha znamená častejší výber. Bez zadanej hodnoty má člen váhu 1.", "enabled": "Zapnuté", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index daf72f9ea..4c8e86f5a 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "Abonelik listesindeki konumu, inbound sırası ile iç içe yerleşir; eşit numarada dengeleyici inbound'dan sonra gelir.", "inbounds": "Inbound'lar", "inboundsCount": "{count} Inbound'lar", + "problems": "Sorunlar", + "problemsCount": "{count} sorun", + "problem": { + "unknown_inbound": "Inbound artık mevcut değil", + "disabled_inbound": "Inbound devre dışı", + "json_incapable_protocol": "Protokolün JSON outbound’u yok, bu yüzden üye olamaz", + "no_members": "Kullanılabilir üye yok: dengeleyici JSON aboneliğinden çıkarıldı", + "inbound_without_clients": "Inbound’un istemcisi yok, bu yüzden hiçbir aboneliğe ulaşmıyor", + "hosts_excluded_from_json": "Bu inbound’un tüm etkin host’ları JSON biçiminden hariç tutuldu" + }, "weights": "Üye ağırlıkları", "weightsHelp": "Yalnızca LeastLoad için: daha düşük ağırlık daha sık seçilir; değeri olmayan üyelerin ağırlığı 1’dir.", "enabled": "Etkin", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 7a9c4f7a0..5733ee7ed 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "Позиція у списку підписки, чергується з порядком інбаундів; за однакового номера йде після інбаунда.", "inbounds": "Інбаунди", "inboundsCount": "{count} Інбаунди", + "problems": "Проблеми", + "problemsCount": "Проблем: {count}", + "problem": { + "unknown_inbound": "Інбаунд більше не існує", + "disabled_inbound": "Інбаунд вимкнено", + "json_incapable_protocol": "Протокол не має JSON-аутбаунду, тому не може бути учасником", + "no_members": "Немає робочого учасника: балансер виключено з JSON-підписки", + "inbound_without_clients": "В інбаунда немає клієнтів, тому він не потрапляє в жодну підписку", + "hosts_excluded_from_json": "Усі увімкнені хости цього інбаунда виключені з JSON-формату" + }, "weights": "Ваги учасників", "weightsHelp": "Лише для LeastLoad: чим менша вага, тим частіше обирається учасник; без значення вага дорівнює 1.", "enabled": "Увімкнено", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 66e1ad1e0..cab6edff2 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "Vị trí trong danh sách đăng ký, xen kẽ với thứ tự inbound; khi cùng số, bộ cân bằng đứng sau inbound.", "inbounds": "Inbound", "inboundsCount": "{count} Inbound", + "problems": "Vấn đề", + "problemsCount": "{count} vấn đề", + "problem": { + "unknown_inbound": "Inbound không còn tồn tại", + "disabled_inbound": "Inbound đang bị tắt", + "json_incapable_protocol": "Giao thức không có outbound JSON nên không thể là thành viên", + "no_members": "Không có thành viên khả dụng: bộ cân bằng bị bỏ khỏi đăng ký JSON", + "inbound_without_clients": "Inbound không có ứng dụng khách nên không xuất hiện trong đăng ký nào", + "hosts_excluded_from_json": "Tất cả máy chủ được bật của inbound này đều bị loại khỏi định dạng JSON" + }, "weights": "Trọng số thành viên", "weightsHelp": "Chỉ dành cho LeastLoad: trọng số nhỏ hơn được chọn thường xuyên hơn; thành viên không có giá trị mang trọng số 1.", "enabled": "Đã bật", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 47c7bee20..21cb49bcb 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "在订阅列表中的位置,与入站顺序交错排列;序号相同时排在入站之后。", "inbounds": "入站", "inboundsCount": "{count} 入站", + "problems": "问题", + "problemsCount": "{count} 个问题", + "problem": { + "unknown_inbound": "入站已不存在", + "disabled_inbound": "入站已禁用", + "json_incapable_protocol": "协议没有 JSON 出站,因此不能作为成员", + "no_members": "没有可用的成员:负载均衡器已从 JSON 订阅中省略", + "inbound_without_clients": "入站没有客户端,因此不会出现在任何订阅中", + "hosts_excluded_from_json": "此入站的所有已启用主机都已从 JSON 格式中排除" + }, "weights": "成员权重", "weightsHelp": "仅适用于 LeastLoad:权重越小越常被选中;未设置的成员权重为 1。", "enabled": "启用", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index e6a0f04db..b3bdd60ef 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -1736,6 +1736,16 @@ "sortOrderHelp": "在訂閱列表中的位置,與入站順序交錯排列;序號相同時排在入站之後。", "inbounds": "入站", "inboundsCount": "{count} 入站", + "problems": "問題", + "problemsCount": "{count} 個問題", + "problem": { + "unknown_inbound": "入站已不存在", + "disabled_inbound": "入站已停用", + "json_incapable_protocol": "協定沒有 JSON 出站,因此不能作為成員", + "no_members": "沒有可用的成員:負載平衡器已從 JSON 訂閱中省略", + "inbound_without_clients": "入站沒有用戶端,因此不會出現在任何訂閱中", + "hosts_excluded_from_json": "此入站的所有已啟用主機都已從 JSON 格式中排除" + }, "weights": "成員權重", "weightsHelp": "僅適用於 LeastLoad:權重越小越常被選中;未設定的成員權重為 1。", "enabled": "啟用", diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index 4eb76045d..971437c7b 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -131,6 +131,8 @@ func run(root, outDir string) error { "HwidSlotStatus", "ClientUsageHistory", "ClientNodeUsage", + "SubBalancerWithProblems", + "SubBalancerProblem", ), AliasAllow: setOf("ProcessState"), },