dsh-mobile-plugin 0.5.81 → 0.5.82

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.
Files changed (55) hide show
  1. package/lib/frpc/provision.cjs +21 -17
  2. package/lib/frpc/runner.cjs +193 -165
  3. package/lib/impl.js +53 -80
  4. package/lib/mirror/pusher.cjs +60 -10
  5. package/lib/mobile/events.js +2 -1
  6. package/lib/mobile/feedback.js +6 -5
  7. package/lib/mobile/file-read.js +4 -2
  8. package/lib/mobile/mux.js +148 -21
  9. package/lib/mobile/paired-devices.js +2 -1
  10. package/lib/mobile/pairing.js +3 -2
  11. package/lib/mobile/relay-control.js +27 -33
  12. package/lib/mobile/session-changes.js +8 -2
  13. package/lib/mobile/session-delivery.js +5 -1
  14. package/lib/mobile/session-file.js +46 -25
  15. package/lib/mobile/session-head.js +7 -3
  16. package/lib/mobile/session-snapshot.js +5 -1
  17. package/lib/mobile/session-step.js +13 -7
  18. package/lib/mobile/session-stop-summary.js +6 -1
  19. package/lib/mobile/stream-registry.js +48 -53
  20. package/lib/mobile/stream.js +17 -2
  21. package/lib/mobile/uploads.js +190 -163
  22. package/lib/p2p/session.cjs +169 -70
  23. package/lib/p2p/wiring.cjs +4 -2
  24. package/lib/panel/index.html +17 -15
  25. package/lib/relay/blob-upload.cjs +103 -0
  26. package/lib/relay/config-store.js +81 -0
  27. package/lib/relay/control.js +94 -46
  28. package/lib/relay/core.js +9 -13
  29. package/lib/relay/lan-proxy.js +44 -7
  30. package/lib/relay/pairing-payload.cjs +14 -5
  31. package/lib/relay/preview-webapp.cjs +150 -0
  32. package/lib/relay/preview.js +35 -8
  33. package/lib/relay/protocol.js +6 -4
  34. package/lib/relay/relay-probe.js +112 -21
  35. package/lib/relay/tunnel-forwarder.cjs +4 -2
  36. package/lib/relay/tunnel.js +39 -8
  37. package/lib/remote/controller.cjs +33 -3
  38. package/lib/remote/host-control.cjs +11 -2
  39. package/lib/remote/router.cjs +83 -33
  40. package/lib/remote/transport.cjs +32 -5
  41. package/lib/remote/tunnel-helper.cjs +51 -25
  42. package/lib/remote/tunnels.cjs +27 -3
  43. package/lib/routes/control-plane.js +25 -17
  44. package/lib/routes/mobile-api.js +21 -18
  45. package/lib/shared/fresh-request.js +32 -1
  46. package/lib/shared/route-order.cjs +118 -132
  47. package/lib/shared/sse-write.js +29 -10
  48. package/lib/shared/via-header.js +5 -12
  49. package/lib/shell/transport-host.js +9 -1
  50. package/lib/sidecar-facade-worker.cjs +156 -112
  51. package/lib/sidecar-facade.cjs +6 -1
  52. package/lib/sidecar-lifecycle.cjs +6 -2
  53. package/lib/tailcat/host-process.cjs +32 -8
  54. package/lib/tailcat/session.cjs +27 -10
  55. package/package.json +6 -6
@@ -1,4 +1,4 @@
1
- // 远程电脑的 Tailcat/P2P 候选:通过已认证控制通道会合,每台绑定独立持有私钥与句柄。
1
+ // 远程隧道候选随助手代次失效,恢复时主动通知路由重建,设备私钥保持不变。
2
2
  'use strict';
3
3
 
4
4
  const { createRemoteTunnelHelper } = require('./tunnel-helper.cjs');
@@ -22,6 +22,22 @@ function createRemoteTunnels({ store, transport, helper = createRemoteTunnelHelp
22
22
  const versions = new Map();
23
23
  let closed = false;
24
24
  const generation = () => helper.status?.().generation || 0;
25
+ const listeners = new Set();
26
+ let recovering = false;
27
+ const unsubscribe = helper.onChange?.(state => {
28
+ if (closed) return;
29
+ if (!state.ready) {
30
+ recovering = true;
31
+ sessions.clear();
32
+ for (const id of jobs.keys()) versions.set(id, (versions.get(id) || 0) + 1);
33
+ } else {
34
+ if (!recovering) return;
35
+ recovering = false;
36
+ }
37
+ for (const listener of listeners) {
38
+ try { Promise.resolve(listener(state)).catch(() => {}); } catch { /* observer */ }
39
+ }
40
+ });
25
41
 
26
42
  function serialized(id, action) {
27
43
  const previous = jobs.get(id) || Promise.resolve();
@@ -106,7 +122,9 @@ function createRemoteTunnels({ store, transport, helper = createRemoteTunnelHelp
106
122
  p2p: { publicKey: keys.p2pPublicKey, candidates: entry.candidates, localCandidates: entry.localCandidates } });
107
123
  if (second.result?.p2p?.publicKey !== peer.publicKey) throw new Error('remote-p2p-identity-changed');
108
124
  // A 更新接收端后会主动打向这块 B socket;保留 B 句柄,让数据面学习 A 的当前地址。
109
- entry.routes.push(candidate);
125
+ entry.p2pRoute = candidate;
126
+ const health = await helper.request('remoteP2PPath', { deviceId: id });
127
+ if (health.path === 'direct') entry.routes.push(candidate);
110
128
  }
111
129
  } catch (error) {
112
130
  try { await helper.request('remoteP2PStop', { deviceId: id }); } catch { /* 助手退出即清理。 */ }
@@ -132,8 +150,11 @@ function createRemoteTunnels({ store, transport, helper = createRemoteTunnelHelp
132
150
  if (closed) return [];
133
151
  const current = sessions.get(id);
134
152
  if (current && current.generation === generation() && helper.status?.().running !== false) {
135
- if (current.routes.some(item => item.channel === 'p2p')) {
153
+ if (current.p2pRoute) {
136
154
  try {
155
+ const health = await helper.request('remoteP2PPath', { deviceId: id });
156
+ current.routes = current.routes.filter(item => item.channel !== 'p2p');
157
+ if (health.path === 'direct') current.routes.push(current.p2pRoute);
137
158
  const local = await helper.request('remoteP2PCandidates', { deviceId: id });
138
159
  if (!same(local.candidates, current.candidates) || !same(local.localCandidates, current.localCandidates)) {
139
160
  const candidates = list(local.candidates);
@@ -149,6 +170,7 @@ function createRemoteTunnels({ store, transport, helper = createRemoteTunnelHelp
149
170
  throw error;
150
171
  }
151
172
  current.routes = current.routes.filter(item => item.channel !== 'p2p');
173
+ current.p2pRoute = null;
152
174
  try { await helper.request('remoteP2PStop', { deviceId: id }); } catch { /* 已退出。 */ }
153
175
  }
154
176
  }
@@ -162,6 +184,7 @@ function createRemoteTunnels({ store, transport, helper = createRemoteTunnelHelp
162
184
  }
163
185
 
164
186
  return {
187
+ onChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
165
188
  routesFor,
166
189
  refresh(binding, { route } = {}) {
167
190
  const id = idOf(binding);
@@ -179,6 +202,7 @@ function createRemoteTunnels({ store, transport, helper = createRemoteTunnelHelp
179
202
  },
180
203
  async closeAll() {
181
204
  closed = true;
205
+ unsubscribe?.(); listeners.clear();
182
206
  for (const id of new Set([...sessions.keys(), ...jobs.keys()])) versions.set(id, (versions.get(id) || 0) + 1);
183
207
  await Promise.all([...jobs.values()].map(job => job.catch(() => {})));
184
208
  sessions.clear();
@@ -1,3 +1,5 @@
1
+ // 注册本机控制面,并在吊销回执完成后关闭本实例在途连接。
2
+ // 本机面板读取上报目的地,FRP 仅在明确保存后启动,停用清除直连目标。
1
3
  'use strict';
2
4
 
3
5
  /**
@@ -306,6 +308,7 @@ function registerControlPlaneRoutes(deps) {
306
308
  // FRP 直连:面板导入配置后真正拉起本地 frpc 的进程管理器(见 lib/frpc/runner.cjs)。
307
309
  // 缺省 null:单独挂 impl 的测试里没有它,那几条路由如实报不可用。
308
310
  frp = null,
311
+ getControlTargetUrl = () => '',
309
312
  restartSidecar,
310
313
  // 「手机上最近来过没有」。**只往本机这条状态路由上补**(和 panelUrl 一样),
311
314
  // 不动 createStatusView——那份 JSON 手机端也在读,给它加字段是另一个决定。
@@ -334,6 +337,7 @@ function registerControlPlaneRoutes(deps) {
334
337
  * 测试里没有流登记):那时吊销仍然对下一次请求生效,只是收不了在途的流。
335
338
  */
336
339
  dropDeviceStreams = () => 0,
340
+ dropAllDeviceStreams = () => 0,
337
341
  } = deps;
338
342
  /**
339
343
  * 面板读的 status 在宿主那份上补一格「公用中转是否被强制停用」。
@@ -346,7 +350,7 @@ function registerControlPlaneRoutes(deps) {
346
350
  * 包在这一层而不是 `createStatusView` 里:那份 JSON 手机端也在读,给它加字段是另一个决定。
347
351
  * 所有 `status()` 调用点(面板页、config / toggle 等写操作回包)都自动带上这一格。
348
352
  */
349
- const status = () => ({ ...rawStatus(), publicRelayBlocked: core.publicRelayBlocked(state) });
353
+ const status = () => ({ ...rawStatus(), publicRelayBlocked: core.publicRelayBlocked(state), controlReportTargetUrl: getControlTargetUrl() });
350
354
  /**
351
355
  * 宿主发布的包管理器调用方式(`profileContext.packageManager`)。
352
356
  *
@@ -605,28 +609,29 @@ function registerControlPlaneRoutes(deps) {
605
609
  if (!deps.frp || typeof deps.frp.start !== 'function') {
606
610
  return sendJson(res, 503, { ok: false, error: { code: 'frp-unavailable', message: '这台宿主没有接入 frpc 运行能力' } })
607
611
  }
608
- deps.frp.saveConfig(config)
609
- const started = await deps.frp.start()
610
- // frpc 起来后从它的管理接口读服务端实际分配的公网地址;读到就写进 TCP 直连地址。服务商配置
611
- // 常不写 remotePort(端口由服务端分配),地址只能这样拿到——否则面板填的那个端口是猜的、拨不通。
612
- let remoteAddress = ''
613
- if (started && started.running && typeof deps.frp.discoverRemoteAddress === 'function') {
614
- remoteAddress = await deps.frp.discoverRemoteAddress(8000).catch(() => '')
612
+ if (/^\s*\[common\]\s*$/im.test(config) || /^\s*server_addr\s*=/im.test(config)) {
613
+ return sendJson(res, 400, { ok: false, error: { code: 'frp-ini-unsupported', message: '旧 INI 格式不能运行,请让服务商提供 TOML 或 JSON 配置' } })
615
614
  }
616
- if (remoteAddress && state) {
617
- state.manualTcpUrl = remoteAddress
618
- try {
619
- if (settings && typeof settings.update === 'function') await settings.update({ manualTcpUrl: remoteAddress })
620
- } catch { /* 落盘失败也不影响这次返回的运行状态 */ }
615
+ try { deps.frp.saveConfig(config) }
616
+ catch (err) { return sendJson(res, 400, { ok: false, error: { code: 'frp-config-invalid', message: err.message || String(err) } }) }
617
+ const started = typeof deps.frp.restart === 'function' ? await deps.frp.restart() : await deps.frp.start()
618
+ // 地址写回由 runner 每代发现统一触发;等待后只回答本次启动仍有效的当前事实。
619
+ const runId = deps.frp.runId
620
+ if (started && started.running && typeof deps.frp.discoverRemoteAddress === 'function') {
621
+ await deps.frp.discoverRemoteAddress(8000).catch(() => '')
621
622
  }
622
- sendJson(res, 200, { ok: true, status: { ...started, remoteAddress: remoteAddress || (started && started.remoteAddress) || '' } })
623
+ const current = typeof deps.frp.status === 'function' ? deps.frp.status() : started
624
+ const sameRun = deps.frp.runId === runId
625
+ const ok = Boolean(sameRun && current && current.running && !current.error)
626
+ sendJson(res, 200, { ok, status: sameRun ? current : { ...current, running: false, remoteAddress: '' } })
623
627
  }) })
624
628
  registerRoute({ kind: 'exact', path: '/api/relay/frp/stop', handler: localOnly('POST', async (_req, res) => {
625
629
  if (!deps.frp || typeof deps.frp.clear !== 'function') {
626
630
  return sendJson(res, 503, { ok: false, error: { code: 'frp-unavailable', message: '这台宿主没有接入 frpc 运行能力' } })
627
631
  }
628
- const state = await deps.frp.clear()
629
- sendJson(res, 200, { ok: true, status: state })
632
+ const stopped = await deps.frp.clear()
633
+ await settings.update({ manualTcpUrl: '' })
634
+ sendJson(res, 200, { ok: true, status: stopped })
630
635
  }) })
631
636
  const tailcatSnapshot = () => {
632
637
  const state = deps.tailcat && typeof deps.tailcat.status === 'function' ? deps.tailcat.status() : null
@@ -921,7 +926,7 @@ function registerControlPlaneRoutes(deps) {
921
926
  const revoked = credentials.revokeDevice(state.instanceId, deviceId)
922
927
  // 已建立的流主动收掉:否则被踢的设备还能继续收消息直到它自己重连。
923
928
  let closed = 0
924
- try { closed = typeof dropDeviceStreams === 'function' ? dropDeviceStreams(deviceId) : 0 } catch { /* 尽力 */ }
929
+ try { closed = typeof dropDeviceStreams === 'function' ? dropDeviceStreams(deviceId, res) : 0 } catch { /* 尽力 */ }
925
930
  return sendJson(res, 200, { ok: true, revoked, closed })
926
931
  }) })
927
932
 
@@ -955,6 +960,7 @@ function registerControlPlaneRoutes(deps) {
955
960
  }) })
956
961
 
957
962
  registerRoute({ kind: 'exact', path: '/api/relay/revoke-all', handler: localOnly('POST', async (_req, res) => {
963
+ const deviceIds = [...new Set((credentials.listDevices?.(state.instanceId) || []).map(device => device.deviceId).filter(Boolean))]
958
964
  // 清除所有授权 = 中转清空本实例全部设备授权 + 本机吊销局域网设备凭据 +
959
965
  // 轮换 lanSecret/配对码。三处都要做:只清中转的话,同网设备仍能用旧的
960
966
  // `dshc_` 凭据直连宿主,而移动端的「撤销全部授权」正是在要求它们全部失效。
@@ -970,6 +976,8 @@ function registerControlPlaneRoutes(deps) {
970
976
  core.rotatePairing(state)
971
977
  core.saveState(state)
972
978
  await syncSidecar().catch(() => undefined)
979
+ for (const deviceId of deviceIds) dropDeviceStreams(deviceId, res)
980
+ dropAllDeviceStreams(res)
973
981
  sendJson(res, 200, { ok: true, revoked: revoked + localRevoked, revokedRelay: revoked, revokedLocal: localRevoked, ...status() })
974
982
  }) })
975
983
  registerRoute({ kind: 'exact', path: '/api/relay/config', handler: localOnly('POST', async (req, res) => {
@@ -1,3 +1,5 @@
1
+ // 公开健康响应保留服务与实例身份、API 代号,不公开精确插件版本。
2
+ // 注册移动端既有路由,并发布独立直连入口与当前注册中转。
1
3
  'use strict';
2
4
  // 手机切模型只改当前会话,App 默认不写回电脑。
3
5
  // 模型目录支持空 sessionId,首次使用无需先创建会话。
@@ -112,8 +114,6 @@ const extensionData = require('../mobile/extension-data.js');
112
114
  const extensionDev = require('../mobile/extension-dev.js');
113
115
  const extensionCatalog = require('../mobile/extension-catalog.js');
114
116
  const sessionDelivery = require('../mobile/session-delivery.js');
115
- // 体检接口要自报身份:版本号只有一个来源,就是包自己的 package.json(与 relay/status.js 同)。
116
- const pkg = require('../../package.json');
117
117
  // 「这一代运行时少挂了什么」(见 host-capabilities.cjs):由 host.js 在启动时落账。
118
118
  const { readCapabilityReport } = require('../host-capabilities.cjs');
119
119
 
@@ -158,6 +158,10 @@ function profileNodeModulesOf(ctx) {
158
158
 
159
159
  function registerMobileRoutes(deps) {
160
160
  const { registerRoute, tailcat, p2p, registerUpgradeRoute, guarded, state, getControl, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, mux = { handleUpgrade: () => {} }, preview, core, pairingApproval, rotatePairing, getHistoryKey, credentials, dropDeviceStreams } = deps;
161
+ const currentRelayUrl = () => {
162
+ const tunnel = getSidecarSnapshot?.()?.tunnel
163
+ return state.enabled && tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || null : null
164
+ }
161
165
  const route = (path, handler) => registerRoute({ kind: 'exact', path, handler: guarded(handler) })
162
166
  // 中转配置那一组要**装配期已有的实例**(config store、sidecar 生命周期),不能靠模块级
163
167
  // 单例去拿:同一进程里两份 relay.json 的真值只会打架。所以这里按装配层给的依赖建一次。
@@ -196,19 +200,17 @@ function registerMobileRoutes(deps) {
196
200
  // 所以这条不是「多带一个字段」,它是「改了地址之后,非局域网用户也能自己恢复」的那
197
201
  // 一发。`enabled` 关掉时给 null,表示「这台机器没有中转」,与「地址是空的」区分开。
198
202
  // 每次请求现算:`state` 是就地改的,注册那一刻算的一份会永远停在旧地址上。
199
- // `relayUrl` 那一格**照原样写**(`app/scripts/test-relay-address.js` 按字面钉着「关掉时给
200
- // null」这条兼容承诺);列表那一格由收敛函数给,保证首项与它一致。
201
- const relayUrls = state.enabled ? relayAddressesOf(state).relayUrls : []
203
+ // 手机只跟随宿主当前注册成功的中转;未注册的配置候选留给宿主故障切换。
204
+ const relayUrl = currentRelayUrl()
205
+ const relayUrls = relayUrl ? [relayUrl] : []
202
206
  sendJson(res, 200, {
203
207
  ok: true,
204
208
  apiVersion: API_VERSION,
205
209
  instanceId: state.instanceId || null,
206
210
  name: state.name || null,
207
211
  remoteEnabled: Boolean(state.enabled),
208
- // 两格一起报:`relayUrl` 是主用那条(老手机只认它,语义一个字没变),`relayUrls`
209
- // 是完整列表且首项恒等于前者。`enabled` 关掉时两格都是 null / [],表示「这台机器
210
- // 没有中转」,与「地址是空的」区分开。
211
- relayUrl: state.enabled ? (state.relayUrl || null) : null,
212
+ // 两格只报当前线路,离线时为 null / [],手机不竞争尚未注册的节点。
213
+ relayUrl,
212
214
  relayUrls,
213
215
  // 总控目录:内置地址 + 这枚设备令牌。APP 拿它去总控查询/订阅本机地址(`null` = 还没连上
214
216
  // 或没启用,此时 APP 就当它不存在、照旧走配对与心跳那条)。令牌只经这条已鉴权的心跳下发。
@@ -289,7 +291,7 @@ function registerMobileRoutes(deps) {
289
291
  })
290
292
 
291
293
  registerRoute({ kind: 'exact', path: '/api/mobile/v1/health', handler: async (_req, res) => {
292
- sendJson(res, 200, { ok: true, service: 'dsh-mobile-plugin', apiVersion: API_VERSION, version: pkg.version })
294
+ sendJson(res, 200, { ok: true, service: 'dsh-mobile-plugin', instanceId: String(state.instanceId || ''), apiVersion: API_VERSION })
293
295
  } })
294
296
 
295
297
  // 历史 blob 的实例密钥(HK):配对响应里已经随封包给过一次,这条是已配对设备的「按需补发」
@@ -366,6 +368,7 @@ function registerMobileRoutes(deps) {
366
368
  const count = record ? store.revokeDevice(instanceId, record.deviceId) : 0
367
369
  // 尽力而为的语义不变:手机那边失败也不阻断本地删除,所以这里始终回 ok,
368
370
  // 但把「到底吊销了几条」如实带上 —— 排查「删了还能用」时这一格是唯一线索。
371
+ if (record && typeof dropDeviceStreams === 'function') dropDeviceStreams(record.deviceId, res)
369
372
  sendJson(res, 200, { ok: true, revoked: count > 0, count })
370
373
  })
371
374
 
@@ -400,27 +403,27 @@ function registerMobileRoutes(deps) {
400
403
  // 手机是按顺序挨个试的,所以只挪顺序、不删候选。选的那条不在了就退回宿主排序。
401
404
  // 手填的直连地址(穿透域名)缀在**最后**当兜底:它绕公网、比内网慢一个数量级,排在前面
402
405
  // 就等于让手机永远选中它、家里那条内网地址一次都不试(见 `withManualCandidate` 的注释)。
403
- const candidates = state.lanEnabled
406
+ const candidates = state.lanEnabled && port > 0
404
407
  ? withManualCandidate(orderCandidates(safeLanCandidates(port), state.preferredLanAddress), state.manualLanUrl)
405
408
  : []
406
409
  // IPv6 直连候选:单独一份、**不参与**上面的排序 —— 它和中转谁更快只有手机实测得出,
407
- // 宿主无从判断对端走哪条路由。与局域网那份同一个开关管(那条监听挂在同一个代理上),
408
- // 关掉局域网直连就没有这条通道。
410
+ // 宿主无从判断对端走哪条路由。IPv6 监听独立于局域网开关,关闭 IPv4 不隐藏 IPv6。
409
411
  //
410
412
  // 这份是手机配对之后**唯一**能拿到新 IPv6 地址的地方:二维码里带的候选只在配对那一刻
411
413
  // 是真值,而隐私地址按小时轮换、运营商换前缀之后旧的那条就拨不通了。少回这一格,
412
414
  // 手机上那条通道就只能靠配对当时的旧地址活着。手填的 IPv6 那条缀在**最后**当兜底
413
415
  // (只追加、不删网卡候选),理由与上面手填的直连地址同一条。
414
- const ipv6 = state.lanEnabled ? withManualIpv6Candidate(safeIpv6Candidates(port), state.manualIpv6Url) : []
416
+ const ipv6 = port > 0 ? withManualIpv6Candidate(safeIpv6Candidates(port), state.manualIpv6Url) : []
415
417
  const lanUpdatedAt = getSidecarSnapshot()?.lan?.updatedAt || Date.now()
416
- const relayUrls = state.enabled ? relayAddressesOf(state).relayUrls : []
418
+ const relayUrl = currentRelayUrl()
419
+ const relayUrls = relayUrl ? [relayUrl] : []
417
420
  sendJson(res, 200, {
418
421
  ok: true,
419
422
  instanceId: state.instanceId || null,
420
423
  name: state.name || null,
421
- // 与心跳同一条形状:主用那条 + 完整列表,首项恒等。
422
- relayUrl: state.enabled ? (state.relayUrl || null) : null,
423
- relayUrls: state.enabled ? relayAddressesOf(state).relayUrls : [],
424
+ // 与心跳同源:只公布当前已注册线路。
425
+ relayUrl,
426
+ relayUrls,
424
427
  lanUrls: candidates,
425
428
  lanCandidates: candidates,
426
429
  ipv6Candidates: ipv6,
@@ -1,3 +1,4 @@
1
+ // 提供读请求标记、连接取消与响应结束后的收尾调度。
1
2
  'use strict'
2
3
 
3
4
  // 「读己所写」标记:写操作之后紧接着的那次列表刷新必须反映这次写入,不能被任何代读副本顶掉。
@@ -15,4 +16,34 @@ function isFreshRequest(target) {
15
16
  return FRESH_QUERY_RE.test(String(target || ''))
16
17
  }
17
18
 
18
- module.exports = { FRESH_QUERY_RE, isFreshRequest }
19
+ const REQUEST_SIGNALS = new WeakMap()
20
+
21
+ /** 同一响应共用取消信号;客户端断开后宿主读任务也停止。 */
22
+ function requestSignal(res) {
23
+ let signal = REQUEST_SIGNALS.get(res)
24
+ if (signal) return signal
25
+ const controller = new AbortController()
26
+ const abort = () => controller.abort()
27
+ signal = controller.signal
28
+ REQUEST_SIGNALS.set(res, signal)
29
+ res.once?.('close', abort)
30
+ res.once?.('error', abort)
31
+ if (res.destroyed || res.writableEnded) abort()
32
+ return signal
33
+ }
34
+
35
+ /** 响应完成后收尾;mux承载请求等待自身有界排空,不用固定延迟猜测。 */
36
+ function afterResponse(res, action) {
37
+ let scheduled = false
38
+ const schedule = () => {
39
+ if (scheduled) return
40
+ scheduled = true
41
+ Promise.resolve(res.__dshMuxDrained).then(() => action()).catch(() => {})
42
+ }
43
+ if (typeof res.once === 'function' && !res.writableFinished) {
44
+ res.once('finish', schedule)
45
+ res.once('close', schedule)
46
+ } else schedule()
47
+ }
48
+
49
+ module.exports = { FRESH_QUERY_RE, isFreshRequest, requestSignal, afterResponse }
@@ -4,8 +4,11 @@ function createRoutePolicy() {
4
4
  const exports = {};
5
5
  "use strict";
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.advanceRouteEvidenceRound = advanceRouteEvidenceRound;
7
8
  exports.noteRouteLatency = noteRouteLatency;
8
9
  exports.noteRouteFailure = noteRouteFailure;
10
+ exports.noteRouteProven = noteRouteProven;
11
+ exports.noteRouteVerified = noteRouteVerified;
9
12
  exports.noteRouteForeign = noteRouteForeign;
10
13
  exports.isRouteForeign = isRouteForeign;
11
14
  exports.routeLatencyOf = routeLatencyOf;
@@ -15,6 +18,26 @@ function createRoutePolicy() {
15
18
  const LOSS_PENALTY_MAX = 4;
16
19
  const FAILURE_PENALTY_STEP = 1.5;
17
20
  const FAILURE_PENALTY_MAX = 4;
21
+ const SAMPLE_WINDOW = 5;
22
+ const MIN_NOISE_SAMPLES = 2;
23
+ const ROUTE_SWITCH_SHARE = 1 / 3;
24
+ const SWITCH_GAIN_FLOOR_MS = 10;
25
+ const SETTLE_ROUNDS = 4;
26
+ const factsByScope = new Map();
27
+ function factsOf(scope) {
28
+ let facts = factsByScope.get(scope);
29
+ if (!facts) {
30
+ facts = {
31
+ latency: new Map(), samples: new Map(), lossPenalty: new Map(), failurePenalty: new Map(),
32
+ foreign: new Set(), evidenceAtRound: new Map(), evidenceRound: 0, staleRounds: 2, lastSwitch: null,
33
+ };
34
+ factsByScope.set(scope, facts);
35
+ }
36
+ return facts;
37
+ }
38
+ function norm(url) {
39
+ return String(url || '').trim().replace(/\/+$/, '');
40
+ }
18
41
  function penaltyOf(attempts) {
19
42
  if (!attempts)
20
43
  return null;
@@ -24,172 +47,135 @@ function createRoutePolicy() {
24
47
  return null;
25
48
  if (!Number.isFinite(ok) || ok <= 0)
26
49
  return LOSS_PENALTY_MAX;
27
- return Math.min(LOSS_PENALTY_MAX, total / ok);
50
+ return Math.max(1, Math.min(LOSS_PENALTY_MAX, total / ok));
51
+ }
52
+ function advanceRouteEvidenceRound(candidateCount, probeLimit, scope = '') {
53
+ const facts = factsOf(scope);
54
+ const count = Number.isFinite(candidateCount) ? Math.max(1, Math.ceil(candidateCount)) : 1;
55
+ const limit = Number.isFinite(probeLimit) ? Math.max(1, Math.floor(probeLimit)) : 1;
56
+ facts.staleRounds = 2 * Math.ceil(count / limit);
57
+ facts.evidenceRound += 1;
58
+ for (const [key, at] of facts.evidenceAtRound) {
59
+ if (facts.evidenceRound - at <= facts.staleRounds)
60
+ continue;
61
+ facts.evidenceAtRound.delete(key);
62
+ facts.samples.delete(key);
63
+ }
64
+ if (facts.lastSwitch && facts.evidenceRound - facts.lastSwitch.round > SETTLE_ROUNDS)
65
+ facts.lastSwitch = null;
28
66
  }
29
- const ROUTE_SWITCH_SHARE = 1 / 3;
30
- const SWITCH_GAIN_FLOOR_MS = 10;
31
- const STALE_EVIDENCE_ROUNDS = 12;
32
- const latency = new Map();
33
- const samples = new Map();
34
- const SAMPLE_WINDOW = 5;
35
- let evidenceRound = 0;
36
- const evidenceAtRound = new Map();
37
- const lossPenalty = new Map();
38
- const failurePenalty = new Map();
39
- const foreign = new Set();
40
- function norm(url) {
41
- return String(url || '').trim().replace(/\/+$/, '');
67
+ function isFresh(facts, key) {
68
+ const at = facts.evidenceAtRound.get(key);
69
+ return at !== undefined && facts.evidenceRound - at <= facts.staleRounds;
42
70
  }
43
- function noteRouteLatency(url, ms, attempts) {
71
+ function noteRouteLatency(url, ms, attempts, scope = '') {
44
72
  const key = norm(url);
45
- if (!key)
73
+ if (!key || typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0)
46
74
  return;
47
- evidenceRound += 1;
48
- if (typeof ms === 'number' && Number.isFinite(ms) && ms >= 0) {
49
- latency.set(key, ms);
50
- evidenceAtRound.set(key, evidenceRound);
51
- const window = samples.get(key) ?? [];
52
- window.push(ms);
53
- samples.set(key, window.length > SAMPLE_WINDOW ? window.slice(window.length - SAMPLE_WINDOW) : window);
54
- const penalty = penaltyOf(attempts);
55
- if (penalty === null)
56
- lossPenalty.delete(key);
57
- else
58
- lossPenalty.set(key, penalty);
59
- failurePenalty.delete(key);
75
+ const facts = factsOf(scope);
76
+ const window = facts.samples.get(key) ?? [];
77
+ window.push(ms);
78
+ facts.samples.set(key, window.slice(-SAMPLE_WINDOW));
79
+ facts.latency.set(key, ms);
80
+ facts.evidenceAtRound.set(key, facts.evidenceRound);
81
+ const penalty = penaltyOf(attempts);
82
+ if (penalty !== null)
83
+ facts.lossPenalty.set(key, penalty);
84
+ }
85
+ function noteRouteFailure(url, scope = '') {
86
+ const key = norm(url);
87
+ if (!key)
60
88
  return;
61
- }
62
- samples.delete(key);
63
- lossPenalty.delete(key);
64
- noteRouteFailure(key);
65
- }
66
- function settledOf(key) {
67
- const window = samples.get(key);
68
- const ms = latency.get(key);
69
- if (!window || window.length === 0)
70
- return ms;
71
- if (window.length === 1)
72
- return window[0];
73
- const sorted = [...window].sort((a, b) => a - b);
74
- const mid = sorted.length >> 1;
75
- return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
76
- }
77
- const MIN_NOISE_SAMPLES = 2;
78
- function sampleCountOf(key) {
79
- return samples.get(key)?.length ?? 0;
89
+ const facts = factsOf(scope);
90
+ const prev = facts.failurePenalty.get(key) ?? 1;
91
+ facts.failurePenalty.set(key, Math.min(FAILURE_PENALTY_MAX, prev * FAILURE_PENALTY_STEP));
80
92
  }
81
- function noiseBandOf(key) {
82
- const window = samples.get(key);
83
- if (!window || window.length < 2)
84
- return 0;
85
- let min = window[0];
86
- let max = window[0];
87
- for (const value of window) {
88
- if (value < min)
89
- min = value;
90
- if (value > max)
91
- max = value;
92
- }
93
- return (max - min) / 2;
94
- }
95
- function noteRouteFailure(url) {
93
+ function noteRouteProven(url, scope = '') {
96
94
  const key = norm(url);
97
95
  if (!key)
98
96
  return;
99
- const prev = failurePenalty.get(key) ?? 1;
100
- failurePenalty.set(key, Math.min(FAILURE_PENALTY_MAX, prev * FAILURE_PENALTY_STEP));
97
+ const facts = factsByScope.get(scope);
98
+ facts?.failurePenalty.delete(key);
99
+ facts?.foreign.delete(key);
101
100
  }
102
- function isFresh(key, threshold = STALE_EVIDENCE_ROUNDS) {
103
- const at = evidenceAtRound.get(key);
104
- return typeof at === 'number' && evidenceRound - at <= threshold;
101
+ function noteRouteVerified(url, scope = '') {
102
+ factsByScope.get(scope)?.foreign.delete(norm(url));
105
103
  }
106
- function staleThresholdFor(routeCount) {
107
- const perRound = Math.max(6, routeCount);
108
- return STALE_EVIDENCE_ROUNDS * Math.max(1, Math.ceil(perRound / 6));
104
+ function noteRouteForeign(url, scope = '') {
105
+ const key = norm(url);
106
+ if (key)
107
+ factsOf(scope).foreign.add(key);
109
108
  }
110
- function settledCostOf(key) {
111
- const ms = settledOf(key);
112
- if (ms === undefined)
113
- return undefined;
114
- return ms * (lossPenalty.get(key) ?? 1) * (failurePenalty.get(key) ?? 1);
109
+ function isRouteForeign(url, scope = '') {
110
+ return factsByScope.get(scope)?.foreign.has(norm(url)) ?? false;
115
111
  }
116
- function noiseCostOf(key) {
117
- return noiseBandOf(key) * (lossPenalty.get(key) ?? 1) * (failurePenalty.get(key) ?? 1);
112
+ function routeLatencyOf(url, scope = '') {
113
+ return factsByScope.get(scope)?.latency.get(norm(url)) ?? null;
118
114
  }
119
- const SETTLE_ROUNDS = 4;
120
- let lastSwitch = null;
121
- function costOf(url) {
122
- const key = norm(url);
123
- const ms = latency.get(key);
124
- if (ms === undefined)
125
- return undefined;
126
- return ms * (lossPenalty.get(key) ?? 1) * (failurePenalty.get(key) ?? 1);
115
+ function penaltyFor(facts, key) {
116
+ return (facts.lossPenalty.get(key) ?? 1) * (facts.failurePenalty.get(key) ?? 1);
127
117
  }
128
- function noteRouteForeign(url) {
118
+ function routeCostOf(url, scope = '') {
119
+ const facts = factsByScope.get(scope);
129
120
  const key = norm(url);
130
- if (key)
131
- foreign.add(key);
121
+ const ms = facts?.latency.get(key);
122
+ return facts && ms !== undefined ? ms * penaltyFor(facts, key) : null;
132
123
  }
133
- function isRouteForeign(url) {
134
- return foreign.has(norm(url));
124
+ function forgetRouteFacts(scope = '') {
125
+ factsByScope.delete(scope);
135
126
  }
136
- function routeLatencyOf(url) {
137
- const value = latency.get(norm(url));
138
- return typeof value === 'number' ? value : null;
127
+ function median(values) {
128
+ const sorted = [...values].sort((a, b) => a - b);
129
+ const mid = sorted.length >> 1;
130
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
139
131
  }
140
- function routeCostOf(url) {
141
- const value = costOf(url);
142
- return typeof value === 'number' ? value : null;
132
+ function settledCostOf(facts, key) {
133
+ const window = facts.samples.get(key);
134
+ const ms = window?.length ? median(window) : facts.latency.get(key);
135
+ return ms === undefined ? undefined : ms * penaltyFor(facts, key);
143
136
  }
144
- function forgetRouteFacts() {
145
- latency.clear();
146
- samples.clear();
147
- lossPenalty.clear();
148
- failurePenalty.clear();
149
- evidenceAtRound.clear();
150
- foreign.clear();
151
- lastSwitch = null;
137
+ function noiseCostOf(facts, key) {
138
+ const sorted = [...(facts.samples.get(key) ?? [])].sort((a, b) => a - b);
139
+ if (sorted.length < MIN_NOISE_SAMPLES)
140
+ return 0;
141
+ const stable = sorted.length >= 4 ? sorted.slice(1, -1) : sorted;
142
+ return (stable[stable.length - 1] - stable[0]) / 2 * penaltyFor(facts, key);
152
143
  }
153
- function orderRouteCandidates(routes, currentUrl = '', suspended = []) {
144
+ function orderRouteCandidates(routes, currentUrl = '', suspended = [], scope = '') {
145
+ const facts = factsOf(scope);
154
146
  const current = norm(currentUrl);
155
- const foreignFree = routes.filter((route) => !foreign.has(norm(route.url)));
147
+ const foreignFree = routes.filter((route) => !facts.foreign.has(norm(route.url)));
156
148
  const cooling = new Set((suspended || []).map(norm).filter(Boolean));
157
149
  const allCooling = foreignFree.length > 0 && foreignFree.every((route) => cooling.has(norm(route.url)));
158
150
  const cool = allCooling ? new Set() : cooling;
159
151
  const warm = foreignFree.filter((route) => !cool.has(norm(route.url)));
160
152
  const cold = foreignFree.filter((route) => cool.has(norm(route.url)));
161
- const staleThreshold = staleThresholdFor(warm.length);
162
- const known = warm
163
- .filter((route) => latency.has(norm(route.url)) && isFresh(norm(route.url), staleThreshold))
164
- .sort((a, b) => settledCostOf(norm(a.url)) - settledCostOf(norm(b.url)));
165
- const unknown = warm.filter((route) => !(latency.has(norm(route.url)) && isFresh(norm(route.url), staleThreshold)));
153
+ const known = warm.filter((route) => isFresh(facts, norm(route.url)))
154
+ .sort((a, b) => settledCostOf(facts, norm(a.url)) - settledCostOf(facts, norm(b.url)));
155
+ const unknown = warm.filter((route) => !isFresh(facts, norm(route.url)));
166
156
  const ordered = [...known, ...unknown, ...cold];
167
157
  const at = ordered.findIndex((route) => norm(route.url) === current);
168
- if (at < 0)
169
- return ordered;
170
- if (at === 0)
171
- return ordered;
172
- if (cool.has(current))
158
+ if (at <= 0 || cool.has(current) || !isFresh(facts, current))
173
159
  return ordered;
174
- const currentCost = isFresh(current, staleThreshold) ? settledCostOf(current) : undefined;
160
+ const currentCost = settledCostOf(facts, current);
175
161
  if (currentCost === undefined)
176
162
  return ordered;
177
- const headUrl = norm(ordered[0].url);
178
- const headCost = settledCostOf(headUrl);
179
- const settleRounds = SETTLE_ROUNDS * Math.max(1, Math.ceil(warm.length / 6));
180
- if (lastSwitch && evidenceRound - lastSwitch.round > settleRounds)
181
- lastSwitch = null;
182
- const bouncingBack = Boolean(lastSwitch && lastSwitch.to === current && lastSwitch.from === headUrl);
183
- const enoughEvidence = sampleCountOf(current) >= MIN_NOISE_SAMPLES
184
- && sampleCountOf(headUrl) >= MIN_NOISE_SAMPLES;
163
+ const challenger = known.find((route) => norm(route.url) !== current
164
+ && (facts.samples.get(norm(route.url))?.length ?? 0) >= MIN_NOISE_SAMPLES);
165
+ const headUrl = challenger ? norm(challenger.url) : '';
166
+ const headCost = challenger ? settledCostOf(facts, headUrl) : undefined;
185
167
  const gain = headCost !== undefined ? currentCost - headCost : 0;
186
- const noise = enoughEvidence ? noiseCostOf(current) + noiseCostOf(headUrl) : 0;
187
- const required = Math.max(noise, currentCost * ROUTE_SWITCH_SHARE, SWITCH_GAIN_FLOOR_MS);
168
+ const noise = noiseCostOf(facts, current) + noiseCostOf(facts, headUrl);
169
+ const clean = penaltyFor(facts, current) === 1 && penaltyFor(facts, headUrl) === 1;
170
+ const required = Math.max(noise, currentCost * ROUTE_SWITCH_SHARE, clean ? SWITCH_GAIN_FLOOR_MS : 0);
171
+ const bouncingBack = facts.lastSwitch?.to === current && facts.lastSwitch.from === headUrl;
188
172
  const worthwhile = headCost !== undefined && gain > required;
189
- const decisive = gain > required * 2;
190
- const settled = !bouncingBack || decisive;
191
- if (settled && worthwhile) {
192
- lastSwitch = { from: current, to: headUrl, round: evidenceRound };
173
+ const settled = !bouncingBack || gain > required * 2;
174
+ if (challenger && settled && worthwhile) {
175
+ facts.lastSwitch = { from: current, to: headUrl, round: facts.evidenceRound };
176
+ const headAt = ordered.indexOf(challenger);
177
+ ordered.splice(headAt, 1);
178
+ ordered.unshift(challenger);
193
179
  return ordered;
194
180
  }
195
181
  const [item] = ordered.splice(at, 1);