订阅健康检查默认开启,编辑支持改名

内核没有默认的健康检查地址,url 为空时检查根本不会运行
(adapter/provider/healthcheck.go:196-199),所以默认值必须写全;
开关只翻 enable,手写的 url/interval 留着下次开启时还用。
改名和策略组 use: 的引用同步收在同一次变换里,链式副本由保存
链路的 syncGenerated 按新名字重建,缓存路径刻意不动——file 类型
的数据本体和副本认亲都靠它。
This commit is contained in:
2026-08-12 17:30:07 +08:00
parent b28fc572f7
commit d6942c5702
6 changed files with 237 additions and 49 deletions
+100 -3
View File
@@ -1,17 +1,27 @@
import { describe, expect, it } from 'bun:test'
import {
DEFAULT_HEALTH_CHECK,
DEFAULT_INTERVAL,
addFileSubscription,
addSubscription,
listSubscriptions,
providerNames,
removeSubscription,
renameSubscription,
setSubscriptionHealthCheck,
subscriptionPathConflict,
subscriptionReferences,
updateSubscription,
} from './providers.ts'
import { applySetup, chainProviderName, providerCachePath } from './inbound-groups.ts'
import {
applySetup,
chainProviderName,
providerCachePath,
pruneGenerated,
syncGenerated,
} 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'
@@ -77,7 +87,7 @@ describe('读出订阅列表', () => {
})
describe('新增订阅', () => {
it('自动生成缓存路径和默认间隔', () => {
it('自动生成缓存路径、默认间隔和默认开启的健康检查', () => {
const next = addSubscription({}, 'subs2', URL)
expect(next['proxy-providers']).toEqual({
subs2: {
@@ -85,6 +95,7 @@ describe('新增订阅', () => {
url: URL,
path: './providers/subs2.yaml',
interval: DEFAULT_INTERVAL,
'health-check': DEFAULT_HEALTH_CHECK,
},
})
})
@@ -106,11 +117,97 @@ describe('新增订阅', () => {
it('从文件导入的订阅是 file 类型,没有地址和间隔', () => {
const next = addFileSubscription({}, 'subs2')
expect(next['proxy-providers']).toEqual({
subs2: { type: 'file', path: './providers/subs2.yaml' },
subs2: {
type: 'file',
path: './providers/subs2.yaml',
'health-check': DEFAULT_HEALTH_CHECK,
},
})
})
})
describe('健康检查开关', () => {
it('开启时缺的字段用默认值补齐', () => {
const data = base()
const subs = (data['proxy-providers'] as ConfigObject).subs as ConfigObject
delete subs['health-check']
const next = setSubscriptionHealthCheck(data, 'subs', true)
const entry = (next['proxy-providers'] as ConfigObject).subs as ConfigObject
expect(entry['health-check']).toEqual(DEFAULT_HEALTH_CHECK)
})
it('关闭只翻 enable,手写的 url 和 interval 留着', () => {
const data = base()
const subs = (data['proxy-providers'] as ConfigObject).subs as ConfigObject
subs['health-check'] = { enable: true, url: 'https://example.com/ping', interval: 60 }
const next = setSubscriptionHealthCheck(data, 'subs', false)
const entry = (next['proxy-providers'] as ConfigObject).subs as ConfigObject
expect(entry['health-check']).toEqual({
enable: false,
url: 'https://example.com/ping',
interval: 60,
})
// 再开启时它们原样回来
const back = setSubscriptionHealthCheck(next, 'subs', true)
expect(listSubscriptions(back)[0]?.healthCheck).toEqual({
url: 'https://example.com/ping',
interval: 60,
})
})
it('本来就没写又要关闭时不做改动', () => {
const data = base()
const subs = (data['proxy-providers'] as ConfigObject).subs as ConfigObject
delete subs['health-check']
expect(setSubscriptionHealthCheck(data, 'subs', false)).toBe(data)
})
it('订阅不存在时不做改动', () => {
const data = base()
expect(setSubscriptionHealthCheck(data, 'ghost', true)).toBe(data)
})
})
describe('订阅改名', () => {
it('改映射键并同步策略组的 use 引用,path 不动', () => {
const next = renameSubscription(base(), 'subs', 'subs-new')
const providers = next['proxy-providers'] as ConfigObject
expect(Object.keys(providers)).toEqual(['subs-new'])
expect((providers['subs-new'] as ConfigObject).path).toBe('./providers/subs.yaml')
const group = (next['proxy-groups'] as ConfigObject[])[0]!
expect(group.use).toEqual(['subs-new'])
})
it('保持条目在映射里的位置', () => {
const data = addSubscription(addSubscription(base(), 'a', URL), 'b', URL)
const next = renameSubscription(data, 'a', 'z')
expect(Object.keys(next['proxy-providers'] as ConfigObject)).toEqual(['subs', 'z', 'b'])
})
it('改名后保存链路按新名字重建链式副本', () => {
const data = applySetup(
{ ...base(), listeners: [{ name: 'test1', type: 'mixed', port: 7778 }] },
'test1',
chainedSetup,
)
const renamed = renameSubscription(data, 'subs', 'subs2')
// 页面 commit() 每次落盘前都跑这两步
const synced = pruneGenerated(syncGenerated(renamed, collectInbounds(renamed)))
expect(providerNames(synced)).toContain(chainProviderName('test1', 'subs2'))
expect(providerNames(synced)).not.toContain(chainProviderName('test1', 'subs'))
// 引用检查也要认得出新名字,删除保护不能因为改名失效
expect(subscriptionReferences(synced, 'subs2')).not.toEqual([])
})
it('原名不存在、新名已占用或没改时都不做改动', () => {
const data = base()
expect(renameSubscription(data, 'ghost', 'x')).toBe(data)
const withX = addSubscription(data, 'x', URL)
expect(renameSubscription(withX, 'subs', 'x')).toBe(withX)
expect(renameSubscription(data, 'subs', 'subs')).toBe(data)
})
})
describe('编辑订阅', () => {
it('只改地址和间隔,其余字段原样保留', () => {
const next = updateSubscription(base(), 'subs', 'http://example.com/new', 3600)
+79 -3
View File
@@ -6,8 +6,8 @@
* 这个模块只操作用户订阅;副本的增删由 `inbound-groups.ts` 的 applySetup/pruneGenerated 负责,
* 写配置的链路(页面里的 commit)每次都会跑它们,所以这里改完不用补同步。
*
* 订阅不提供改名:名字被策略组的 `use:` 和生成的副本引用,改名等于改一个被引用的
* 标识符,要同步更新所有引用,漏一处就是断引用。删了重建更简单。
* 改名必须走 renameSubscription:名字被策略组的 `use:` 和生成的副本引用,改名和
* 同步引用要在同一次变换里完成,散开做漏一处就是断引用。
*/
import type { ConfigObject } from '../vendor/config-editor/index.ts'
import { isGenerated, providerCachePath } from './inbound-groups.ts'
@@ -15,6 +15,19 @@ import { isGenerated, providerCachePath } from './inbound-groups.ts'
/** 新增订阅时的默认更新间隔,秒。一天一次。 */
export const DEFAULT_INTERVAL = 86400
/**
* 新增订阅或开启健康检查时写入的默认值。
*
* `url` 必须写:内核没有默认检查地址,为空时 interval 被强制归零、检查不会运行
* (内核源码 adapter/provider/healthcheck.go:196-199)。`interval` 与内核在
* enable 时的默认一致(adapter/provider/parser.go:66-68),写死一个更稳。
*/
export const DEFAULT_HEALTH_CHECK = {
enable: true,
url: 'https://www.gstatic.com/generate_204',
interval: 300,
}
/** 一个用户订阅在界面上的样子。只读配置文件的 `proxy-providers` 段(决策记录 0004)。 */
export interface Subscription {
name: string
@@ -104,6 +117,7 @@ export function addSubscription(
url,
path: providerCachePath(name),
...(interval !== null ? { interval } : {}),
'health-check': { ...DEFAULT_HEALTH_CHECK },
},
}
return next
@@ -137,7 +151,11 @@ export function addFileSubscription(data: ConfigObject, name: string): ConfigObj
const next = { ...data }
next['proxy-providers'] = {
...providersOf(data),
[name]: { type: 'file', path: providerCachePath(name) },
[name]: {
type: 'file',
path: providerCachePath(name),
'health-check': { ...DEFAULT_HEALTH_CHECK },
},
}
return next
}
@@ -162,6 +180,64 @@ export function updateSubscription(
return next
}
/**
* 开关一个订阅的健康检查。
*
* 关闭写 `enable: false` 而不是删掉整个键:用户手写的 url/interval 要留着,
* 下次开启时还用它们。开启时缺的字段用默认值补齐——url 不能缺,内核没有默认
* 检查地址(见 DEFAULT_HEALTH_CHECK 的注)。
*/
export function setSubscriptionHealthCheck(
data: ConfigObject,
name: string,
enable: boolean,
): ConfigObject {
const entry = providersOf(data)[name]
if (!isPlainObject(entry)) return data
const existing = isPlainObject(entry['health-check']) ? entry['health-check'] : null
// 本来就没写又要关闭,不必写一个 enable: false 的完整声明进去
if (!enable && existing === null) return data
const next = { ...data }
next['proxy-providers'] = {
...providersOf(data),
[name]: { ...entry, 'health-check': { ...DEFAULT_HEALTH_CHECK, ...existing, enable } },
}
return next
}
/**
* 改订阅的名字,并同步所有策略组 `use:` 里的引用。
*
* 缓存路径 `path` 保持不变:file 类型的数据本体就在旧路径上,链式代理的副本靠
* 「和原订阅同一个 path」认来源(见 inbound-groups.ts),路径一动这两件事都得另做迁移。
* 生成的副本这里不碰:写配置的链路每次都跑 syncGenerated/pruneGenerated,
* 会按新名字重建副本、清掉旧的。
*/
export function renameSubscription(
data: ConfigObject,
oldName: string,
newName: string,
): ConfigObject {
const providers = providersOf(data)
if (oldName === newName || !(oldName in providers) || newName in providers) return data
const next = { ...data }
// 逐项重建以保住条目在映射里的位置,diff 才不会把整段重排
next['proxy-providers'] = Object.fromEntries(
Object.entries(providers).map(([name, entry]) => [name === oldName ? newName : name, entry]),
)
if (Array.isArray(data['proxy-groups'])) {
next['proxy-groups'] = data['proxy-groups'].map((group) => {
if (!isPlainObject(group) || !Array.isArray(group.use)) return group
if (!group.use.includes(oldName)) return group
return { ...group, use: group.use.map((item) => (item === oldName ? newName : item)) }
})
}
return next
}
/** 删除一个订阅。删到最后一个时把整个键去掉,不在文件里留空映射。 */
export function removeSubscription(data: ConfigObject, name: string): ConfigObject {
const providers = { ...providersOf(data) }
+2 -17
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
/**
* 订阅列表。每行一个订阅:名字、当前线路数、上次更新时间、健康检查开没开。
* 订阅列表。每行一个订阅:名字、当前线路数、上次更新时间。
*
* 只管显示和选中,不碰任何数据。
*/
@@ -13,8 +13,6 @@ defineProps<{
lines: number | null
/** 上次拉取成功的时刻。null 表示不知道或从没拉取过 */
updated: Date | null
/** 健康检查开没开 */
healthCheck: boolean
}>
}>()
const selected = defineModel<string | null>('selected', { required: true })
@@ -40,9 +38,6 @@ function formatUpdated(at: Date): string {
<template v-else>—</template>
</span>
<span class="updated mono">{{ row.updated ? formatUpdated(row.updated) : '—' }}</span>
<span :class="['hc', !row.healthCheck && 'is-off']">
{{ row.healthCheck ? '健康检查' : '—' }}
</span>
</button>
</li>
</ol>
@@ -66,7 +61,7 @@ function formatUpdated(at: Date): string {
.line {
width: 100%;
display: grid;
grid-template-columns: minmax(0, 1fr) 4rem 6.5rem 4.5rem;
grid-template-columns: minmax(0, 1fr) 4rem 6.5rem;
align-items: center;
gap: var(--s-3);
padding: var(--s-3) var(--s-4);
@@ -98,14 +93,4 @@ function formatUpdated(at: Date): string {
font-variant-numeric: tabular-nums;
color: var(--c-text-soft);
}
.hc {
text-align: right;
font-size: var(--t-xs);
color: var(--c-text-soft);
}
.hc.is-off {
color: var(--c-text-faint);
}
</style>
+28 -4
View File
@@ -15,6 +15,8 @@ import {
listSubscriptions,
providerNames,
removeSubscription,
renameSubscription,
setSubscriptionHealthCheck,
subscriptionPathConflict,
subscriptionReferences,
updateSubscription,
@@ -103,7 +105,6 @@ const rows = computed(() =>
name: s.name,
lines: info ? info.proxies.length : null,
updated: parseUpdated(info?.updatedAt),
healthCheck: s.healthCheck !== null,
}
}),
)
@@ -149,7 +150,8 @@ async function submitForm(draft: {
}) {
const editing = formEditing.value
// 名字查重放行了、但净化后的缓存路径和别人相同的,在这里拦(编辑不改名,只查新增)
// 名字查重放行了、但净化后的缓存路径和别人相同的,在这里拦
// (只查新增:改名不动缓存路径,不会制造新的撞车)
if (!editing) {
const path = providerCachePath(draft.name)
const clash = subscriptionPathConflict(props.data, draft.name, path)
@@ -173,8 +175,17 @@ async function submitForm(draft: {
}
}
// 编辑时先改名再改字段。名字没动时 renameSubscription 原样返回;
// file 类型只有名称可改,不能走 updateSubscription——它会写进 url
const next = editing
? updateSubscription(clone(), editing.name, draft.url, draft.interval)
? editing.type === 'file'
? renameSubscription(clone(), editing.name, draft.name)
: updateSubscription(
renameSubscription(clone(), editing.name, draft.name),
draft.name,
draft.url,
draft.interval,
)
: draft.file
? addFileSubscription(clone(), draft.name)
: addSubscription(clone(), draft.name, draft.url, draft.interval)
@@ -182,7 +193,8 @@ async function submitForm(draft: {
// 失败时不能关对话框——关了再打开就是空表单,填的名称、地址、间隔全没了
if (!ok) return
formOpen.value = false
if (!editing) selectedName.value = draft.name
// 新增和改名都要把选中跟过去,否则选中名失效会被重置到第一行
selectedName.value = draft.name
}
function askRemove() {
@@ -205,6 +217,17 @@ async function removeConfirmed() {
await commit(removeSubscription(clone(), target.name), `已删除 ${target.name}`)
}
/** 开关选中订阅的健康检查。写配置文件,走 commit()。 */
async function toggleHealthCheck() {
const target = selected.value
if (!target || saving.value) return
const enable = target.healthCheck === null
await commit(
setSubscriptionHealthCheck(clone(), target.name, enable),
enable ? `已开启 ${target.name} 的健康检查` : `已关闭 ${target.name} 的健康检查`,
)
}
/** 让内核立刻重新拉取。运行时动作,不写配置文件,所以不走 commit()。 */
async function refresh() {
const target = selected.value
@@ -290,6 +313,7 @@ async function refreshAll() {
@edit="openEdit"
@remove="askRemove"
@refresh="refresh"
@toggle-health-check="toggleHealthCheck"
/>
</div>
+17 -15
View File
@@ -1,6 +1,9 @@
<script setup lang="ts">
/**
* 选中那个订阅的详情:地址、更新间隔、健康检查,和它带来的线路。
* 选中那个订阅的详情:地址、更新间隔,和它带来的线路。
*
* 健康检查不在字段区展示,只是右上角一个开关动作:默认就是开着的,
* 值得占一行的只有「被谁关掉了」这件事,而按钮文案本身已经说明了状态。
*
* 线路列表只读。这些线路不在内核的全局名字表里,不能被入站直接引用,
* 只能经策略组的 `use:` 整批引入,所以这里没有「换线」可点。
@@ -13,6 +16,7 @@ import IconEdit from '~icons/ri/edit-line'
import IconDelete from '~icons/ri/delete-bin-line'
import IconRefresh from '~icons/ri/refresh-line'
import IconOffline from '~icons/ri/cloud-off-line'
import IconPulse from '~icons/ri/pulse-line'
const props = defineProps<{
subscription: Subscription
@@ -30,6 +34,8 @@ const emit = defineEmits<{
remove: []
/** 让内核立刻重新拉取。运行时动作,不写配置文件 */
refresh: []
/** 开关健康检查。写配置文件,走保存链路 */
toggleHealthCheck: []
}>()
const lines = computed(() => props.info?.proxies ?? [])
@@ -48,15 +54,13 @@ function delayClass(ms: number | null): string {
<div class="title">
<span class="name">{{ subscription.name }}</span>
<div class="acts">
<button type="button" :disabled="saving" @click="emit('toggleHealthCheck')">
<IconPulse /> {{ subscription.healthCheck ? '关闭健康检查' : '开启健康检查' }}
</button>
<button type="button" :disabled="!online || refreshing" @click="emit('refresh')">
<IconRefresh /> {{ refreshing ? '更新中' : '更新订阅' }}
</button>
<button
type="button"
:disabled="saving || subscription.type === 'file'"
:title="subscription.type === 'file' ? '文件导入的订阅没有可编辑的字段' : undefined"
@click="emit('edit')"
>
<button type="button" :disabled="saving" @click="emit('edit')">
<IconEdit /> 编辑
</button>
<button type="button" class="danger" :disabled="saving" @click="emit('remove')">
@@ -78,14 +82,6 @@ function delayClass(ms: number | null): string {
{{ subscription.interval !== null ? `每 ${subscription.interval} 秒` : '已关闭' }}
</dd>
</template>
<dt>健康检查</dt>
<dd class="mono">
<template v-if="subscription.healthCheck">
{{ subscription.healthCheck.url
}}{{ subscription.healthCheck.interval !== null ? `,每 ${subscription.healthCheck.interval} 秒` : '' }}
</template>
<template v-else>未开启</template>
</dd>
</dl>
</header>
@@ -221,6 +217,12 @@ h3 {
padding: 0;
max-height: 420px;
overflow-y: auto;
/* 细杆加透明轨道,别让系统滚动条压在延迟列上;gutter 常驻,
线路数跨过滚动阈值时右缘不横跳 */
scrollbar-width: thin;
scrollbar-color: var(--c-border-strong) transparent;
scrollbar-gutter: stable;
padding-right: var(--s-2);
}
.row {
+11 -7
View File
@@ -3,8 +3,8 @@
* 新增或编辑一个订阅。
*
* 原生 <dialog>,同 InboundForm。缓存路径不写进表单:它由名字自动生成,
* 让用户填只会填出和链式代理对不上的路径。订阅不能改名——名字被策略组的 `use:`
* 和生成的副本引用,改名要同步所有引用,所以编辑时名字只是静态展示,想换名就删了重建。
* 让用户填只会填出和链式代理对不上的路径。编辑时名字也能改,引用同步和
* 副本重建由保存链路负责(renameSubscription + syncGenerated)。
*
* 新增时地址之外还能从文件导入:选了文件就是 file 类型的订阅,没有地址也没有
* 自动更新(内核靠文件监视跟进变化),相关字段随之收起。
@@ -28,7 +28,7 @@ const props = defineProps<{
const emit = defineEmits<{
close: []
/** 编辑时 name 是被编辑那个订阅的原名。file 非 null 表示从文件导入 */
/** 编辑时 name 和原名不同就是改名。file 非 null 表示从文件导入 */
submit: [
draft: {
name: string
@@ -66,6 +66,8 @@ watch(
const nameError = computed(() => {
const n = name.value.trim()
if (n === '') return ''
// 编辑时名字没动不算重名,takenNames 里有它自己
if (n === props.editing?.name) return ''
// 带这个前缀的会被当成 Patchbay 生成物:列表里不显示,pruneGenerated 还会把它清掉
if (n.startsWith(GENERATED_PREFIX)) return `名称不能以 ${GENERATED_PREFIX} 开头`
if (props.takenNames.includes(n)) return '名称已存在'
@@ -80,8 +82,9 @@ const intervalInvalid = computed(() => {
const canSubmit = computed(() => {
if (props.saving) return false
if (props.editing === null && (name.value.trim() === '' || nameError.value !== '')) return false
if (name.value.trim() === '' || nameError.value !== '') return false
if (file.value !== null) return true
if (props.editing?.type === 'file') return true
return url.value.trim() !== '' && !intervalInvalid.value
})
@@ -92,7 +95,7 @@ function onFile(fileName: string, content: string) {
function submit() {
if (!canSubmit.value) return
emit('submit', {
name: props.editing?.name ?? name.value.trim(),
name: name.value.trim(),
url: url.value.trim(),
interval: autoUpdate.value ? Number(interval.value.trim()) : null,
file: file.value,
@@ -130,7 +133,7 @@ function onBackdrop(event: MouseEvent) {
</header>
<div class="body">
<label v-if="!editing" class="row">
<label class="row">
<span class="k">名称</span>
<span class="v">
<input v-model="name" type="text" placeholder="subs" autocomplete="off" />
@@ -138,7 +141,8 @@ function onBackdrop(event: MouseEvent) {
</span>
</label>
<template v-if="file === null">
<!-- file 类型没有地址和自动更新,编辑它只有名称可改 -->
<template v-if="file === null && editing?.type !== 'file'">
<label class="row">
<span class="k">地址</span>
<span class="v">