dsh-clash-subscription 0.4.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client.js +48 -0
- package/index.js +247 -10
- package/lib/core.js +172 -39
- package/lib/routes.js +3 -0
- package/lib/select.js +178 -0
- package/package.json +1 -1
package/client.js
CHANGED
|
@@ -62,6 +62,17 @@ const en = {
|
|
|
62
62
|
runtime: 'Runtime',
|
|
63
63
|
corePath: 'Core binary',
|
|
64
64
|
corePathHint: 'Path to a mihomo/mihomo-compatible executable. Leave empty to use the copy bundled with this plugin.',
|
|
65
|
+
capability: 'Node capability',
|
|
66
|
+
capabilityHint: 'A node is chosen only when it can reach every required service. Latency alone is not enough: a fast node that OpenAI blocks silently breaks one thing after another.',
|
|
67
|
+
requiredProbes: 'Required services',
|
|
68
|
+
requiredProbesHint: 'Comma-separated probe ids a node must reach, e.g. openai, google. Empty means every probe. Built-ins: gstatic, google, openai, anthropic.',
|
|
69
|
+
probes: 'Extra probes',
|
|
70
|
+
probesHint: 'One id=url per line, for services the built-in list does not cover. Example: hf=https://huggingface.co',
|
|
71
|
+
reselect: 'Re-pick node by capability',
|
|
72
|
+
reselecting: 'Testing nodes…',
|
|
73
|
+
chosenNode: 'Chosen: {node}',
|
|
74
|
+
noUsableNode: 'No node reached every required service.',
|
|
75
|
+
usableCount: '{usable} / {total} nodes usable',
|
|
65
76
|
autoFetchCore: 'Fetch a core automatically',
|
|
66
77
|
autoFetchCoreHint: 'When no mihomo binary is present, download a verified private copy on startup instead of waiting for you to press Download.',
|
|
67
78
|
dns: 'DNS servers',
|
|
@@ -149,6 +160,17 @@ const zh = {
|
|
|
149
160
|
runtime: '运行时',
|
|
150
161
|
corePath: '内核程序',
|
|
151
162
|
corePathHint: 'mihomo 兼容内核的可执行文件路径。留空则使用插件自带的那个。',
|
|
163
|
+
capability: '节点能力',
|
|
164
|
+
capabilityHint: '只有能访问所有必需服务的节点才会被选中。只看延迟不够:延迟很低但被 OpenAI 屏蔽的节点,会让人以为是插件坏了。',
|
|
165
|
+
requiredProbes: '必需服务',
|
|
166
|
+
requiredProbesHint: '逗号分隔的探测项,节点必须全部可达,例如 openai, google。留空表示全部。内置:gstatic、google、openai、anthropic。',
|
|
167
|
+
probes: '额外探测',
|
|
168
|
+
probesHint: '一行一个 id=url,用于补充内置清单之外的服务。例:hf=https://huggingface.co',
|
|
169
|
+
reselect: '按能力重挑节点',
|
|
170
|
+
reselecting: '正在测节点…',
|
|
171
|
+
chosenNode: '已选:{node}',
|
|
172
|
+
noUsableNode: '没有任何节点能访问全部必需服务。',
|
|
173
|
+
usableCount: '{usable} / {total} 个节点可用',
|
|
152
174
|
autoFetchCore: '自动获取内核',
|
|
153
175
|
autoFetchCoreHint: '机器上没有 mihomo 时,启动时自动下载一份经过校验的私有内核,不用手动点下载。',
|
|
154
176
|
dns: 'DNS 服务器',
|
|
@@ -295,6 +317,14 @@ function sections(t) {
|
|
|
295
317
|
{ key: 'speedTestCount', kind: 'number', label: t('count'), hint: t('countHint'), min: 1, max: 40, step: 1 },
|
|
296
318
|
],
|
|
297
319
|
},
|
|
320
|
+
{
|
|
321
|
+
id: 'capability',
|
|
322
|
+
title: t('capability'),
|
|
323
|
+
fields: [
|
|
324
|
+
{ key: 'requiredProbes', kind: 'text', label: t('requiredProbes'), hint: t('requiredProbesHint'), placeholder: 'openai, google' },
|
|
325
|
+
{ key: 'probes', kind: 'text', label: t('probes'), hint: t('probesHint'), placeholder: 'hf=https://huggingface.co' },
|
|
326
|
+
],
|
|
327
|
+
},
|
|
298
328
|
{
|
|
299
329
|
id: 'lists',
|
|
300
330
|
title: t('lists'),
|
|
@@ -513,6 +543,23 @@ function Panel(props) {
|
|
|
513
543
|
h('h4', { key: 'ti' }, t('routing')),
|
|
514
544
|
h('p', { key: 'hi', className: 'clxp-hint' }, t('routingHint')),
|
|
515
545
|
h('p', { key: 'cu', className: 'clxp-note' }, fill(t('currentNode'), { node: live?.node ?? t('autoSelect') })),
|
|
546
|
+
live?.capability !== undefined && Array.isArray(live.capability.nodes) && live.capability.nodes.length > 0
|
|
547
|
+
? h('p', { key: 'cp', className: 'clxp-note' }, fill(t('usableCount'), {
|
|
548
|
+
usable: live.capability.nodes.filter((row) => row.usable).length,
|
|
549
|
+
total: live.capability.nodes.length,
|
|
550
|
+
}) + ' · ' + t('requiredProbes') + ': ' + (live.capability.required ?? []).join(', '))
|
|
551
|
+
: null,
|
|
552
|
+
live?.capability !== undefined && Array.isArray(live.capability.nodes)
|
|
553
|
+
? h('div', { key: 'cpl', className: 'clxp-subs' },
|
|
554
|
+
live.capability.nodes
|
|
555
|
+
.filter((row) => !row.usable)
|
|
556
|
+
.slice(0, 6)
|
|
557
|
+
.map((row) => h('div', { key: row.name, className: 'clxp-sub' }, [
|
|
558
|
+
h('span', { key: 'n', className: 'clxp-node-name' }, row.name),
|
|
559
|
+
h('span', { key: 'f', className: 'clxp-delay bad' }, (row.failed ?? []).join(', ') || '-'),
|
|
560
|
+
])))
|
|
561
|
+
: null,
|
|
562
|
+
|
|
516
563
|
nodes.length === 0
|
|
517
564
|
? h('p', { key: 'em', className: 'clxp-note' }, t('noNodes'))
|
|
518
565
|
: h('div', { key: 'ls', className: 'clxp-nodes', role: 'listbox', 'aria-label': t('routing') },
|
|
@@ -544,6 +591,7 @@ function Panel(props) {
|
|
|
544
591
|
h('div', { key: 'ac', className: 'clxp-actions' }, [
|
|
545
592
|
h('button', { key: 'te', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('test') }, busy === 'test' ? t('testing') : t('testNow')),
|
|
546
593
|
h('button', { key: 'ta', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('test', { all: true }) }, busy === 'test' ? t('testing') : t('testAll')),
|
|
594
|
+
h('button', { key: 'rs', type: 'button', className: 'clxp-primary', disabled: busy !== '' || !running, onClick: () => void props.onAction('reselect') }, busy === 'reselect' ? t('reselecting') : t('reselect')),
|
|
547
595
|
]),
|
|
548
596
|
]),
|
|
549
597
|
|
package/index.js
CHANGED
|
@@ -20,6 +20,7 @@ import { Core, findCoreBinary, splitList } from './lib/core.js'
|
|
|
20
20
|
import { installCore, installCoreFromFile, platformKey } from './lib/corefetch.js'
|
|
21
21
|
import { installVendoredCore, vendoredFor } from './lib/vendored.js'
|
|
22
22
|
import { fetchGeoDatabases, hasGeoDatabase } from './lib/geo.js'
|
|
23
|
+
import { DEFAULT_PROBES, judgeNode, rankNodes, resolveProbes } from './lib/select.js'
|
|
23
24
|
import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
|
|
24
25
|
import { Routing } from './lib/routing.js'
|
|
25
26
|
import {
|
|
@@ -72,6 +73,27 @@ export const CONFIG_DEFAULTS = {
|
|
|
72
73
|
coreVersion: '',
|
|
73
74
|
/** Fetch GeoIP databases after routing works; they are an upgrade, not a requirement. */
|
|
74
75
|
autoFetchGeo: true,
|
|
76
|
+
/** Extra capability probes as `id=url` lines; built-ins cover gstatic/google/openai/anthropic. */
|
|
77
|
+
probes: '',
|
|
78
|
+
/**
|
|
79
|
+
* Probe ids a node must pass to be chosen. Empty means every probe in the set.
|
|
80
|
+
* This is what turns "fastest node" into "node that actually works for my services".
|
|
81
|
+
*/
|
|
82
|
+
requiredProbes: '',
|
|
83
|
+
/** How long the startup node search may spend, in milliseconds. */
|
|
84
|
+
selectBudgetMs: 90000,
|
|
85
|
+
/** Re-check the live node on a schedule and switch only when it stops working. */
|
|
86
|
+
autoReselect: true,
|
|
87
|
+
/** How often that check runs, in minutes; 0 disables it. */
|
|
88
|
+
reselectMinutes: 15,
|
|
89
|
+
/** Active connections above which a re-selection waits, so nothing is interrupted. */
|
|
90
|
+
reselectIdleConnections: 2,
|
|
91
|
+
/** How long the line must stay quiet before switching, in milliseconds. */
|
|
92
|
+
reselectIdleGraceMs: 20000,
|
|
93
|
+
/** Attempts per probe when judging a node; every attempt must answer. */
|
|
94
|
+
probeSamples: 2,
|
|
95
|
+
/** Per-probe budget in milliseconds. */
|
|
96
|
+
probeTimeoutMs: 8000,
|
|
75
97
|
}
|
|
76
98
|
|
|
77
99
|
/**
|
|
@@ -104,6 +126,15 @@ async function buildConfigSchema() {
|
|
|
104
126
|
autoFetchCore: z.boolean().default(false),
|
|
105
127
|
coreVersion: z.string().default(''),
|
|
106
128
|
autoFetchGeo: z.boolean().default(true),
|
|
129
|
+
probes: z.string().default(''),
|
|
130
|
+
requiredProbes: z.string().default(''),
|
|
131
|
+
selectBudgetMs: z.number().default(90000),
|
|
132
|
+
autoReselect: z.boolean().default(true),
|
|
133
|
+
reselectMinutes: z.number().default(15),
|
|
134
|
+
reselectIdleConnections: z.number().default(2),
|
|
135
|
+
reselectIdleGraceMs: z.number().default(20000),
|
|
136
|
+
probeSamples: z.number().default(2),
|
|
137
|
+
probeTimeoutMs: z.number().default(8000),
|
|
107
138
|
})
|
|
108
139
|
} catch {
|
|
109
140
|
return undefined
|
|
@@ -127,7 +158,8 @@ export function resolveConfig(raw) {
|
|
|
127
158
|
config.autoStart = config.autoStart !== false && config.autoStart !== 'false'
|
|
128
159
|
config.autoFetchCore = config.autoFetchCore === true || config.autoFetchCore === 'true'
|
|
129
160
|
config.autoFetchGeo = config.autoFetchGeo !== false && config.autoFetchGeo !== 'false'
|
|
130
|
-
|
|
161
|
+
config.autoReselect = config.autoReselect !== false && config.autoReselect !== 'false'
|
|
162
|
+
for (const field of ['subscriptionUrls', 'subscriptionUrl', 'node', 'corePath', 'coreVersion', 'dnsServers', 'directDomains', 'proxyDomains', 'dataDir', 'probes', 'requiredProbes']) {
|
|
131
163
|
config[field] = String(config[field] ?? '').trim()
|
|
132
164
|
}
|
|
133
165
|
// A profile written by 0.2 carries only `subscriptionUrl`. Normalizing it into the
|
|
@@ -142,6 +174,12 @@ export function resolveConfig(raw) {
|
|
|
142
174
|
config.speedTestMinutes = clamp(config.speedTestMinutes, 0, 1440, 30)
|
|
143
175
|
config.speedTestCount = clamp(config.speedTestCount, 1, 40, 8)
|
|
144
176
|
config.healthCheckMinutes = clamp(config.healthCheckMinutes, 0, 60, 1)
|
|
177
|
+
config.selectBudgetMs = clamp(config.selectBudgetMs, 5_000, 600_000, 90_000)
|
|
178
|
+
config.reselectMinutes = clamp(config.reselectMinutes, 0, 1440, 15)
|
|
179
|
+
config.reselectIdleConnections = clamp(config.reselectIdleConnections, 0, 100, 2)
|
|
180
|
+
config.reselectIdleGraceMs = clamp(config.reselectIdleGraceMs, 0, 600_000, 20_000)
|
|
181
|
+
config.probeSamples = clamp(config.probeSamples, 1, 5, 2)
|
|
182
|
+
config.probeTimeoutMs = clamp(config.probeTimeoutMs, 1_000, 60_000, 8_000)
|
|
145
183
|
return config
|
|
146
184
|
}
|
|
147
185
|
|
|
@@ -180,6 +218,14 @@ export class Runtime {
|
|
|
180
218
|
this.bootstrap = undefined
|
|
181
219
|
/** True while a download is in flight, so two clicks cannot race one archive. */
|
|
182
220
|
this.bootstrapping = false
|
|
221
|
+
/** Last capability matrix, so the panel can explain a selection. */
|
|
222
|
+
this.lastMatrix = []
|
|
223
|
+
/** When the line last became idle, so a switch waits for a quiet moment. */
|
|
224
|
+
this.idleSince = undefined
|
|
225
|
+
/** When the current node was last verified. */
|
|
226
|
+
this.lastCheckAt = undefined
|
|
227
|
+
/** Timer for the periodic re-check. */
|
|
228
|
+
this.reselectTimer = undefined
|
|
183
229
|
/** Progress/result of the optional GeoIP upgrade. */
|
|
184
230
|
this.geo = undefined
|
|
185
231
|
/** True while that upgrade is running. */
|
|
@@ -430,6 +476,142 @@ export class Runtime {
|
|
|
430
476
|
}, minutes * 60_000)
|
|
431
477
|
}
|
|
432
478
|
|
|
479
|
+
/**
|
|
480
|
+
* Should the node be re-chosen right now?
|
|
481
|
+
*
|
|
482
|
+
* Changing the selected node tears down every connection that node is carrying. Doing that
|
|
483
|
+
* mid-session breaks whatever is in flight — a streaming response, a download, a tool call —
|
|
484
|
+
* and the user sees a stalled request with no obvious cause. So the re-check is periodic and
|
|
485
|
+
* only acts when the core reports no active connections.
|
|
486
|
+
*
|
|
487
|
+
* The idle requirement is deliberately strict: any live connection postpones the pass to the
|
|
488
|
+
* next tick, which costs nothing because the next tick is a minute away.
|
|
489
|
+
*
|
|
490
|
+
* @param options - `force` skips the idle gate (used by an explicit request), `graceMs`
|
|
491
|
+
* requires the idle state to have lasted this long.
|
|
492
|
+
* @returns whether a re-selection may run now, and why not when it may not.
|
|
493
|
+
*/
|
|
494
|
+
async canReselectNow(options = {}) {
|
|
495
|
+
if (this.core === undefined || this.core.running !== true) return { ok: false, reason: 'core-not-running' }
|
|
496
|
+
if (this.starting === true) return { ok: false, reason: 'starting' }
|
|
497
|
+
if (options.force === true) return { ok: true, reason: 'forced' }
|
|
498
|
+
if (this.config.autoReselect === false) return { ok: false, reason: 'disabled' }
|
|
499
|
+
|
|
500
|
+
let traffic
|
|
501
|
+
try {
|
|
502
|
+
traffic = await this.core.connections()
|
|
503
|
+
} catch {
|
|
504
|
+
return { ok: false, reason: 'traffic-unreadable' }
|
|
505
|
+
}
|
|
506
|
+
// A few connections are the plugin's own control calls and the core's health checks; the
|
|
507
|
+
// threshold keeps those from blocking forever while still catching real work.
|
|
508
|
+
const limit = Number(this.config.reselectIdleConnections ?? 2)
|
|
509
|
+
if (traffic.count > limit) {
|
|
510
|
+
this.idleSince = undefined
|
|
511
|
+
return { ok: false, reason: 'busy', connections: traffic.count }
|
|
512
|
+
}
|
|
513
|
+
const now = Date.now()
|
|
514
|
+
if (this.idleSince === undefined) this.idleSince = now
|
|
515
|
+
const grace = Number(this.config.reselectIdleGraceMs ?? 20_000)
|
|
516
|
+
if (now - this.idleSince < grace) {
|
|
517
|
+
return { ok: false, reason: 'warming', idleMs: now - this.idleSince, graceMs: grace }
|
|
518
|
+
}
|
|
519
|
+
return { ok: true, reason: 'idle', idleMs: now - this.idleSince }
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Re-check the current node's capabilities and switch only when it is no longer usable.
|
|
524
|
+
*
|
|
525
|
+
* This is the automatic half of selection. The startup choice already proves a node can
|
|
526
|
+
* reach every required service, but a node degrades: a service starts blocking the range, a
|
|
527
|
+
* provider rotates the server behind a name. Re-running the full matrix on every tick would
|
|
528
|
+
* be wasteful and would keep tearing down connections, so the current node is verified first
|
|
529
|
+
* and the expensive search only runs when that verification fails.
|
|
530
|
+
*
|
|
531
|
+
* @param options - `force` bypasses the idle gate.
|
|
532
|
+
* @returns what happened and why.
|
|
533
|
+
*/
|
|
534
|
+
async autoReselect(options = {}) {
|
|
535
|
+
const gate = await this.canReselectNow(options)
|
|
536
|
+
if (!gate.ok) return { state: 'skipped', ...gate }
|
|
537
|
+
|
|
538
|
+
const plan = resolveProbes(this.config.probes, this.config.requiredProbes)
|
|
539
|
+
const group = await this.core.group()
|
|
540
|
+
const current = group.now
|
|
541
|
+
if (current === undefined || current === 'DIRECT') {
|
|
542
|
+
// Nothing real is selected; a full search is the only way forward and it disturbs nobody.
|
|
543
|
+
const result = await this.core.autoSelect(this.preferredNode, {
|
|
544
|
+
probes: plan.probes,
|
|
545
|
+
required: plan.required,
|
|
546
|
+
budgetMs: this.config.selectBudgetMs,
|
|
547
|
+
})
|
|
548
|
+
this.lastMatrix = result.matrix
|
|
549
|
+
if (result.chosen !== undefined) this.rememberNode(result.chosen)
|
|
550
|
+
return { state: result.chosen === undefined ? 'no-node' : 'selected', chosen: result.chosen, required: plan.required }
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// Cheap check first: is the node already selected still good for every required service?
|
|
554
|
+
const results = await this.core.capabilities(current, plan.probes, {
|
|
555
|
+
timeoutMs: this.config.probeTimeoutMs ?? 8000,
|
|
556
|
+
samples: this.config.probeSamples ?? 2,
|
|
557
|
+
})
|
|
558
|
+
const verdict = judgeNode(results, plan.required)
|
|
559
|
+
this.lastMatrix = [{ name: current, results }]
|
|
560
|
+
this.lastCheckAt = Date.now()
|
|
561
|
+
if (verdict.usable) {
|
|
562
|
+
this.log('node ' + current + ' still reaches ' + plan.required.join('/'))
|
|
563
|
+
return { state: 'kept', node: current, required: plan.required, results }
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
this.log('node ' + current + ' lost ' + (verdict.failed.join(',') || verdict.missing.join(',')) + '; searching again')
|
|
567
|
+
const result = await this.core.autoSelect('', {
|
|
568
|
+
probes: plan.probes,
|
|
569
|
+
required: plan.required,
|
|
570
|
+
budgetMs: this.config.selectBudgetMs,
|
|
571
|
+
samples: this.config.probeSamples ?? 2,
|
|
572
|
+
})
|
|
573
|
+
this.lastMatrix = result.matrix
|
|
574
|
+
if (result.chosen === undefined) {
|
|
575
|
+
return { state: 'no-alternative', lostNode: current, failed: verdict.failed, required: plan.required }
|
|
576
|
+
}
|
|
577
|
+
if (result.chosen === current) {
|
|
578
|
+
// The search re-picked the same node, which contradicts the probe; report rather than loop.
|
|
579
|
+
return { state: 'unchanged', node: current, failed: verdict.failed }
|
|
580
|
+
}
|
|
581
|
+
this.rememberNode(result.chosen)
|
|
582
|
+
this.log('switched ' + current + ' -> ' + result.chosen)
|
|
583
|
+
return { state: 'switched', from: current, to: result.chosen, failed: verdict.failed, required: plan.required }
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Arm the periodic capability re-check.
|
|
588
|
+
*
|
|
589
|
+
* Same rule as the other cycles: the interval must be created in the plugin context, so this
|
|
590
|
+
* is only ever called from a callback the plugin registered itself. A tick that finds the
|
|
591
|
+
* line busy returns immediately, which is why the period can be short without ever
|
|
592
|
+
* interrupting work.
|
|
593
|
+
*
|
|
594
|
+
* @param schedule - timer factory from the plugin context.
|
|
595
|
+
*/
|
|
596
|
+
scheduleReselect(schedule) {
|
|
597
|
+
if (this.reselectTimer !== undefined) this.reselectTimer()
|
|
598
|
+
this.reselectTimer = undefined
|
|
599
|
+
const minutes = this.config.reselectMinutes
|
|
600
|
+
if (this.config.autoReselect === false || minutes <= 0 || typeof schedule !== 'function') return
|
|
601
|
+
this.reselectTimer = schedule(() => {
|
|
602
|
+
void this.autoReselect().catch((error) => {
|
|
603
|
+
this.log('capability re-check failed: ' + String(error?.message ?? error))
|
|
604
|
+
})
|
|
605
|
+
}, minutes * 60_000)
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Stop the re-check. Safe to call when none is running. */
|
|
609
|
+
stopReselect() {
|
|
610
|
+
if (this.reselectTimer === undefined) return
|
|
611
|
+
this.reselectTimer()
|
|
612
|
+
this.reselectTimer = undefined
|
|
613
|
+
}
|
|
614
|
+
|
|
433
615
|
/**
|
|
434
616
|
* One liveness pass: is the core still listening, and does the policy still route?
|
|
435
617
|
*
|
|
@@ -873,9 +1055,30 @@ export class Runtime {
|
|
|
873
1055
|
const preferred = String(options.node ?? this.preferredNode ?? '').trim()
|
|
874
1056
|
// A fresh group starts on DIRECT, which would route foreign traffic straight out.
|
|
875
1057
|
// Selecting a real node is part of bringing routing up, not an optional extra.
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
1058
|
+
// Selection is capability-based: a node must reach every required service, not merely
|
|
1059
|
+
// answer a latency check. The matrix is kept so the panel can show why a node lost.
|
|
1060
|
+
const plan = resolveProbes(this.config.probes, this.config.requiredProbes)
|
|
1061
|
+
const selection = group.all.some((entry) => entry !== 'DIRECT')
|
|
1062
|
+
? await this.core
|
|
1063
|
+
.autoSelect(preferred, {
|
|
1064
|
+
probes: plan.probes,
|
|
1065
|
+
required: plan.required,
|
|
1066
|
+
budgetMs: this.config.selectBudgetMs,
|
|
1067
|
+
})
|
|
1068
|
+
.catch((error) => {
|
|
1069
|
+
this.log('capability selection failed: ' + String(error?.message ?? error))
|
|
1070
|
+
return { chosen: undefined, matrix: [] }
|
|
1071
|
+
})
|
|
1072
|
+
: { chosen: undefined, matrix: [] }
|
|
1073
|
+
const selected = selection.chosen
|
|
1074
|
+
this.lastMatrix = selection.matrix
|
|
1075
|
+
const ranked = rankNodes(selection.matrix, plan.required)
|
|
1076
|
+
if (selected === undefined && selection.matrix.length > 0) {
|
|
1077
|
+
this.log('no node could reach every required probe: ' + plan.required.join(', '))
|
|
1078
|
+
} else if (selected !== undefined) {
|
|
1079
|
+
this.log('selected ' + selected + ' (' + plan.required.join('/') + ' all reachable)')
|
|
1080
|
+
}
|
|
1081
|
+
void ranked
|
|
879
1082
|
this.lastError = undefined
|
|
880
1083
|
this.degraded = undefined
|
|
881
1084
|
// Routing is now up under this activation's ownership, which is what arms the
|
|
@@ -1032,6 +1235,29 @@ export class Runtime {
|
|
|
1032
1235
|
bootstrap: this.bootstrap,
|
|
1033
1236
|
/** Optional GeoIP upgrade state; domestic routing works without it. */
|
|
1034
1237
|
geoUpgrade: this.geo,
|
|
1238
|
+
/** Automatic re-selection: whether it is armed, when it runs, and when it last acted. */
|
|
1239
|
+
reselect: {
|
|
1240
|
+
enabled: this.config.autoReselect !== false && this.config.reselectMinutes > 0,
|
|
1241
|
+
everyMinutes: this.config.reselectMinutes,
|
|
1242
|
+
idleConnections: this.config.reselectIdleConnections,
|
|
1243
|
+
idleGraceMs: this.config.reselectIdleGraceMs,
|
|
1244
|
+
lastCheckAt: this.lastCheckAt === undefined ? null : new Date(this.lastCheckAt).toISOString(),
|
|
1245
|
+
idleSince: this.idleSince === undefined ? null : new Date(this.idleSince).toISOString(),
|
|
1246
|
+
},
|
|
1247
|
+
/** Per-node probe results from the last selection, and which services gate it. */
|
|
1248
|
+
capability: {
|
|
1249
|
+
required: resolveProbes(this.config.probes, this.config.requiredProbes).required,
|
|
1250
|
+
probes: resolveProbes(this.config.probes, this.config.requiredProbes).probes.map((probe) => ({ id: probe.id, label: probe.label })),
|
|
1251
|
+
nodes: this.lastMatrix.map((row) => {
|
|
1252
|
+
const verdict = rankNodes([row], resolveProbes(this.config.probes, this.config.requiredProbes).required).usable[0]
|
|
1253
|
+
return {
|
|
1254
|
+
name: row.name,
|
|
1255
|
+
results: row.results,
|
|
1256
|
+
usable: verdict !== undefined,
|
|
1257
|
+
failed: Object.entries(row.results).filter(([, value]) => value === null).map(([id]) => id),
|
|
1258
|
+
}
|
|
1259
|
+
}),
|
|
1260
|
+
},
|
|
1035
1261
|
/** Whether the core uses an embedded CIDR rule set for the domestic bypass. */
|
|
1036
1262
|
cnRuleSet: this.core?.cnRuleSet === undefined
|
|
1037
1263
|
? undefined
|
|
@@ -1062,6 +1288,7 @@ export async function apply(ctx, rawConfig) {
|
|
|
1062
1288
|
ctx.effect(() => () => {
|
|
1063
1289
|
runtime.stopTimer()
|
|
1064
1290
|
runtime.stopWatchdog()
|
|
1291
|
+
runtime.stopReselect()
|
|
1065
1292
|
void runtime.stop()
|
|
1066
1293
|
})
|
|
1067
1294
|
|
|
@@ -1094,13 +1321,16 @@ export async function apply(ctx, rawConfig) {
|
|
|
1094
1321
|
runtime.rearm = () => {
|
|
1095
1322
|
runtime.scheduleSpeedTest(schedule)
|
|
1096
1323
|
runtime.scheduleWatchdog(schedule)
|
|
1324
|
+
runtime.scheduleReselect(schedule)
|
|
1097
1325
|
}
|
|
1098
1326
|
runtime.scheduleSpeedTest(schedule)
|
|
1099
1327
|
runtime.scheduleWatchdog(schedule)
|
|
1328
|
+
runtime.scheduleReselect(schedule)
|
|
1100
1329
|
return () => {
|
|
1101
1330
|
runtime.rearm = undefined
|
|
1102
1331
|
runtime.stopTimer()
|
|
1103
1332
|
runtime.stopWatchdog()
|
|
1333
|
+
runtime.stopReselect()
|
|
1104
1334
|
}
|
|
1105
1335
|
}, 'clash-proxy: speed test cycle and watchdog')
|
|
1106
1336
|
})
|
|
@@ -1171,7 +1401,7 @@ function subscriptionTool(runtime) {
|
|
|
1171
1401
|
properties: {
|
|
1172
1402
|
action: {
|
|
1173
1403
|
type: 'string',
|
|
1174
|
-
enum: ['status', 'import', 'start', 'stop', 'select', 'test', 'refresh', 'bootstrap'],
|
|
1404
|
+
enum: ['status', 'import', 'start', 'stop', 'select', 'test', 'refresh', 'bootstrap', 'reselect'],
|
|
1175
1405
|
description: 'status reports state; import sets or appends subscriptions; start/stop control routing; select switches the exit node; test measures latency; refresh re-downloads every subscription; bootstrap downloads and installs a private mihomo core when the machine has none.',
|
|
1176
1406
|
},
|
|
1177
1407
|
url: { type: 'string', description: 'One or more subscription URLs for action=import, one per line. A leading "name " is kept as the display name.' },
|
|
@@ -1240,11 +1470,18 @@ function subscriptionTool(runtime) {
|
|
|
1240
1470
|
const report = await runtime.start()
|
|
1241
1471
|
return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
|
|
1242
1472
|
}
|
|
1243
|
-
if (action === '
|
|
1244
|
-
const
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1473
|
+
if (action === 'reselect') {
|
|
1474
|
+
const result = await runtime.autoReselect({ force: true })
|
|
1475
|
+
return {
|
|
1476
|
+
...result,
|
|
1477
|
+
summary: result.state === 'kept'
|
|
1478
|
+
? '当前节点「' + result.node + '」仍能访问全部必需服务(' + (result.required ?? []).join('/') + '),未切换。'
|
|
1479
|
+
: result.state === 'switched'
|
|
1480
|
+
? '已从「' + result.from + '」切到「' + result.to + '」(原节点失去 ' + (result.failed ?? []).join(',') + ')。'
|
|
1481
|
+
: result.state === 'selected'
|
|
1482
|
+
? '已选「' + result.chosen + '」。'
|
|
1483
|
+
: '没有可用节点:' + (result.required ?? []).join(', ') + ' 无法全部访问。',
|
|
1484
|
+
}
|
|
1248
1485
|
}
|
|
1249
1486
|
if (action === 'test') {
|
|
1250
1487
|
const target = String(args?.node ?? '').trim()
|
package/lib/core.js
CHANGED
|
@@ -553,59 +553,192 @@ export class Core {
|
|
|
553
553
|
return null
|
|
554
554
|
}
|
|
555
555
|
|
|
556
|
+
/**
|
|
557
|
+
* Ask one node to reach one URL, using the core's own health-check.
|
|
558
|
+
*
|
|
559
|
+
* The core reports a delay when the target answers at all — measured, a 401 from
|
|
560
|
+
* api.openai.com counts as success while a blocked node returns 503. That is what makes
|
|
561
|
+
* this usable as a capability probe: it answers "can this node carry traffic to this
|
|
562
|
+
* service", which is the question latency alone cannot answer.
|
|
563
|
+
*
|
|
564
|
+
* @param name - node name.
|
|
565
|
+
* @param url - the URL to reach through that node.
|
|
566
|
+
* @param timeoutMs - per-probe budget.
|
|
567
|
+
* @returns the delay in ms, or null when the node could not reach it.
|
|
568
|
+
*/
|
|
569
|
+
async reach(name, url, timeoutMs = 8000) {
|
|
570
|
+
const query = new URLSearchParams({ timeout: String(timeoutMs), url })
|
|
571
|
+
const encoded = encodeURIComponent(name)
|
|
572
|
+
const owner = await this.providerOf(name)
|
|
573
|
+
const paths = [
|
|
574
|
+
...(owner === undefined ? [] : ['/providers/proxies/' + encodeURIComponent(owner) + '/' + encoded + '/healthcheck']),
|
|
575
|
+
...this.providerNames.map((provider) => '/providers/proxies/' + encodeURIComponent(provider) + '/' + encoded + '/healthcheck'),
|
|
576
|
+
'/proxies/' + encoded + '/delay',
|
|
577
|
+
]
|
|
578
|
+
for (const path of paths) {
|
|
579
|
+
try {
|
|
580
|
+
const data = await this.api(path + '?' + query)
|
|
581
|
+
if (typeof data?.delay === 'number' && data.delay >= 0) return data.delay
|
|
582
|
+
} catch {
|
|
583
|
+
// try the next namespace
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return null
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Measure how one node behaves against every probe.
|
|
591
|
+
*
|
|
592
|
+
* @param name - node name.
|
|
593
|
+
* @param probes - probe descriptors with id and url.
|
|
594
|
+
* @param options - timeoutMs per probe, concurrency across probes.
|
|
595
|
+
* @returns probe id to delay, or null where the node could not reach it.
|
|
596
|
+
*/
|
|
597
|
+
async capabilities(name, probes, options = {}) {
|
|
598
|
+
const timeoutMs = options.timeoutMs ?? 8000
|
|
599
|
+
const list = Array.isArray(probes) ? probes : []
|
|
600
|
+
const samples = Math.max(1, Number(options.samples ?? 2))
|
|
601
|
+
const limit = Math.max(1, Math.min(Number(options.concurrency ?? 3), list.length || 1))
|
|
602
|
+
// Repeat every probe: a single answer can come from a connection the previous node
|
|
603
|
+
// established, and measured, that reported a blocked node as working. Averaging only
|
|
604
|
+
// across attempts that all succeeded turns that into a reliable verdict.
|
|
605
|
+
const attempts = Array.from({ length: samples }, () => ({}))
|
|
606
|
+
for (let round = 0; round < samples; round += 1) {
|
|
607
|
+
let next = 0
|
|
608
|
+
const worker = async () => {
|
|
609
|
+
while (next < list.length) {
|
|
610
|
+
const probe = list[next]
|
|
611
|
+
next += 1
|
|
612
|
+
attempts[round][probe.id] = await this.reach(name, probe.url, timeoutMs)
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
await Promise.all(Array.from({ length: limit }, worker))
|
|
616
|
+
if (round + 1 < samples) await new Promise((resolve) => setTimeout(resolve, options.sampleGapMs ?? 400))
|
|
617
|
+
}
|
|
618
|
+
const results = {}
|
|
619
|
+
for (const probe of list) {
|
|
620
|
+
const values = attempts.map((attempt) => attempt[probe.id])
|
|
621
|
+
const allAnswered = values.every((value) => typeof value === 'number')
|
|
622
|
+
results[probe.id] = allAnswered ? Math.round(values.reduce((sum, value) => sum + value, 0) / values.length) : null
|
|
623
|
+
}
|
|
624
|
+
return results
|
|
625
|
+
}
|
|
626
|
+
|
|
556
627
|
/**
|
|
557
|
-
*
|
|
558
|
-
* lowest measured latency across a sample, then a single-node verification of the
|
|
559
|
-
* rest. Nodes whose latency cannot be measured are dead and are never chosen.
|
|
628
|
+
* Build the capability matrix for a set of nodes.
|
|
560
629
|
*
|
|
561
|
-
*
|
|
562
|
-
*
|
|
630
|
+
* Two phases, because a 54-node subscription times a probe set of four would cost
|
|
631
|
+
* minutes: a cheap baseline pass over every node drops the dead ones, then the full set
|
|
632
|
+
* runs over the survivors only, cheapest first, and stops as soon as a node passes
|
|
633
|
+
* everything — the search is for a node that works, not for the very best one.
|
|
563
634
|
*
|
|
564
|
-
* @param
|
|
565
|
-
* @returns the
|
|
635
|
+
* @param options - nodes to test, probes, budgets and a progress callback.
|
|
636
|
+
* @returns the matrix, the chosen node, how many were tested and which were skipped.
|
|
566
637
|
*/
|
|
567
|
-
async
|
|
638
|
+
async capabilityMatrix(options = {}) {
|
|
639
|
+
const probes = Array.isArray(options.probes) ? options.probes : []
|
|
640
|
+
const required = Array.isArray(options.required) ? options.required : probes.map((probe) => probe.id)
|
|
641
|
+
const baseline = options.baseline ?? probes[0]
|
|
642
|
+
const candidates = (Array.isArray(options.nodes) ? options.nodes : []).filter((name) => name !== 'DIRECT')
|
|
643
|
+
const report = options.onProgress ?? (() => {})
|
|
644
|
+
const deadline = Date.now() + (options.budgetMs ?? this.selectBudgetMs ?? 90_000)
|
|
645
|
+
const batchSize = Math.max(1, Math.min(Number(options.batchSize ?? 8), 16))
|
|
646
|
+
|
|
647
|
+
const matrix = []
|
|
648
|
+
let tested = 0
|
|
649
|
+
const skipped = []
|
|
650
|
+
|
|
651
|
+
// Phase 1 — baseline reachability, so dead nodes never reach the per-service probes.
|
|
652
|
+
const alive = []
|
|
653
|
+
for (let at = 0; at < candidates.length && Date.now() < deadline; at += batchSize) {
|
|
654
|
+
const batch = candidates.slice(at, at + batchSize)
|
|
655
|
+
const rows = await Promise.all(
|
|
656
|
+
batch.map(async (name) => ({
|
|
657
|
+
name,
|
|
658
|
+
delay: baseline === undefined ? 0 : await this.reach(name, baseline.url, options.baselineTimeoutMs ?? 5000),
|
|
659
|
+
})),
|
|
660
|
+
)
|
|
661
|
+
for (const row of rows) {
|
|
662
|
+
tested += 1
|
|
663
|
+
if (row.delay === null) {
|
|
664
|
+
matrix.push({ name: row.name, results: baseline === undefined ? {} : { [baseline.id]: null } })
|
|
665
|
+
continue
|
|
666
|
+
}
|
|
667
|
+
alive.push({ name: row.name, baselineDelay: row.delay })
|
|
668
|
+
}
|
|
669
|
+
report({ phase: 'baseline', tested, alive: alive.length, total: candidates.length })
|
|
670
|
+
}
|
|
671
|
+
for (const name of candidates) {
|
|
672
|
+
if (!alive.some((entry) => entry.name === name) && !matrix.some((entry) => entry.name === name)) skipped.push(name)
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// Phase 2 — the full probe set, cheapest baseline first so a good node is found early.
|
|
676
|
+
alive.sort((a, b) => a.baselineDelay - b.baselineDelay)
|
|
677
|
+
let chosen
|
|
678
|
+
for (const entry of alive) {
|
|
679
|
+
if (Date.now() > deadline) {
|
|
680
|
+
skipped.push(entry.name)
|
|
681
|
+
continue
|
|
682
|
+
}
|
|
683
|
+
const results = await this.capabilities(entry.name, probes, {
|
|
684
|
+
timeoutMs: options.timeoutMs ?? 8000,
|
|
685
|
+
concurrency: options.concurrency ?? 3,
|
|
686
|
+
samples: options.samples ?? 2,
|
|
687
|
+
sampleGapMs: options.sampleGapMs ?? 400,
|
|
688
|
+
})
|
|
689
|
+
matrix.push({ name: entry.name, results })
|
|
690
|
+
report({ phase: 'probes', node: entry.name, results })
|
|
691
|
+
const passesAll = required.every((id) => typeof results[id] === 'number')
|
|
692
|
+
if (passesAll) {
|
|
693
|
+
chosen = entry.name
|
|
694
|
+
for (const rest of alive) if (rest.name !== entry.name && !matrix.some((row) => row.name === rest.name)) skipped.push(rest.name)
|
|
695
|
+
break
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
return { matrix, chosen, tested, skipped }
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Choose a working exit node.
|
|
704
|
+
*
|
|
705
|
+
* The caller's explicit preference still wins when it exists and can actually reach every
|
|
706
|
+
* required service — honouring a pin is the point of a pin, but a pinned node that cannot
|
|
707
|
+
* reach OpenAI would otherwise reproduce the exact bug this method exists to prevent, so
|
|
708
|
+
* the preference is verified rather than trusted.
|
|
709
|
+
*
|
|
710
|
+
* @param preferred - a node name to honour when usable.
|
|
711
|
+
* @param options - probes, required ids, budgets.
|
|
712
|
+
* @returns the chosen node and the matrix it was chosen from.
|
|
713
|
+
*/
|
|
714
|
+
async autoSelect(preferred, options = {}) {
|
|
568
715
|
const group = await this.group()
|
|
569
716
|
const candidates = group.all.filter((entry) => entry !== 'DIRECT')
|
|
570
|
-
if (candidates.length === 0) return undefined
|
|
717
|
+
if (candidates.length === 0) return { chosen: undefined, matrix: [] }
|
|
571
718
|
|
|
572
719
|
const wanted = String(preferred ?? '').trim()
|
|
720
|
+
const probes = Array.isArray(options.probes) ? options.probes : []
|
|
721
|
+
const required = Array.isArray(options.required) ? options.required : probes.map((probe) => probe.id)
|
|
722
|
+
|
|
723
|
+
// A pinned node is checked first and, when it passes, ends the search immediately.
|
|
573
724
|
if (wanted !== '' && candidates.includes(wanted)) {
|
|
574
|
-
const
|
|
575
|
-
|
|
725
|
+
const results = await this.capabilities(wanted, probes, { timeoutMs: options.timeoutMs ?? 8000, samples: options.samples ?? 2 })
|
|
726
|
+
const passesAll = required.every((id) => typeof results[id] === 'number')
|
|
727
|
+
if (passesAll) {
|
|
576
728
|
await this.select(wanted)
|
|
577
|
-
return wanted
|
|
729
|
+
return { chosen: wanted, matrix: [{ name: wanted, results }] }
|
|
578
730
|
}
|
|
579
|
-
|
|
731
|
+
const unmet = required.filter((id) => typeof results[id] !== 'number')
|
|
732
|
+
this.log('preferred node "' + wanted + '" cannot reach ' + unmet.join(', ') + '; choosing another')
|
|
580
733
|
}
|
|
581
734
|
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
// the choice.
|
|
587
|
-
const deadline = Date.now() + (this.selectBudgetMs ?? 45_000)
|
|
588
|
-
const batchSize = 10
|
|
589
|
-
let best
|
|
590
|
-
for (let at = 0; at < candidates.length && Date.now() < deadline; at += batchSize) {
|
|
591
|
-
const batch = candidates.slice(at, at + batchSize)
|
|
592
|
-
const results = await Promise.all(
|
|
593
|
-
batch.map(async (name) => ({ name, delay: await this.delay(name, 4000) })),
|
|
594
|
-
)
|
|
595
|
-
for (const result of results) {
|
|
596
|
-
if (result.delay === null) continue
|
|
597
|
-
if (best === undefined || result.delay < best.delay) best = result
|
|
598
|
-
}
|
|
599
|
-
// A clearly good node ends the search early: the first working exit is enough to
|
|
600
|
-
// bring routing up, and the panel can re-test later.
|
|
601
|
-
if (best !== undefined && best.delay <= 1200) break
|
|
602
|
-
}
|
|
603
|
-
if (best === undefined) {
|
|
604
|
-
this.log('no node answered a latency test; leaving the group on its current selection')
|
|
605
|
-
return undefined
|
|
735
|
+
const result = await this.capabilityMatrix({ nodes: candidates, probes, required, ...options })
|
|
736
|
+
if (result.chosen === undefined) {
|
|
737
|
+
this.log('no node passed every required probe; leaving the group on its current selection')
|
|
738
|
+
return { chosen: undefined, matrix: result.matrix }
|
|
606
739
|
}
|
|
607
|
-
await this.select(
|
|
608
|
-
return
|
|
740
|
+
await this.select(result.chosen)
|
|
741
|
+
return { chosen: result.chosen, matrix: result.matrix }
|
|
609
742
|
}
|
|
610
743
|
|
|
611
744
|
/**
|
package/lib/routes.js
CHANGED
package/lib/select.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Capability-aware node selection.
|
|
3
|
+
*
|
|
4
|
+
* Latency answers "is this node alive", not "does this node work for me". Measured on a live
|
|
5
|
+
* subscription, `🇺🇸 美国01` answered the gstatic check in 472 ms and google in 278 ms — a
|
|
6
|
+
* plausible "fastest node" — while OpenAI was unreachable through it. Choosing on latency
|
|
7
|
+
* therefore produced a node that silently broke one service, and the symptom looked like the
|
|
8
|
+
* plugin being down rather than a wrong node.
|
|
9
|
+
*
|
|
10
|
+
* The fix is to ask the node the same question the workload will ask it. mihomo's
|
|
11
|
+
* `healthcheck` endpoint accepts a URL and reports a delay when the target answers at all,
|
|
12
|
+
* which is exactly the signal needed: measured, a 401 from `api.openai.com` counts as success
|
|
13
|
+
* (`delay: 269`) while a blocked node returns 503. So each required service becomes a probe,
|
|
14
|
+
* and a node is usable only when it passes every probe that matters.
|
|
15
|
+
*
|
|
16
|
+
* Two phases keep this affordable on a 54-node subscription: a cheap gstatic pass over every
|
|
17
|
+
* node, then the full probe set over only the survivors, cheapest first.
|
|
18
|
+
*
|
|
19
|
+
* @module dsh-clash-proxy/select
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Services a node may be asked to carry.
|
|
24
|
+
*
|
|
25
|
+
* These are the ones that actually fail differently per node in practice: a generic 204
|
|
26
|
+
* endpoint says the tunnel works, while the AI APIs reject datacenter ranges and Google is
|
|
27
|
+
* the usual reachability baseline. `custom` extends the list per configuration.
|
|
28
|
+
*
|
|
29
|
+
* `delay` is a display hint only — it orders the probe run, never decides usability.
|
|
30
|
+
*
|
|
31
|
+
* @type {ReadonlyArray<{id: string, label: string, url: string, delay: boolean}>}
|
|
32
|
+
*/
|
|
33
|
+
export const DEFAULT_PROBES = [
|
|
34
|
+
{ id: 'gstatic', label: '基础连通', url: 'http://www.gstatic.com/generate_204', delay: false },
|
|
35
|
+
{ id: 'google', label: 'Google', url: 'http://www.google.com/generate_204', delay: true },
|
|
36
|
+
{ id: 'openai', label: 'OpenAI', url: 'https://api.openai.com/v1/models', delay: true },
|
|
37
|
+
{ id: 'anthropic', label: 'Anthropic', url: 'https://api.anthropic.com/v1/messages', delay: true },
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Parse the user's probe configuration.
|
|
42
|
+
*
|
|
43
|
+
* Accepts `id=url` per line or per comma, so the panel can expose one box instead of a
|
|
44
|
+
* structured editor. An entry without `=` is treated as a bare URL and named after its host.
|
|
45
|
+
*
|
|
46
|
+
* @param text - the configured probe list.
|
|
47
|
+
* @returns probe descriptors, or an empty array when nothing was configured.
|
|
48
|
+
*/
|
|
49
|
+
export function parseProbes(text) {
|
|
50
|
+
const probes = []
|
|
51
|
+
for (const chunk of String(text ?? '').split(/[\n,]+/)) {
|
|
52
|
+
const entry = chunk.trim()
|
|
53
|
+
if (entry === '') continue
|
|
54
|
+
const at = entry.indexOf('=')
|
|
55
|
+
if (at > 0) {
|
|
56
|
+
const id = entry.slice(0, at).trim()
|
|
57
|
+
const url = entry.slice(at + 1).trim()
|
|
58
|
+
if (id === '' || !/^https?:\/\//i.test(url)) continue
|
|
59
|
+
try {
|
|
60
|
+
if (new URL(url).hostname === '') continue
|
|
61
|
+
} catch {
|
|
62
|
+
continue
|
|
63
|
+
}
|
|
64
|
+
probes.push({ id, label: id, url, delay: true })
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
if (!/^https?:\/\//i.test(entry)) continue
|
|
68
|
+
let host
|
|
69
|
+
try {
|
|
70
|
+
host = new URL(entry).hostname
|
|
71
|
+
} catch {
|
|
72
|
+
// 'http://' has a scheme and nothing else; it parses as neither a host nor a target.
|
|
73
|
+
continue
|
|
74
|
+
}
|
|
75
|
+
if (host === '') continue
|
|
76
|
+
probes.push({ id: host, label: host, url: entry, delay: true })
|
|
77
|
+
}
|
|
78
|
+
return probes
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The probe set to run: the built-in services plus any configured extras.
|
|
83
|
+
*
|
|
84
|
+
* @param configured - the `probes` configuration field.
|
|
85
|
+
* @param required - ids that must pass; empty means "every probe in the set".
|
|
86
|
+
* @returns the probes to run and the ids that gate usability.
|
|
87
|
+
*/
|
|
88
|
+
export function resolveProbes(configured, required) {
|
|
89
|
+
const extra = parseProbes(configured)
|
|
90
|
+
const byId = new Map(DEFAULT_PROBES.map((probe) => [probe.id, probe]))
|
|
91
|
+
for (const probe of extra) byId.set(probe.id, probe)
|
|
92
|
+
const wanted = String(required ?? '')
|
|
93
|
+
.split(/[\s,]+/)
|
|
94
|
+
.map((entry) => entry.trim())
|
|
95
|
+
.filter((entry) => entry !== '')
|
|
96
|
+
const all = [...byId.values()]
|
|
97
|
+
if (wanted.length === 0) return { probes: all, required: all.map((probe) => probe.id), all: all.map((probe) => probe.id) }
|
|
98
|
+
// Keep EVERY required id, including ones no probe defines. Filtering them out would make
|
|
99
|
+
// a typo silently weaken the gate — the selector would then choose a node that never had
|
|
100
|
+
// to pass the service the user actually cares about. An undefined id simply can never be
|
|
101
|
+
// satisfied, so the caller reports it instead of choosing a bad node.
|
|
102
|
+
return { probes: all, required: wanted, all: all.map((probe) => probe.id) }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Summarise one node's probe results into a usability verdict.
|
|
107
|
+
*
|
|
108
|
+
* @param results - probe id to delay (number) or null.
|
|
109
|
+
* @param required - ids that must be present in `results`.
|
|
110
|
+
* @returns `{ usable, failed, missing, total }`.
|
|
111
|
+
*/
|
|
112
|
+
/**
|
|
113
|
+
* Decide whether repeated probe results show a stable capability.
|
|
114
|
+
*
|
|
115
|
+
* One measurement is not evidence. Measured on a live subscription: the same node returned
|
|
116
|
+
* `401` for `api.openai.com` immediately after switching to it and `000` for six attempts
|
|
117
|
+
* in a row a minute later — the first answer came from a connection the previous node had
|
|
118
|
+
* established, so a single probe reported a blocked node as working. Choosing on one sample
|
|
119
|
+
* therefore selects nodes that fail the moment real traffic arrives.
|
|
120
|
+
*
|
|
121
|
+
* A service counts as reachable only when every attempt in the sample succeeded.
|
|
122
|
+
*
|
|
123
|
+
* @param attempts - one array of delays (number) or failures (null) per probe.
|
|
124
|
+
* @param required - ids that must pass.
|
|
125
|
+
* @returns the same shape as {@link judgeNode}, plus the attempt count.
|
|
126
|
+
*/
|
|
127
|
+
export function judgeNodeStable(attempts, required) {
|
|
128
|
+
const results = {}
|
|
129
|
+
let samples = 0
|
|
130
|
+
for (const id of required) {
|
|
131
|
+
const values = attempts.map((attempt) => attempt?.[id])
|
|
132
|
+
const present = values.filter((value) => value !== undefined)
|
|
133
|
+
samples = Math.max(samples, present.length)
|
|
134
|
+
if (present.length === 0) {
|
|
135
|
+
results[id] = undefined
|
|
136
|
+
continue
|
|
137
|
+
}
|
|
138
|
+
// Every sample must have answered; a single timeout makes the capability unreliable.
|
|
139
|
+
const allAnswered = present.length === values.length && present.every((value) => typeof value === 'number')
|
|
140
|
+
results[id] = allAnswered ? Math.round(present.reduce((sum, value) => sum + value, 0) / present.length) : null
|
|
141
|
+
}
|
|
142
|
+
return { ...judgeNode(results, required), results, samples }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function judgeNode(results, required) {
|
|
146
|
+
const failed = []
|
|
147
|
+
const missing = []
|
|
148
|
+
let total = 0
|
|
149
|
+
for (const id of required) {
|
|
150
|
+
const value = results?.[id]
|
|
151
|
+
if (value === undefined) {
|
|
152
|
+
missing.push(id)
|
|
153
|
+
continue
|
|
154
|
+
}
|
|
155
|
+
total += value
|
|
156
|
+
if (value === null) failed.push(id)
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
usable: failed.length === 0 && missing.length === 0,
|
|
160
|
+
failed,
|
|
161
|
+
missing,
|
|
162
|
+
total: total === 0 ? undefined : total,
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Rank candidates: every probe must pass, then lowest total delay wins.
|
|
168
|
+
*
|
|
169
|
+
* @param matrix - one entry per node: `{ name, results }`.
|
|
170
|
+
* @param required - ids that must pass.
|
|
171
|
+
* @returns usable nodes, best first, each carrying its failed/missing detail.
|
|
172
|
+
*/
|
|
173
|
+
export function rankNodes(matrix, required) {
|
|
174
|
+
const judged = matrix.map((entry) => ({ name: entry.name, results: entry.results, ...judgeNode(entry.results, required) }))
|
|
175
|
+
const usable = judged.filter((entry) => entry.usable).sort((a, b) => (a.total ?? Infinity) - (b.total ?? Infinity))
|
|
176
|
+
const unusable = judged.filter((entry) => !entry.usable).sort((a, b) => a.failed.length - b.failed.length)
|
|
177
|
+
return { usable, unusable }
|
|
178
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-clash-subscription",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Import one or more Clash/mihomo subscriptions and route the Harness outbound traffic through the private core bundled with this plugin, so blocked sites work while domestic traffic stays direct — no other software involved.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|