dsh-remote-agent 0.0.0-stage → 0.4.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.md +700 -0
- package/CONTRIBUTING.md +358 -0
- package/KNOWN-ISSUES.md +601 -0
- package/LICENSE +21 -0
- package/README.en.md +353 -0
- package/README.md +317 -2
- package/SECURITY.md +348 -0
- package/bin/dsh-remote-relay.js +257 -0
- package/bin/dsh-remote-setup.js +440 -0
- package/bin//345/217/214/345/207/273/350/277/220/350/241/214-/351/205/215/347/275/256/345/220/221/345/257/274.cmd +28 -0
- package/cordis.patch.yml +87 -0
- package/deploy/relay-vps/Caddyfile +24 -0
- package/deploy/relay-vps/README.md +132 -0
- package/deploy/relay-vps/dsh-remote-relay.service +47 -0
- package/deploy/relay-vps/nginx.conf +49 -0
- package/deploy/relay-vps/relay.env.example +20 -0
- package/docs/dispatch-automation-eval.md +140 -0
- package/docs/screenshots/panel-main.png +0 -0
- package/docs/screenshots/panel-task-detail.png +0 -0
- package/docs/verification-agent-e2e.md +425 -0
- package/docs/verification-repos-routing-real.md +521 -0
- package/docs/verification-resume-real.md +254 -0
- package/docs/worker-setup-pitfalls.md +266 -0
- package/lib/artifacts.js +451 -0
- package/lib/client.js +1752 -0
- package/lib/e2e.js +304 -0
- package/lib/glob.js +225 -0
- package/lib/hub/audit-log.js +161 -0
- package/lib/hub/hub-util.js +114 -0
- package/lib/hub/index.js +500 -0
- package/lib/hub/node-registry.js +943 -0
- package/lib/hub/pull-manager.js +781 -0
- package/lib/hub/registry-handshake.js +403 -0
- package/lib/hub/registry-ingest.js +346 -0
- package/lib/hub/relay-link.js +228 -0
- package/lib/hub/subagent-provider.js +424 -0
- package/lib/hub/templates.js +693 -0
- package/lib/hub/tools.js +1059 -0
- package/lib/hub/ui-routes.js +856 -0
- package/lib/hub/views.js +351 -0
- package/lib/identity.js +271 -0
- package/lib/index.js +272 -0
- package/lib/node/artifact-service.js +231 -0
- package/lib/node/diff.js +124 -0
- package/lib/node/exec.js +536 -0
- package/lib/node/hub-pin.js +71 -0
- package/lib/node/index.js +1022 -0
- package/lib/node/repos.js +134 -0
- package/lib/node/resource.js +63 -0
- package/lib/node/runner.js +792 -0
- package/lib/node/task-engine.js +712 -0
- package/lib/node/task-store.js +273 -0
- package/lib/node/transport.js +763 -0
- package/lib/pairing.js +186 -0
- package/lib/protocol.js +414 -0
- package/lib/relay-config.js +317 -0
- package/lib/relay.js +732 -0
- package/lib/setup-routes.js +313 -0
- package/lib/setup.js +522 -0
- package/lib/ws.js +466 -0
- package/package.json +103 -4
- package/profiles/README.md +573 -0
- package/profiles/hub.cordis.yml +84 -0
- package/profiles/worker.cordis.yml +60 -0
- package/scripts/check-doc-drift.mjs +785 -0
- package/scripts/check-packaging.mjs +130 -0
- package/scripts/diag-inject.mjs +243 -0
- package/scripts/e2e-live-check.mjs +181 -0
- package/scripts/relay-init.ps1 +286 -0
- package/scripts/relay-init.sh +199 -0
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NodeRegistry 的「上行帧处理」职责(P1-4 自 node-registry.js 拆出)。
|
|
3
|
+
*
|
|
4
|
+
* 以 mixin 形式合入:`class NodeRegistry extends withIngest(NodeRegistryCore)`。
|
|
5
|
+
* 这是**纯搬移** —— 四个方法体与拆分前的 node-registry.js 一字不差,行为由
|
|
6
|
+
* 652 条既有测试整体兜底(task/sync 对账、资源遥测摄入、产物分块路由等都在
|
|
7
|
+
* 这段里)。搬出动机:帧摄入是「协议→注册表状态」的翻译层,与注册表的
|
|
8
|
+
* 连接管理/视图查询是两种变更节奏,混在一个 1465 行的文件里没法读。
|
|
9
|
+
*
|
|
10
|
+
* this.* 依赖面(全部由 NodeRegistryCore 提供):
|
|
11
|
+
* nodes / tasks / limits / log / pulls / send / ensureTask / resolveWaiters
|
|
12
|
+
*/
|
|
13
|
+
import { ERROR_CODE, HUB_TO_NODE, NODE_TO_HUB, TASK_STATUS, TERMINAL_STATUS } from '../protocol.js'
|
|
14
|
+
import { E2E_MARKER } from '../e2e.js'
|
|
15
|
+
import { errText, numOr } from './hub-util.js'
|
|
16
|
+
|
|
17
|
+
export function withIngest(Base) {
|
|
18
|
+
return class extends Base {
|
|
19
|
+
// ─────────────────────────── 上行帧处理 ───────────────────────────
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 上行文本帧分发。未知帧记日志忽略;任何异常都被吞掉。
|
|
23
|
+
*/
|
|
24
|
+
handleFrameFor(nodeId, frame, meta = {}) {
|
|
25
|
+
const rec = this.nodes.get(nodeId)
|
|
26
|
+
if (rec) {
|
|
27
|
+
rec.lastSeen = Date.now()
|
|
28
|
+
if (rec.transport === 'direct' && !rec.conn && meta.conn) rec.conn = meta.conn
|
|
29
|
+
} else if (frame.t !== NODE_TO_HUB.HELLO) {
|
|
30
|
+
// 未知来源的上行帧(hub 重启后副机仍在跑):登记一个"影子节点",不丢任务视图
|
|
31
|
+
this.log('warn', 'frame from unknown node', { nodeId, type: frame.t })
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// E2E 解密(提案 #1):带标记的帧先拆密再做业务分发。
|
|
35
|
+
// 会话不存在(hub 重启后副机的连接还在、密钥已丢)→ 回 e2e-reset 让
|
|
36
|
+
// 副机重新握手,本帧丢弃 —— 副机的遥测/仓库帧是周期性的,重协商
|
|
37
|
+
// 最迟一个遥测周期内自动完成。
|
|
38
|
+
let payload = frame.d
|
|
39
|
+
if (payload && payload.e2e === E2E_MARKER) {
|
|
40
|
+
if (!rec?.e2e) {
|
|
41
|
+
this.log('warn', 'e2e frame without session, requesting re-key', { nodeId, type: frame.t })
|
|
42
|
+
this.send(nodeId, HUB_TO_NODE.ERROR, { code: ERROR_CODE.E2E_RESET, message: 'e2e session unknown; please re-offer' })
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
payload = rec.e2e.openFrame(frame.t, frame.id, payload)
|
|
47
|
+
} catch (err) {
|
|
48
|
+
// 认证失败 = 中间人伪造 / 实现错乱。丢这一帧并大声记录;
|
|
49
|
+
// 不杀连接 —— 单帧失败不应放大成断连,连续伪造会在日志里显形。
|
|
50
|
+
this.log('warn', 'e2e open failed, frame dropped', { nodeId, type: frame.t, error: errText(err) })
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const d = payload && typeof payload === 'object' ? payload : {}
|
|
55
|
+
|
|
56
|
+
switch (frame.t) {
|
|
57
|
+
case NODE_TO_HUB.HELLO:
|
|
58
|
+
this.ingestHello({ helloData: d, conn: meta.conn, transport: meta.transport ?? 'direct', pending: undefined })
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
case NODE_TO_HUB.TASK_ACCEPT: {
|
|
62
|
+
const t = this.ensureTask(nodeId, d.taskId)
|
|
63
|
+
if (!t) return
|
|
64
|
+
t.accepted = true
|
|
65
|
+
t.acceptedAt = Date.now()
|
|
66
|
+
t.duplicate = d.duplicate === true
|
|
67
|
+
if (typeof d.status === 'string') t.status = d.status
|
|
68
|
+
if (typeof d.workspace === 'string') t.workspace = d.workspace
|
|
69
|
+
if (typeof d.runner === 'string') t.runner = d.runner
|
|
70
|
+
t.updatedAt = Date.now()
|
|
71
|
+
this.resolveWaiters(t)
|
|
72
|
+
return
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
case NODE_TO_HUB.TASK_PROGRESS: {
|
|
76
|
+
const t = this.ensureTask(nodeId, d.taskId)
|
|
77
|
+
if (!t) return
|
|
78
|
+
if (typeof d.status === 'string') t.status = d.status
|
|
79
|
+
const entry = {
|
|
80
|
+
phase: typeof d.phase === 'string' ? d.phase : 'progress',
|
|
81
|
+
detail: typeof d.detail === 'string' ? d.detail : typeof d.command === 'string' ? d.command : undefined,
|
|
82
|
+
at: typeof d.at === 'number' ? d.at : Date.now(),
|
|
83
|
+
}
|
|
84
|
+
t.progressTail.push(entry)
|
|
85
|
+
if (t.progressTail.length > 20) t.progressTail.splice(0, t.progressTail.length - 20)
|
|
86
|
+
t.updatedAt = Date.now()
|
|
87
|
+
this.resolveWaiters(t)
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
case NODE_TO_HUB.TASK_SUMMARY: {
|
|
92
|
+
const t = this.ensureTask(nodeId, d.taskId)
|
|
93
|
+
if (!t) return
|
|
94
|
+
if (d.handoff && typeof d.handoff === 'object') {
|
|
95
|
+
t.handoff = d.handoff
|
|
96
|
+
if (typeof d.handoff.status === 'string') t.status = d.handoff.status
|
|
97
|
+
if (Array.isArray(d.handoff.changed)) t.changed = d.handoff.changed
|
|
98
|
+
if (d.handoff.summary && typeof d.handoff.summary === 'object') t.summary = d.handoff.summary
|
|
99
|
+
if (d.handoff.exit && typeof d.handoff.exit === 'object') t.exit = d.handoff.exit
|
|
100
|
+
if (typeof d.handoff.workspace === 'string') t.workspace = d.handoff.workspace
|
|
101
|
+
const a = d.handoff.artifacts
|
|
102
|
+
if (a && typeof a === 'object') {
|
|
103
|
+
t.manifest = {
|
|
104
|
+
counts: a.counts ?? null,
|
|
105
|
+
bytesFinal: typeof a.bytesFinal === 'number' ? a.bytesFinal : 0,
|
|
106
|
+
final: Array.isArray(a.final) ? a.final : [],
|
|
107
|
+
intermediateCount: typeof a.intermediateCount === 'number' ? a.intermediateCount : 0,
|
|
108
|
+
note: typeof a.note === 'string' ? a.note : '',
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
t.updatedAt = Date.now()
|
|
113
|
+
this.resolveWaiters(t)
|
|
114
|
+
return
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
case NODE_TO_HUB.TASK_END: {
|
|
118
|
+
const t = this.ensureTask(nodeId, d.taskId)
|
|
119
|
+
if (!t) return
|
|
120
|
+
if (typeof d.status === 'string') t.status = d.status
|
|
121
|
+
t.endedAt = typeof d.endedAt === 'number' ? d.endedAt : Date.now()
|
|
122
|
+
if (typeof d.durationMs === 'number') t.durationMs = d.durationMs
|
|
123
|
+
if (d.error && typeof d.error === 'object') t.error = d.error
|
|
124
|
+
if (d.manifestCounts && typeof d.manifestCounts === 'object') t.manifestCounts = d.manifestCounts
|
|
125
|
+
t.updatedAt = Date.now()
|
|
126
|
+
this.log('info', 'task ended', { taskId: t.taskId, nodeId, status: t.status })
|
|
127
|
+
this.resolveWaiters(t)
|
|
128
|
+
return
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
case NODE_TO_HUB.TASK_SYNC:
|
|
132
|
+
this.applySync(nodeId, d)
|
|
133
|
+
return
|
|
134
|
+
|
|
135
|
+
case NODE_TO_HUB.ARTIFACT_MANIFEST: {
|
|
136
|
+
const t = this.ensureTask(nodeId, d.taskId)
|
|
137
|
+
if (!t) return
|
|
138
|
+
if (d.manifest && typeof d.manifest === 'object') t.manifest = d.manifest
|
|
139
|
+
t.updatedAt = Date.now()
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
case NODE_TO_HUB.ARTIFACT_DONE:
|
|
144
|
+
// 允许副机把 done 走文本帧(正常走二进制帧,见 handleBinaryFor)
|
|
145
|
+
this.pulls?.ingestDone?.(d)
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
case HUB_TO_NODE.PING: {
|
|
149
|
+
// 副机的应用层心跳:回 pong,并顺手刷新 lastSeen(上面已做)
|
|
150
|
+
this.send(nodeId, NODE_TO_HUB.PONG, { echo: frame.id })
|
|
151
|
+
return
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
case NODE_TO_HUB.RESOURCE: {
|
|
155
|
+
// 资源遥测(~30s 一次):只更新 rec.resource,绝不影响任务链路。
|
|
156
|
+
// 尽力而为的字段级校验:缺/类型不对就落 null —— 一个畸形遥测帧
|
|
157
|
+
// 不能让节点记录缺胳膊少腿,更不能抛(单帧故障隔离不变式)。
|
|
158
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)
|
|
159
|
+
rec.resource = {
|
|
160
|
+
cpuPct: num(d.cpuPct),
|
|
161
|
+
load1: num(d.load1),
|
|
162
|
+
memUsedMb: num(d.memUsedMb),
|
|
163
|
+
memTotalMb: num(d.memTotalMb),
|
|
164
|
+
at: Date.now(),
|
|
165
|
+
}
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
case NODE_TO_HUB.REPOS: {
|
|
170
|
+
// 仓库清单(提案 #13):整帧替换 rec.repos —— 清单是全量快照,
|
|
171
|
+
// 不是增量。字段级清洗 + 数量/长度封顶,与遥测同一条不变式:
|
|
172
|
+
// 一个畸形帧不能伤害注册表,更不能抛。节点下线后清单保留
|
|
173
|
+
// (rec 是持久的),路由时靠 online 过滤,重连后副机会重报。
|
|
174
|
+
// rec 为空(hub 重启后的影子节点)直接丢帧 —— 没有登记点可挂。
|
|
175
|
+
const REPOS_CAP = 50
|
|
176
|
+
const s = (v, cap) => (typeof v === 'string' ? v.slice(0, cap) : '')
|
|
177
|
+
const list = Array.isArray(d.repos) ? d.repos : []
|
|
178
|
+
if (rec) {
|
|
179
|
+
rec.repos = []
|
|
180
|
+
for (const r of list) {
|
|
181
|
+
if (rec.repos.length >= REPOS_CAP) break
|
|
182
|
+
if (!r || typeof r !== 'object') continue
|
|
183
|
+
const name = s(r.name, 200)
|
|
184
|
+
const url = s(r.url, 500)
|
|
185
|
+
const p = s(r.path, 500)
|
|
186
|
+
if (name === '' && url === '' && p === '') continue
|
|
187
|
+
rec.repos.push({ name, url, path: p })
|
|
188
|
+
}
|
|
189
|
+
rec.reposAt = Date.now()
|
|
190
|
+
this.log('info', 'node repos updated', { nodeId, count: rec.repos.length })
|
|
191
|
+
}
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
case NODE_TO_HUB.E2E_OFFER:
|
|
196
|
+
// E2E 密钥交换提议(提案 #1):握手职责在 registry-handshake(那里
|
|
197
|
+
// 有身份密钥)。明文帧 —— 此时还没有任何共享密钥。
|
|
198
|
+
this.handleE2EOffer(nodeId, d)
|
|
199
|
+
return
|
|
200
|
+
|
|
201
|
+
case NODE_TO_HUB.PONG:
|
|
202
|
+
return
|
|
203
|
+
|
|
204
|
+
case NODE_TO_HUB.ERROR:
|
|
205
|
+
this.log('warn', 'node reported error', { nodeId, code: d.code, taskId: d.taskId })
|
|
206
|
+
if (d.code === ERROR_CODE.E2E_REQUIRED) {
|
|
207
|
+
// 副机在会话已建立后收到明文业务帧才会报这个错 —— 典型成因是
|
|
208
|
+
// hub 侧丢了会话(重启)。让副机重新走一次握手(它还握着旧会话,
|
|
209
|
+
// 但 hub 这边已经没有了)。
|
|
210
|
+
this.send(nodeId, HUB_TO_NODE.ERROR, { code: ERROR_CODE.E2E_RESET, message: 'hub lost e2e session; please re-offer' })
|
|
211
|
+
}
|
|
212
|
+
if (d.taskId) {
|
|
213
|
+
const t = this.tasks.get(d.taskId)
|
|
214
|
+
if (t) {
|
|
215
|
+
t.error = { code: d.code ?? 'node-error', message: d.message ?? '' }
|
|
216
|
+
t.updatedAt = Date.now()
|
|
217
|
+
this.resolveWaiters(t)
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return
|
|
221
|
+
|
|
222
|
+
default:
|
|
223
|
+
this.log('info', 'unknown frame ignored', { nodeId, type: String(frame.t) })
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** 二进制上行帧:产物分块 / 完成帧交给 PullManager。 */
|
|
228
|
+
handleBinaryFor(nodeId, header, payload, meta = {}) {
|
|
229
|
+
// E2E 解密(提案 #1):带标记的先拆密。外层 header 只留 t/seq/iv,
|
|
230
|
+
// pullId/offset/sha256 等都在内层密文里 —— 中继看不到文件名与完整性字段。
|
|
231
|
+
let hdr = header
|
|
232
|
+
let pl = payload
|
|
233
|
+
if (header && header.e2e === E2E_MARKER) {
|
|
234
|
+
const rec = this.nodes.get(nodeId)
|
|
235
|
+
if (!rec?.e2e) {
|
|
236
|
+
this.log('warn', 'e2e binary frame without session, dropped', { nodeId, type: header.t })
|
|
237
|
+
this.send(nodeId, HUB_TO_NODE.ERROR, { code: ERROR_CODE.E2E_RESET, message: 'e2e session unknown; please re-offer' })
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
try {
|
|
241
|
+
const opened = rec.e2e.openBinary(header.t, header, payload)
|
|
242
|
+
hdr = opened.header
|
|
243
|
+
pl = opened.payload
|
|
244
|
+
} catch (err) {
|
|
245
|
+
this.log('warn', 'e2e binary open failed, frame dropped', { nodeId, type: header.t, error: errText(err) })
|
|
246
|
+
return
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const type = hdr?.t
|
|
250
|
+
if (type === NODE_TO_HUB.ARTIFACT_CHUNK) {
|
|
251
|
+
this.pulls?.ingestBinary?.(hdr, pl, { conn: meta.conn })
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
if (type === NODE_TO_HUB.ARTIFACT_DONE) {
|
|
255
|
+
this.pulls?.ingestDone?.(hdr)
|
|
256
|
+
return
|
|
257
|
+
}
|
|
258
|
+
this.log('info', 'unknown binary frame ignored', { nodeId, type: String(type) })
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* task/sync:副机的**全量**任务列表 → 重建该节点视图。
|
|
263
|
+
* 列表里没有的、且不是"刚派出去还在途"的任务,从 hub 视图里移除。
|
|
264
|
+
*/
|
|
265
|
+
applySync(nodeId, d) {
|
|
266
|
+
const rec = this.nodes.get(nodeId)
|
|
267
|
+
if (!rec) return
|
|
268
|
+
const list = Array.isArray(d?.tasks) ? d.tasks : null
|
|
269
|
+
if (!list) {
|
|
270
|
+
this.log('warn', 'task/sync without tasks[]', { nodeId })
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
const seen = new Set()
|
|
274
|
+
for (const view of list) {
|
|
275
|
+
if (!view || typeof view.taskId !== 'string') continue
|
|
276
|
+
seen.add(view.taskId)
|
|
277
|
+
const t = this.ensureTask(nodeId, view.taskId)
|
|
278
|
+
if (!t) continue
|
|
279
|
+
this.applyView(t, view)
|
|
280
|
+
}
|
|
281
|
+
for (const [taskId, t] of [...rec.tasks]) {
|
|
282
|
+
if (seen.has(taskId)) continue
|
|
283
|
+
// 审批挂起中的任务从未到过副机(提案 #2):它本来就不会出现在
|
|
284
|
+
// sync 里,宽限期逻辑不适用 —— 绝不能因为 sync 里没有就被清掉。
|
|
285
|
+
if (t.status === TASK_STATUS.PENDING_APPROVAL) continue
|
|
286
|
+
// 宽限期只给"本 hub 派出去、还没等到 accept"的任务 —— 它可能正在路上。
|
|
287
|
+
// 副机上报过(adopted)却不再出现在 sync 里的任务,说明副机那边已经没有了,
|
|
288
|
+
// 以副机为权威直接移除;否则幽灵任务会一直挂在 hub 视图里。
|
|
289
|
+
if (t.adopted !== true && t.accepted !== true && Date.now() - t.createdAt < this.limits.ackTimeoutMs) continue
|
|
290
|
+
rec.tasks.delete(taskId)
|
|
291
|
+
if (this.tasks.get(taskId) === t) this.tasks.delete(taskId)
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ── 顺手做一次自动清理(防视图无限累积)────────────────────────────
|
|
295
|
+
//
|
|
296
|
+
// 副机的 TaskStore 默认保留 7 天,所以它会在 sync 里**持续上报**这些终态
|
|
297
|
+
// 任务 —— 上面那个"不在 sync 里就删"的循环因此不会清理它们。hub 视图
|
|
298
|
+
// 一路累积到 `maxTasksPerNode`,然后**任何新任务都被拒**(实测踩到,
|
|
299
|
+
// 连"派一条清理命令"都做不到)。
|
|
300
|
+
//
|
|
301
|
+
// 所以这里主动清:**终态 + 已上报 + 超过保留期**的视图。条件是保守的 ——
|
|
302
|
+
// 只看超过 retainMs 的,刚结束的任务仍可被 remote_status / remote_handoff
|
|
303
|
+
// 查到(那是用户最需要看结果的时候)。
|
|
304
|
+
//
|
|
305
|
+
// 想立即清(不等保留期)用 `remote_purge`。
|
|
306
|
+
const retainMs = this.limits.taskViewRetainMs
|
|
307
|
+
if (retainMs > 0) {
|
|
308
|
+
const cutoff = Date.now() - retainMs
|
|
309
|
+
let pruned = 0
|
|
310
|
+
for (const [taskId, t] of [...rec.tasks]) {
|
|
311
|
+
if (!TERMINAL_STATUS.has(t.status)) continue
|
|
312
|
+
const endedAt = numOr(t.endedAt, 0) || numOr(t.updatedAt, 0) || numOr(t.createdAt, 0)
|
|
313
|
+
if (endedAt >= cutoff) continue
|
|
314
|
+
rec.tasks.delete(taskId)
|
|
315
|
+
if (this.tasks.get(taskId) === t) this.tasks.delete(taskId)
|
|
316
|
+
pruned += 1
|
|
317
|
+
}
|
|
318
|
+
if (pruned > 0) {
|
|
319
|
+
this.log('info', 'pruned old task views', { nodeId, pruned, retainMs })
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
this.log('info', 'node task view rebuilt from sync', { nodeId, count: seen.size })
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
applyView(t, view) {
|
|
327
|
+
const strFields = ['status', 'mode', 'goal', 'workspace', 'sessionId']
|
|
328
|
+
for (const f of strFields) {
|
|
329
|
+
if (typeof view[f] === 'string') t[f] = view[f]
|
|
330
|
+
}
|
|
331
|
+
const numFields = ['createdAt', 'updatedAt', 'startedAt', 'endedAt', 'durationMs']
|
|
332
|
+
for (const f of numFields) {
|
|
333
|
+
if (typeof view[f] === 'number') t[f] = view[f]
|
|
334
|
+
}
|
|
335
|
+
if (view.exit && typeof view.exit === 'object') t.exit = view.exit
|
|
336
|
+
if (Array.isArray(view.changed)) t.changed = view.changed
|
|
337
|
+
if (view.error && typeof view.error === 'object') t.error = view.error
|
|
338
|
+
if (view.summary && typeof view.summary === 'object') t.summary = view.summary
|
|
339
|
+
if (view.manifestCounts && typeof view.manifestCounts === 'object') t.manifestCounts = view.manifestCounts
|
|
340
|
+
if (Array.isArray(view.progressTail)) t.progressTail = view.progressTail.slice(-20)
|
|
341
|
+
if (Array.isArray(view.logTail)) t.logTail = view.logTail.slice(-40)
|
|
342
|
+
t.viewUpdatedAt = Date.now()
|
|
343
|
+
this.resolveWaiters(t)
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hub 侧中继链路(零外部依赖)。
|
|
3
|
+
*
|
|
4
|
+
* 从 node-registry.js 拆出(P1-4):CHANGELOG/KNOWN-ISSUES 早已记着
|
|
5
|
+
* 「node-registry 集多职责于一身,建议把 RelayLink 拆出去」—— 它与注册表
|
|
6
|
+
* 之间唯一的联系是 registry.relay 持有一个实例,本身完全自包含。
|
|
7
|
+
*
|
|
8
|
+
* 中继链路:hub 拨入中继,之后所有下行帧带 `to`,中继负责投递。
|
|
9
|
+
*
|
|
10
|
+
* 断线自动重连(指数退避 + 抖动,封顶 60s)。断连期间 hub 侧任务记录不动 ——
|
|
11
|
+
* 副机那边任务照跑,重连后副机 task/sync 会把视图补回来。
|
|
12
|
+
*
|
|
13
|
+
* ── 两条并发不变式(t1 动态测试查出,此前无护栏)────────────────────
|
|
14
|
+
*
|
|
15
|
+
* 1. **同时只允许一条在途连接**。`start()` 与退避 timer 都会调 `connectOnce()`,
|
|
16
|
+
* 而 `connect()` 要等 101 响应才 resolve —— 这个窗口里 `this.conn` 还是
|
|
17
|
+
* undefined,任何一次重入都会再开一条 TCP 连接。实测(真中继):连调两次
|
|
18
|
+
* `start()` → 中继侧 `hubs.size === 2`;`stop()` 只关得掉 `this.conn` 那一条,
|
|
19
|
+
* 另一条变成**无人引用的孤儿连接**,永久占着中继的 hub 槽位,且 `stop()`
|
|
20
|
+
* 之后再无任何路径能关掉它。用 `connecting` 闸门 + `start()` 幂等堵住。
|
|
21
|
+
*
|
|
22
|
+
* 2. **close 处理器必须确认自己就是当前连接**。真正的问题在**陈旧连接**:
|
|
23
|
+
* 若它已被新连接取代(`this.conn` 指向新的),旧连接的 'close' 仍会把
|
|
24
|
+
* `this.conn` 清成 undefined 并排重连 —— 于是「已连上的新连接」被一条早就
|
|
25
|
+
* 死掉的旧连接伪造成「掉线」。实测:造出两条连接、断开其中陈旧的那条,
|
|
26
|
+
* `ready` 由 true 翻成 false、`attempt` 涨到 1、还排了一个多余的 timer。
|
|
27
|
+
* 修复即比较 `this.conn === conn` 再动手。
|
|
28
|
+
*/
|
|
29
|
+
import { decodeBinaryFrame, decodeFrame, encodeFrame, envelope, RELAY_FRAME } from '../protocol.js'
|
|
30
|
+
import { connect } from '../ws.js'
|
|
31
|
+
import { errText } from './hub-util.js'
|
|
32
|
+
|
|
33
|
+
export class RelayLink {
|
|
34
|
+
constructor({ url, token = '', log, onFrame, onBinary, reconnectMs = 5000, name = 'hub-relay' } = {}) {
|
|
35
|
+
this.url = url
|
|
36
|
+
this.token = token
|
|
37
|
+
this.log = log ?? (() => {})
|
|
38
|
+
this.onFrame = onFrame ?? (() => {})
|
|
39
|
+
this.onBinary = onBinary ?? (() => {})
|
|
40
|
+
this.reconnectMs = reconnectMs
|
|
41
|
+
this.name = name
|
|
42
|
+
this.conn = undefined
|
|
43
|
+
this.timer = undefined
|
|
44
|
+
/** 有一次 connectOnce() 正在 await 中(见上面不变式 1)。 */
|
|
45
|
+
this.connecting = false
|
|
46
|
+
this.attempt = 0
|
|
47
|
+
this.stopped = true
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
get ready() {
|
|
51
|
+
return Boolean(this.conn && !this.conn.closed)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 启动链路。**幂等**:已连接或已有在途连接时直接返回。
|
|
56
|
+
*
|
|
57
|
+
* 为什么必须幂等:hub/index.js 在 `ctx.effect` 里调它,而 Cordis 的 effect
|
|
58
|
+
* 可能因配置热重载而重跑 —— 不幂等就会每次多开一条连接,且旧的那条再无人
|
|
59
|
+
* 引用(见类注释不变式 1)。
|
|
60
|
+
*
|
|
61
|
+
* 注意 `stopped = false` 必须在闸门**之前**:`start() → stop() → start()`
|
|
62
|
+
* 的快速序列里,第二次 start() 会因 `connecting` 仍为 true 而提前返回;
|
|
63
|
+
* 若此时 stopped 还是 true,那条在途连接 resolve 后会走 `if (this.stopped)`
|
|
64
|
+
* 分支把自己关掉 —— 调用方调了 start() 却永远连不上。先置 false 则那条
|
|
65
|
+
* 在途连接会被正常采纳,语义与「重启」一致。
|
|
66
|
+
*/
|
|
67
|
+
start() {
|
|
68
|
+
this.stopped = false
|
|
69
|
+
if (this.ready || this.connecting) return
|
|
70
|
+
void this.connectOnce()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 中继 URL(不带 token),用于日志。 */
|
|
74
|
+
describe() {
|
|
75
|
+
try {
|
|
76
|
+
const u = new URL(this.url)
|
|
77
|
+
return `${u.origin}${u.pathname}`
|
|
78
|
+
} catch {
|
|
79
|
+
return '(invalid-relay-url)'
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async connectOnce() {
|
|
84
|
+
if (this.stopped) return
|
|
85
|
+
// 并发闸门:await connect() 期间 this.conn 仍为 undefined,不设这道闸门
|
|
86
|
+
// 就会再开一条 TCP 连接(见类注释不变式 1)。
|
|
87
|
+
if (this.connecting || this.ready) return
|
|
88
|
+
let target
|
|
89
|
+
try {
|
|
90
|
+
target = new URL(this.url)
|
|
91
|
+
} catch {
|
|
92
|
+
this.log('error', 'relay url invalid', { url: this.describe() })
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
target.searchParams.set('role', 'hub')
|
|
96
|
+
// ⚠ token 走 header,**不进 URL query** —— URL 会进中继的 access log、
|
|
97
|
+
// 反向代理日志、CDN 日志。中继侧本来就 header 优先:
|
|
98
|
+
// `url.searchParams.get('token') ?? req.headers['x-relay-token']`
|
|
99
|
+
// 副机侧的 RelayTransport 也做了同样的改动(lib/node/transport.js)。
|
|
100
|
+
|
|
101
|
+
this.connecting = true
|
|
102
|
+
try {
|
|
103
|
+
const headers = this.token ? { 'x-relay-token': this.token } : {}
|
|
104
|
+
const conn = await connect(target.toString(), { name: this.name, headers })
|
|
105
|
+
if (this.stopped) {
|
|
106
|
+
conn.close(1000, 'stopped')
|
|
107
|
+
return
|
|
108
|
+
}
|
|
109
|
+
this.conn = conn
|
|
110
|
+
this.attempt = 0
|
|
111
|
+
conn.on('message', (payload, isBinary) => {
|
|
112
|
+
try {
|
|
113
|
+
if (isBinary) {
|
|
114
|
+
const dec = decodeBinaryFrame(payload)
|
|
115
|
+
if (!dec.ok) {
|
|
116
|
+
this.log('warn', 'relay binary frame undecodable', { error: dec.error })
|
|
117
|
+
return
|
|
118
|
+
}
|
|
119
|
+
this.onBinary(dec.header, dec.payload)
|
|
120
|
+
return
|
|
121
|
+
}
|
|
122
|
+
const dec = decodeFrame(payload)
|
|
123
|
+
if (!dec.ok) {
|
|
124
|
+
this.log('warn', 'relay frame undecodable', { error: dec.error })
|
|
125
|
+
return
|
|
126
|
+
}
|
|
127
|
+
this.onFrame(dec.frame)
|
|
128
|
+
} catch (err) {
|
|
129
|
+
this.log('error', 'relay frame handler failed', { error: errText(err) })
|
|
130
|
+
}
|
|
131
|
+
})
|
|
132
|
+
conn.on('close', (code) => {
|
|
133
|
+
// 只有「当前生效的那条连接」断开才算掉线。
|
|
134
|
+
// 陈旧连接的 close 若不校验身份,会把已被新连接顶替的状态清成「掉线」
|
|
135
|
+
// (见类注释不变式 2)。
|
|
136
|
+
if (this.conn !== conn) {
|
|
137
|
+
this.log('info', 'stale relay connection closed', { code })
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
this.conn = undefined
|
|
141
|
+
this.log('warn', 'relay link closed', { code })
|
|
142
|
+
this.schedule()
|
|
143
|
+
})
|
|
144
|
+
conn.on('error', (err) => this.log('warn', 'relay link error', { error: errText(err) }))
|
|
145
|
+
this.log('info', 'hub attached to relay', { relay: this.describe() })
|
|
146
|
+
|
|
147
|
+
// 主动拉一次节点目录。
|
|
148
|
+
//
|
|
149
|
+
// 为什么不能只等中继的 hello/hub:中继在 acceptUpgrade 之后立刻发这一帧,
|
|
150
|
+
// 而它可能和 101 响应挤在同一个 TCP 段里 —— 那时 ws.js 的 connect() 还没
|
|
151
|
+
// resolve,'message' 监听器尚未挂上,帧就丢了。同理,重连时中继也不会为
|
|
152
|
+
// 已连着的节点重播 node/online。显式请求是唯一可靠的对齐方式。
|
|
153
|
+
//
|
|
154
|
+
// 实测(真中继,10 次连接):hello/hub 到达 0 次、node/list 到达 10 次 ——
|
|
155
|
+
// 该帧确实 100% 丢在 head 里,上面的理由不是推测。
|
|
156
|
+
this.requestNodeList()
|
|
157
|
+
} catch (err) {
|
|
158
|
+
this.log('warn', 'relay connect failed', { relay: this.describe(), error: errText(err) })
|
|
159
|
+
this.schedule()
|
|
160
|
+
} finally {
|
|
161
|
+
this.connecting = false
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** 请求中继回一份当前节点目录(幂等,可随时调用)。 */
|
|
166
|
+
requestNodeList() {
|
|
167
|
+
if (!this.ready) return false
|
|
168
|
+
try {
|
|
169
|
+
this.conn.send(encodeFrame(envelope(RELAY_FRAME.NODE_LIST, {})))
|
|
170
|
+
return true
|
|
171
|
+
} catch {
|
|
172
|
+
return false
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
schedule() {
|
|
177
|
+
if (this.stopped || this.timer) return
|
|
178
|
+
const base = Math.min(this.reconnectMs * 2 ** Math.min(this.attempt, 4), 60_000)
|
|
179
|
+
const delay = base + Math.floor(base * 0.2 * Math.random())
|
|
180
|
+
this.attempt += 1
|
|
181
|
+
this.timer = setTimeout(() => {
|
|
182
|
+
this.timer = undefined
|
|
183
|
+
void this.connectOnce()
|
|
184
|
+
}, delay)
|
|
185
|
+
if (this.timer.unref) this.timer.unref()
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 文本下行帧:text 里已带 `to`,中继靠它路由。 */
|
|
189
|
+
send(_nodeId, text) {
|
|
190
|
+
if (!this.ready) return false
|
|
191
|
+
try {
|
|
192
|
+
this.conn.send(text)
|
|
193
|
+
return true
|
|
194
|
+
} catch {
|
|
195
|
+
return false
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** 二进制下行帧:buf 头部已带 `to`。 */
|
|
200
|
+
sendBinary(_nodeId, buf) {
|
|
201
|
+
if (!this.ready) return false
|
|
202
|
+
try {
|
|
203
|
+
this.conn.sendBinary(buf)
|
|
204
|
+
return true
|
|
205
|
+
} catch {
|
|
206
|
+
return false
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
stop() {
|
|
211
|
+
this.stopped = true
|
|
212
|
+
if (this.timer) {
|
|
213
|
+
clearTimeout(this.timer)
|
|
214
|
+
this.timer = undefined
|
|
215
|
+
}
|
|
216
|
+
const conn = this.conn
|
|
217
|
+
this.conn = undefined
|
|
218
|
+
if (conn && !conn.closed) {
|
|
219
|
+
try {
|
|
220
|
+
conn.close(1000, 'hub stopping')
|
|
221
|
+
} catch {
|
|
222
|
+
/* 已断 */
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
// connecting 不清:connectOnce 的 finally 会清,且它 resolve 后走
|
|
226
|
+
// `if (this.stopped)` 分支把刚建好的连接关掉(不留半开)。
|
|
227
|
+
}
|
|
228
|
+
}
|