原本换一条线要改 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。
159 lines
5.8 KiB
TypeScript
159 lines
5.8 KiB
TypeScript
/**
|
||
* 跟 mihomo 内核打交道的两条通道。
|
||
*
|
||
* 一条是命令行:`mihomo -t` 校验一份配置能不能被内核接受。
|
||
* 一条是 HTTP 管理接口:读运行时状态、让内核重新加载配置。
|
||
*
|
||
* 两条通道的能力边界不一样,而且有一处不对称必须记住:
|
||
* `mihomo -t` **不检查入站的 `proxy:` 指向的出站是否存在**(实测 v1.19.29,
|
||
* 这类配置校验通过、重载成功,直到有流量走到那个入站才在日志里报错)。
|
||
* 所以这一层不是安全网的全部,落盘前还要跑 Patchbay 自己的检查。
|
||
*/
|
||
import type { Env } from './env.ts'
|
||
|
||
export interface ValidateResult {
|
||
ok: boolean
|
||
/** 内核输出的原文,校验失败时用来告诉用户到底哪里不对 */
|
||
message: string
|
||
}
|
||
|
||
/**
|
||
* 用 `mihomo -t` 校验一份配置文件。
|
||
*
|
||
* 超时设得比较宽,因为内核首次校验时可能同步下载 GEO 数据库。
|
||
*/
|
||
export async function validateConfigFile(
|
||
env: Env,
|
||
configPath: string,
|
||
timeoutMs = 300_000,
|
||
): Promise<ValidateResult> {
|
||
const proc = Bun.spawn([env.mihomoBin, '-t', '-d', env.mihomoHome, '-f', configPath], {
|
||
stdout: 'pipe',
|
||
stderr: 'pipe',
|
||
})
|
||
|
||
const timer = setTimeout(() => proc.kill(), timeoutMs)
|
||
try {
|
||
const [stdout, stderr, exitCode] = await Promise.all([
|
||
new Response(proc.stdout).text(),
|
||
new Response(proc.stderr).text(),
|
||
proc.exited,
|
||
])
|
||
const message = [stdout, stderr].filter(Boolean).join('\n').trim()
|
||
if (exitCode === 0) return { ok: true, message }
|
||
return {
|
||
ok: false,
|
||
message: message || `mihomo -t 以退出码 ${String(exitCode)} 结束,但没有任何输出`,
|
||
}
|
||
} finally {
|
||
clearTimeout(timer)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 启动时先把内核二进制跑一次,什么都不做。
|
||
*
|
||
* `mihomo -t` 的第一次调用要 4 秒,之后 55 毫秒(在目标机器那种规格上实测差距只会更大)。
|
||
* 差的是把这个几十兆的可执行文件读进系统文件缓存的时间,跟配置内容无关。不预热的话,
|
||
* 这 4 秒会落在用户按下的第一次保存上,而那正是他最容易以为「这个工具很慢」的时刻。
|
||
*
|
||
* 失败不用管:内核二进制不可用这件事,第一次真正校验时会带着完整错误信息报出来。
|
||
*/
|
||
export function warmUpKernelBinary(env: Env): void {
|
||
try {
|
||
const proc = Bun.spawn([env.mihomoBin, '-v'], { stdout: 'ignore', stderr: 'ignore' })
|
||
void proc.exited
|
||
} catch {
|
||
// 同上
|
||
}
|
||
}
|
||
|
||
/** 带上认证头访问管理接口。 */
|
||
async function callApi(env: Env, path: string, init?: RequestInit): Promise<Response> {
|
||
return fetch(`${env.mihomoApi}${path}`, {
|
||
...init,
|
||
headers: {
|
||
Authorization: `Bearer ${env.mihomoSecret}`,
|
||
'Content-Type': 'application/json',
|
||
...init?.headers,
|
||
},
|
||
})
|
||
}
|
||
|
||
/** 内核是否在线,在线时返回版本号。 */
|
||
export async function kernelVersion(env: Env): Promise<{ online: boolean; version?: string }> {
|
||
try {
|
||
const res = await callApi(env, '/version', { signal: AbortSignal.timeout(5_000) })
|
||
if (!res.ok) return { online: false }
|
||
const body = (await res.json()) as { version?: string }
|
||
return { online: true, version: body.version }
|
||
} catch {
|
||
return { online: false }
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 让内核重新加载配置文件,不重启进程。
|
||
*
|
||
* `force=true` 意味着连端口这类需要重开监听的改动也一并生效——正是本项目改入站时需要的。
|
||
* 注意 `path` 是**内核所在机器上的路径**:部署时 Patchbay 和内核在同一台机器上所以没有问题,
|
||
* 但开发时如果 Patchbay 在本机、内核在远端,这个调用不会加载到本地的文件。
|
||
*/
|
||
export async function reloadConfig(env: Env, configPath: string): Promise<ValidateResult> {
|
||
try {
|
||
const res = await callApi(env, '/configs?force=true', {
|
||
method: 'PUT',
|
||
body: JSON.stringify({ path: configPath }),
|
||
signal: AbortSignal.timeout(30_000),
|
||
})
|
||
if (res.ok) return { ok: true, message: '' }
|
||
return { ok: false, message: (await res.text()) || `管理接口返回 ${String(res.status)}` }
|
||
} catch (error) {
|
||
return { ok: false, message: `连不上管理接口:${String(error)}` }
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 切换某个策略组当前选中哪个成员。
|
||
*
|
||
* 这是运行时状态,不写配置文件——所以不走 config-store 那条保护链路,也不需要备份和还原。
|
||
* 内核重启后会不会记住,取决于配置里的 profile.store-selected。
|
||
*/
|
||
export async function selectProxy(
|
||
env: Env,
|
||
group: string,
|
||
member: string,
|
||
): Promise<ValidateResult> {
|
||
try {
|
||
const res = await callApi(env, `/proxies/${encodeURIComponent(group)}`, {
|
||
method: 'PUT',
|
||
body: JSON.stringify({ name: member }),
|
||
signal: AbortSignal.timeout(10_000),
|
||
})
|
||
if (res.ok) return { ok: true, message: '' }
|
||
return { ok: false, message: (await res.text()) || `管理接口返回 ${String(res.status)}` }
|
||
} catch (error) {
|
||
return { ok: false, message: `连不上管理接口:${String(error)}` }
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 透传一个管理接口的 GET 请求。
|
||
*
|
||
* `stream` 为真时不设超时:流量、内存、日志这三个接口不升级 WebSocket 时会退化成
|
||
* 持续吐 JSON 的分块流(内核源码 hub/route/server.go:380-383),给它们设超时等于
|
||
* 每隔一会儿就把连接掐断一次。
|
||
*/
|
||
export async function proxyGet(env: Env, path: string, stream = false): Promise<Response> {
|
||
return callApi(env, path, stream ? {} : { signal: AbortSignal.timeout(15_000) })
|
||
}
|
||
|
||
/** 透传一个写操作。目前只有断开连接和刷新订阅两处。 */
|
||
export async function proxyWrite(
|
||
env: Env,
|
||
method: 'PUT' | 'DELETE',
|
||
path: string,
|
||
): Promise<Response> {
|
||
return callApi(env, path, { method, signal: AbortSignal.timeout(30_000) })
|
||
}
|