dsh-clash-subscription 0.6.4 → 0.8.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/CHANGELOG-0.8.0.md +120 -0
- package/client.js +120 -3
- package/index.js +585 -112
- package/lib/core.js +218 -1
- package/lib/health.js +7 -58
- package/lib/realprobe.js +629 -0
- package/lib/routes.js +36 -0
- package/lib/skill.js +153 -0
- package/lib/watch.js +148 -0
- package/package.json +6 -5
- package/CHANGELOG-0.6.4.md +0 -47
package/lib/realprobe.js
ADDED
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real request probes, because the core's own health check cannot answer this question.
|
|
3
|
+
*
|
|
4
|
+
* `GET /proxies/<name>/delay?url=…` (and the provider `healthcheck` form) reports a delay
|
|
5
|
+
* whenever the target sends *any* response — measured on this machine, `api.github.com`
|
|
6
|
+
* answering `403 API rate limit exceeded` came back as `{"delay":179}`, and a path that
|
|
7
|
+
* returns `404` came back as `{"delay":301}`. The `expected` query parameter that would
|
|
8
|
+
* turn a status code into a verdict is ignored by the bundled core: asked for `expected=418`
|
|
9
|
+
* on a URL that returns `200`, it still answered `{"delay":187}`.
|
|
10
|
+
*
|
|
11
|
+
* So a node that is rate limited for GitHub, or that cannot finish a git fetch at all, is
|
|
12
|
+
* reported as healthy. That is the exact symptom this module exists to remove: the question
|
|
13
|
+
* is not "did something answer" but "did the thing I need actually work".
|
|
14
|
+
*
|
|
15
|
+
* The only honest way to ask that is to send the request the workload will send. This module
|
|
16
|
+
* does it through a dedicated listener bound to a dedicated selector group, so measuring a
|
|
17
|
+
* node never disturbs the node live traffic is using.
|
|
18
|
+
*
|
|
19
|
+
* @module dsh-clash-proxy/realprobe
|
|
20
|
+
*/
|
|
21
|
+
import { connect as netConnect } from 'node:net'
|
|
22
|
+
import { connect as tlsConnect } from 'node:tls'
|
|
23
|
+
|
|
24
|
+
/** Response bodies are only inspected, never stored; a few KB settles every verdict. */
|
|
25
|
+
const MAX_BODY_BYTES = 8 * 1024
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Send one GET through a local proxy port and read the real answer.
|
|
29
|
+
*
|
|
30
|
+
* Both schemes are driven over a raw socket rather than through `http.request`, and that is a
|
|
31
|
+
* measured decision, not a style one: the first implementation used `http.request({method:
|
|
32
|
+
* 'CONNECT'})` and handed `response.socket` to `tls.connect`, and against a live node every
|
|
33
|
+
* HTTPS probe came back `Client network socket disconnected before secure TLS connection was
|
|
34
|
+
* established` while `curl` and a raw-socket prototype both answered `200` through the same
|
|
35
|
+
* port. The HTTP client's tunnel path neither exposes the bytes already buffered after the
|
|
36
|
+
* `200 Connection established` line nor guarantees the socket is still unclaimed, so the TLS
|
|
37
|
+
* handshake started on a socket the client had already begun managing.
|
|
38
|
+
*
|
|
39
|
+
* HTTPS therefore: `CONNECT host:port`, read the status line itself, then hand the socket to
|
|
40
|
+
* `tls.connect` and write the request in plain text. HTTP sends an absolute-form request URI,
|
|
41
|
+
* which is what a proxy expects. No `accept-encoding` is sent, so the body arrives readable and
|
|
42
|
+
* a protocol banner can be matched without a decompressor.
|
|
43
|
+
*
|
|
44
|
+
* Killed connections (`socket hang up`, `ECONNRESET`) are reported as failures rather than
|
|
45
|
+
* retried, because a node that drops the first request does not carry work either.
|
|
46
|
+
*
|
|
47
|
+
* @param port - loopback proxy port to send through.
|
|
48
|
+
* @param url - the URL to fetch.
|
|
49
|
+
* @param options - `timeoutMs`, `maxBodyBytes`.
|
|
50
|
+
* @returns `{ ok: true, status, headers, body, ms }` or `{ ok: false, reason, ms }`.
|
|
51
|
+
*/
|
|
52
|
+
export function fetchViaProxy(port, url, options = {}) {
|
|
53
|
+
const timeoutMs = Number(options.timeoutMs ?? 10_000)
|
|
54
|
+
const maxBody = Number(options.maxBodyBytes ?? MAX_BODY_BYTES)
|
|
55
|
+
const startedAt = Date.now()
|
|
56
|
+
let target
|
|
57
|
+
try {
|
|
58
|
+
target = new URL(url)
|
|
59
|
+
} catch {
|
|
60
|
+
return Promise.resolve({ ok: false, reason: 'invalid-url', ms: 0 })
|
|
61
|
+
}
|
|
62
|
+
const secure = target.protocol === 'https:'
|
|
63
|
+
const host = target.hostname
|
|
64
|
+
const hostPort = target.port === '' ? (secure ? 443 : 80) : Number(target.port)
|
|
65
|
+
const path = `${target.pathname === '' ? '/' : target.pathname}${target.search}`
|
|
66
|
+
|
|
67
|
+
return new Promise((resolve) => {
|
|
68
|
+
let settled = false
|
|
69
|
+
const finish = (value) => {
|
|
70
|
+
if (settled) return
|
|
71
|
+
settled = true
|
|
72
|
+
clearTimeout(timer)
|
|
73
|
+
try {
|
|
74
|
+
socket.destroy()
|
|
75
|
+
} catch {
|
|
76
|
+
// already closed
|
|
77
|
+
}
|
|
78
|
+
resolve({ ...value, ms: Date.now() - startedAt })
|
|
79
|
+
}
|
|
80
|
+
const timer = setTimeout(() => finish({ ok: false, reason: 'timeout' }), timeoutMs)
|
|
81
|
+
const socket = netConnect(port, '127.0.0.1')
|
|
82
|
+
socket.on('error', (error) => finish({ ok: false, reason: `connect:${describeError(error)}` }))
|
|
83
|
+
|
|
84
|
+
if (!secure) {
|
|
85
|
+
socket.on('connect', () => {
|
|
86
|
+
socket.write(
|
|
87
|
+
`GET ${url} HTTP/1.1\r\nHost: ${host}\r\nUser-Agent: dsh-clash-subscription-probe\r\nAccept: */*\r\nConnection: close\r\n\r\n`,
|
|
88
|
+
)
|
|
89
|
+
})
|
|
90
|
+
readPlainResponse(socket, maxBody, finish)
|
|
91
|
+
return
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Phase 1 — the tunnel. Only the status line of the proxy's answer matters.
|
|
95
|
+
let preamble = ''
|
|
96
|
+
const onPreamble = (chunk) => {
|
|
97
|
+
preamble += chunk.toString('latin1')
|
|
98
|
+
const end = preamble.indexOf('\r\n\r\n')
|
|
99
|
+
if (end < 0) return
|
|
100
|
+
socket.off('data', onPreamble)
|
|
101
|
+
const statusLine = preamble.slice(0, preamble.indexOf('\r\n'))
|
|
102
|
+
const status = Number((statusLine.match(/ (\d{3}) /) ?? [])[1])
|
|
103
|
+
if (status !== 200) {
|
|
104
|
+
finish({ ok: false, reason: `connect-${Number.isFinite(status) ? status : 'fail'}` })
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
// Phase 2 — TLS over the same socket, then the request in plain text.
|
|
108
|
+
const secured = tlsConnect({ socket, servername: host, rejectUnauthorized: false })
|
|
109
|
+
secured.on('error', (error) => finish({ ok: false, reason: `tls:${describeError(error)}` }))
|
|
110
|
+
secured.on('secureConnect', () => {
|
|
111
|
+
secured.write(
|
|
112
|
+
`GET ${path} HTTP/1.1\r\nHost: ${host}\r\nUser-Agent: dsh-clash-subscription-probe\r\nAccept: */*\r\nConnection: close\r\n\r\n`,
|
|
113
|
+
)
|
|
114
|
+
})
|
|
115
|
+
readPlainResponse(secured, maxBody, finish)
|
|
116
|
+
}
|
|
117
|
+
socket.on('connect', () => {
|
|
118
|
+
socket.write(`CONNECT ${host}:${hostPort} HTTP/1.1\r\nHost: ${host}:${hostPort}\r\n\r\n`)
|
|
119
|
+
})
|
|
120
|
+
socket.on('data', onPreamble)
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Parse headers as soon as they arrive, then resolve on a short body prefix.
|
|
126
|
+
*
|
|
127
|
+
* The body is not read to the end, and that is a measured correction: `info/refs?service=
|
|
128
|
+
* git-upload-pack` on `github.com` answers with the repository's whole ref advertisement —
|
|
129
|
+
* measured here at 266 KB for `octocat/Hello-World` and 357 KB for `git/git`, taking 6–18 s to
|
|
130
|
+
* transfer. Waiting for `end` therefore reported a working node as `timeout` purely because the
|
|
131
|
+
* probe was polite. Every judgement this module makes reads the status line, the headers, or the
|
|
132
|
+
* first few hundred bytes of the body (a protocol banner, a rate-limit notice), so the answer is
|
|
133
|
+
* complete as soon as that much has arrived.
|
|
134
|
+
*
|
|
135
|
+
* @param socket - the connected socket (plain or TLS).
|
|
136
|
+
* @param maxBody - body bytes to keep.
|
|
137
|
+
* @param finish - completion callback.
|
|
138
|
+
*/
|
|
139
|
+
function readPlainResponse(socket, maxBody, finish) {
|
|
140
|
+
/** Enough body to match any banner or notice this module looks for. */
|
|
141
|
+
const ENOUGH = 1024
|
|
142
|
+
let raw = ''
|
|
143
|
+
let settled = false
|
|
144
|
+
const settle = (value) => {
|
|
145
|
+
if (settled) return
|
|
146
|
+
settled = true
|
|
147
|
+
socket.destroy()
|
|
148
|
+
finish(value)
|
|
149
|
+
}
|
|
150
|
+
socket.setEncoding('utf8')
|
|
151
|
+
socket.on('data', (chunk) => {
|
|
152
|
+
raw += chunk
|
|
153
|
+
const split = raw.indexOf('\r\n\r\n')
|
|
154
|
+
if (split >= 0 && (raw.length - split - 4 >= ENOUGH || /content-length:\s*0\b/i.test(raw.slice(0, split)))) {
|
|
155
|
+
settle(parseResponse(raw, maxBody))
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
if (raw.length > maxBody * 8 + 16_384) settle(parseResponse(raw, maxBody))
|
|
159
|
+
})
|
|
160
|
+
socket.on('error', (error) => settle({ ok: false, reason: describeError(error) }))
|
|
161
|
+
// `end` is a clean EOF and is preferred over `close`, which can fire on a socket that was
|
|
162
|
+
// destroyed from under us (a TLS teardown, a proxy resetting the tunnel) with nothing read yet.
|
|
163
|
+
socket.on('end', () => settle(parseResponse(raw, maxBody)))
|
|
164
|
+
socket.on('close', () => {
|
|
165
|
+
// A hash collision with an in-flight `end` is impossible here: `settle` is idempotent, and
|
|
166
|
+
// an empty buffer is reported as `empty` only when nothing at all arrived.
|
|
167
|
+
if (!settled && raw !== '') settle(parseResponse(raw, maxBody))
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Turn a raw response into `{ ok, status, headers, body }`.
|
|
173
|
+
*
|
|
174
|
+
* @param raw - everything read off the socket.
|
|
175
|
+
* @param maxBody - body bytes to keep.
|
|
176
|
+
* @returns the parsed answer, or a failure when no status line arrived.
|
|
177
|
+
*/
|
|
178
|
+
function parseResponse(raw, maxBody) {
|
|
179
|
+
const split = raw.indexOf('\r\n\r\n')
|
|
180
|
+
if (split < 0) return { ok: false, reason: raw === '' ? 'empty' : 'no-headers' }
|
|
181
|
+
const lines = raw.slice(0, split).split('\r\n')
|
|
182
|
+
const status = Number((lines[0].match(/ (\d{3}) /) ?? [])[1])
|
|
183
|
+
if (!Number.isFinite(status)) return { ok: false, reason: 'bad-status-line' }
|
|
184
|
+
const headers = {}
|
|
185
|
+
for (const line of lines.slice(1)) {
|
|
186
|
+
const at = line.indexOf(':')
|
|
187
|
+
if (at <= 0) continue
|
|
188
|
+
headers[line.slice(0, at).trim().toLowerCase()] = line.slice(at + 1).trim()
|
|
189
|
+
}
|
|
190
|
+
return { ok: true, status, headers, body: raw.slice(split + 4, split + 4 + maxBody) }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* What counts as a working answer, per built-in service.
|
|
195
|
+
*
|
|
196
|
+
* `expect` is the status set that means "the service is reachable through this node".
|
|
197
|
+
* An entry missing from `expect` is a failure even though bytes arrived — that is the whole
|
|
198
|
+
* point. `quotaHeader` + `quotaHeaderMin` catch the case a status code cannot express: a
|
|
199
|
+
* `200` whose body is a rate-limit notice carrying `x-ratelimit-remaining: 0`. `bodyMustNot`
|
|
200
|
+
* catches the same condition when the service only says it in prose, and `bodyMust` proves
|
|
201
|
+
* the response came from the service that was asked for rather than an intercepting portal.
|
|
202
|
+
*
|
|
203
|
+
* `gating` decides whether the probe participates in the usable/not-usable verdict. A probe
|
|
204
|
+
* that is merely informative (an AI API that some node ranges cannot reach) stays out of the
|
|
205
|
+
* gate so one unreachable extra never empties the candidate list.
|
|
206
|
+
*
|
|
207
|
+
* @type {ReadonlyArray<object>}
|
|
208
|
+
*/
|
|
209
|
+
export const REAL_PROBES = [
|
|
210
|
+
{
|
|
211
|
+
id: 'gstatic',
|
|
212
|
+
label: '基础连通',
|
|
213
|
+
url: 'http://www.gstatic.com/generate_204',
|
|
214
|
+
expect: [204],
|
|
215
|
+
gating: true,
|
|
216
|
+
delay: true,
|
|
217
|
+
},
|
|
218
|
+
{
|
|
219
|
+
id: 'google',
|
|
220
|
+
label: 'Google',
|
|
221
|
+
url: 'http://www.google.com/generate_204',
|
|
222
|
+
expect: [200, 204],
|
|
223
|
+
gating: false,
|
|
224
|
+
delay: true,
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
id: 'github',
|
|
228
|
+
label: 'GitHub API',
|
|
229
|
+
/**
|
|
230
|
+
* The one probe that would have caught the reported bug. `x-ratelimit-remaining` is the
|
|
231
|
+
* per-address hourly budget, so a node whose exit address is exhausted answers `200` with
|
|
232
|
+
* zero left and is useless for any API call until the reset — which the panel now shows.
|
|
233
|
+
*/
|
|
234
|
+
url: 'https://api.github.com/rate_limit',
|
|
235
|
+
expect: [200],
|
|
236
|
+
quotaHeader: 'x-ratelimit-remaining',
|
|
237
|
+
quotaHeaderMin: 1,
|
|
238
|
+
resetHeader: 'x-ratelimit-reset',
|
|
239
|
+
bodyMustNot: [/rate limit exceeded/i, /secondary rate limit/i],
|
|
240
|
+
gating: true,
|
|
241
|
+
delay: true,
|
|
242
|
+
timeoutMs: 12_000,
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
id: 'git',
|
|
246
|
+
label: 'Git 拉取',
|
|
247
|
+
/**
|
|
248
|
+
* Smart-HTTP discovery is the request `git clone`/`git fetch` opens with, and the body
|
|
249
|
+
* must carry the protocol banner: a captive portal or an HTML error page answers `200`
|
|
250
|
+
* and would otherwise pass. Measured, several nodes time out here while their latency
|
|
251
|
+
* health check is under 500 ms.
|
|
252
|
+
*/
|
|
253
|
+
url: 'https://github.com/git/git/info/refs?service=git-upload-pack',
|
|
254
|
+
expect: [200],
|
|
255
|
+
bodyMust: [/service=git-upload-pack/],
|
|
256
|
+
bodyMustNot: [/rate limit exceeded/i],
|
|
257
|
+
gating: true,
|
|
258
|
+
delay: true,
|
|
259
|
+
timeoutMs: 15_000,
|
|
260
|
+
},
|
|
261
|
+
{
|
|
262
|
+
id: 'openai',
|
|
263
|
+
label: 'OpenAI',
|
|
264
|
+
/** `401` proves reachability: the API answered and refused the key, not the network. */
|
|
265
|
+
url: 'https://api.openai.com/v1/models',
|
|
266
|
+
expect: [200, 401],
|
|
267
|
+
gating: false,
|
|
268
|
+
delay: true,
|
|
269
|
+
timeoutMs: 10_000,
|
|
270
|
+
},
|
|
271
|
+
{
|
|
272
|
+
id: 'anthropic',
|
|
273
|
+
label: 'Anthropic',
|
|
274
|
+
/** A `400`/`405` is the API rejecting the shape of the probe, which still means it answered. */
|
|
275
|
+
url: 'https://api.anthropic.com/v1/messages',
|
|
276
|
+
expect: [200, 400, 401, 404, 405],
|
|
277
|
+
gating: false,
|
|
278
|
+
delay: true,
|
|
279
|
+
timeoutMs: 10_000,
|
|
280
|
+
},
|
|
281
|
+
]
|
|
282
|
+
|
|
283
|
+
/** Probes a caller may add by URL alone: reachability only, no service semantics. */
|
|
284
|
+
const GENERIC_EXPECT = [200, 204, 301, 302]
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Make one failure readable without pretending it was a network status.
|
|
289
|
+
*
|
|
290
|
+
* @param error - the error Node raised.
|
|
291
|
+
* @returns a short stable token the panel can translate.
|
|
292
|
+
*/
|
|
293
|
+
function describeError(error) {
|
|
294
|
+
const message = String(error?.message ?? error)
|
|
295
|
+
if (/hang up|ECONNRESET|socket hang/i.test(message)) return 'reset'
|
|
296
|
+
if (/ETIMEDOUT|timeout/i.test(message)) return 'timeout'
|
|
297
|
+
if (/ENOTFOUND|EAI_AGAIN|dns/i.test(message)) return 'dns'
|
|
298
|
+
if (/ECONNREFUSED/i.test(message)) return 'refused'
|
|
299
|
+
if (/certificate|self signed/i.test(message)) return 'tls'
|
|
300
|
+
return message.slice(0, 80)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Every state a single probe can end in. `limited` is a working tunnel with no usable quota. */
|
|
304
|
+
export const PROBE_STATES = ['ok', 'limited', 'blocked']
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Turn one response into a verdict.
|
|
308
|
+
*
|
|
309
|
+
* @param spec - the probe definition.
|
|
310
|
+
* @param answer - output of {@link fetchViaProxy}.
|
|
311
|
+
* @returns `{ ok, state, reason, detail }`, where `ok` means the probe passed the gate.
|
|
312
|
+
*/
|
|
313
|
+
export function judgeProbe(spec, answer) {
|
|
314
|
+
if (answer === undefined || answer.ok !== true) {
|
|
315
|
+
return { ok: false, state: 'blocked', reason: answer?.reason ?? 'no-answer', detail: undefined }
|
|
316
|
+
}
|
|
317
|
+
const expect = Array.isArray(spec?.expect) && spec.expect.length > 0 ? spec.expect : GENERIC_EXPECT
|
|
318
|
+
if (!expect.includes(answer.status)) {
|
|
319
|
+
// A 407/407-style proxy refusal and a 403 from the service are different failures: only
|
|
320
|
+
// the latter can still be "the tunnel works, this service refuses the address".
|
|
321
|
+
const state = answer.status === 403 || answer.status === 429 ? 'limited' : 'blocked'
|
|
322
|
+
return { ok: false, state, reason: `status-${answer.status}`, detail: { status: answer.status } }
|
|
323
|
+
}
|
|
324
|
+
for (const pattern of Array.isArray(spec?.bodyMustNot) ? spec.bodyMustNot : []) {
|
|
325
|
+
if (pattern.test(answer.body ?? '')) {
|
|
326
|
+
return { ok: false, state: 'limited', reason: 'rate-limited-in-body', detail: { status: answer.status } }
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
for (const pattern of Array.isArray(spec?.bodyMust) ? spec.bodyMust : []) {
|
|
330
|
+
if (!pattern.test(answer.body ?? '')) {
|
|
331
|
+
return { ok: false, state: 'blocked', reason: 'unexpected-body', detail: { status: answer.status } }
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if (typeof spec?.quotaHeader === 'string' && spec.quotaHeader !== '') {
|
|
335
|
+
const raw = headerOf(answer.headers, spec.quotaHeader)
|
|
336
|
+
if (raw !== undefined) {
|
|
337
|
+
const remaining = Number(raw)
|
|
338
|
+
const minimum = Number(spec.quotaHeaderMin ?? 1)
|
|
339
|
+
if (Number.isFinite(remaining) && remaining < minimum) {
|
|
340
|
+
const reset = headerOf(answer.headers, spec.resetHeader)
|
|
341
|
+
return {
|
|
342
|
+
ok: false,
|
|
343
|
+
state: 'limited',
|
|
344
|
+
reason: `quota-${remaining}`,
|
|
345
|
+
detail: {
|
|
346
|
+
status: answer.status,
|
|
347
|
+
header: spec.quotaHeader,
|
|
348
|
+
remaining: Number.isFinite(remaining) ? remaining : undefined,
|
|
349
|
+
resetAt: Number.isFinite(Number(reset)) ? new Date(Number(reset) * 1000).toISOString() : undefined,
|
|
350
|
+
},
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
return { ok: true, state: 'ok', reason: 'ok', detail: { status: answer.status } }
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Read one response header case-insensitively.
|
|
360
|
+
*
|
|
361
|
+
* @param headers - the response headers object.
|
|
362
|
+
* @param name - lower-case header name.
|
|
363
|
+
* @returns the value, or undefined.
|
|
364
|
+
*/
|
|
365
|
+
function headerOf(headers, name) {
|
|
366
|
+
const wanted = String(name ?? '').toLowerCase()
|
|
367
|
+
for (const [key, value] of Object.entries(headers ?? {})) {
|
|
368
|
+
if (key.toLowerCase() !== wanted) continue
|
|
369
|
+
const text = Array.isArray(value) ? value[0] : value
|
|
370
|
+
return text === undefined || text === null ? undefined : String(text)
|
|
371
|
+
}
|
|
372
|
+
return undefined
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Probe one service through one loopback port.
|
|
377
|
+
*
|
|
378
|
+
* A transport-level failure is retried once. Measured on a live subscription, three concurrent
|
|
379
|
+
* probes occasionally produced `empty` at almost exactly 3 000 ms — the node accepted the tunnel
|
|
380
|
+
* and then tore it down before any byte arrived, while the identical request a moment later
|
|
381
|
+
* answered `200` in 400 ms. Real clients behave the same way (git reopens, curl retries), so a
|
|
382
|
+
* single dropped connection is not evidence that a node cannot carry the request; an HTTP status
|
|
383
|
+
* is, and that is never retried.
|
|
384
|
+
*
|
|
385
|
+
* @param port - proxy port bound to the selector group under test.
|
|
386
|
+
* @param spec - probe definition.
|
|
387
|
+
* @param options - `timeoutMs` override, `attempts` (default 2).
|
|
388
|
+
* @returns `{ id, state, ok, reason, ms, status, remaining, resetAt, attempts }`.
|
|
389
|
+
*/
|
|
390
|
+
export async function runProbe(port, spec, options = {}) {
|
|
391
|
+
const timeoutMs = Number(options.timeoutMs ?? spec?.timeoutMs ?? 10_000)
|
|
392
|
+
const attempts = Math.max(1, Math.min(Number(options.attempts ?? 2), 4))
|
|
393
|
+
let answer
|
|
394
|
+
let used = 0
|
|
395
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
396
|
+
used = attempt + 1
|
|
397
|
+
answer = await fetchViaProxy(port, spec.url, { timeoutMs })
|
|
398
|
+
// Only a transport failure is worth repeating. A response — even a 502 from the node — is
|
|
399
|
+
// the node's answer, and asking twice would only make the verdict slower to be wrong.
|
|
400
|
+
if (answer.ok === true || TRANSPORT_FAILURES.has(answer.reason) === false) break
|
|
401
|
+
}
|
|
402
|
+
const verdict = judgeProbe(spec, answer)
|
|
403
|
+
return {
|
|
404
|
+
id: spec.id,
|
|
405
|
+
label: spec.label,
|
|
406
|
+
state: verdict.state,
|
|
407
|
+
ok: verdict.ok,
|
|
408
|
+
reason: verdict.reason,
|
|
409
|
+
ms: answer.ms,
|
|
410
|
+
status: verdict.detail?.status ?? answer.status,
|
|
411
|
+
remaining: verdict.detail?.remaining,
|
|
412
|
+
resetAt: verdict.detail?.resetAt,
|
|
413
|
+
attempts: used,
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Failures that say "this connection died", not "this node cannot do it".
|
|
419
|
+
*
|
|
420
|
+
* `timeout` is deliberately absent: a request that never answered inside a 10–15 s budget is a
|
|
421
|
+
* real result, and retrying it would double the cost of every dead node in a subscription.
|
|
422
|
+
*
|
|
423
|
+
* @type {ReadonlySet<string>}
|
|
424
|
+
*/
|
|
425
|
+
const TRANSPORT_FAILURES = new Set(['empty', 'reset', 'connect:reset', 'connect:EOF', 'no-headers'])
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Probe every spec against one port, limited concurrency.
|
|
429
|
+
*
|
|
430
|
+
* Concurrency defaults to 1, and that is measured rather than cautious: four rounds of the
|
|
431
|
+
* three gating probes through one live node gave `0` failures serially, `1` at concurrency 2 and
|
|
432
|
+
* `0` at concurrency 3 — with the failure always the same shape (the node accepted the tunnel and
|
|
433
|
+
* dropped it before answering). A probe set of three on a node is a few seconds when serial, and
|
|
434
|
+
* the cost of parallelism here is not speed but false negatives, which is precisely the bug this
|
|
435
|
+
* module exists to remove. Raise `concurrency` only when the node set is known to tolerate it.
|
|
436
|
+
*
|
|
437
|
+
* @param port - proxy port bound to the selector group under test.
|
|
438
|
+
* @param specs - probe definitions.
|
|
439
|
+
* @param options - `concurrency` (default 1), `timeoutMs`, `attempts`.
|
|
440
|
+
* @returns probe id to result map, in spec order.
|
|
441
|
+
*/
|
|
442
|
+
export async function runProbes(port, specs, options = {}) {
|
|
443
|
+
const list = Array.isArray(specs) ? specs : []
|
|
444
|
+
const concurrency = Math.max(1, Math.min(Number(options.concurrency ?? 1), list.length || 1))
|
|
445
|
+
const results = new Array(list.length)
|
|
446
|
+
let at = 0
|
|
447
|
+
const worker = async () => {
|
|
448
|
+
while (at < list.length) {
|
|
449
|
+
const index = at
|
|
450
|
+
at += 1
|
|
451
|
+
results[index] = await runProbe(port, list[index], options)
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
await Promise.all(Array.from({ length: concurrency }, worker))
|
|
455
|
+
const byId = {}
|
|
456
|
+
for (const row of results) byId[row.id] = row
|
|
457
|
+
return byId
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Merge configured probes over the built-in table.
|
|
462
|
+
*
|
|
463
|
+
* A configured entry keeps its built-in judgement when the id matches, so
|
|
464
|
+
* `github=https://api.github.com/rate_limit` cannot silently drop the quota check by being
|
|
465
|
+
* written out again. Inline options (`;expect=200,401`) let a user override deliberately.
|
|
466
|
+
*
|
|
467
|
+
* @param text - configured probe lines, `id=url` per line or comma.
|
|
468
|
+
* @param required - ids that must pass; empty means every gating probe.
|
|
469
|
+
* @returns `{ probes, gating }`.
|
|
470
|
+
*/
|
|
471
|
+
export function resolveProbes(text, required) {
|
|
472
|
+
const byId = new Map(REAL_PROBES.map((spec) => [spec.id, { ...spec }]))
|
|
473
|
+
for (const spec of parseConfigured(text)) {
|
|
474
|
+
const base = byId.get(spec.id) ?? { id: spec.id, label: spec.label, gating: false, delay: true }
|
|
475
|
+
byId.set(spec.id, { ...base, ...spec, gating: base.gating === true })
|
|
476
|
+
}
|
|
477
|
+
const probes = [...byId.values()]
|
|
478
|
+
const wanted = splitIds(required)
|
|
479
|
+
const gating = wanted.length > 0 ? [...new Set(wanted)] : probes.filter((spec) => spec.gating === true).map((spec) => spec.id)
|
|
480
|
+
return { probes, gating }
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Parse the configured probe text.
|
|
485
|
+
*
|
|
486
|
+
* Supported forms: `id=url`, `url`, and either followed by `;expect=200,401` / `;forbid=403`
|
|
487
|
+
* / `;gating=1` / `;quota=header@min`.
|
|
488
|
+
*
|
|
489
|
+
* @param text - the configuration field.
|
|
490
|
+
* @returns probe descriptors.
|
|
491
|
+
*/
|
|
492
|
+
export function parseConfigured(text) {
|
|
493
|
+
const out = []
|
|
494
|
+
for (const chunk of String(text ?? '').split(/[\n,]+/)) {
|
|
495
|
+
const entry = chunk.trim()
|
|
496
|
+
if (entry === '') continue
|
|
497
|
+
const [head, ...rest] = entry.split(';')
|
|
498
|
+
const options = {}
|
|
499
|
+
for (const part of rest) {
|
|
500
|
+
const at = part.indexOf('=')
|
|
501
|
+
if (at < 0) continue
|
|
502
|
+
const key = part.slice(0, at).trim().toLowerCase()
|
|
503
|
+
const value = part.slice(at + 1).trim()
|
|
504
|
+
if (key === 'expect') options.expect = value.split(/[|,\s]+/).map(Number).filter((n) => Number.isFinite(n))
|
|
505
|
+
else if (key === 'forbid') options.forbid = value.split(/[|,\s]+/).map(Number).filter((n) => Number.isFinite(n))
|
|
506
|
+
else if (key === 'gating') options.gating = value !== '0' && value !== 'false'
|
|
507
|
+
else if (key === 'quota') {
|
|
508
|
+
const [header, min] = value.split('@')
|
|
509
|
+
if (header !== undefined && header !== '') options.quotaHeader = header.trim()
|
|
510
|
+
const numeric = Number(min)
|
|
511
|
+
if (Number.isFinite(numeric)) options.quotaHeaderMin = numeric
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
const at = head.indexOf('=')
|
|
515
|
+
if (at > 0) {
|
|
516
|
+
const id = head.slice(0, at).trim()
|
|
517
|
+
const url = head.slice(at + 1).trim()
|
|
518
|
+
if (id === '' || !isUrl(url)) continue
|
|
519
|
+
out.push({ id, label: id, url, ...options })
|
|
520
|
+
continue
|
|
521
|
+
}
|
|
522
|
+
if (!isUrl(head)) continue
|
|
523
|
+
let host
|
|
524
|
+
try {
|
|
525
|
+
host = new URL(head).hostname
|
|
526
|
+
} catch {
|
|
527
|
+
continue
|
|
528
|
+
}
|
|
529
|
+
if (host === '') continue
|
|
530
|
+
out.push({ id: host, label: host, url: head, ...options })
|
|
531
|
+
}
|
|
532
|
+
return out
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Whether a string is an absolute http(s) URL with a host.
|
|
537
|
+
*
|
|
538
|
+
* @param value - candidate.
|
|
539
|
+
* @returns true when usable.
|
|
540
|
+
*/
|
|
541
|
+
function isUrl(value) {
|
|
542
|
+
if (!/^https?:\/\//i.test(value)) return false
|
|
543
|
+
try {
|
|
544
|
+
return new URL(value).hostname !== ''
|
|
545
|
+
} catch {
|
|
546
|
+
return false
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Split a comma/space separated id list.
|
|
552
|
+
*
|
|
553
|
+
* @param value - raw list.
|
|
554
|
+
* @returns ids.
|
|
555
|
+
*/
|
|
556
|
+
function splitIds(value) {
|
|
557
|
+
return String(value ?? '')
|
|
558
|
+
.split(/[\s,]+/)
|
|
559
|
+
.map((entry) => entry.trim())
|
|
560
|
+
.filter((entry) => entry !== '')
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* The probes that gate usability, resolved to definitions.
|
|
565
|
+
*
|
|
566
|
+
* @param probes - resolved probe list.
|
|
567
|
+
* @param gating - gating ids.
|
|
568
|
+
* @returns the specs to run for a verdict.
|
|
569
|
+
*/
|
|
570
|
+
export function gatingSpecs(probes, gating) {
|
|
571
|
+
const wanted = new Set(Array.isArray(gating) ? gating : [])
|
|
572
|
+
return (Array.isArray(probes) ? probes : []).filter((spec) => wanted.has(spec.id))
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Reduce one node's probe results to a verdict plus the reason it lost.
|
|
577
|
+
*
|
|
578
|
+
* Three outcomes, and the middle one is the whole point:
|
|
579
|
+
*
|
|
580
|
+
* - `blocked` — the tunnel or the service did not answer. This is a hard failure: the node
|
|
581
|
+
* cannot carry the request at all, so it must not be selected.
|
|
582
|
+
* - `limited` — the node answered and the service refused it for quota. Measured on this
|
|
583
|
+
* subscription, **every** node's exit address had `x-ratelimit-remaining: 0` for GitHub at one
|
|
584
|
+
* point, while all of them still carried git, the base endpoint and every other request fine.
|
|
585
|
+
* Treating that as a hard failure made a healthy subscription report "no usable node" and
|
|
586
|
+
* wedged the switch on `no-alternative` forever — so it is a *degradation*, not a failure: the
|
|
587
|
+
* node stays selectable and only loses a tie-break against a node with quota left.
|
|
588
|
+
* - `ok` — everything answered.
|
|
589
|
+
*
|
|
590
|
+
* `usable` therefore means "no hard failure", and `degraded` says "usable but short on quota".
|
|
591
|
+
* Both are reported so the panel can name the difference instead of collapsing it.
|
|
592
|
+
*
|
|
593
|
+
* @param results - probe id to `{ ok, state, reason }`.
|
|
594
|
+
* @param gating - ids that participate in the verdict.
|
|
595
|
+
* @returns `{ usable, degraded, failed, limited, blocked, total, score }`.
|
|
596
|
+
*/
|
|
597
|
+
export function judgeNodeHealth(results, gating) {
|
|
598
|
+
const failed = []
|
|
599
|
+
const limited = []
|
|
600
|
+
const blocked = []
|
|
601
|
+
let total = 0
|
|
602
|
+
for (const id of Array.isArray(gating) ? gating : []) {
|
|
603
|
+
const row = results?.[id]
|
|
604
|
+
if (row === undefined) {
|
|
605
|
+
// Never measured is not evidence of a fault; it counts as a soft miss so an untested node
|
|
606
|
+
// cannot outrank a measured-good one, but it does not make the node unusable either.
|
|
607
|
+
failed.push(id)
|
|
608
|
+
limited.push(id)
|
|
609
|
+
continue
|
|
610
|
+
}
|
|
611
|
+
if (row.ok === true) {
|
|
612
|
+
if (typeof row.ms === 'number') total += row.ms
|
|
613
|
+
continue
|
|
614
|
+
}
|
|
615
|
+
failed.push(id)
|
|
616
|
+
if (row.state === 'limited') limited.push(id)
|
|
617
|
+
else blocked.push(id)
|
|
618
|
+
}
|
|
619
|
+
return {
|
|
620
|
+
usable: blocked.length === 0,
|
|
621
|
+
degraded: blocked.length === 0 && limited.length > 0,
|
|
622
|
+
failed,
|
|
623
|
+
limited,
|
|
624
|
+
blocked,
|
|
625
|
+
total: total === 0 ? undefined : total,
|
|
626
|
+
/** Hard failures first, then quota misses: this is what orders the search. */
|
|
627
|
+
score: blocked.length * 100 + limited.length,
|
|
628
|
+
}
|
|
629
|
+
}
|
package/lib/routes.js
CHANGED
|
@@ -40,6 +40,15 @@ export const EDITABLE_FIELDS = [
|
|
|
40
40
|
'requiredProbes',
|
|
41
41
|
'blocklist',
|
|
42
42
|
'selectBudgetMs',
|
|
43
|
+
'autoReselect',
|
|
44
|
+
'reselectMinutes',
|
|
45
|
+
'autoSwitch',
|
|
46
|
+
'healthRoundSeconds',
|
|
47
|
+
'healthStrikeLimit',
|
|
48
|
+
'healthMaxDelayMs',
|
|
49
|
+
'healthSwitchCandidates',
|
|
50
|
+
'healthSurveyEvery',
|
|
51
|
+
'switchWhileBusy',
|
|
43
52
|
]
|
|
44
53
|
|
|
45
54
|
/**
|
|
@@ -296,6 +305,33 @@ export function mountRoutes(webServer, runtime, log) {
|
|
|
296
305
|
sendJson(response, answer.ok ? 200 : 400, answer)
|
|
297
306
|
return
|
|
298
307
|
}
|
|
308
|
+
if (action === 'health') {
|
|
309
|
+
// One real-request round on the live node. Long-running by nature (four probes, each a
|
|
310
|
+
// full TLS handshake through a node), so the caller gets the finished report rather than
|
|
311
|
+
// a stream; the panel polls status meanwhile.
|
|
312
|
+
const report = await runtime.healthRound({ force: true })
|
|
313
|
+
sendJson(response, 200, { ok: report.state === 'ok' || report.state === 'switched', ...report })
|
|
314
|
+
return
|
|
315
|
+
}
|
|
316
|
+
if (action === 'probeNode') {
|
|
317
|
+
// Measure one named node for real, without moving live traffic.
|
|
318
|
+
const name = String(body.node ?? '').trim()
|
|
319
|
+
if (name === '') {
|
|
320
|
+
sendJson(response, 400, { error: 'node is required' })
|
|
321
|
+
return
|
|
322
|
+
}
|
|
323
|
+
const plan = runtime.probePlan()
|
|
324
|
+
const { results, verdict } = await runtime.core.checkNodeReal(name, plan.specs, plan.gating, {
|
|
325
|
+
timeoutMs: runtime.config.probeTimeoutMs ?? 8000,
|
|
326
|
+
})
|
|
327
|
+
if (Object.keys(results).length === 0) {
|
|
328
|
+
sendJson(response, 503, { ok: false, error: 'the probe listener is not answering' })
|
|
329
|
+
return
|
|
330
|
+
}
|
|
331
|
+
runtime.healthRows.set(name, { results, verdict, at: Date.now() })
|
|
332
|
+
sendJson(response, 200, { ok: verdict.usable, node: name, results, verdict, required: plan.gating })
|
|
333
|
+
return
|
|
334
|
+
}
|
|
299
335
|
if (action === 'test') {
|
|
300
336
|
// A `node` narrows the run to one node and `all` covers every node; without
|
|
301
337
|
// either the cycle measures the configured sample. The panel offers all three.
|