每路入站配一组专属策略组,换线不再改配置文件
原本换一条线要改 config.yaml、跑校验、等内核重载,几秒起步;而换线恰恰是这个工具 最高频的动作,把它放在最重的路径上方向就错了。现在每一路配一个 select 组加 AUTO、 FALLBACK 两个,入站的 proxy 永久指向 select,换线只是调一次内核接口。这样做的前提是 选中不会丢:内核把它写进 cache 文件,重启后由 patchSelectGroup 恢复,而 profile.store-selected 默认为真。 链式代理靠给来源订阅复制一份声明、挂上 override.dialer-proxy 实现,因为这个字段写在 策略组上内核只会打条日志然后忽略。副本是 type: file 读原订阅已经落盘的缓存,而不是 自己再拉一次:自己拉的话订阅地址一不可达副本就是空的,那一路入站会一条线都不剩, 表现是端口还在监听却没有任何出口。 顺带把 shared/outbound-chain.ts 里「只有 Selector 接受手动选择」那条断言删了,它是 错的(内核检查的是 SelectAble 接口,URLTest 和 Fallback 也实现了)。界面仍然只让 Selector 可点,但理由换成了另外两种的手动指定会被它们自己撤销。 完整取舍见工作区决策记录 0007。
This commit is contained in:
@@ -1,110 +0,0 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import {
|
||||
generatedGroupName,
|
||||
isGeneratedGroup,
|
||||
lineFilter,
|
||||
makeFilterGroup,
|
||||
pinnedLineOf,
|
||||
pruneGeneratedGroups,
|
||||
} from './filter-groups.ts'
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
|
||||
const LINE = '[vless]Gomami.SIN Secret'
|
||||
|
||||
describe('筛选条件', () => {
|
||||
it('转义正则元字符', () => {
|
||||
// 线路名里的 [ ] . 不转义会当成正则语法,匹配到别的线路上去
|
||||
expect(lineFilter(LINE)).toBe('^\\[vless\\]Gomami\\.SIN Secret$')
|
||||
})
|
||||
|
||||
it('前后加锚点,避免匹配到名字更长的线路', () => {
|
||||
// 内核的筛选是部分匹配:不加锚点时「香港01」会把「香港011」也捞进来
|
||||
expect(lineFilter('香港01')).toBe('^香港01$')
|
||||
})
|
||||
|
||||
it('线路名含反引号时表达不了,返回空让调用方说明原因', () => {
|
||||
// 反引号在内核里是多个筛选条件的分隔符,塞进一条正则会被切成两半
|
||||
expect(lineFilter('怪`名字')).toBeNull()
|
||||
})
|
||||
|
||||
it('转义后的正则确实只匹配它自己', () => {
|
||||
const re = new RegExp(lineFilter(LINE)!)
|
||||
expect(re.test(LINE)).toBe(true)
|
||||
expect(re.test('[vless]GomamiXSIN Secret')).toBe(false)
|
||||
expect(re.test(`${LINE} 备用`)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('生成的组', () => {
|
||||
it('名字带前缀,这是识别它的唯一可靠标记', () => {
|
||||
// 注释靠不住——被碰到的段落重写时会丢,见决策记录 0002
|
||||
const name = generatedGroupName(LINE)
|
||||
expect(isGeneratedGroup(name)).toBe(true)
|
||||
expect(pinnedLineOf(name)).toBe(LINE)
|
||||
})
|
||||
|
||||
it('用户自己建的组不会被认成生成的', () => {
|
||||
expect(isGeneratedGroup('PROXY')).toBe(false)
|
||||
expect(pinnedLineOf('PROXY')).toBeNull()
|
||||
})
|
||||
|
||||
it('组里只有那一条线路,类型是手动选', () => {
|
||||
expect(makeFilterGroup(LINE, 'subs')).toEqual({
|
||||
name: `patchbay:${LINE}`,
|
||||
type: 'select',
|
||||
use: ['subs'],
|
||||
filter: '^\\[vless\\]Gomami\\.SIN Secret$',
|
||||
})
|
||||
})
|
||||
|
||||
it('表达不了的线路名不生成组', () => {
|
||||
expect(makeFilterGroup('怪`名字', 'subs')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('清理没人用的生成组', () => {
|
||||
const generated = (line: string) => ({ name: generatedGroupName(line), type: 'select' })
|
||||
|
||||
it('入站还指着它就留着', () => {
|
||||
const data: ConfigObject = {
|
||||
listeners: [{ name: 'A', type: 'mixed', port: 1, proxy: generatedGroupName(LINE) }],
|
||||
'proxy-groups': [generated(LINE)],
|
||||
}
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('没人再指它就删掉', () => {
|
||||
const data: ConfigObject = {
|
||||
listeners: [{ name: 'A', type: 'mixed', port: 1 }],
|
||||
'proxy-groups': [generated(LINE)],
|
||||
}
|
||||
// 不清理的话,改几次出站文件里就攒下一堆用户从没主动建过的组
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('被别的策略组当成员引用也算在用', () => {
|
||||
const data: ConfigObject = {
|
||||
'proxy-groups': [generated(LINE), { name: 'PROXY', proxies: [generatedGroupName(LINE)] }],
|
||||
}
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('被规则引用也算在用', () => {
|
||||
const data: ConfigObject = {
|
||||
'proxy-groups': [generated(LINE)],
|
||||
rules: [`MATCH,${generatedGroupName(LINE)}`],
|
||||
}
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('用户自己建的组一律不碰,哪怕真的没人引用', () => {
|
||||
const data: ConfigObject = { 'proxy-groups': [{ name: '我建的组', type: 'select' }] }
|
||||
expect(pruneGeneratedGroups(data)['proxy-groups']).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('没有可删的时候原样返回,不制造无谓的改动', () => {
|
||||
// 返回同一个对象,落盘链路才看得出「内容没变」而跳过备份和重载
|
||||
const data: ConfigObject = { 'proxy-groups': [{ name: 'PROXY' }] }
|
||||
expect(pruneGeneratedGroups(data)).toBe(data)
|
||||
})
|
||||
})
|
||||
@@ -1,118 +0,0 @@
|
||||
/**
|
||||
* 把一路入站固定到某一条订阅线路。
|
||||
*
|
||||
* 内核不允许直接这么写:入站的 `proxy:` 只认全局名字表里的名字,而订阅线路不在表上
|
||||
* (见决策记录 0005)。绕法是给那条线路单独建一个只装它的策略组,入站指向这个组。
|
||||
*
|
||||
* 这些组是 Patchbay 自己造的,用户不该看到也不该管。名字带前缀是唯一可靠的标记——
|
||||
* 注释靠不住,被碰到的段落重写时会丢。
|
||||
*/
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
|
||||
/** 自动生成的筛选组的名字前缀。改它会让已有配置里的组失去标记,别改。 */
|
||||
export const GENERATED_PREFIX = 'patchbay:'
|
||||
|
||||
export function isGeneratedGroup(name: string): boolean {
|
||||
return name.startsWith(GENERATED_PREFIX)
|
||||
}
|
||||
|
||||
/** 固定到某条线路时,生成的组叫什么。名字里带上线路名,翻文件时一眼看得懂。 */
|
||||
export function generatedGroupName(line: string): string {
|
||||
return `${GENERATED_PREFIX}${line}`
|
||||
}
|
||||
|
||||
/** 这个组固定的是哪条线路。不是生成的组返回 null。 */
|
||||
export function pinnedLineOf(groupName: string): string | null {
|
||||
return isGeneratedGroup(groupName) ? groupName.slice(GENERATED_PREFIX.length) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 出站在界面上怎么念。
|
||||
*
|
||||
* 生成的组显示成它固定的那条线路——用户从没建过这个组,让他在界面上读到
|
||||
* `patchbay:[vless]Gomami` 只会莫名其妙。
|
||||
*/
|
||||
export function displayOutboundName(name: string): string {
|
||||
return pinnedLineOf(name) ?? name
|
||||
}
|
||||
|
||||
/**
|
||||
* 把线路名转成只匹配它自己的筛选条件。
|
||||
*
|
||||
* 两件事必须做对:
|
||||
* 转义正则元字符——线路名形如 `[vmess]DMIT.LAX.Pro.MTYQ`,`[`、`]`、`.` 不转义会匹配错
|
||||
* 前后加锚点——内核的筛选是部分匹配,不加锚点时 `香港01` 会把 `香港011` 也匹配进来
|
||||
*
|
||||
* 反引号在内核里是多个筛选条件的分隔符(adapter/outboundgroup/groupbase.go:72-76),
|
||||
* 线路名里含它就没法用一条正则表达,这种情况返回 null,调用方据此告诉用户做不到。
|
||||
*/
|
||||
export function lineFilter(line: string): string | null {
|
||||
if (line.includes('`')) return null
|
||||
const escaped = line.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
return `^${escaped}$`
|
||||
}
|
||||
|
||||
/**
|
||||
* 造一个只装指定线路的策略组。
|
||||
*
|
||||
* 用 `select` 而不是 `url-test`:组里只有一条线路,没什么可测的,而 `select` 的语义
|
||||
* 就是「用这一个」。
|
||||
*/
|
||||
export function makeFilterGroup(line: string, provider: string): ConfigObject | null {
|
||||
const filter = lineFilter(line)
|
||||
if (filter === null) return null
|
||||
return {
|
||||
name: generatedGroupName(line),
|
||||
type: 'select',
|
||||
use: [provider],
|
||||
filter,
|
||||
}
|
||||
}
|
||||
|
||||
/** 配置里所有指向某个名字的位置。用来判断一个生成的组还有没有人在用。 */
|
||||
function referencesTo(data: ConfigObject, name: string): number {
|
||||
let count = 0
|
||||
|
||||
for (const entry of Array.isArray(data.listeners) ? data.listeners : []) {
|
||||
if (typeof entry === 'object' && entry !== null) {
|
||||
if ((entry as Record<string, unknown>).proxy === name) count += 1
|
||||
}
|
||||
}
|
||||
|
||||
for (const group of Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []) {
|
||||
if (typeof group !== 'object' || group === null) continue
|
||||
const members = (group as Record<string, unknown>).proxies
|
||||
if (Array.isArray(members) && members.includes(name)) count += 1
|
||||
}
|
||||
|
||||
for (const rule of Array.isArray(data.rules) ? data.rules : []) {
|
||||
// 规则的目标是逗号分隔的最后一段之前那个位置,形如 MATCH,目标 或 DOMAIN,x,目标
|
||||
if (typeof rule === 'string' && rule.split(',').some((part) => part.trim() === name)) count += 1
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* 删掉没人再引用的生成组。
|
||||
*
|
||||
* 每次改完配置都跑一遍。不清理的话,改几次出站文件里就攒下一堆没用的组,而用户
|
||||
* 并不知道它们是干嘛的——他从来没主动建过它们。
|
||||
*
|
||||
* 只动带前缀的组,用户自己建的一律不碰,哪怕它确实没人引用。
|
||||
*/
|
||||
export function pruneGeneratedGroups(data: ConfigObject): ConfigObject {
|
||||
const groups = Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []
|
||||
const kept = groups.filter((group) => {
|
||||
if (typeof group !== 'object' || group === null) return true
|
||||
const name = (group as Record<string, unknown>).name
|
||||
if (typeof name !== 'string' || !isGeneratedGroup(name)) return true
|
||||
return referencesTo(data, name) > 0
|
||||
})
|
||||
|
||||
if (kept.length === groups.length) return data
|
||||
const next = { ...data }
|
||||
if (kept.length === 0) delete next['proxy-groups']
|
||||
else next['proxy-groups'] = kept
|
||||
return next
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import {
|
||||
applySetup,
|
||||
chainGroupName,
|
||||
chainProviderName,
|
||||
panelGroups,
|
||||
syncGenerated,
|
||||
isGenerated,
|
||||
linesMatching,
|
||||
proxyGroupName,
|
||||
pruneGenerated,
|
||||
readSetup,
|
||||
} from './inbound-groups.ts'
|
||||
import type { OutboundSetup } from './inbound-groups.ts'
|
||||
import { collectInbounds } from './inbounds.ts'
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
|
||||
const URL = 'http://127.0.0.1:3001/token/download/V2House'
|
||||
|
||||
/** 一份最小但完整的配置:一个订阅、一路入站,还没被 Patchbay 接管过。 */
|
||||
function base(): ConfigObject {
|
||||
return {
|
||||
'proxy-providers': {
|
||||
subs: { type: 'http', url: URL, path: './providers/subs.yaml', interval: 86400 },
|
||||
},
|
||||
listeners: [{ name: 'test1', type: 'mixed', port: 7778 }],
|
||||
}
|
||||
}
|
||||
|
||||
const plain: OutboundSetup = { proxy: { sources: ['subs'], filter: null }, chain: null }
|
||||
const chained: OutboundSetup = {
|
||||
proxy: { sources: ['subs'], filter: null },
|
||||
chain: { sources: ['subs'], filter: '(?i)DMIT' },
|
||||
}
|
||||
|
||||
describe('名字', () => {
|
||||
it('三种生成物都带前缀', () => {
|
||||
// 前缀是识别它们的唯一可靠标记,注释会被配置改写引擎丢掉(决策记录 0002)
|
||||
expect(isGenerated(proxyGroupName('test1'))).toBe(true)
|
||||
expect(isGenerated(chainGroupName('test1'))).toBe(true)
|
||||
expect(isGenerated(chainProviderName('test1', 'subs'))).toBe(true)
|
||||
})
|
||||
|
||||
it('用户自己建的组不会被认成生成的', () => {
|
||||
expect(isGenerated('PROXY')).toBe(false)
|
||||
})
|
||||
|
||||
it('不同的「入站 × 来源」组合不撞名', () => {
|
||||
// proxy-providers 是个映射,撞名会让其中一份被静默丢掉,
|
||||
// 表现是链式代理挂到了别的入站上
|
||||
const names = new Set([
|
||||
chainProviderName('a', 'b c'),
|
||||
chainProviderName('a b', 'c'),
|
||||
chainProviderName('a', 'b'),
|
||||
])
|
||||
expect(names.size).toBe(3)
|
||||
})
|
||||
|
||||
|
||||
})
|
||||
|
||||
describe('筛选预览', () => {
|
||||
const lines = ['[vmess]DMIT.LAX.Pro.MTYQ', '[vless]Gomami.SIN Secret', '香港01', '香港011']
|
||||
|
||||
it('没写筛选条件就是全要', () => {
|
||||
expect(linesMatching(null, lines)).toEqual(lines)
|
||||
})
|
||||
|
||||
it('部分匹配,不自动加锚点', () => {
|
||||
// 内核的筛选就是部分匹配,界面预览必须跟它一致,否则预览的数字骗人
|
||||
expect(linesMatching('香港01', lines)).toEqual(['香港01', '香港011'])
|
||||
})
|
||||
|
||||
it('反引号切成多条正则,取并集', () => {
|
||||
expect(linesMatching('DMIT`Gomami', lines)).toEqual([
|
||||
'[vmess]DMIT.LAX.Pro.MTYQ',
|
||||
'[vless]Gomami.SIN Secret',
|
||||
])
|
||||
})
|
||||
|
||||
it('写法有误时返回空,让界面提示而不是显示一个错的数字', () => {
|
||||
expect(linesMatching('[未闭合', lines)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('一路入站的三个组', () => {
|
||||
it('SELECT 的成员是 DIRECT 加另外两个组,加上订阅', () => {
|
||||
// 这三种挑法是所有 clash 配置里固定的那几种,让用户从零拼一遍没有意义
|
||||
const groups = applySetup(base(), 'test1', plain)['proxy-groups'] as ConfigObject[]
|
||||
expect(groups[0]).toEqual({
|
||||
name: 'patchbay:test1',
|
||||
type: 'select',
|
||||
proxies: ['DIRECT', 'patchbay:test1 AUTO', 'patchbay:test1 FALLBACK'],
|
||||
use: ['subs'],
|
||||
})
|
||||
})
|
||||
|
||||
it('AUTO 是 url-test,FALLBACK 是 fallback,都带测速地址', () => {
|
||||
// 不写测速地址时内核会去借来源订阅的健康检查配置,那依赖订阅写了它,不能指望
|
||||
const groups = applySetup(base(), 'test1', plain)['proxy-groups'] as ConfigObject[]
|
||||
expect(groups[1]).toEqual({
|
||||
name: 'patchbay:test1 AUTO',
|
||||
type: 'url-test',
|
||||
use: ['subs'],
|
||||
url: 'https://www.gstatic.com/generate_204',
|
||||
interval: 300,
|
||||
})
|
||||
expect((groups[2] as ConfigObject).type).toBe('fallback')
|
||||
})
|
||||
|
||||
it('tab 的顺序是 SELECT、AUTO、FALLBACK,只有 SELECT 能点', () => {
|
||||
// 另外两个自己决定用哪条,手动指定会被它们自己撤销,见 outbound-chain.ts
|
||||
const data = applySetup(base(), 'test1', plain)
|
||||
const runtime = {
|
||||
'patchbay:test1': { type: 'Selector' },
|
||||
'patchbay:test1 AUTO': { type: 'URLTest' },
|
||||
'patchbay:test1 FALLBACK': { type: 'Fallback' },
|
||||
}
|
||||
const inbound = collectInbounds(data)[0]!
|
||||
const panel = panelGroups(data, runtime, inbound)
|
||||
|
||||
expect(panel.shared).toBe(false)
|
||||
expect(panel.groups.map((g) => g.label)).toEqual(['SELECT', 'AUTO', 'FALLBACK'])
|
||||
expect(panel.groups.map((g) => g.pickable)).toEqual([true, false, false])
|
||||
expect(panel.groups[0]!.uses).toEqual(['subs'])
|
||||
})
|
||||
|
||||
it('内核里还没有的组不出现在 tab 上', () => {
|
||||
// 保存完到内核重载完之间会有这么一小段,画一个点不出东西的 tab 只会让人以为坏了
|
||||
const data = applySetup(base(), 'test1', plain)
|
||||
const inbound = collectInbounds(data)[0]!
|
||||
expect(panelGroups(data, {}, inbound).groups).toEqual([])
|
||||
})
|
||||
|
||||
it('没接管的入站落到它顺着规则表走到的那个手动选择组,并标为共用', () => {
|
||||
const data: ConfigObject = {
|
||||
...base(),
|
||||
rules: ['MATCH,PROXY'],
|
||||
'proxy-groups': [{ name: 'PROXY', type: 'select', use: ['subs'] }],
|
||||
}
|
||||
const runtime = { PROXY: { type: 'Selector', now: 'A', all: ['A'] } }
|
||||
const panel = panelGroups(data, runtime, collectInbounds(data)[0]!)
|
||||
|
||||
expect(panel.shared).toBe(true)
|
||||
expect(panel.groups).toEqual([
|
||||
{ name: 'PROXY', label: 'PROXY', uses: ['subs'], pickable: true },
|
||||
])
|
||||
})
|
||||
|
||||
it('筛选条件三个组共用一份', () => {
|
||||
const groups = applySetup(base(), 'test1', {
|
||||
proxy: { sources: ['subs'], filter: '(?i)hk' },
|
||||
chain: null,
|
||||
})['proxy-groups'] as ConfigObject[]
|
||||
for (const g of groups) expect((g as ConfigObject).filter).toBe('(?i)hk')
|
||||
})
|
||||
})
|
||||
|
||||
describe('重建成当前形状', () => {
|
||||
it('旧形状的生成组会被补齐成三个', () => {
|
||||
// 改过生成规则之后,早先建的那些停在旧形状上,界面按新形状去找就静默少一块
|
||||
const stale: ConfigObject = {
|
||||
...base(),
|
||||
'proxy-groups': [{ name: 'patchbay:test1', type: 'select', use: ['subs'] }],
|
||||
listeners: [{ name: 'test1', type: 'mixed', port: 7778, proxy: 'patchbay:test1' }],
|
||||
}
|
||||
const fixed = syncGenerated(stale, collectInbounds(stale))
|
||||
const names = (fixed['proxy-groups'] as ConfigObject[]).map((g) => (g as ConfigObject).name)
|
||||
|
||||
expect(names).toEqual(['patchbay:test1', 'patchbay:test1 AUTO', 'patchbay:test1 FALLBACK'])
|
||||
})
|
||||
|
||||
it('没接管的入站不碰', () => {
|
||||
const data = base()
|
||||
expect(syncGenerated(data, collectInbounds(data))).toBe(data)
|
||||
})
|
||||
})
|
||||
|
||||
describe('读取设置', () => {
|
||||
it('没有代理组时返回空,表示这一路由别的方式决定去向', () => {
|
||||
expect(readSetup(base(), 'test1')).toBeNull()
|
||||
})
|
||||
|
||||
it('没开链式代理时,来源就是代理组的 use', () => {
|
||||
const setup: OutboundSetup = { proxy: { sources: ['subs'], filter: '(?i)hk' }, chain: null }
|
||||
expect(readSetup(applySetup(base(), 'test1', setup), 'test1')).toEqual(setup)
|
||||
})
|
||||
|
||||
it('开了链式代理时,来源从副本的 url 还原', () => {
|
||||
// 代理组的 use 这时指向副本,用户选的订阅只能靠 url 相同认回来
|
||||
const data = applySetup(base(), 'test1', chained)
|
||||
expect(readSetup(data, 'test1')).toEqual(chained)
|
||||
})
|
||||
})
|
||||
|
||||
describe('写回设置', () => {
|
||||
it('开链式代理时建入口组,三个组一起改用副本', () => {
|
||||
const groups = applySetup(base(), 'test1', chained)['proxy-groups'] as ConfigObject[]
|
||||
const copyName = chainProviderName('test1', 'subs')
|
||||
|
||||
// 只有副本挂着 dialer-proxy,自动测速和故障转移也得走副本,否则那两条路绕过了中转
|
||||
for (const g of groups.slice(0, 3)) expect((g as ConfigObject).use).toEqual([copyName])
|
||||
expect(groups[3]).toEqual({
|
||||
name: 'patchbay:test1 链式',
|
||||
type: 'select',
|
||||
use: ['subs'],
|
||||
filter: '(?i)DMIT',
|
||||
})
|
||||
})
|
||||
|
||||
it('副本读原订阅的缓存文件,自己不联网', () => {
|
||||
// 副本要是自己去拉,订阅地址一不可达它就是空的,那一路入站的线路会全部消失,
|
||||
// 表现是端口还在监听却一条线都没有
|
||||
const data = applySetup(base(), 'test1', chained)
|
||||
const copy = (data['proxy-providers'] as ConfigObject)[
|
||||
chainProviderName('test1', 'subs')
|
||||
] as ConfigObject
|
||||
|
||||
expect(copy.type).toBe('file')
|
||||
expect(copy.path).toBe('./providers/subs.yaml')
|
||||
expect(copy.url).toBeUndefined()
|
||||
expect(copy.interval).toBeUndefined()
|
||||
expect(copy.override).toEqual({ 'dialer-proxy': 'patchbay:test1 链式' })
|
||||
})
|
||||
|
||||
it('原订阅没写 path 时给它补一个,否则副本认不到该读哪个文件', () => {
|
||||
// 内核会按 url 哈希自己生成缓存路径,那个路径 Patchbay 算不出来
|
||||
const data = base()
|
||||
delete ((data['proxy-providers'] as ConfigObject).subs as ConfigObject).path
|
||||
const next = applySetup(data, 'test1', chained)
|
||||
const providers = next['proxy-providers'] as ConfigObject
|
||||
|
||||
expect((providers.subs as ConfigObject).path).toBe('./providers/subs.yaml')
|
||||
expect(readSetup(next, 'test1')).toEqual(chained)
|
||||
})
|
||||
|
||||
it('源订阅原有的 override 保留,不被覆盖', () => {
|
||||
const data = base()
|
||||
;((data['proxy-providers'] as ConfigObject).subs as ConfigObject).override = { udp: true }
|
||||
const next = applySetup(data, 'test1', chained)
|
||||
const copy = (next['proxy-providers'] as ConfigObject)[
|
||||
chainProviderName('test1', 'subs')
|
||||
] as ConfigObject
|
||||
|
||||
expect(copy.override).toEqual({ udp: true, 'dialer-proxy': 'patchbay:test1 链式' })
|
||||
})
|
||||
|
||||
it('关掉链式代理时,入口组和副本一起消失', () => {
|
||||
const off = applySetup(applySetup(base(), 'test1', chained), 'test1', plain)
|
||||
const names = (off['proxy-groups'] as ConfigObject[]).map((g) => (g as ConfigObject).name)
|
||||
|
||||
expect(names).not.toContain('patchbay:test1 链式')
|
||||
expect(Object.keys(off['proxy-providers'] as ConfigObject)).toEqual(['subs'])
|
||||
})
|
||||
|
||||
it('换来源时旧副本立刻消失', () => {
|
||||
// 留着的话就是一份没人引用、却还在按 interval 定时联网的订阅
|
||||
const data = base()
|
||||
const providers = data['proxy-providers'] as ConfigObject
|
||||
providers.other = { type: 'http', url: 'http://other.example/x', path: './providers/o.yaml' }
|
||||
|
||||
const first = applySetup(data, 'test1', chained)
|
||||
const second = applySetup(first, 'test1', {
|
||||
proxy: { sources: ['other'], filter: null },
|
||||
chain: { sources: ['subs'], filter: null },
|
||||
})
|
||||
|
||||
const names = Object.keys(second['proxy-providers'] as ConfigObject)
|
||||
expect(names).toContain(chainProviderName('test1', 'other'))
|
||||
expect(names).not.toContain(chainProviderName('test1', 'subs'))
|
||||
})
|
||||
|
||||
it('两路入站各自的副本互不干扰', () => {
|
||||
const data = base()
|
||||
;(data.listeners as ConfigObject[]).push({ name: 'test2', type: 'mixed', port: 7779 })
|
||||
|
||||
const next = applySetup(applySetup(data, 'test1', chained), 'test2', chained)
|
||||
const providers = next['proxy-providers'] as ConfigObject
|
||||
|
||||
expect(Object.keys(providers)).toHaveLength(3)
|
||||
expect(readSetup(next, 'test1')).toEqual(chained)
|
||||
expect(readSetup(next, 'test2')).toEqual(chained)
|
||||
})
|
||||
})
|
||||
|
||||
describe('清理', () => {
|
||||
it('删掉入站之后,几个组和副本连锁消失', () => {
|
||||
// 链式引用:SELECT 引 AUTO 和 FALLBACK,三者引副本,副本引入口组,要反复扫才清得干净
|
||||
const withInbound = applySetup(base(), 'test1', chained)
|
||||
const removed: ConfigObject = { ...withInbound, listeners: [] }
|
||||
|
||||
const cleaned = pruneGenerated(removed)
|
||||
expect(cleaned['proxy-groups']).toBeUndefined()
|
||||
expect(Object.keys(cleaned['proxy-providers'] as ConfigObject)).toEqual(['subs'])
|
||||
})
|
||||
|
||||
it('入站还在就一个都不删', () => {
|
||||
const data = applySetup(base(), 'test1', chained)
|
||||
expect(pruneGenerated(data)).toBe(data)
|
||||
})
|
||||
|
||||
it('用户自己建的组和订阅一律不碰,哪怕真的没人引用', () => {
|
||||
const data: ConfigObject = {
|
||||
'proxy-groups': [{ name: '我建的组', type: 'select', use: ['subs'] }],
|
||||
'proxy-providers': { subs: { type: 'http', url: URL } },
|
||||
}
|
||||
expect(pruneGenerated(data)).toBe(data)
|
||||
})
|
||||
|
||||
it('没有可删的时候原样返回,不制造无谓的改动', () => {
|
||||
// 返回同一个对象,落盘链路才看得出「内容没变」而跳过备份和重载
|
||||
const data: ConfigObject = { 'proxy-groups': [{ name: 'PROXY' }] }
|
||||
expect(pruneGenerated(data)).toBe(data)
|
||||
})
|
||||
|
||||
it('被规则引用的生成组不删,连它引用的两个组一起留下', () => {
|
||||
const data = applySetup(base(), 'test1', plain)
|
||||
const orphaned: ConfigObject = { ...data, listeners: [], rules: ['MATCH,patchbay:test1'] }
|
||||
expect((pruneGenerated(orphaned)['proxy-groups'] as ConfigObject[]).length).toBe(3)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,501 @@
|
||||
/**
|
||||
* 每一路入站的专属策略组。
|
||||
*
|
||||
* 一路入站配三个组,入站的 `proxy:` 指向其中的 SELECT,换线是换那个组的当前选中,
|
||||
* 不改配置文件(决策记录 0007):
|
||||
* SELECT 手动选。它的成员是 DIRECT、下面两个组,加上订阅里的线路
|
||||
* AUTO url-test,自动挑延迟最低的
|
||||
* FALLBACK fallback,按顺序挑第一个测得通的
|
||||
* 界面上这三个是并排的 tab。做成三个而不是让用户自己配,是因为它们就是所有 clash 配置
|
||||
* 里那三种固定的挑法,让人从零拼一遍没有意义。
|
||||
*
|
||||
* 开了链式代理时再多一个入口组,以及若干份订阅声明的副本——`dialer-proxy` 写不到策略组
|
||||
* 上,只能挂在整个订阅上(内核源码 adapter/outboundgroup/parser.go:68-70)。
|
||||
*
|
||||
* 配置里的东西属于谁全靠三条线索还原,不靠解析名字:
|
||||
* 四个组 名字由入站名推出来
|
||||
* 订阅副本 override.dialer-proxy 指向哪一路的入口组
|
||||
* 副本的来源 url 和哪个用户订阅相同
|
||||
*/
|
||||
import type { ConfigObject } from '../vendor/config-editor/index.ts'
|
||||
import { resolveDestination } from './inbounds.ts'
|
||||
import type { Inbound } from './inbounds.ts'
|
||||
import { lastSwitchableGroup, resolveChain } from './outbound-chain.ts'
|
||||
import type { RuntimeNode } from './outbound-chain.ts'
|
||||
|
||||
/**
|
||||
* Patchbay 自动创建的策略组和订阅的名字前缀。
|
||||
*
|
||||
* 名字是识别它们的唯一可靠标记。注释靠不住——配置改写引擎重建整个被碰到的顶层段落,
|
||||
* 段落内的注释会丢(决策记录 0002)。改这个前缀会让已有配置里的组失去标记,别改。
|
||||
*/
|
||||
export const GENERATED_PREFIX = 'patchbay:'
|
||||
|
||||
export function isGenerated(name: string): boolean {
|
||||
return name.startsWith(GENERATED_PREFIX)
|
||||
}
|
||||
|
||||
/** 手动选的那个组。入站的 `proxy:` 指向它,它的当前选中决定这一路走哪。 */
|
||||
export function proxyGroupName(inbound: string): string {
|
||||
return `${GENERATED_PREFIX}${inbound}`
|
||||
}
|
||||
|
||||
/** 自动测速组,作为 SELECT 的一个成员出现。 */
|
||||
export function autoGroupName(inbound: string): string {
|
||||
return `${GENERATED_PREFIX}${inbound} AUTO`
|
||||
}
|
||||
|
||||
/** 故障转移组,同上。 */
|
||||
export function fallbackGroupName(inbound: string): string {
|
||||
return `${GENERATED_PREFIX}${inbound} FALLBACK`
|
||||
}
|
||||
|
||||
/** 链式代理的入口组。订阅副本的 `dialer-proxy` 指向它。 */
|
||||
export function chainGroupName(inbound: string): string {
|
||||
return `${GENERATED_PREFIX}${inbound} 链式`
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个出站在界面上叫什么。
|
||||
*
|
||||
* 生成的组要去掉 `patchbay:` 前缀和入站名。用户从没建过这些组,让他在卡片和链条上读到
|
||||
* `patchbay:test1 FALLBACK` 只是噪音——那一屏本来就是这一路入站的详情,名字里再重复
|
||||
* 一遍入站名不增加任何信息。
|
||||
*/
|
||||
export function displayName(name: string): string {
|
||||
if (!isGenerated(name)) return name
|
||||
const rest = name.slice(GENERATED_PREFIX.length)
|
||||
for (const [suffix, label] of [
|
||||
[' AUTO', 'AUTO'],
|
||||
[' FALLBACK', 'FALLBACK'],
|
||||
[' 链式', '链式代理'],
|
||||
] as const) {
|
||||
if (rest.endsWith(suffix)) return label
|
||||
}
|
||||
return rest
|
||||
}
|
||||
|
||||
/** 这一路的三个组,按界面上的显示顺序。 */
|
||||
function ownGroups(inbound: string): Array<{ name: string; label: string }> {
|
||||
return [
|
||||
{ name: proxyGroupName(inbound), label: 'SELECT' },
|
||||
{ name: autoGroupName(inbound), label: 'AUTO' },
|
||||
{ name: fallbackGroupName(inbound), label: 'FALLBACK' },
|
||||
]
|
||||
}
|
||||
|
||||
/** FNV-1a。只用来给名字和文件名去重,不是安全用途,所以不引哈希库,浏览器端也要能算。 */
|
||||
function shortHash(text: string): string {
|
||||
let h = 0x811c9dc5
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
h ^= text.charCodeAt(i)
|
||||
h = Math.imul(h, 0x01000193) >>> 0
|
||||
}
|
||||
return h.toString(16).padStart(8, '0')
|
||||
}
|
||||
|
||||
const pairKey = (inbound: string, source: string) => `${inbound} ${source}`
|
||||
|
||||
/**
|
||||
* 「某一路入站 × 某个来源订阅」这个组合对应的订阅副本叫什么。
|
||||
*
|
||||
* 名字里带哈希是因为 `proxy-providers` 是个映射,两个组合撞名会让其中一个被静默丢掉,
|
||||
* 表现是链式代理挂到了别的入站上。带上入站名只是为了翻配置文件时读得懂。
|
||||
*/
|
||||
export function chainProviderName(inbound: string, source: string): string {
|
||||
return `${GENERATED_PREFIX}chain ${inbound} ${shortHash(pairKey(inbound, source))}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个订阅的缓存文件落在哪。
|
||||
*
|
||||
* 内核把拉回来的内容写在这里(内核源码 component/resource/vehicle.go:42-47)。没写
|
||||
* `path:` 时它按 url 哈希自己生成一个(adapter/provider/parser.go:87),那个路径 Patchbay
|
||||
* 算不出来,所以缺的时候补一个确定的进去。
|
||||
*/
|
||||
export function providerCachePath(name: string): string {
|
||||
const safe = name.replace(/[^\p{L}\p{N}_-]+/gu, '-').replace(/^-+|-+$/g, '')
|
||||
return `./providers/${safe || shortHash(name)}.yaml`
|
||||
}
|
||||
|
||||
/** 一组线路从哪来、要哪些。三个组共用同一份,它们只是挑法不同。 */
|
||||
export interface GroupSpec {
|
||||
/** 成员来自哪几个订阅,写进组的 `use:` */
|
||||
sources: string[]
|
||||
/** 只要名字匹配这个正则的线路。null 表示全要 */
|
||||
filter: string | null
|
||||
}
|
||||
|
||||
/** 一路入站的出站设置。 */
|
||||
export interface OutboundSetup {
|
||||
proxy: GroupSpec
|
||||
/** 链式代理的入口。null 表示没开 */
|
||||
chain: GroupSpec | null
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is ConfigObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function groupsOf(data: ConfigObject): ConfigObject[] {
|
||||
return (Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []).filter(isPlainObject)
|
||||
}
|
||||
|
||||
function providersOf(data: ConfigObject): ConfigObject {
|
||||
return isPlainObject(data['proxy-providers']) ? data['proxy-providers'] : {}
|
||||
}
|
||||
|
||||
function findGroup(data: ConfigObject, name: string): ConfigObject | null {
|
||||
return groupsOf(data).find((g) => g.name === name) ?? null
|
||||
}
|
||||
|
||||
function stringList(value: unknown): string[] {
|
||||
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
|
||||
}
|
||||
|
||||
function specOf(group: ConfigObject): GroupSpec {
|
||||
return {
|
||||
sources: stringList(group.use),
|
||||
filter: typeof group.filter === 'string' && group.filter ? group.filter : null,
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户自己配的订阅,不含 Patchbay 生成的副本。界面上「来源」能选的就是这些。 */
|
||||
export function userProviders(data: ConfigObject): string[] {
|
||||
return Object.keys(providersOf(data)).filter((name) => !isGenerated(name))
|
||||
}
|
||||
|
||||
/** 某个策略组从哪几个订阅取成员。组不存在时返回 null。 */
|
||||
export function groupUses(data: ConfigObject, name: string): string[] | null {
|
||||
const group = findGroup(data, name)
|
||||
return group ? stringList(group.use) : null
|
||||
}
|
||||
|
||||
/** 这个订阅副本是哪一路入站的。不是副本、或者认不出归属时返回 null。 */
|
||||
function chainOwnerOf(provider: unknown): string | null {
|
||||
if (!isPlainObject(provider)) return null
|
||||
const override = provider.override
|
||||
if (!isPlainObject(override)) return null
|
||||
const target = override['dialer-proxy']
|
||||
if (typeof target !== 'string' || !isGenerated(target)) return null
|
||||
const suffix = ' 链式'
|
||||
if (!target.endsWith(suffix)) return null
|
||||
return target.slice(GENERATED_PREFIX.length, target.length - suffix.length)
|
||||
}
|
||||
|
||||
/** 副本的来源订阅叫什么。靠读同一个缓存文件来认,因为名字不可靠解析。 */
|
||||
function sourceOfCopy(data: ConfigObject, copy: ConfigObject): string | null {
|
||||
if (typeof copy.path !== 'string') return null
|
||||
for (const [name, entry] of Object.entries(providersOf(data))) {
|
||||
if (isGenerated(name) || !isPlainObject(entry)) continue
|
||||
if (entry.path === copy.path) return name
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 读出这一路入站当前的出站设置。
|
||||
*
|
||||
* 返回 null 表示它还没在专属组模式下,可能是走规则表、直连,或者指向用户自己建的组。
|
||||
*/
|
||||
export function readSetup(data: ConfigObject, inbound: string): OutboundSetup | null {
|
||||
const proxyGroup = findGroup(data, proxyGroupName(inbound))
|
||||
if (!proxyGroup) return null
|
||||
|
||||
const spec = specOf(proxyGroup)
|
||||
const providers = providersOf(data)
|
||||
const copies = spec.sources.filter((name) => chainOwnerOf(providers[name]) === inbound)
|
||||
|
||||
if (copies.length === 0) return { proxy: spec, chain: null }
|
||||
|
||||
const chainGroup = findGroup(data, chainGroupName(inbound))
|
||||
const sources = copies
|
||||
.map((name) => sourceOfCopy(data, providers[name] as ConfigObject))
|
||||
.filter((name): name is string => name !== null)
|
||||
|
||||
return {
|
||||
proxy: { sources, filter: spec.filter },
|
||||
chain: chainGroup ? specOf(chainGroup) : { sources: [], filter: null },
|
||||
}
|
||||
}
|
||||
|
||||
function makeGroup(
|
||||
name: string,
|
||||
type: string,
|
||||
use: string[],
|
||||
filter: string | null,
|
||||
members: string[] = [],
|
||||
): ConfigObject {
|
||||
const group: ConfigObject = { name, type }
|
||||
if (members.length > 0) group.proxies = members
|
||||
if (use.length > 0) group.use = use
|
||||
if (filter) group.filter = filter
|
||||
// url-test 和 fallback 要有测速地址才知道谁快谁通。不写的话内核会借用来源订阅自己的
|
||||
// 健康检查地址(adapter/outboundgroup/parser.go:139-148),但那依赖订阅写了它,
|
||||
// 不能指望;写死一个和内核默认一致的更稳。
|
||||
if (type !== 'select') {
|
||||
group.url = 'https://www.gstatic.com/generate_204'
|
||||
group.interval = 300
|
||||
}
|
||||
return group
|
||||
}
|
||||
|
||||
function upsert(list: ConfigObject[], entry: ConfigObject): ConfigObject[] {
|
||||
const at = list.findIndex((item) => item.name === entry.name)
|
||||
if (at < 0) return [...list, entry]
|
||||
const next = [...list]
|
||||
next[at] = entry
|
||||
return next
|
||||
}
|
||||
|
||||
/**
|
||||
* 照着一个用户订阅做出带 `dialer-proxy` 的那一份。
|
||||
*
|
||||
* 副本是 `type: file`,读的正是原订阅那个缓存文件,自己不联网。这一点是硬性的:副本要是
|
||||
* 自己去拉,订阅地址一不可达它就是空的,而这一路入站的线路全部来自它,结果是端口还在
|
||||
* 监听却一条线都没有。派生自原订阅已经落盘的内容,原订阅有什么副本就有什么。
|
||||
*
|
||||
* 内核对 file 类型的 provider 自带文件监视(component/resource/fetcher.go:212-228),
|
||||
* 原订阅刷新写盘之后副本自动跟着更新,不需要 Patchbay 做任何事。
|
||||
*
|
||||
* `filter` 这些影响「这个订阅里有哪些线路」的字段照抄,`url` 和 `interval` 去掉,
|
||||
* 它们只对 http 类型有意义。
|
||||
*/
|
||||
function makeChainProvider(source: ConfigObject, inbound: string, cachePath: string): ConfigObject {
|
||||
const override = isPlainObject(source.override) ? { ...source.override } : {}
|
||||
override['dialer-proxy'] = chainGroupName(inbound)
|
||||
const { url: _url, interval: _interval, ...rest } = source
|
||||
return { ...rest, type: 'file', path: cachePath, override }
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一路入站的出站设置写回配置。
|
||||
*
|
||||
* 开了链式代理时,三个组的成员都改从订阅副本里取,因为只有副本挂着 `dialer-proxy`。
|
||||
* 用户选的来源订阅仍然可以从副本的 `url` 还原出来,所以配置文件之外不需要另存状态。
|
||||
*/
|
||||
export function applySetup(data: ConfigObject, inbound: string, setup: OutboundSetup): ConfigObject {
|
||||
const next = { ...data }
|
||||
const chained = setup.chain !== null
|
||||
const providers = { ...providersOf(next) }
|
||||
|
||||
// 先清掉这一路原有的副本,再按新的来源重建。改来源时旧的副本必须消失,
|
||||
// 否则代理组不再引用它,它就成了一份没人用却还在定时拉取的订阅。
|
||||
for (const [name, entry] of Object.entries(providers)) {
|
||||
if (chainOwnerOf(entry) === inbound) delete providers[name]
|
||||
}
|
||||
|
||||
const use: string[] = []
|
||||
if (chained) {
|
||||
for (const sourceName of setup.proxy.sources) {
|
||||
const source = providers[sourceName]
|
||||
if (!isPlainObject(source)) continue
|
||||
// 副本靠「读同一个缓存文件」认亲。原订阅没写 path 时内核按 url 哈希自己生成一个,
|
||||
// 那个路径这边算不出来,所以先给原订阅补一个确定的。
|
||||
const cachePath =
|
||||
typeof source.path === 'string' && source.path ? source.path : providerCachePath(sourceName)
|
||||
providers[sourceName] = { ...source, path: cachePath }
|
||||
const copyName = chainProviderName(inbound, sourceName)
|
||||
providers[copyName] = makeChainProvider(providers[sourceName], inbound, cachePath)
|
||||
use.push(copyName)
|
||||
}
|
||||
} else {
|
||||
use.push(...setup.proxy.sources)
|
||||
}
|
||||
|
||||
const { filter } = setup.proxy
|
||||
let groups = groupsOf(next)
|
||||
groups = upsert(
|
||||
groups,
|
||||
makeGroup(proxyGroupName(inbound), 'select', use, filter, [
|
||||
'DIRECT',
|
||||
autoGroupName(inbound),
|
||||
fallbackGroupName(inbound),
|
||||
]),
|
||||
)
|
||||
groups = upsert(groups, makeGroup(autoGroupName(inbound), 'url-test', use, filter))
|
||||
groups = upsert(groups, makeGroup(fallbackGroupName(inbound), 'fallback', use, filter))
|
||||
|
||||
if (chained) {
|
||||
groups = upsert(
|
||||
groups,
|
||||
makeGroup(chainGroupName(inbound), 'select', setup.chain!.sources, setup.chain!.filter),
|
||||
)
|
||||
} else {
|
||||
groups = groups.filter((g) => g.name !== chainGroupName(inbound))
|
||||
}
|
||||
next['proxy-groups'] = groups
|
||||
|
||||
if (Object.keys(providers).length === 0) delete next['proxy-providers']
|
||||
else next['proxy-providers'] = providers
|
||||
|
||||
const listeners = (Array.isArray(next.listeners) ? next.listeners : []).map((entry) =>
|
||||
isPlainObject(entry) && entry.name === inbound
|
||||
? { ...entry, proxy: proxyGroupName(inbound) }
|
||||
: entry,
|
||||
)
|
||||
if (listeners.length > 0) next.listeners = listeners
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
/** 配置里指向某个名字的地方有几处。用来判断生成的东西还有没有人在用。 */
|
||||
function referencesTo(data: ConfigObject, name: string): number {
|
||||
let count = 0
|
||||
|
||||
for (const entry of Array.isArray(data.listeners) ? data.listeners : []) {
|
||||
if (isPlainObject(entry) && entry.proxy === name) count += 1
|
||||
}
|
||||
|
||||
for (const group of groupsOf(data)) {
|
||||
if (stringList(group.proxies).includes(name)) count += 1
|
||||
if (stringList(group.use).includes(name)) count += 1
|
||||
}
|
||||
|
||||
for (const entry of Object.values(providersOf(data))) {
|
||||
if (!isPlainObject(entry) || !isPlainObject(entry.override)) continue
|
||||
if (entry.override['dialer-proxy'] === name) count += 1
|
||||
}
|
||||
|
||||
for (const rule of Array.isArray(data.rules) ? data.rules : []) {
|
||||
// 规则是逗号分隔的,目标出站是其中一段,形如 MATCH,目标 或 DOMAIN,x,目标
|
||||
if (typeof rule === 'string' && rule.split(',').some((part) => part.trim() === name)) count += 1
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* 删掉没人再引用的生成组和订阅副本。
|
||||
*
|
||||
* 每次改完配置都跑一遍。删一路入站之后,它的几个组和几份副本会先后变成孤儿,不清理的话
|
||||
* 文件里就攒下一堆用户从没主动建过的东西,而副本还在按 interval 定时联网。
|
||||
*
|
||||
* 要反复扫:AUTO 和 FALLBACK 被 SELECT 引用,入口组被副本引用,副本被那三个组引用,
|
||||
* 所以删掉 SELECT 之后下一轮才轮到它们。只动带前缀的,用户自己建的一律不碰。
|
||||
*/
|
||||
export function pruneGenerated(data: ConfigObject): ConfigObject {
|
||||
const groups = Array.isArray(data['proxy-groups']) ? data['proxy-groups'] : []
|
||||
const keptGroups = groups.filter((group) => {
|
||||
if (!isPlainObject(group)) return true
|
||||
const name = group.name
|
||||
if (typeof name !== 'string' || !isGenerated(name)) return true
|
||||
return referencesTo(data, name) > 0
|
||||
})
|
||||
|
||||
const providers = providersOf(data)
|
||||
const keptProviders = Object.entries(providers).filter(
|
||||
([name]) => !isGenerated(name) || referencesTo(data, name) > 0,
|
||||
)
|
||||
const providersChanged = keptProviders.length !== Object.keys(providers).length
|
||||
|
||||
if (keptGroups.length === groups.length && !providersChanged) return data
|
||||
|
||||
const next = { ...data }
|
||||
if (keptGroups.length === 0) delete next['proxy-groups']
|
||||
else next['proxy-groups'] = keptGroups
|
||||
|
||||
if (providersChanged) {
|
||||
if (keptProviders.length === 0) delete next['proxy-providers']
|
||||
else next['proxy-providers'] = Object.fromEntries(keptProviders)
|
||||
}
|
||||
|
||||
return pruneGenerated(next)
|
||||
}
|
||||
|
||||
/**
|
||||
* 把所有已接管入站的生成组按当前的生成规则重建一遍。
|
||||
*
|
||||
* 每次写配置前跑。生成的东西必须永远和生成它的代码一致,否则改过生成规则之后,早先建的
|
||||
* 那些就停在旧形状上,界面按新形状去找,找不到就静默少一块——tab 少了两个正是这么来的。
|
||||
* `applySetup` 幂等,形状没变时返回的内容一样,落盘链路会看出内容没变而跳过重载。
|
||||
*/
|
||||
export function syncGenerated(data: ConfigObject, inbounds: Inbound[]): ConfigObject {
|
||||
let next = data
|
||||
for (const inbound of inbounds) {
|
||||
const setup = readSetup(next, inbound.name)
|
||||
const mode = inbound.outbound
|
||||
if (!setup || mode.kind !== 'named' || mode.name !== proxyGroupName(inbound.name)) continue
|
||||
next = applySetup(next, inbound.name, setup)
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
/** 面板上一个 tab 对应的策略组。 */
|
||||
export interface PanelGroup {
|
||||
name: string
|
||||
/** tab 上显示什么。自己的组显示挑法,共用的组显示它自己的名字 */
|
||||
label: string
|
||||
/** 它从哪几个订阅取成员。测延迟要顺着来源找,见 web/runtime.ts 的 membersOf */
|
||||
uses: string[]
|
||||
/** 能不能点成员换选中 */
|
||||
pickable: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 这一路入站的面板上能操作哪些策略组。
|
||||
*
|
||||
* 只此一处回答这个问题。之前它散在四个地方(页面算一次能不能点、组件再算一次、
|
||||
* 共用与否又各算一次),加一种情况就要同时改四处,漏一处就是界面和实际操作对不上。
|
||||
*
|
||||
* 两种情况:接管过的入站是它自己那三个组;没接管的(比如 `mixed-port`,配置顶层的端口
|
||||
* 字段没有 `proxy` 可写)落到它顺着规则表走到的那个手动选择组上,那个组是共用的。
|
||||
*/
|
||||
export function panelGroups(
|
||||
data: ConfigObject,
|
||||
runtime: Record<string, RuntimeNode>,
|
||||
inbound: Inbound,
|
||||
): { groups: PanelGroup[]; shared: boolean } {
|
||||
const mode = inbound.outbound
|
||||
const managed = mode.kind === 'named' && mode.name === proxyGroupName(inbound.name)
|
||||
|
||||
if (managed) {
|
||||
return {
|
||||
shared: false,
|
||||
groups: ownGroups(inbound.name)
|
||||
// 保存完到内核重载完之间,组已经在配置里但运行时还没有,这时先不显示那个 tab
|
||||
.filter((g) => runtime[g.name])
|
||||
.map((g) => ({
|
||||
...g,
|
||||
uses: groupUses(data, g.name) ?? [],
|
||||
// 只有手动选的那个能点。另外两个自己决定用哪条,理由见 outbound-chain.ts
|
||||
pickable: runtime[g.name]?.type === 'Selector',
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
const chain = resolveChain(runtime, resolveDestination(data, inbound))
|
||||
const fallback = lastSwitchableGroup(runtime, chain)
|
||||
if (!fallback) return { groups: [], shared: false }
|
||||
return {
|
||||
shared: true,
|
||||
groups: [
|
||||
{
|
||||
name: fallback.group,
|
||||
label: fallback.group,
|
||||
uses: groupUses(data, fallback.group) ?? [],
|
||||
pickable: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 筛选条件会留下哪些线路。界面上用来在保存前当场告诉用户「匹配到几条」。
|
||||
*
|
||||
* 照着内核的规则算(`adapter/outboundgroup/groupbase.go:72-76, 168-195`):反引号把
|
||||
* 条件切成多条独立正则,取并集;每条都是部分匹配,不自动加锚点。
|
||||
*
|
||||
* 内核用的是支持前后向查找的 .NET 风味引擎,浏览器只有 JS 的,所以复杂写法这里算出来的
|
||||
* 数字可能和内核不一致。写法有误时返回 null,界面据此提示而不是显示一个错的数字。
|
||||
*/
|
||||
export function linesMatching(filter: string | null, lines: string[]): string[] | null {
|
||||
if (!filter) return lines
|
||||
let regexps: RegExp[]
|
||||
try {
|
||||
regexps = filter.split('`').map((part) => new RegExp(part))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return lines.filter((line) => regexps.some((re) => re.test(line)))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'bun:test'
|
||||
import { acceptsManualChoice, lastSwitchableGroup, resolveChain } from './outbound-chain.ts'
|
||||
import { lastSwitchableGroup, resolveChain } from './outbound-chain.ts'
|
||||
import type { RuntimeNode } from './outbound-chain.ts'
|
||||
|
||||
/**
|
||||
@@ -41,25 +41,11 @@ describe('解析流量最终走到哪条线', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('哪种策略组接受手动选择', () => {
|
||||
it('只有 Selector', () => {
|
||||
expect(acceptsManualChoice('Selector')).toBe(true)
|
||||
})
|
||||
|
||||
it('自动决定的那几种都不接受', () => {
|
||||
// 内核里 URLTest 按延迟挑、Fallback 挑第一个可用、LoadBalance 分摊,
|
||||
// 它们的选中结果是算出来的,点了会被算回去
|
||||
for (const type of ['URLTest', 'Fallback', 'LoadBalance', 'Relay']) {
|
||||
expect(acceptsManualChoice(type)).toBe(false)
|
||||
}
|
||||
expect(acceptsManualChoice(undefined)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('找出用户能换选中的那一层', () => {
|
||||
it('跳过自动决定的组,落在最后一个 Selector 上', () => {
|
||||
// 链条是 PROXY(Selector) → AUTO(URLTest) → 线路。
|
||||
// 能点的是 PROXY,不是 AUTO——让人去点 URLTest 的成员,点完会被延迟测试算回去。
|
||||
// 链条是 PROXY(Selector) → AUTO(URLTest) → 线路。能点的是 PROXY 不是 AUTO:
|
||||
// 内核对 URLTest 也接受手动指定,但那条线测不通时指定会临时让位,
|
||||
// 和「选了就一直是它」不是一回事,摆成同一个控件会骗人。
|
||||
const chain = resolveChain(runtime, 'PROXY')
|
||||
expect(lastSwitchableGroup(runtime, chain)).toEqual({
|
||||
group: 'PROXY',
|
||||
@@ -78,7 +64,7 @@ describe('找出用户能换选中的那一层', () => {
|
||||
expect(lastSwitchableGroup(nested, resolveChain(nested, '外层'))?.group).toBe('内层')
|
||||
})
|
||||
|
||||
it('整条链都是自动决定时返回空', () => {
|
||||
it('整条链都不是 Selector 时返回空', () => {
|
||||
const auto: Record<string, RuntimeNode> = {
|
||||
AUTO: { type: 'URLTest', now: '线路A', all: ['线路A'] },
|
||||
线路A: { type: 'Vmess' },
|
||||
|
||||
@@ -19,18 +19,6 @@ export interface RuntimeNode {
|
||||
all?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 这个类型的策略组接不接受手动选择。
|
||||
*
|
||||
* 内核里只有 `Selector` 是「由人来选」的(内核源码 constant/adapters.go:240-248 列出
|
||||
* 全部类型)。`URLTest` 按延迟挑最快的、`Fallback` 挑第一个可用的、`LoadBalance` 在成员
|
||||
* 之间分摊——它们的选中结果是算出来的,界面上给一个能点的列表只会让人困惑:点完可能
|
||||
* 立刻被算回去。`Relay` 已经被内核移除。
|
||||
*/
|
||||
export function acceptsManualChoice(type: string | undefined): boolean {
|
||||
return type === 'Selector'
|
||||
}
|
||||
|
||||
/**
|
||||
* 从落脚的出站一路跟着「当前选中」往下走。
|
||||
*
|
||||
@@ -58,13 +46,16 @@ export interface SwitchableGroup {
|
||||
}
|
||||
|
||||
/**
|
||||
* 链条上最后一个能由人来选的策略组。
|
||||
* 链条上最后一个 `Selector` 组。这一路入站没被 Patchbay 接管时,界面上能点的就是它。
|
||||
*
|
||||
* 取最后一个而不是第一个,是因为越靠近线路的那一层越接近「换线路」这个意图;
|
||||
* 前面的层换的是「走哪套策略」,那是另一回事。
|
||||
*
|
||||
* 跳过自动决定的组:让人去点一个 URLTest 组的成员,点完会被延迟测试算回去,
|
||||
* 那不是选择,是错觉。
|
||||
* 只认 `Selector`,尽管内核对 `URLTest` 和 `Fallback` 也接受手动指定
|
||||
* (hub/route/proxies.go:85-90 检查的是 `SelectAble` 接口,不是类型)。原因是那两种的
|
||||
* 手动指定会自己失效:`URLTest` 选中的线路测不通时临时让位给最快的
|
||||
* (adapter/outboundgroup/urltest.go:103-116),`Fallback` 更狠,测不通一次就把手动指定
|
||||
* 永久清掉(fallback.go:117)。把它们和「选了就一直是它」摆成同一个控件会骗人。
|
||||
*/
|
||||
export function lastSwitchableGroup(
|
||||
runtime: Record<string, RuntimeNode>,
|
||||
@@ -73,7 +64,7 @@ export function lastSwitchableGroup(
|
||||
for (let i = chain.length - 1; i >= 0; i -= 1) {
|
||||
const name = chain[i]!
|
||||
const node = runtime[name]
|
||||
if (!node?.all?.length || !acceptsManualChoice(node.type)) continue
|
||||
if (!node?.all?.length || node.type !== 'Selector') continue
|
||||
return { group: name, members: node.all, now: node.now ?? '' }
|
||||
}
|
||||
return null
|
||||
|
||||
Reference in New Issue
Block a user