@capyclaw/wall-suite 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +20 -2
- package/composition.lock.json +48 -0
- package/contract/wall-contract.json +8 -0
- package/cordis.patch.yml +6 -0
- package/dsh-suite.json +128 -0
- package/lib/index.mjs +6 -0
- package/node_modules/@capyclaw/asset-service/README.md +48 -0
- package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
- package/node_modules/@capyclaw/asset-service/package.json +59 -0
- package/node_modules/@capyclaw/asset-service/src/index.mjs +310 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/node_modules/@capyclaw/portal/README.md +70 -0
- package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
- package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
- package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
- package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
- package/node_modules/@capyclaw/portal/package.json +40 -0
- package/node_modules/@capyclaw/service-broker/README.md +104 -0
- package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
- package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
- package/node_modules/@capyclaw/service-broker/lib/control.mjs +209 -0
- package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
- package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1290 -0
- package/node_modules/@capyclaw/service-broker/lib/host.mjs +187 -0
- package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +262 -0
- package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +275 -0
- package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +48 -0
- package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
- package/node_modules/@capyclaw/service-broker/package.json +65 -0
- package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
- package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
- package/node_modules/@capyclaw/service-broker/services.json +3 -0
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +570 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- package/node_modules/@capyclaw/tool-host/README.md +56 -0
- package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
- package/node_modules/@capyclaw/tool-host/package.json +59 -0
- package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
- package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
- package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
- package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
- package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
- package/node_modules/@capyclaw/wall-workbench/README.md +58 -0
- package/node_modules/@capyclaw/wall-workbench/contract/wall-contract.json +8 -0
- package/node_modules/@capyclaw/wall-workbench/lib/host.mjs +1 -0
- package/node_modules/@capyclaw/wall-workbench/package.json +63 -0
- package/node_modules/@capyclaw/wall-workbench/plugin.mjs +13 -0
- package/node_modules/@capyclaw/wall-workbench/server/activate-log.mjs +66 -0
- package/node_modules/@capyclaw/wall-workbench/server/constants.mjs +12 -0
- package/node_modules/@capyclaw/wall-workbench/server/contract.mjs +12 -0
- package/node_modules/@capyclaw/wall-workbench/server/embedded-host.mjs +162 -0
- package/node_modules/@capyclaw/wall-workbench/server/infra/http.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/infra/tuning.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/relay.mjs +68 -0
- package/node_modules/@capyclaw/wall-workbench/server/routes/claim.mjs +46 -0
- package/node_modules/@capyclaw/wall-workbench/server/routes/workbench.mjs +29 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/SHARED_MANIFEST.json +70 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/asset-service.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/editor-host.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/editor/lease.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/api.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/http.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/mcp-http.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tools/validate.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tuning.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/kit/util/fs-lock.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/service-host.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/tool-host.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/shared/tuning.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/tools/capabilities/index.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/tools/index.mjs +12 -0
- package/node_modules/@capyclaw/wall-workbench/server/tools.mjs +2 -0
- package/node_modules/@capyclaw/wall-workbench/server/workbench-framework.mjs +339 -0
- package/node_modules/@capyclaw/wall-workbench/ui/app.js +225 -0
- package/node_modules/@capyclaw/wall-workbench/ui/index.html +20 -0
- package/node_modules/@capyclaw/wall-workbench/ui/style.css +77 -0
- package/package.json +72 -4
- package/services.json +3 -0
|
@@ -0,0 +1,1290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/service-broker 引擎:服务编排核心。
|
|
3
|
+
*
|
|
4
|
+
* 职责边界(对应服务解耦标准):
|
|
5
|
+
* - 接收「结构化命令」(清单或外部投递),把每个服务作为**独立进程**拉起;
|
|
6
|
+
* - 服务之间不互相感知、不互相带动;跨端口组织只发生在这里;
|
|
7
|
+
* - 复用优先:目标端口已有健康实例(/healthz 且带 pid)则收编不重启;
|
|
8
|
+
* - keepAlive 守护:进程死亡自动按原端口重启(限次);
|
|
9
|
+
* - 运行事实写入 discovery 注册表(discovery.mjs),供 UI/侧栏/外部查询。
|
|
10
|
+
*
|
|
11
|
+
* 引擎不 import 任何 dsh 代码:embedded(cordis 插件壳)与 standalone
|
|
12
|
+
* (server.mjs)两种形态共用这一份逻辑。
|
|
13
|
+
*/
|
|
14
|
+
import fs from 'node:fs'
|
|
15
|
+
import net from 'node:net'
|
|
16
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
17
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
18
|
+
import os from 'node:os'
|
|
19
|
+
import path from 'node:path'
|
|
20
|
+
import { loadDiscovery, saveDiscovery, withDiscoveryLock } from './discovery.mjs'
|
|
21
|
+
import { marker, markerAsync, absent, receiptPath, writeReceipt, removeReceipt, receiptResolvable, waitReceiptResolvable } from './recovery.mjs'
|
|
22
|
+
|
|
23
|
+
const VAR_RE = /\$\{([^{}]+)\}/g
|
|
24
|
+
const IS_WIN = process.platform === 'win32'
|
|
25
|
+
/* 旧版本实例替换的限流窗口:窗口内超过次数就停止替换并报错,避免重启风暴。 */
|
|
26
|
+
const RETIRE_WINDOW_MS = 10 * 60 * 1000
|
|
27
|
+
const MAX_RETIRES = 3
|
|
28
|
+
|
|
29
|
+
/* ------------------------------------------------------------------ *
|
|
30
|
+
* 基础探测原语(与 @capyclaw/suite-kit/src/runtime.mjs 同口径)
|
|
31
|
+
* ------------------------------------------------------------------ */
|
|
32
|
+
|
|
33
|
+
export function pidAlive(pid) {
|
|
34
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
35
|
+
try { process.kill(pid, 0); return true } catch (err) { return err.code === 'EPERM' }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// OS creation identity, not a health endpoint's self-reported PID. Unsupported or
|
|
39
|
+
// inaccessible platforms deliberately return null and cannot authorize a kill.
|
|
40
|
+
export function processIdentity(pid) {
|
|
41
|
+
return marker(pid)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 异步版身份查询:不阻塞事件循环(Windows marker 单次约 900ms,同步会冻结整个宿主)。
|
|
45
|
+
* 所有 async 路径一律用它;同步 processIdentity 仅为兼容保留。 */
|
|
46
|
+
export async function processIdentityAsync(pid) {
|
|
47
|
+
return markerAsync(pid)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function canConnect(port, timeoutMs = 800) {
|
|
51
|
+
return new Promise((resolve) => {
|
|
52
|
+
const socket = net.connect({ port, host: '127.0.0.1' })
|
|
53
|
+
const done = (ok) => { try { socket.destroy() } catch { /* 已销毁 */ } resolve(ok) }
|
|
54
|
+
socket.setTimeout(timeoutMs)
|
|
55
|
+
socket.once('connect', () => done(true))
|
|
56
|
+
socket.once('timeout', () => done(false))
|
|
57
|
+
socket.once('error', () => done(false))
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** bind :0 取一个当前空闲端口(分配后立刻释放,存在理论竞争,和 works_runtime 同口径)。 */
|
|
62
|
+
export function allocatePort() {
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
const server = net.createServer()
|
|
65
|
+
server.once('error', reject)
|
|
66
|
+
server.listen(0, '127.0.0.1', () => {
|
|
67
|
+
const { port } = server.address()
|
|
68
|
+
server.close(() => resolve(port))
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function probeHttp(url, timeoutMs = 1500) {
|
|
74
|
+
try {
|
|
75
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) })
|
|
76
|
+
return { ok: res.ok, status: res.status, body: await res.text() }
|
|
77
|
+
} catch {
|
|
78
|
+
return { ok: false, status: 0, body: '' }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 健康探测并尽力取回对端自报的 pid(服务标准:/healthz 带 pid 字段)。
|
|
83
|
+
* 返回:null=不健康;-1=健康但无 pid;>0=健康且自报 pid。 */
|
|
84
|
+
export async function healthzPid(url, timeoutMs = 1500) {
|
|
85
|
+
const hit = await probeHttp(url, timeoutMs)
|
|
86
|
+
if (!hit.ok) return null
|
|
87
|
+
try {
|
|
88
|
+
const parsed = JSON.parse(hit.body)
|
|
89
|
+
return Number.isInteger(parsed?.pid) && parsed.pid > 0 ? parsed.pid : -1
|
|
90
|
+
} catch {
|
|
91
|
+
return -1
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/* ------------------------------------------------------------------ *
|
|
96
|
+
* 规格规范化与 ${VAR} 展开(与桌面后端 works_services 契约对齐)
|
|
97
|
+
* ------------------------------------------------------------------ */
|
|
98
|
+
|
|
99
|
+
export function normalizeSpec(raw) {
|
|
100
|
+
if (!raw || typeof raw !== 'object') throw new Error('service spec 必须是对象')
|
|
101
|
+
const spec = { ...raw }
|
|
102
|
+
if (typeof spec.id !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/i.test(spec.id)) {
|
|
103
|
+
throw new Error(`service spec.id 非法: ${JSON.stringify(spec?.id)}`)
|
|
104
|
+
}
|
|
105
|
+
if (spec.cmd !== undefined) {
|
|
106
|
+
if (!Array.isArray(spec.cmd) || !spec.cmd.length || !spec.cmd.every((a) => typeof a === 'string')) {
|
|
107
|
+
throw new Error(`service ${spec.id}: cmd 必须是非空字符串数组`)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (spec.requires !== undefined && !Array.isArray(spec.requires)) {
|
|
111
|
+
throw new Error(`service ${spec.id}: requires 必须是数组`)
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
cmd: undefined,
|
|
115
|
+
env: {},
|
|
116
|
+
cwd: undefined,
|
|
117
|
+
ports: {},
|
|
118
|
+
url: undefined,
|
|
119
|
+
healthPath: '/healthz',
|
|
120
|
+
keepAlive: true,
|
|
121
|
+
requires: [],
|
|
122
|
+
logFile: undefined,
|
|
123
|
+
...spec,
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function specHash(spec) {
|
|
128
|
+
const pick = (({ cmd, env, cwd, ports, url, healthPath }) =>
|
|
129
|
+
JSON.stringify({ cmd, env, cwd, ports, url, healthPath }))(spec)
|
|
130
|
+
return Buffer.from(pick).toString('base64url')
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** ${VAR} 展开:ctx 缺失的变量 → 空串(诚实降级,与桌面后端同口径)。 */
|
|
134
|
+
export function expandVars(value, ctx) {
|
|
135
|
+
return String(value).replace(VAR_RE, (_, name) => (name in ctx ? String(ctx[name]) : ''))
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function expandSpec(spec, ctx) {
|
|
139
|
+
const out = { ...spec, env: { ...spec.env } }
|
|
140
|
+
if (Array.isArray(out.cmd)) out.cmd = out.cmd.map((a) => expandVars(a, ctx))
|
|
141
|
+
for (const key of ['url', 'cwd', 'logFile']) {
|
|
142
|
+
if (typeof out[key] === 'string') out[key] = expandVars(out[key], ctx)
|
|
143
|
+
}
|
|
144
|
+
for (const [k, v] of Object.entries(out.env)) out.env[k] = expandVars(v, ctx)
|
|
145
|
+
return out
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/* ------------------------------------------------------------------ *
|
|
149
|
+
* 引擎
|
|
150
|
+
* ------------------------------------------------------------------ */
|
|
151
|
+
|
|
152
|
+
export class ServiceEngine {
|
|
153
|
+
/**
|
|
154
|
+
* @param {{
|
|
155
|
+
* discoveryPath?: string, // discovery 注册表落点,缺省 ~/.dsh/services.json
|
|
156
|
+
* logDir?: string, // 预留:服务日志落点,缺省 <discovery 目录>/logs
|
|
157
|
+
* log?: (msg: string) => void,
|
|
158
|
+
* defaultWaitMs?: number,
|
|
159
|
+
* }} options
|
|
160
|
+
*/
|
|
161
|
+
constructor(options = {}) {
|
|
162
|
+
// discovery 是用户级事实表:固定 ~/.dsh/services.json(DSH_DISCOVERY_FILE
|
|
163
|
+
// 可覆盖)。不随 DSH_HOME 走——broker 可能由网关拉起(无 DSH_HOME),
|
|
164
|
+
// 而 dsh 内的消费者(侧栏等)带着自己的 DSH_HOME,两边必须指向同一张表。
|
|
165
|
+
const discoveryPath = options.discoveryPath
|
|
166
|
+
|| process.env.DSH_DISCOVERY_FILE
|
|
167
|
+
|| path.join(os.homedir(), '.dsh', 'services.json')
|
|
168
|
+
this.discoveryPath = discoveryPath
|
|
169
|
+
this.logDir = options.logDir || path.join(path.dirname(discoveryPath), 'logs')
|
|
170
|
+
this.log = options.log || ((msg) => console.log(`[service-broker] ${msg}`))
|
|
171
|
+
this.defaultWaitMs = options.defaultWaitMs ?? 20000
|
|
172
|
+
this._guardTimer = null
|
|
173
|
+
this._guardFailures = new Map() // id → 连续重启次数
|
|
174
|
+
this._lastSpecs = new Map() // id → 最近一次 up 的原始 spec(守护重启用)
|
|
175
|
+
/* 规格落盘:宿主重启后即使清单暂时读不到(BOM/路径变化/开机竞态),
|
|
176
|
+
* 守护仍知道怎么把 keepAlive 服务拉回来。持久化只存 JSON 化的 spec。 */
|
|
177
|
+
this._specsPath = options.specsPath || `${discoveryPath}.specs.json`
|
|
178
|
+
this._restoreSpecs()
|
|
179
|
+
this._upLocks = new Map() // id → 启动互斥尾(同 id 并发 up 排队)
|
|
180
|
+
this._regLock = null // 注册表读-改-写互斥尾
|
|
181
|
+
this._stopping = false
|
|
182
|
+
this._owned = new Map() // per-engine authority, never restored from discovery
|
|
183
|
+
// 替换旧版本实例的限流表:id → 最近替换时间戳。
|
|
184
|
+
this._retires = new Map()
|
|
185
|
+
// 自愈监督:id → 连续不健康次数(进程活着但服务不可用)。
|
|
186
|
+
this._unhealthy = new Map()
|
|
187
|
+
// 深探节流:id → 上次健康/工具探测时间。
|
|
188
|
+
this._lastProbe = new Map()
|
|
189
|
+
// 重启退避:id → 上次自动重启尝试时间(崩溃循环不再每 2s 硬拉一次)。
|
|
190
|
+
this._lastRestart = new Map()
|
|
191
|
+
// error 态恢复:id → { count, lastAt }(冷却指数翻倍,不再永久移出扫描)。
|
|
192
|
+
this._errorRetries = new Map()
|
|
193
|
+
// broker 自身的创建身份在本进程生命周期内不变;Windows 上 marker() 约 900ms,
|
|
194
|
+
// 每次 up 重算会白烧近 1 秒。null 时不缓存(瞬时查询失败可重试)。
|
|
195
|
+
this._brokerMarker = null
|
|
196
|
+
// 服务日志按大小轮转,避免长期运行把磁盘写满。
|
|
197
|
+
this.maxLogBytes = Number(options.maxLogBytes) || 8 * 1024 * 1024
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* 打开服务日志并写一行 spawn 头,返回 fd;失败返回 null(退化为丢弃输出,
|
|
202
|
+
* 但绝不影响拉起)。
|
|
203
|
+
*/
|
|
204
|
+
_openServiceLog(logFile, cmd) {
|
|
205
|
+
try {
|
|
206
|
+
fs.mkdirSync(path.dirname(logFile), { recursive: true })
|
|
207
|
+
let size = 0
|
|
208
|
+
try { size = fs.statSync(logFile).size } catch { /* 不存在 */ }
|
|
209
|
+
if (size > this.maxLogBytes) {
|
|
210
|
+
try { fs.renameSync(logFile, `${logFile}.1`) } catch { /* 轮转失败不致命 */ }
|
|
211
|
+
}
|
|
212
|
+
const fd = fs.openSync(logFile, 'a')
|
|
213
|
+
fs.writeSync(fd, `\n===== ${new Date().toISOString()} spawn: ${cmd.join(' ')} =====\n`)
|
|
214
|
+
return fd
|
|
215
|
+
} catch {
|
|
216
|
+
return null
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/* ---------- discovery / 状态 ---------- */
|
|
221
|
+
|
|
222
|
+
/** 注册表读-改-写互斥:并发的 adopt/stop/守护标记在同一把进程内锁里排队,
|
|
223
|
+
* 保证后写者基于前写者的结果(否则并发拉起会互相覆盖丢行)。
|
|
224
|
+
* 进程内锁之外再套跨进程文件锁:embedded + standalone / 双 profile 共享同一
|
|
225
|
+
* services.json 时,读-改-写整体原子,杜绝跨进程 lost update(P1-2)。 */
|
|
226
|
+
_locked(fn) {
|
|
227
|
+
const runLocked = () => withDiscoveryLock(this.discoveryPath, fn)
|
|
228
|
+
const run = (this._regLock = this._regLock || Promise.resolve()).then(runLocked, runLocked)
|
|
229
|
+
this._regLock = run.then(() => {}, () => {})
|
|
230
|
+
return run
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async _loadRegistry() {
|
|
234
|
+
const reg = await loadDiscovery(this.discoveryPath)
|
|
235
|
+
return reg?.services && typeof reg.services === 'object' ? reg.services : {}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async _saveRegistry(services) {
|
|
239
|
+
await saveDiscovery(this.discoveryPath, {
|
|
240
|
+
version: 1,
|
|
241
|
+
updatedAt: new Date().toISOString(),
|
|
242
|
+
services,
|
|
243
|
+
})
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
async list() {
|
|
247
|
+
const services = await this._loadRegistry()
|
|
248
|
+
return Object.values(services).map((row) => ({
|
|
249
|
+
...row,
|
|
250
|
+
running: row.state === 'running' && pidAlive(row.pid),
|
|
251
|
+
}))
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async statusOf(id) {
|
|
255
|
+
const row = (await this._loadRegistry())[id]
|
|
256
|
+
return row ? { ...row, running: row.state === 'running' && pidAlive(row.pid) } : null
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** 最近一次 up/收编用过的规格(内存),供控制面按 id 重放启动。注册表行不含 cmd,
|
|
260
|
+
* 死行要重启只能靠这里或开机清单(P1-5)。 */
|
|
261
|
+
specOf(id) {
|
|
262
|
+
return this._lastSpecs.get(id) || null
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async doctor(id) {
|
|
266
|
+
const row = await this.statusOf(id)
|
|
267
|
+
if (!row) return { id, state: 'unknown', issues: ['discovery 无此服务记录'] }
|
|
268
|
+
const issues = []
|
|
269
|
+
if (!pidAlive(row.pid)) issues.push(`pid ${row.pid ?? '-'} 不存活`)
|
|
270
|
+
const health = row.url ? await healthzPid(this._healthUrl(row)) : null
|
|
271
|
+
if (health === null) issues.push('健康端点无响应')
|
|
272
|
+
return { ...row, issues, healthy: issues.length === 0 }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 健康端点完整地址(discovery 行带自己当初的 healthPath)。 */
|
|
276
|
+
_healthUrl(row) {
|
|
277
|
+
return row.url + (row.healthPath || '/healthz')
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/* ---------- 端口与占位符 ---------- */
|
|
281
|
+
|
|
282
|
+
async _resolvePorts(spec) {
|
|
283
|
+
const ports = {}
|
|
284
|
+
const declared = spec.ports && typeof spec.ports === 'object' ? spec.ports : {}
|
|
285
|
+
const names = Object.keys(declared)
|
|
286
|
+
if (!names.includes('main')) names.push('main')
|
|
287
|
+
for (const name of names) {
|
|
288
|
+
const want = declared[name]
|
|
289
|
+
if (want === 'auto' || want === undefined || want === null || want === '') {
|
|
290
|
+
ports[name] = await allocatePort()
|
|
291
|
+
continue
|
|
292
|
+
}
|
|
293
|
+
const num = Number(want)
|
|
294
|
+
if (!Number.isInteger(num) || num <= 0) throw new Error(`service ${spec.id}: 端口 ${name}=${want} 非法`)
|
|
295
|
+
ports[name] = num
|
|
296
|
+
}
|
|
297
|
+
return ports
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
_placeholderCtx(ports) {
|
|
301
|
+
const ctx = {}
|
|
302
|
+
for (const [name, port] of Object.entries(ports || {})) {
|
|
303
|
+
ctx[name === 'main' ? 'PORT' : `PORT_${name.toUpperCase()}`] = String(port)
|
|
304
|
+
}
|
|
305
|
+
return ctx
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
_urlFor(spec, ports) {
|
|
309
|
+
const main = ports.main
|
|
310
|
+
if (!main) throw new Error(`service ${spec.id}: 缺少主端口`)
|
|
311
|
+
return spec.url
|
|
312
|
+
? expandVars(spec.url, this._placeholderCtx(ports)).replace(/\/$/, '')
|
|
313
|
+
: `http://127.0.0.1:${main}`
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/* ---------- 拉起 / 复用 ---------- */
|
|
317
|
+
|
|
318
|
+
/** 同一服务的并发 up 必须排队:首个执行拉起,其余落到复用路径。
|
|
319
|
+
* 否则竞态下会各自分配端口各自 spawn,制造出 N 个"同名服务"。
|
|
320
|
+
* 锁表按 id 保留(服务数量有限,不做清理)。 */
|
|
321
|
+
up(rawSpec, { waitMs } = {}) {
|
|
322
|
+
const id = rawSpec && rawSpec.id
|
|
323
|
+
const prev = this._upLocks.get(id) || Promise.resolve()
|
|
324
|
+
const run = prev.catch(() => {}).then(() => this._upOnce(rawSpec, { waitMs }))
|
|
325
|
+
this._upLocks.set(id, run.catch(() => {}))
|
|
326
|
+
return run
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async _upOnce(rawSpec, { waitMs } = {}) {
|
|
330
|
+
if (this._stopping) throw new Error('service broker 正在卸载,拒绝启动新服务')
|
|
331
|
+
const spec = normalizeSpec(rawSpec)
|
|
332
|
+
const id = spec.id
|
|
333
|
+
const wait = waitMs ?? this.defaultWaitMs
|
|
334
|
+
const deadline = Date.now() + wait
|
|
335
|
+
|
|
336
|
+
// A previous broker's unresolved spawn cannot be made safe by a healthy
|
|
337
|
+
// endpoint. Only this engine's own verified process may bypass the receipt.
|
|
338
|
+
const prev = (await this._loadRegistry())[id]
|
|
339
|
+
if (existsSync(receiptPath(this.discoveryPath, id))) {
|
|
340
|
+
let existing
|
|
341
|
+
try { existing = JSON.parse(readFileSync(receiptPath(this.discoveryPath, id), 'utf8')) } catch {}
|
|
342
|
+
const owned = this._owned.get(id)
|
|
343
|
+
const local = existing?.state === 'spawned' && existing.brokerPid === process.pid && existing.pid === owned?.pid && existing.identity === owned?.identity && owned?.identity && (await processIdentityAsync(owned.pid)) === owned.identity
|
|
344
|
+
const liveOwner = existing?.id === id && existing.state === 'spawned' && existing.brokerMarker && (await markerAsync(existing.brokerPid)) === existing.brokerMarker && prev?.state === 'running' && prev.ownership === 'owned' && prev.pid === existing.pid && existing.identity && (await processIdentityAsync(existing.pid)) === existing.identity
|
|
345
|
+
if (!local && !liveOwner) {
|
|
346
|
+
/* 跨进程重启:上一代 broker 已经不在了,但它拉起的 keepAlive 服务还活着
|
|
347
|
+
* (detached + 独立端口正是设计意图)。此时收据不是"未解决的 spawn",
|
|
348
|
+
* 而是一份可验证的归属证据:进程身份仍与收据记录一致、健康端点也响应。
|
|
349
|
+
* 这种形态必须接管,否则每次 DSH 重启都会被自己的收据挡死。 */
|
|
350
|
+
const adoptable = existing?.state === 'spawned'
|
|
351
|
+
&& Number.isInteger(existing.pid) && existing.pid > 0
|
|
352
|
+
&& existing.identity
|
|
353
|
+
&& (await processIdentityAsync(existing.pid)) === existing.identity
|
|
354
|
+
/* 收编前必须先核版本:上一代留下的可能是旧版本实例。若 expect.version 不符,
|
|
355
|
+
* 不能静默收编(那会绕过升级、且删掉收据后永远无法证明归属→停不掉也升不了)。
|
|
356
|
+
* 收据此时仍可证明归属(adoptable 已核验 identity),交给 _retireStaleInstance
|
|
357
|
+
* 替换后再走正常拉起。retireHandled 用于跳过下方「死根收据作废」分支。 */
|
|
358
|
+
let retireHandled = false
|
|
359
|
+
if (adoptable) {
|
|
360
|
+
const port = existing.ports?.main
|
|
361
|
+
if (Number.isInteger(port) && port > 0) {
|
|
362
|
+
const url = (spec.url ? expandVars(spec.url, this._placeholderCtx({ main: port })) : `http://127.0.0.1:${port}`).replace(/\/$/, '')
|
|
363
|
+
const healthUrl = url + (spec.healthPath || '/healthz')
|
|
364
|
+
const pid = await healthzPid(healthUrl)
|
|
365
|
+
if (pid !== null) {
|
|
366
|
+
const body = await this._healthBody(healthUrl)
|
|
367
|
+
const expectVersion = spec.expect?.version
|
|
368
|
+
const staleVersion = !!expectVersion && !!body && this._isOwnHealth(id, body)
|
|
369
|
+
&& !!body.version && body.version !== expectVersion
|
|
370
|
+
if (staleVersion) {
|
|
371
|
+
this.log(`⟳ ${id} 接管发现旧版本 ${body.version}(期望 ${expectVersion}),保留收据先替换再拉起`)
|
|
372
|
+
await this._retireStaleInstance(id, spec, port)
|
|
373
|
+
retireHandled = true
|
|
374
|
+
/* retire 成功已删收据并释放端口;不 return,落到下方正常 spawn。 */
|
|
375
|
+
} else {
|
|
376
|
+
this._guardFailures.delete(id)
|
|
377
|
+
this.log(`✓ ${id} 接管上一代 broker 留下的存活实例 ${url}(pid ${pid > 0 ? pid : '未知'})`)
|
|
378
|
+
this._lastSpecs.set(id, spec)
|
|
379
|
+
/* 收据身份已核验且 healthz 自报 pid 吻合 → 恢复 owned 权威(而非 borrowed),
|
|
380
|
+
* 否则重启后服务停不掉、shutdown stopAll 也停不掉(P1-1)。 */
|
|
381
|
+
const adoptedIdentity = pid === existing.pid ? existing.identity : null
|
|
382
|
+
if (adoptedIdentity) {
|
|
383
|
+
/* 收据是跨重启的唯一归属证明,owned 接管绝不能删它——否则下一次重启
|
|
384
|
+
* 就没有收据、退化成 registry-reuse 的 borrowed(owned 只活一次重启)。
|
|
385
|
+
* 把收据刷新到当前 broker 名下,让归属无限次跨重启延续。 */
|
|
386
|
+
const brokerMarker = this._brokerMarker ?? (this._brokerMarker = await markerAsync(process.pid))
|
|
387
|
+
writeReceipt(this.discoveryPath, id, {
|
|
388
|
+
id, brokerPid: process.pid, brokerMarker, ports: existing.ports || { main: port },
|
|
389
|
+
state: 'spawned', pid: existing.pid, identity: adoptedIdentity,
|
|
390
|
+
})
|
|
391
|
+
} else {
|
|
392
|
+
/* healthz 自报 pid 与收据不符:证明不了归属,按 borrowed 收编并清收据。 */
|
|
393
|
+
removeReceipt(this.discoveryPath, id)
|
|
394
|
+
}
|
|
395
|
+
return this._adopt(id, spec, url, pid, existing.ports || { main: port }, true, undefined, adoptedIdentity)
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
// A dead root whose declared ports are all free left nothing of this
|
|
401
|
+
// service behind; keeping the receipt would block the product forever.
|
|
402
|
+
if (!retireHandled) {
|
|
403
|
+
if (await receiptResolvable(existing, prev?.ports)) removeReceipt(this.discoveryPath, id)
|
|
404
|
+
else throw new Error(`service ${id}: 存在未解决的归属记录,拒绝启动或收编`)
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// 1) 套件升级后残留的旧版本实例:先替换,再走正常的复用/拉起。
|
|
410
|
+
// keepAlive 让旧 relay 在插件卸载后继续占着固定端口,而 relay 的复用校验
|
|
411
|
+
// 是「同版本才复用」,于是新版本要么被旧版本顶住、要么直接启动失败。
|
|
412
|
+
// 这里在拉起前把"我们自己留下的旧版本"换掉,避免升级必然要求人工杀进程。
|
|
413
|
+
{
|
|
414
|
+
const probePort = prev?.ports?.main ?? (Number.isInteger(spec.ports?.main) ? spec.ports.main : null)
|
|
415
|
+
if (probePort) await this._retireStaleInstance(id, spec, probePort)
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// 2) 复用优先:discovery 有存活记录且健康端点有响应 → 收编,不重启
|
|
419
|
+
if (prev?.url && prev.state === 'running') {
|
|
420
|
+
const pid = await healthzPid(this._healthUrl(prev))
|
|
421
|
+
if (pid !== null) {
|
|
422
|
+
/* ${PACKAGE_DIR} 是清单级变量:loadManifest 开机时已展开成绝对路径,引擎无法
|
|
423
|
+
* 复现该展开。若传入的仍是含 ${PACKAGE_DIR} 的原始模板,与已展开的 prev.specHash
|
|
424
|
+
* 哈希基线不同,比较会假阳性(把同一配置误判成变更)。此时跳过比较按原样复用;
|
|
425
|
+
* 真正改配置(展开后的 cmd/env 不同)仍会被检出。 */
|
|
426
|
+
const incomingHasPkgDir = Array.isArray(spec.cmd) && spec.cmd.some((a) => String(a).includes('${PACKAGE_DIR}'))
|
|
427
|
+
const configChanged = !incomingHasPkgDir && !!prev.specHash && prev.specHash !== specHash(spec)
|
|
428
|
+
if (!configChanged) {
|
|
429
|
+
this._guardFailures.delete(id)
|
|
430
|
+
this.log(`✓ ${id} 复用已运行实例 ${prev.url}(pid ${pid > 0 ? pid : '未知'})`)
|
|
431
|
+
this._lastSpecs.set(id, spec)
|
|
432
|
+
return this._adopt(id, spec, prev.url, pid, prev.ports, true)
|
|
433
|
+
}
|
|
434
|
+
/* 配置已变更(cmd/env/ports/url/healthPath):绝不静默复用旧进程冒充新配置(P1-4)。
|
|
435
|
+
* 能证明归属就替换后重新拉起;证明不了就诚实标记 staleConfig,绝不谎报成功。 */
|
|
436
|
+
this.log(`⟳ ${id} 运行中实例配置已变更(specHash 不符),尝试替换旧进程 pid ${pid}`)
|
|
437
|
+
const replaced = await this._replaceIfProvable(id, pid)
|
|
438
|
+
if (!replaced) {
|
|
439
|
+
this.log(`! ${id} 配置已变更但无法证明旧实例归属,保留运行并标记 staleConfig`)
|
|
440
|
+
this._lastSpecs.set(id, spec)
|
|
441
|
+
const row = await this._adopt(id, spec, prev.url, pid, prev.ports, true)
|
|
442
|
+
return { ...row, staleConfig: true }
|
|
443
|
+
}
|
|
444
|
+
this._guardFailures.delete(id)
|
|
445
|
+
/* 替换成功 → 落到下方正常 spawn 拉起新配置。 */
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// 2) 按声明解析端口 → 展开占位符 → 校验 → spawn
|
|
450
|
+
const ports = await this._resolvePorts(spec)
|
|
451
|
+
const ctx = { ...process.env, ...spec.env, ...this._placeholderCtx(ports) }
|
|
452
|
+
const expanded = expandSpec(spec, ctx)
|
|
453
|
+
if (!Array.isArray(expanded.cmd) || !expanded.cmd.length) {
|
|
454
|
+
throw new Error(`service ${id}: 缺少 cmd,无法拉起`)
|
|
455
|
+
}
|
|
456
|
+
const exe = expanded.cmd[0]
|
|
457
|
+
// 绝对路径不存在 → 诚实报错(${VAR} 展开失败最常见的样子);
|
|
458
|
+
// 裸命令名(node/npx…)交给 PATH 解析,spawn 失败会在下面捕获。
|
|
459
|
+
if (/^([a-z]:\\|\/)/i.test(exe) && !existsSync(exe)) {
|
|
460
|
+
throw new Error(`service ${id}: cmd 可执行文件不存在: ${exe}`)
|
|
461
|
+
}
|
|
462
|
+
const url = this._urlFor(expanded, ports)
|
|
463
|
+
const healthUrl = url + (expanded.healthPath || '/healthz')
|
|
464
|
+
|
|
465
|
+
// 目标端口已被占但非本服务(健康端点无响应)→ 不抢,诚实失败
|
|
466
|
+
if (await canConnect(ports.main)) {
|
|
467
|
+
const pid = await healthzPid(healthUrl)
|
|
468
|
+
if (pid === null) throw new Error(`service ${id}: 端口 ${ports.main} 已被其他进程占用`)
|
|
469
|
+
/* 健康≠是我们的:端口上可能跑着别的服务。收编前必须核对自报身份,否则
|
|
470
|
+
* 会把别人的进程记成自己的服务,后续 stop/重启都会打在错误目标上。 */
|
|
471
|
+
const body = await this._healthBody(healthUrl)
|
|
472
|
+
if (!this._isOwnHealth(id, body)) {
|
|
473
|
+
throw new Error(
|
|
474
|
+
`service ${id}: 端口 ${ports.main} 被另一个服务占用(自报 ${body?.service || body?.bridge || '未知'});拒绝收编`,
|
|
475
|
+
)
|
|
476
|
+
}
|
|
477
|
+
// 健康但 discovery 无记录(比如 broker 换了 discovery 文件)→ 收编
|
|
478
|
+
this.log(`✓ ${id} 端口上发现健康实例,收编 ${url}`)
|
|
479
|
+
this._lastSpecs.set(id, spec)
|
|
480
|
+
return this._adopt(id, spec, url, pid, ports, true)
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// Never overwrite an unresolved receipt, including a crash in the spawn window.
|
|
484
|
+
if (existsSync(receiptPath(this.discoveryPath, id))) throw new Error(`service ${id}: 存在未解决的归属记录,拒绝启动`)
|
|
485
|
+
/* 卸载竞态:boot/控制请求的在途 up 可能在 dispose 之后才走到 spawn;这里再查一次,
|
|
486
|
+
* 避免宿主已卸载却又拉起一个没人管的新服务(P1-10)。 */
|
|
487
|
+
if (this._stopping) throw new Error('service broker 正在卸载,拒绝启动新服务')
|
|
488
|
+
if (!this._brokerMarker) this._brokerMarker = await markerAsync(process.pid)
|
|
489
|
+
const brokerMarker = this._brokerMarker
|
|
490
|
+
if (!brokerMarker) throw new Error(`service ${id}: 无法验证 broker 身份,拒绝启动`)
|
|
491
|
+
const receipt = { id, brokerPid: process.pid, brokerMarker, ports, state: 'pending' }
|
|
492
|
+
writeReceipt(this.discoveryPath, id, receipt)
|
|
493
|
+
const logFile = expanded.logFile || path.join(this.logDir, `service-${id}.log`)
|
|
494
|
+
this.log(`⏏ 拉起 ${id}: ${expanded.cmd.join(' ')}(日志 ${logFile})`)
|
|
495
|
+
/* 子进程输出必须落盘:历史上 stdio:'ignore' 把「为什么起不来」一起丢掉,
|
|
496
|
+
* 报错信息里写着日志路径、那个文件却永远不存在——故障不可取证。 */
|
|
497
|
+
const logFd = this._openServiceLog(logFile, expanded.cmd)
|
|
498
|
+
let child
|
|
499
|
+
try {
|
|
500
|
+
child = spawn(expanded.cmd[0], expanded.cmd.slice(1), {
|
|
501
|
+
cwd: expanded.cwd || undefined,
|
|
502
|
+
env: ctx,
|
|
503
|
+
detached: true,
|
|
504
|
+
/* 用文件 fd 而不是管道:管道在受限环境下会被拒绝(EPERM),
|
|
505
|
+
* 且父进程退出后子进程写管道会 EPIPE。 */
|
|
506
|
+
stdio: logFd === null ? 'ignore' : ['ignore', logFd, logFd],
|
|
507
|
+
windowsHide: true,
|
|
508
|
+
})
|
|
509
|
+
} catch (err) {
|
|
510
|
+
if (logFd !== null) { try { fs.closeSync(logFd) } catch { /* 已关闭 */ } }
|
|
511
|
+
removeReceipt(this.discoveryPath, id)
|
|
512
|
+
throw new Error(`service ${id}: spawn 失败: ${err.message}`)
|
|
513
|
+
}
|
|
514
|
+
if (logFd !== null) { try { fs.closeSync(logFd) } catch { /* 子进程已持副本 */ } }
|
|
515
|
+
// Wait for the definitive spawn outcome before interpreting a missing PID.
|
|
516
|
+
// An asynchronous ENOENT has created no process and cannot leave descendants.
|
|
517
|
+
const spawnError = await new Promise((resolve) => {
|
|
518
|
+
child.once('spawn', () => resolve(null))
|
|
519
|
+
child.once('error', resolve)
|
|
520
|
+
})
|
|
521
|
+
// Retain an error listener after startup as ChildProcess may emit later errors.
|
|
522
|
+
child.on('error', () => {})
|
|
523
|
+
if (spawnError) {
|
|
524
|
+
if (!child.pid) removeReceipt(this.discoveryPath, id)
|
|
525
|
+
throw new Error(`service ${id}: spawn 失败: ${spawnError.message}`)
|
|
526
|
+
}
|
|
527
|
+
child.unref()
|
|
528
|
+
const childIdentity = await markerAsync(child.pid)
|
|
529
|
+
if (child.pid && childIdentity) writeReceipt(this.discoveryPath, id, { ...receipt, state: 'spawned', pid: child.pid, identity: childIdentity })
|
|
530
|
+
else if (!child.pid) removeReceipt(this.discoveryPath, id)
|
|
531
|
+
|
|
532
|
+
// 超时/早退时回收刚拉起的进程树——执行器不生产孤儿
|
|
533
|
+
const reapChild = async () => {
|
|
534
|
+
if (!childIdentity || (await processIdentityAsync(child.pid)) !== childIdentity) return false
|
|
535
|
+
if (IS_WIN) {
|
|
536
|
+
const result = spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10000 })
|
|
537
|
+
return result.status === 0
|
|
538
|
+
}
|
|
539
|
+
/* detached 子进程自成进程组:杀整组而非只杀根,避免孙进程泄漏。
|
|
540
|
+
* 回收是中止语境,直接 SIGKILL 组;组不存在(ESRCH)退化为杀根。 */
|
|
541
|
+
try { process.kill(-child.pid, 'SIGKILL'); return true } catch {
|
|
542
|
+
try { process.kill(child.pid, 'SIGKILL'); return true } catch { return false }
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// 3) 等健康
|
|
547
|
+
while (Date.now() < deadline) {
|
|
548
|
+
if (!pidAlive(child.pid)) {
|
|
549
|
+
/* 子进程退出 ≠ 服务失败:两种真实形态都要收编——
|
|
550
|
+
* a) allowReuse 服务发现端口上已有健康实例 → 直接返回并退出(relay reused 路径);
|
|
551
|
+
* b) 子进程派生/守护了真正的服务进程后自己退出(detached 孙进程还在启动)。
|
|
552
|
+
* 给一个短宽限窗持续探测健康端点,健康即收编,而不是把日志留成 error。
|
|
553
|
+
* (2026-11-02 稳定性测试实测;宽限窗上限 3s,避免病态服务拖长失败时间) */
|
|
554
|
+
const graceDeadline = Date.now() + Math.min(3000, Math.max(0, deadline - Date.now()))
|
|
555
|
+
for (;;) {
|
|
556
|
+
const adopted = await healthzPid(healthUrl)
|
|
557
|
+
if (adopted !== null) {
|
|
558
|
+
const body = await this._healthBody(healthUrl)
|
|
559
|
+
if (!this._isOwnHealth(id, body)) break // 端口上是别人的服务,别收编
|
|
560
|
+
this._guardFailures.delete(id)
|
|
561
|
+
this.log(`✓ ${id} 子进程退出但端口上已有健康实例,收编 ${url}`)
|
|
562
|
+
this._lastSpecs.set(id, spec)
|
|
563
|
+
// Adopted as borrowed: no receipt, because this engine never gains
|
|
564
|
+
// authority to stop the healthy instance it did not spawn.
|
|
565
|
+
removeReceipt(this.discoveryPath, id)
|
|
566
|
+
return this._adopt(id, spec, url, adopted, ports, true)
|
|
567
|
+
}
|
|
568
|
+
if (Date.now() >= graceDeadline) break
|
|
569
|
+
await new Promise((r) => setTimeout(r, 200))
|
|
570
|
+
}
|
|
571
|
+
// An exited wrapper may have left a daemon behind. Keep the receipt
|
|
572
|
+
// only while one of its declared ports is still occupied.
|
|
573
|
+
if (!(await receiptResolvable({ ...receipt, pid: child.pid, identity: childIdentity }, ports))) removeReceipt(this.discoveryPath, id)
|
|
574
|
+
else writeReceipt(this.discoveryPath, id, { ...receipt, state: 'unverified' })
|
|
575
|
+
throw new Error(`service ${id}: 进程在健康检查通过前退出(pid ${child.pid},日志 ${logFile})`)
|
|
576
|
+
}
|
|
577
|
+
const pid = await healthzPid(healthUrl)
|
|
578
|
+
if (pid !== null) {
|
|
579
|
+
/* 拉起后自报版本必须与 expect 一致。不一致说明生成器写错了 expect
|
|
580
|
+
* (例如套件版本与 workbench 包版本脱钩),此时如果放行,下一轮 up 又会
|
|
581
|
+
* 把它判成"旧版本"替换掉——变成重启死循环。这里一次性失败,别让它循环。 */
|
|
582
|
+
if (spec.expect?.version) {
|
|
583
|
+
const body = await this._healthBody(healthUrl)
|
|
584
|
+
if (body?.version && body.version !== spec.expect.version) {
|
|
585
|
+
/* 拉起成功但版本不对:立即回收这个进程,别让它占着端口继续骗人
|
|
586
|
+
* (否则下一轮会把它当"旧版本"再替换一次,形成重启风暴)。 */
|
|
587
|
+
await reapChild()
|
|
588
|
+
for (let i = 0; i < 30 && pidAlive(child.pid); i++) await new Promise((r) => setTimeout(r, 100))
|
|
589
|
+
if (child.pid && absent(child.pid)) removeReceipt(this.discoveryPath, id)
|
|
590
|
+
throw new Error(
|
|
591
|
+
`service ${id}: 拉起后自报版本 ${body.version} 与 expect.version ${spec.expect.version} 不一致;` +
|
|
592
|
+
`这是 services.json 生成错误(套件版本与 workbench 包版本脱钩),请修构建而不是重启`,
|
|
593
|
+
)
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
this._guardFailures.delete(id)
|
|
597
|
+
this.log(`✓ ${id} 就绪 ${url}(pid ${pid > 0 ? pid : '未知'})`)
|
|
598
|
+
this._lastSpecs.set(id, spec)
|
|
599
|
+
const owned = pid === child.pid && childIdentity && (await processIdentityAsync(child.pid)) === childIdentity
|
|
600
|
+
return this._adopt(id, spec, url, pid, ports, !owned, child.pid, owned ? childIdentity : null)
|
|
601
|
+
}
|
|
602
|
+
await new Promise((r) => setTimeout(r, 300))
|
|
603
|
+
}
|
|
604
|
+
/* 超时前最后一探:若健康端点已可用(服务慢启动/自治子进程),收编不杀。 */
|
|
605
|
+
const latePid = await healthzPid(healthUrl)
|
|
606
|
+
if (latePid !== null) {
|
|
607
|
+
this._guardFailures.delete(id)
|
|
608
|
+
this.log(`✓ ${id} 超时窗口后已就绪,收编 ${url}`)
|
|
609
|
+
this._lastSpecs.set(id, spec)
|
|
610
|
+
// Borrowed adoption: the healthy endpoint was not proven to be our child.
|
|
611
|
+
removeReceipt(this.discoveryPath, id)
|
|
612
|
+
return this._adopt(id, spec, url, latePid, ports, true)
|
|
613
|
+
}
|
|
614
|
+
const reaped = await reapChild()
|
|
615
|
+
if (!reaped) {
|
|
616
|
+
/* 身份不可验证 → 没杀成:僵尸可能仍占着端口。把收据降级 unverified 并写一条
|
|
617
|
+
* error 行,让 doctor/list/控制面看得见、可定位回收,而不是收据永久堵死后续
|
|
618
|
+
* 所有 up 却无人知晓(P1-9)。operator 手动结束僵尸后端口释放,下次 up 即可作废收据。 */
|
|
619
|
+
writeReceipt(this.discoveryPath, id, { ...receipt, state: 'unverified', pid: child.pid, identity: childIdentity })
|
|
620
|
+
await this._locked(async () => {
|
|
621
|
+
const services = await this._loadRegistry()
|
|
622
|
+
services[id] = {
|
|
623
|
+
id, state: 'error', url, pid: child.pid, ports, keepAlive: !!spec.keepAlive,
|
|
624
|
+
error: `健康检查超时且无法证明归属(pid ${child.pid}),未能安全回收;请手动结束该进程后重试`,
|
|
625
|
+
startedAt: new Date().toISOString(),
|
|
626
|
+
}
|
|
627
|
+
await this._saveRegistry(services)
|
|
628
|
+
})
|
|
629
|
+
}
|
|
630
|
+
// Sending a signal, or even observing the root exit, does not verify its
|
|
631
|
+
// descendants. Retain the original receipt and identity across restarts.
|
|
632
|
+
throw new Error(`service ${id}: ${Math.round(wait / 1000)}s 内未通过健康检查(${healthUrl},日志 ${logFile});${reaped ? '已发送停止请求,但子进程清理未验证' : '未能安全回收启动进程(已记 error 行,可见可回收)'}`)
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** /healthz 自报的服务身份是否就是本服务(防止把别人的端口误收编成自己的)。 */
|
|
636
|
+
_isOwnHealth(id, body) {
|
|
637
|
+
if (!body || typeof body !== 'object') return false
|
|
638
|
+
if (typeof body.service === 'string' && body.service !== id) return false
|
|
639
|
+
if (typeof body.bridge === 'string' && body.bridge !== id) return false
|
|
640
|
+
return true
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** 读一次 /healthz 的 JSON 体;不可用或非 JSON 返回 null。 */
|
|
644
|
+
async _healthBody(url) {
|
|
645
|
+
const hit = await probeHttp(url)
|
|
646
|
+
if (!hit.ok) return null
|
|
647
|
+
try { return JSON.parse(hit.body) } catch { return null }
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* 替换套件升级后残留的旧版本实例。
|
|
652
|
+
*
|
|
653
|
+
* keepAlive + 固定端口 + "同版本才复用" 组合起来,会让每次套件升级都要求人工
|
|
654
|
+
* 杀进程:旧 relay 还占着端口,新 relay 要么拒绝启动、要么被旧实例顶成假启动。
|
|
655
|
+
* 这里在拉起前识别并替换——但**只在能证明该进程由本套件拉起时**(收据里的 pid
|
|
656
|
+
* 与进程身份都吻合)。证明不了一律拒绝,绝不杀掉一个来历不明的进程。
|
|
657
|
+
*
|
|
658
|
+
* 另外带替换限流:如果 expect.version 写错了,无限制替换会变成重启风暴,
|
|
659
|
+
* 三次之后必须停下来报错,而不是把机器拖垮。
|
|
660
|
+
*/
|
|
661
|
+
async _retireStaleInstance(id, spec, port) {
|
|
662
|
+
const expectVersion = spec.expect?.version
|
|
663
|
+
if (!expectVersion) return { acted: false }
|
|
664
|
+
const base = (spec.url
|
|
665
|
+
? expandVars(spec.url, this._placeholderCtx({ main: port }))
|
|
666
|
+
: `http://127.0.0.1:${port}`).replace(/\/$/, '')
|
|
667
|
+
const body = await this._healthBody(base + (spec.healthPath || '/healthz'))
|
|
668
|
+
if (!body || !this._isOwnHealth(id, body)) return { acted: false }
|
|
669
|
+
const runningVersion = body.version
|
|
670
|
+
if (!runningVersion || runningVersion === expectVersion) return { acted: false }
|
|
671
|
+
|
|
672
|
+
const pid = Number(body.pid)
|
|
673
|
+
let receipt = null
|
|
674
|
+
try { receipt = JSON.parse(readFileSync(receiptPath(this.discoveryPath, id), 'utf8')) } catch { receipt = null }
|
|
675
|
+
const provable = Number.isInteger(pid) && pid > 0
|
|
676
|
+
&& receipt?.pid === pid && receipt?.identity
|
|
677
|
+
&& (await processIdentityAsync(pid)) === receipt.identity
|
|
678
|
+
if (!provable) {
|
|
679
|
+
throw new Error(
|
|
680
|
+
`service ${id}: 端口 ${port} 上是旧版本实例(pid ${Number.isInteger(pid) ? pid : '未知'},` +
|
|
681
|
+
`version ${runningVersion},期望 ${expectVersion}),但无法证明它由本套件拉起;` +
|
|
682
|
+
`拒绝杀掉外部进程,请手动结束后重试`,
|
|
683
|
+
)
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const now = Date.now()
|
|
687
|
+
const recent = (this._retires.get(id) || []).filter((at) => now - at < RETIRE_WINDOW_MS)
|
|
688
|
+
if (recent.length >= MAX_RETIRES) {
|
|
689
|
+
throw new Error(
|
|
690
|
+
`service ${id}: ${Math.round(RETIRE_WINDOW_MS / 60000)} 分钟内已替换旧版本实例 ${recent.length} 次,` +
|
|
691
|
+
`仍报告 version ${runningVersion}(期望 ${expectVersion});` +
|
|
692
|
+
`疑似 services.json 的 expect.version 写错,已停止替换以免重启风暴`,
|
|
693
|
+
)
|
|
694
|
+
}
|
|
695
|
+
recent.push(now)
|
|
696
|
+
this._retires.set(id, recent)
|
|
697
|
+
|
|
698
|
+
this.log(`⟳ ${id} 端口 ${port} 上是旧版本 ${runningVersion}(期望 ${expectVersion}),替换旧进程 pid ${pid}`)
|
|
699
|
+
if (IS_WIN) {
|
|
700
|
+
const r = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10000 })
|
|
701
|
+
if (r.status !== 0 && pidAlive(pid)) throw new Error(`service ${id}: 无法停止旧版本实例(pid ${pid})`)
|
|
702
|
+
} else {
|
|
703
|
+
try { process.kill(pid, 'SIGTERM') } catch (err) {
|
|
704
|
+
if (err.code !== 'ESRCH') throw new Error(`service ${id}: 无法停止旧版本实例: ${err.message}`)
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
for (let i = 0; i < 50 && pidAlive(pid); i++) await new Promise((r) => setTimeout(r, 100))
|
|
708
|
+
if (pidAlive(pid)) {
|
|
709
|
+
/* POSIX:SIGTERM 没杀死 → 升级 SIGKILL 进程组(detached 自成组,杀整组防孙进程)。
|
|
710
|
+
* 仍不死则**保留收据**并报错——绝不删收据,否则旧实例会被下一轮静默重新收编(P1-8)。 */
|
|
711
|
+
if (!IS_WIN) {
|
|
712
|
+
try { process.kill(-pid, 'SIGKILL') } catch { try { process.kill(pid, 'SIGKILL') } catch { /* ESRCH */ } }
|
|
713
|
+
for (let i = 0; i < 30 && pidAlive(pid); i++) await new Promise((r) => setTimeout(r, 100))
|
|
714
|
+
}
|
|
715
|
+
if (pidAlive(pid)) throw new Error(`service ${id}: 无法停止旧版本实例(pid ${pid}),已保留归属收据,请手动结束后重试`)
|
|
716
|
+
}
|
|
717
|
+
removeReceipt(this.discoveryPath, id)
|
|
718
|
+
// 端口释放可能滞后于进程退出,给一段有界等待,避免紧接着的 spawn 撞端口。
|
|
719
|
+
for (let i = 0; i < 30; i++) {
|
|
720
|
+
if (!(await canConnect(port))) break
|
|
721
|
+
await new Promise((r) => setTimeout(r, 100))
|
|
722
|
+
}
|
|
723
|
+
return { acted: true, from: runningVersion, to: expectVersion, pid }
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** 配置变更时替换旧实例:只在能证明归属(_owned 或收据身份吻合)时杀,杀整组防孙进程。
|
|
727
|
+
* 证明不了 / 杀不死 → 返回 false(调用方据此降级 staleConfig 告警,绝不冒充新配置)。 */
|
|
728
|
+
async _replaceIfProvable(id, pid) {
|
|
729
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
730
|
+
const owned = this._owned.get(id)
|
|
731
|
+
let identity = owned?.pid === pid ? owned.identity : null
|
|
732
|
+
if (!identity) {
|
|
733
|
+
try {
|
|
734
|
+
const r = JSON.parse(readFileSync(receiptPath(this.discoveryPath, id), 'utf8'))
|
|
735
|
+
if (r?.pid === pid) identity = r.identity
|
|
736
|
+
} catch { /* 无收据 */ }
|
|
737
|
+
}
|
|
738
|
+
if (!identity || (await processIdentityAsync(pid)) !== identity) return false
|
|
739
|
+
if (IS_WIN) {
|
|
740
|
+
const r = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10000 })
|
|
741
|
+
if (r.status !== 0 && pidAlive(pid)) return false
|
|
742
|
+
} else {
|
|
743
|
+
try { process.kill(-pid, 'SIGKILL') } catch { try { process.kill(pid, 'SIGKILL') } catch { /* ESRCH */ } }
|
|
744
|
+
}
|
|
745
|
+
for (let i = 0; i < 50 && pidAlive(pid); i++) await new Promise((r) => setTimeout(r, 100))
|
|
746
|
+
if (pidAlive(pid)) return false
|
|
747
|
+
removeReceipt(this.discoveryPath, id)
|
|
748
|
+
this._owned.delete(id)
|
|
749
|
+
return true
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/* ---------- 端口活动(基建能力,业务插件零代码) ---------- */
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* 把自己的服务记进「端口活动台账」——**不开窗**。
|
|
756
|
+
*
|
|
757
|
+
* 窗口不在自动流程里:台账只供主区舞台(@capyclaw/portal-hud)补标题/最近使用
|
|
758
|
+
* 时间,开不开窗由舞台的内容闸与链接拦截决定。这里只保证「基建拉起来的服务」
|
|
759
|
+
* 在台账里露过脸,计数靠后续每次调用累加。仅对 services.json 里声明了 window
|
|
760
|
+
* 的服务生效(workbench 走进程内 cordis 行,不经此路径)。
|
|
761
|
+
*/
|
|
762
|
+
_maybeMarkActivity(id, spec, url, ownedKey) {
|
|
763
|
+
if (!spec?.window || !ownedKey) return
|
|
764
|
+
Promise.resolve()
|
|
765
|
+
.then(async () => {
|
|
766
|
+
const { recordActivity } = await import('@capyclaw/portal')
|
|
767
|
+
recordActivity({
|
|
768
|
+
id,
|
|
769
|
+
url: String(url || '').replace(/\/(healthz|health)\/?$/, ''),
|
|
770
|
+
title: spec.window?.title || spec.title || id,
|
|
771
|
+
window: spec.window,
|
|
772
|
+
kind: 'service',
|
|
773
|
+
})
|
|
774
|
+
})
|
|
775
|
+
.catch((error) => {
|
|
776
|
+
this.log(`! ${id} 记账失败(服务不受影响):${error?.message || error}`)
|
|
777
|
+
})
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
_maybeCloseWindow(id) {
|
|
781
|
+
Promise.resolve()
|
|
782
|
+
.then(async () => {
|
|
783
|
+
const { closeServiceWindow } = await import('@capyclaw/portal')
|
|
784
|
+
await closeServiceWindow(id)
|
|
785
|
+
})
|
|
786
|
+
.catch(() => { /* 窗口关不掉不影响停止 */ })
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
async _adopt(id, spec, url, healthPid, ports, reused, spawnPid, identity = null) {
|
|
790
|
+
const pid = healthPid && healthPid > 0 ? healthPid : (spawnPid ?? null)
|
|
791
|
+
const previous = this._owned.get(id)
|
|
792
|
+
// A wrapper/daemon or an unrelated endpoint cannot transfer authority.
|
|
793
|
+
// Borrowed adoptions must not leave a receipt behind: otherwise every
|
|
794
|
+
// later stop would report an ownership record it can never resolve.
|
|
795
|
+
if (reused && spawnPid && existsSync(receiptPath(this.discoveryPath, id))) {
|
|
796
|
+
removeReceipt(this.discoveryPath, id)
|
|
797
|
+
}
|
|
798
|
+
const ownedIdentity = identity || (previous?.pid === pid && (await processIdentityAsync(pid)) === previous.identity ? previous.identity : null)
|
|
799
|
+
if (ownedIdentity) this._owned.set(id, { pid, identity: ownedIdentity })
|
|
800
|
+
else this._owned.delete(id)
|
|
801
|
+
this._maybeMarkActivity(id, spec, url, ownedIdentity)
|
|
802
|
+
const row = {
|
|
803
|
+
id,
|
|
804
|
+
state: 'running',
|
|
805
|
+
url,
|
|
806
|
+
healthPath: spec.healthPath || '/healthz',
|
|
807
|
+
pid,
|
|
808
|
+
ports,
|
|
809
|
+
specHash: specHash(spec),
|
|
810
|
+
keepAlive: !!spec.keepAlive,
|
|
811
|
+
reused: ownedIdentity ? false : !!reused,
|
|
812
|
+
ownership: ownedIdentity ? 'owned' : 'borrowed',
|
|
813
|
+
startedAt: new Date().toISOString(),
|
|
814
|
+
}
|
|
815
|
+
return this._locked(async () => {
|
|
816
|
+
const services = await this._loadRegistry()
|
|
817
|
+
/* A health response is not proof of ownership. In particular, another
|
|
818
|
+
* engine reusing this endpoint must not erase the owning engine's record.
|
|
819
|
+
* 但"记录里的 owner 早已死掉"是另一回事:那种残留行正是"注册表说
|
|
820
|
+
* running、实际没有进程"的来源,必须用当前事实覆盖,否则消费者会一直
|
|
821
|
+
* 对着死端口握手(历史故障:mcp 行 active 但 0 个工具)。 */
|
|
822
|
+
const current = services[id]
|
|
823
|
+
const otherOwnerAlive = current?.ownership === 'owned' && current?.state === 'running'
|
|
824
|
+
&& current.pid !== pid && current.pid > 0 && pidAlive(current.pid)
|
|
825
|
+
if (!ownedIdentity && otherOwnerAlive) {
|
|
826
|
+
return { ...row, running: true }
|
|
827
|
+
}
|
|
828
|
+
services[id] = row
|
|
829
|
+
await this._saveRegistry(services)
|
|
830
|
+
return { ...row, reused: !!reused, running: true }
|
|
831
|
+
})
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/* ---------- 停止 / 守护 ---------- */
|
|
835
|
+
|
|
836
|
+
stop(id, _options = {}) {
|
|
837
|
+
const prev = this._upLocks.get(id) || Promise.resolve()
|
|
838
|
+
const run = prev.catch(() => {}).then(() => this._stopOnce(id))
|
|
839
|
+
this._upLocks.set(id, run.catch(() => {}))
|
|
840
|
+
return run
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** 校验 pid 仍是启动时那个进程;查询不可用时重试,区分"查不到"与"不一样"。 */
|
|
844
|
+
async _verifyIdentity(pid, identity, attempts = 3) {
|
|
845
|
+
if (!identity) {
|
|
846
|
+
return { ok: false, reason: '缺少启动时的进程身份记录,无法排除 pid 复用,拒绝停止' }
|
|
847
|
+
}
|
|
848
|
+
for (let i = 0; i < attempts; i++) {
|
|
849
|
+
const current = await processIdentityAsync(pid)
|
|
850
|
+
if (current === identity) return { ok: true }
|
|
851
|
+
if (current !== null) return { ok: false, reason: `进程身份已变化(pid ${pid} 可能被复用),拒绝停止` }
|
|
852
|
+
if (i < attempts - 1) await new Promise((r) => setTimeout(r, 200))
|
|
853
|
+
}
|
|
854
|
+
return {
|
|
855
|
+
ok: false,
|
|
856
|
+
reason: `进程身份查询连续 ${attempts} 次不可用(PowerShell 超时或被策略拦截),拒绝停止 pid ${pid};请重试或手动结束`,
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
async _stopOnce(id) {
|
|
861
|
+
const row = (await this._loadRegistry())[id]
|
|
862
|
+
if (!row) return { id, state: 'unknown', stopped: false }
|
|
863
|
+
if (row.state === 'stopped') return { id, state: 'stopped', stopped: true }
|
|
864
|
+
const owned = this._owned.get(id)
|
|
865
|
+
if (!owned || owned.pid !== row.pid) {
|
|
866
|
+
return { id, state: row.state, stopped: false, reason: 'borrowed' }
|
|
867
|
+
}
|
|
868
|
+
const { pid, identity } = owned
|
|
869
|
+
if (!pidAlive(pid)) {
|
|
870
|
+
// Root already gone. Only clear the record when nothing listens on the
|
|
871
|
+
// declared ports; otherwise a detached descendant may still own them.
|
|
872
|
+
if (!(await waitReceiptResolvable({ pid, ports: row.ports }, row.ports))) {
|
|
873
|
+
throw new Error(`service ${id}: 根进程已退出且声明端口仍被占用,拒绝清除归属记录`)
|
|
874
|
+
}
|
|
875
|
+
} else {
|
|
876
|
+
/* 身份校验要区分两种失败:
|
|
877
|
+
* - 查到了但不一样 → pid 被复用,绝对不能杀;
|
|
878
|
+
* - 查不到(PowerShell 超时/被策略拦)→ 拒绝杀,但错误文案要能指导人。
|
|
879
|
+
* 另外给重试:身份查询在机器繁忙时偶发超时,一次失败就拒绝会让 stop 变成
|
|
880
|
+
* 随机失败,进而把 keepAlive 服务漏成僵尸。 */
|
|
881
|
+
const verified = await this._verifyIdentity(pid, identity)
|
|
882
|
+
if (!verified.ok) throw new Error(`service ${id}: ${verified.reason}`)
|
|
883
|
+
if (IS_WIN) {
|
|
884
|
+
const result = spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { encoding: 'utf8', windowsHide: true, timeout: 10000 })
|
|
885
|
+
if (result.status !== 0 && pidAlive(pid)) throw new Error(`service ${id}: taskkill 失败: ${result.error?.message || result.stderr || result.status}`)
|
|
886
|
+
} else {
|
|
887
|
+
try { process.kill(pid, 'SIGTERM') } catch (err) {
|
|
888
|
+
if (err.code !== 'ESRCH') throw new Error(`service ${id}: 停止失败: ${err.message}`)
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
/* 只等 pid 消失:再查身份既慢(Windows 上每次约 1s)又无意义——
|
|
892
|
+
* 进程已经不在,身份查询只会拿到 null。 */
|
|
893
|
+
for (let i = 0; i < 50 && pidAlive(pid); i++) {
|
|
894
|
+
await new Promise((r) => setTimeout(r, 100))
|
|
895
|
+
}
|
|
896
|
+
if (pidAlive(pid) && !IS_WIN) {
|
|
897
|
+
/* SIGTERM 宽限期满仍存活 → 升级 SIGKILL 进程组(detached 自成组),
|
|
898
|
+
* 避免只杀根留下孙进程占端口(P1-7)。 */
|
|
899
|
+
try { process.kill(-pid, 'SIGKILL') } catch { try { process.kill(pid, 'SIGKILL') } catch { /* ESRCH */ } }
|
|
900
|
+
for (let i = 0; i < 30 && pidAlive(pid); i++) await new Promise((r) => setTimeout(r, 100))
|
|
901
|
+
}
|
|
902
|
+
if (pidAlive(pid)) throw new Error(`service ${id}: 停止超时,进程 ${pid} 仍存活`)
|
|
903
|
+
}
|
|
904
|
+
await this._locked(async () => {
|
|
905
|
+
const services = await this._loadRegistry()
|
|
906
|
+
if (!services[id] || services[id].pid !== pid || services[id].startedAt !== row.startedAt) {
|
|
907
|
+
throw new Error(`service ${id}: 停止期间记录已变更`)
|
|
908
|
+
}
|
|
909
|
+
services[id] = { ...services[id], state: 'stopped', pid: null, stoppedAt: new Date().toISOString() }
|
|
910
|
+
await this._saveRegistry(services)
|
|
911
|
+
})
|
|
912
|
+
if (absent(pid)) removeReceipt(this.discoveryPath, id)
|
|
913
|
+
this._owned.delete(id)
|
|
914
|
+
this._maybeCloseWindow(id)
|
|
915
|
+
this.log(`■ ${id} 已停止(pid ${pid})`)
|
|
916
|
+
return { id, state: 'stopped', stopped: true }
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/** 记录各服务最近一次 up 的原始 spec,供守护按原样重启。 */
|
|
920
|
+
rememberSpec(spec) {
|
|
921
|
+
this._lastSpecs.set(spec.id, normalizeSpec(spec))
|
|
922
|
+
this._persistSpecs()
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/* ---------- 规格持久化 ---------- */
|
|
926
|
+
|
|
927
|
+
_persistSpecs() {
|
|
928
|
+
try {
|
|
929
|
+
fs.mkdirSync(path.dirname(this._specsPath), { recursive: true })
|
|
930
|
+
const data = {}
|
|
931
|
+
for (const [id, spec] of this._lastSpecs) data[id] = spec
|
|
932
|
+
const tmp = `${this._specsPath}.${process.pid}.tmp`
|
|
933
|
+
fs.writeFileSync(tmp, JSON.stringify({ version: 1, updatedAt: new Date().toISOString(), specs: data }, null, 2))
|
|
934
|
+
fs.renameSync(tmp, this._specsPath)
|
|
935
|
+
} catch { /* 落盘失败不影响内存里的守护能力 */ }
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
_restoreSpecs() {
|
|
939
|
+
let data = null
|
|
940
|
+
try { data = JSON.parse(fs.readFileSync(this._specsPath, 'utf8')) } catch { return }
|
|
941
|
+
for (const [id, spec] of Object.entries(data?.specs || {})) {
|
|
942
|
+
if (!spec || !Array.isArray(spec.cmd) || !spec.cmd.length) continue
|
|
943
|
+
/* 套件升级/移动后旧路径会失效:命令里带路径且已不存在就丢弃,
|
|
944
|
+
* 免得守护拿死路径反复失败把服务标成 error。 */
|
|
945
|
+
const missing = spec.cmd.slice(1).some((arg) => typeof arg === 'string'
|
|
946
|
+
&& /[\\/]/.test(arg) && !arg.startsWith('-') && !/\$\{/.test(arg) && !existsSync(arg))
|
|
947
|
+
if (missing) continue
|
|
948
|
+
this._lastSpecs.set(id, spec)
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* 自愈监督器。
|
|
954
|
+
*
|
|
955
|
+
* 只盯"进程还活着"是不够的——真实故障形态里,进程活着但服务已经不能用更常见:
|
|
956
|
+
* - 端口被别的进程接手(pid 还在但端点换了)
|
|
957
|
+
* - relay 卡死,/healthz 超时
|
|
958
|
+
* - relay 起来了但工具没注册(构建产物缺失),会话里"没有工具"
|
|
959
|
+
* 这三种都不该等人重启,也不该让同一个 broker 里的其他服务跟着坏掉。
|
|
960
|
+
*
|
|
961
|
+
* 每轮并行探测所有 keepAlive 服务:健康端点 + (bridge 服务)tools/list。
|
|
962
|
+
* 连续 maxUnhealthy 次不健康 → 杀掉自愈重启;单个服务失败只影响它自己。
|
|
963
|
+
*/
|
|
964
|
+
startGuard({
|
|
965
|
+
intervalMs = 2000,
|
|
966
|
+
maxConsecutive = 3,
|
|
967
|
+
maxUnhealthy = 3,
|
|
968
|
+
requireTools = true,
|
|
969
|
+
probeEveryMs = 15000,
|
|
970
|
+
errorRetryMs = 300000,
|
|
971
|
+
} = {}) {
|
|
972
|
+
if (this._guardTimer) return
|
|
973
|
+
this._guardConfig = { maxConsecutive, maxUnhealthy, requireTools, probeEveryMs, errorRetryMs }
|
|
974
|
+
this._guardTimer = setInterval(() => {
|
|
975
|
+
if (this._stopping || this._sweeping) return
|
|
976
|
+
this._sweeping = true
|
|
977
|
+
this._sweepOnce(maxConsecutive).finally(() => { this._sweeping = false })
|
|
978
|
+
}, intervalMs)
|
|
979
|
+
this._guardTimer.unref?.()
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
/** 探测一次服务是否"真的可用":进程/健康端点/工具清单三层。 */
|
|
983
|
+
async _probeService(row) {
|
|
984
|
+
const cfg = this._guardConfig || {}
|
|
985
|
+
const healthUrl = row.url ? row.url + (row.healthPath || '/healthz') : null
|
|
986
|
+
if (!healthUrl) return { ok: false, reason: '注册表缺少 url' }
|
|
987
|
+
let body
|
|
988
|
+
try {
|
|
989
|
+
const res = await fetch(healthUrl, { signal: AbortSignal.timeout(3000) })
|
|
990
|
+
if (!res.ok) return { ok: false, reason: `健康端点 HTTP ${res.status}` }
|
|
991
|
+
body = await res.json()
|
|
992
|
+
} catch (error) {
|
|
993
|
+
return { ok: false, reason: `健康端点无响应(${error.name === 'TimeoutError' ? '超时' : error.message})` }
|
|
994
|
+
}
|
|
995
|
+
if (body && body.ok === false) return { ok: false, reason: '健康端点自报不健康' }
|
|
996
|
+
if (row.id && body?.service && body.service !== row.id) {
|
|
997
|
+
return { ok: false, reason: `端口上换成了别的服务(自报 ${body.service})` }
|
|
998
|
+
}
|
|
999
|
+
/* 工具为空 = 会话里"没有工具",比进程挂掉更难发现,必须当成不健康。 */
|
|
1000
|
+
if (cfg.requireTools !== false && body?.bridge) {
|
|
1001
|
+
const tools = await this._probeTools(row.url)
|
|
1002
|
+
if (!tools.ok) return { ok: false, reason: `MCP 不可用(${tools.reason || 'initialize 失败'})` }
|
|
1003
|
+
if (tools.count === 0) return { ok: false, reason: 'MCP 工具列表为空(构建产物可能缺 tools)' }
|
|
1004
|
+
}
|
|
1005
|
+
return { ok: true }
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/** initialize + tools/list,返回工具数量;失败带原因。 */
|
|
1009
|
+
async _probeTools(baseUrl, timeoutMs = 4000) {
|
|
1010
|
+
const url = String(baseUrl).replace(/\/$/, '') + '/mcp'
|
|
1011
|
+
const headers = { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }
|
|
1012
|
+
const post = async (payload) => {
|
|
1013
|
+
const res = await fetch(url, {
|
|
1014
|
+
method: 'POST',
|
|
1015
|
+
headers,
|
|
1016
|
+
body: JSON.stringify(payload),
|
|
1017
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
1018
|
+
})
|
|
1019
|
+
if (!res.ok) return { ok: false, reason: `HTTP ${res.status}` }
|
|
1020
|
+
const sid = res.headers.get('mcp-session-id')
|
|
1021
|
+
if (sid) headers['mcp-session-id'] = sid
|
|
1022
|
+
const text = await res.text()
|
|
1023
|
+
let parsed = null
|
|
1024
|
+
try { parsed = JSON.parse(text) } catch {
|
|
1025
|
+
for (const line of text.split(/\r?\n/)) {
|
|
1026
|
+
const data = line.startsWith('data:') ? line.slice(5).trim() : line.trim()
|
|
1027
|
+
if (!data.startsWith('{')) continue
|
|
1028
|
+
try { parsed = JSON.parse(data); break } catch { /* 下一行 */ }
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
return { ok: true, message: parsed }
|
|
1032
|
+
}
|
|
1033
|
+
try {
|
|
1034
|
+
const init = await post({
|
|
1035
|
+
jsonrpc: '2.0', id: 1, method: 'initialize',
|
|
1036
|
+
params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'dsh-broker', version: '1' } },
|
|
1037
|
+
})
|
|
1038
|
+
if (!init.ok) return init
|
|
1039
|
+
const list = await post({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} })
|
|
1040
|
+
if (!list.ok) return list
|
|
1041
|
+
const tools = list.message?.result?.tools
|
|
1042
|
+
return { ok: true, count: Array.isArray(tools) ? tools.length : 0 }
|
|
1043
|
+
} catch (error) {
|
|
1044
|
+
return { ok: false, reason: error.name === 'TimeoutError' ? '超时' : error.message }
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
async _markError(row, message) {
|
|
1049
|
+
await this._locked(async () => {
|
|
1050
|
+
const cur = await this._loadRegistry()
|
|
1051
|
+
const current = cur[row.id]
|
|
1052
|
+
if (!current || current.state !== 'running' || current.pid !== row.pid || current.startedAt !== row.startedAt) return
|
|
1053
|
+
cur[row.id] = { ...current, state: 'error', error: message }
|
|
1054
|
+
await this._saveRegistry(cur)
|
|
1055
|
+
})
|
|
1056
|
+
/* 冷却从「进入 error 态」起算,而不是从恢复尝试起算:否则 breaker 触发前的
|
|
1057
|
+
* 最后一次重启时间会被当成冷却起点,errorRetryMs 短于崩溃循环时长时,
|
|
1058
|
+
* 行刚变 error 就立刻被重试,冷却形同虚设。仅状态真的翻转时登记。 */
|
|
1059
|
+
const after = (await this._loadRegistry())[row.id]
|
|
1060
|
+
if (after?.state === 'error' && after.pid === row.pid && after.startedAt === row.startedAt) {
|
|
1061
|
+
this._errorRetries.set(row.id, { count: 0, lastAt: Date.now() })
|
|
1062
|
+
}
|
|
1063
|
+
this.log(`✗ ${row.id} ${message}`)
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
async _sweepOnce(maxConsecutive) {
|
|
1067
|
+
try {
|
|
1068
|
+
const services = await this._loadRegistry()
|
|
1069
|
+
/* 监督范围 = 自己拉起的(_owned)+ 有重启规格的(_lastSpecs,含上个宿主留下的
|
|
1070
|
+
* 孤儿行)。只看 _owned 是历史故障的根因:服务被外部杀掉后行还在、_owned 里
|
|
1071
|
+
* 没有它,于是 2s 一轮的守护永远跳过它,注册表一直写着 running 的假状态。 */
|
|
1072
|
+
const rows = Object.values(services).filter((row) =>
|
|
1073
|
+
row.keepAlive && (row.state === 'running' || row.state === 'error')
|
|
1074
|
+
&& (this._owned.has(row.id) || this._lastSpecs.has(row.id)))
|
|
1075
|
+
/* 并行探测:一个服务探测慢/超时不能拖住其他服务的巡检。 */
|
|
1076
|
+
await Promise.all(rows.map((row) => this._sweepOne(row, maxConsecutive).catch(() => {})))
|
|
1077
|
+
} catch { /* 巡检一轮失败不致命,下轮再来 */ }
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
async _sweepOne(row, maxConsecutive) {
|
|
1081
|
+
/* error 态不是终点:带冷却地重试(见 _recoverError),不再永久移出扫描。 */
|
|
1082
|
+
if (row.state === 'error') return this._recoverError(row)
|
|
1083
|
+
if (pidAlive(row.pid)) {
|
|
1084
|
+
/* 注意:这里**不能**无条件清 _guardFailures——进程只要活过一个巡检间隔
|
|
1085
|
+
* 就把计数清零,「起-死-起」崩溃循环(活得比巡检间隔长)永远打不满熔断,
|
|
1086
|
+
* 变成无限重试。计数只在下方「稳定跑过一分钟」或手动 up 成功时翻篇。 */
|
|
1087
|
+
/* 分两档节奏:
|
|
1088
|
+
* - 存活检查每一轮都做(默认 2s 一轮)→ 进程一死,2s 内就重启;
|
|
1089
|
+
* - 健康/工具深探按 probeEveryMs(默认 15s)做一次,避免频繁打 HTTP。
|
|
1090
|
+
* 只有深探失败才计入"不健康",不会因为探测太频繁而误杀。 */
|
|
1091
|
+
const probeEvery = this._guardConfig?.probeEveryMs ?? 15000
|
|
1092
|
+
const last = this._lastProbe.get(row.id) || 0
|
|
1093
|
+
if (Date.now() - last < probeEvery) return
|
|
1094
|
+
this._lastProbe.set(row.id, Date.now())
|
|
1095
|
+
const probe = await this._probeService(row)
|
|
1096
|
+
if (probe.ok) {
|
|
1097
|
+
this._unhealthy.delete(row.id)
|
|
1098
|
+
/* "连续"重启次数:稳定跑过一分钟才算翻篇,避免“起-死-起”抖动
|
|
1099
|
+
* 每次都把计数清零,最后无限重试。 */
|
|
1100
|
+
const startedAt = Date.parse(row.startedAt || '') || 0
|
|
1101
|
+
if (startedAt && Date.now() - startedAt > 60_000) {
|
|
1102
|
+
this._guardFailures.delete(row.id)
|
|
1103
|
+
this._errorRetries.delete(row.id)
|
|
1104
|
+
this._lastRestart.delete(row.id)
|
|
1105
|
+
}
|
|
1106
|
+
return
|
|
1107
|
+
}
|
|
1108
|
+
const count = (this._unhealthy.get(row.id) || 0) + 1
|
|
1109
|
+
const limit = this._guardConfig?.maxUnhealthy ?? 3
|
|
1110
|
+
this._unhealthy.set(row.id, count)
|
|
1111
|
+
if (count < limit) {
|
|
1112
|
+
this.log(`… ${row.id} 不健康(${probe.reason})${count}/${limit}`)
|
|
1113
|
+
return
|
|
1114
|
+
}
|
|
1115
|
+
this._unhealthy.delete(row.id)
|
|
1116
|
+
this.log(`⟲ ${row.id} 连续 ${count} 次不健康(${probe.reason}),自愈重启`)
|
|
1117
|
+
await this._withServiceLock(row.id, async () => {
|
|
1118
|
+
if (this._stopping) return
|
|
1119
|
+
const owned = this._owned.get(row.id)
|
|
1120
|
+
if (!owned || owned.pid !== row.pid) return
|
|
1121
|
+
try {
|
|
1122
|
+
await this._stopOnce(row.id)
|
|
1123
|
+
} catch (err) {
|
|
1124
|
+
await this._markError(row, `自愈停止失败: ${err.message}`)
|
|
1125
|
+
return
|
|
1126
|
+
}
|
|
1127
|
+
const spec = this._lastSpecs.get(row.id)
|
|
1128
|
+
if (!spec) { await this._markError(row, '缺少重启规格,拒绝自动重启'); return }
|
|
1129
|
+
try {
|
|
1130
|
+
await this._upOnce(spec, {})
|
|
1131
|
+
this.log(`↻ ${row.id} 已自愈重启`)
|
|
1132
|
+
} catch (err) {
|
|
1133
|
+
await this._markError(row, `自愈重启失败: ${err.message}`)
|
|
1134
|
+
}
|
|
1135
|
+
})
|
|
1136
|
+
return
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
// Root death alone is not proof its descendants are gone. Serialize the
|
|
1140
|
+
// decision with up/stop, then require the declared ports to be free
|
|
1141
|
+
// before dropping the receipt or starting a replacement.
|
|
1142
|
+
await this._withServiceLock(row.id, async () => {
|
|
1143
|
+
if (this._stopping) return
|
|
1144
|
+
const owned = this._owned.get(row.id)
|
|
1145
|
+
/* 不是自己拉起的行(上个宿主的孤儿 / 桥拉起后被接管)也允许重启:
|
|
1146
|
+
* 这时没有归属记录可核对,只要 pid 确实不在了就按规格重来。 */
|
|
1147
|
+
if (owned && owned.pid !== row.pid) return
|
|
1148
|
+
if (owned && !absent(owned.pid)) return
|
|
1149
|
+
if (owned) {
|
|
1150
|
+
if (!(await waitReceiptResolvable({ pid: owned.pid, ports: row.ports }, row.ports))) {
|
|
1151
|
+
await this._markError(row, '进程已退出但声明端口仍被占用,拒绝自动重启')
|
|
1152
|
+
return
|
|
1153
|
+
}
|
|
1154
|
+
removeReceipt(this.discoveryPath, row.id)
|
|
1155
|
+
this._owned.delete(row.id)
|
|
1156
|
+
}
|
|
1157
|
+
const failures = this._guardFailures.get(row.id) || 0
|
|
1158
|
+
const spec = this._lastSpecs.get(row.id)
|
|
1159
|
+
if (!spec) { await this._markError(row, '缺少重启规格,拒绝自动重启'); return }
|
|
1160
|
+
if (failures >= maxConsecutive) { await this._markError(row, '连续重启次数超限,进入冷却(稍后自动重试)'); return }
|
|
1161
|
+
/* 重启退避:崩溃循环不能每 2s 硬拉一次,间隔随失败次数翻倍(2s→4s→8s…上限 60s)。 */
|
|
1162
|
+
const backoff = Math.min(2000 * 2 ** failures, 60_000)
|
|
1163
|
+
const lastRestart = this._lastRestart.get(row.id) || 0
|
|
1164
|
+
if (Date.now() - lastRestart < backoff) return
|
|
1165
|
+
this._lastRestart.set(row.id, Date.now())
|
|
1166
|
+
try {
|
|
1167
|
+
await this._upOnce(spec, {})
|
|
1168
|
+
/* 计数必须在重启**成功后**累加:_upOnce 的健康拉起路径会清 _guardFailures
|
|
1169
|
+
* (手动 up 语义=翻篇),守护重启若先加后清,崩溃循环永远打不满熔断。
|
|
1170
|
+
* 只有「稳定跑过 60s」或手动 up 才真正翻篇(见 _sweepOne)。 */
|
|
1171
|
+
this._guardFailures.set(row.id, failures + 1)
|
|
1172
|
+
this.log(`↻ ${row.id} 已自动重启`)
|
|
1173
|
+
} catch (err) {
|
|
1174
|
+
await this._markError(row, `自动重启失败: ${err.message}`)
|
|
1175
|
+
}
|
|
1176
|
+
})
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
/** error 态恢复:冷却指数翻倍(默认 5min→10min→20min…上限 30min)后按规格重试。
|
|
1180
|
+
* _upOnce 自带仲裁——端口上已有健康实例就复用,不会双开;成功即回到 running,
|
|
1181
|
+
* 稳定跑过 60s 后冷却计数清零(见 _sweepOne)。没有重启规格的行无法自愈,留给手动 up。 */
|
|
1182
|
+
async _recoverError(row) {
|
|
1183
|
+
const cfg = this._guardConfig || {}
|
|
1184
|
+
const base = cfg.errorRetryMs ?? 300_000
|
|
1185
|
+
const retry = this._errorRetries.get(row.id) || { count: 0, lastAt: 0 }
|
|
1186
|
+
const cooldown = Math.min(base * 2 ** retry.count, 1_800_000)
|
|
1187
|
+
if (Date.now() - retry.lastAt < cooldown) return
|
|
1188
|
+
const spec = this._lastSpecs.get(row.id)
|
|
1189
|
+
if (!spec) return
|
|
1190
|
+
await this._withServiceLock(row.id, async () => {
|
|
1191
|
+
if (this._stopping) return
|
|
1192
|
+
this._errorRetries.set(row.id, { count: retry.count + 1, lastAt: Date.now() })
|
|
1193
|
+
/* error 恢复是新一轮:不背旧的连续重启计数。 */
|
|
1194
|
+
this._guardFailures.delete(row.id)
|
|
1195
|
+
this._unhealthy.delete(row.id)
|
|
1196
|
+
try {
|
|
1197
|
+
await this._upOnce(spec, {})
|
|
1198
|
+
this.log(`↻ ${row.id} 已从 error 态恢复(第 ${retry.count + 1} 次尝试)`)
|
|
1199
|
+
} catch (err) {
|
|
1200
|
+
this.log(`… ${row.id} error 恢复失败(第 ${retry.count + 1} 次尝试):${err.message},冷却后再试`)
|
|
1201
|
+
}
|
|
1202
|
+
})
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/** 与服务级启动锁串行,避免与并发的 up/stop 交叉执行。 */
|
|
1206
|
+
_withServiceLock(id, fn) {
|
|
1207
|
+
const prev = this._upLocks.get(id) || Promise.resolve()
|
|
1208
|
+
const run = prev.catch(() => {}).then(fn)
|
|
1209
|
+
this._upLocks.set(id, run.catch(() => {}))
|
|
1210
|
+
return run
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
async shutdown({ stopAll = false } = {}) {
|
|
1214
|
+
this._stopping = true
|
|
1215
|
+
if (this._guardTimer) { clearInterval(this._guardTimer); this._guardTimer = null }
|
|
1216
|
+
if (!stopAll) return { ok: true, services: [], errors: [] }
|
|
1217
|
+
const services = await this._loadRegistry()
|
|
1218
|
+
const results = [], errors = []
|
|
1219
|
+
for (const row of Object.values(services)) {
|
|
1220
|
+
if (row.state === 'running') {
|
|
1221
|
+
try {
|
|
1222
|
+
const result = await this.stop(row.id)
|
|
1223
|
+
results.push(result)
|
|
1224
|
+
if (!result.stopped) errors.push({ id: row.id, error: result.reason || 'not stopped' })
|
|
1225
|
+
} catch (err) {
|
|
1226
|
+
errors.push({ id: row.id, error: err.message })
|
|
1227
|
+
this.log(`✗ 停止 ${row.id} 失败: ${err.message}`)
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
return { ok: errors.length === 0, services: results, errors }
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
/* ---------- 结构化命令投递 ---------- */
|
|
1235
|
+
|
|
1236
|
+
/**
|
|
1237
|
+
* commands: [{op:'up', service:{...spec}} | {op:'stop', id}]
|
|
1238
|
+
* up 按 requires 闭包拓扑排序;已健康的服务幂等跳过。
|
|
1239
|
+
*/
|
|
1240
|
+
async apply(commands, { waitMs } = {}) {
|
|
1241
|
+
if (!Array.isArray(commands)) throw new Error('apply: commands 必须是数组')
|
|
1242
|
+
const bad = commands.filter((c) => !c || !['up', 'stop'].includes(c.op))
|
|
1243
|
+
if (bad.length) throw new Error(`apply: 未知命令 op: ${bad.map((c) => c?.op).join(', ')}`)
|
|
1244
|
+
|
|
1245
|
+
const byId = new Map()
|
|
1246
|
+
for (const c of commands) {
|
|
1247
|
+
if (c.op !== 'up') continue
|
|
1248
|
+
const spec = normalizeSpec(c.service)
|
|
1249
|
+
byId.set(spec.id, spec)
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
// 拓扑排序(requires 闭包;指向本批之外的服务视为已由别处管理,跳过)
|
|
1253
|
+
const ordered = []
|
|
1254
|
+
const visiting = new Set()
|
|
1255
|
+
const done = new Set()
|
|
1256
|
+
const visit = (id, chain = []) => {
|
|
1257
|
+
if (done.has(id)) return
|
|
1258
|
+
if (visiting.has(id)) throw new Error(`apply: requires 成环: ${[...chain, id].join(' → ')}`)
|
|
1259
|
+
const spec = byId.get(id)
|
|
1260
|
+
if (!spec) return
|
|
1261
|
+
visiting.add(id)
|
|
1262
|
+
for (const dep of spec.requires || []) visit(dep, [...chain, id])
|
|
1263
|
+
visiting.delete(id)
|
|
1264
|
+
done.add(id)
|
|
1265
|
+
ordered.push(spec)
|
|
1266
|
+
}
|
|
1267
|
+
for (const id of byId.keys()) visit(id)
|
|
1268
|
+
|
|
1269
|
+
const results = []
|
|
1270
|
+
const errors = []
|
|
1271
|
+
for (const spec of ordered) {
|
|
1272
|
+
this.rememberSpec(spec)
|
|
1273
|
+
try {
|
|
1274
|
+
results.push(await this.up(spec, { waitMs }))
|
|
1275
|
+
} catch (err) {
|
|
1276
|
+
errors.push({ id: spec.id, error: err.message })
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
for (const cmd of commands.filter((c) => c.op === 'stop')) {
|
|
1280
|
+
try {
|
|
1281
|
+
const result = await this.stop(cmd.id)
|
|
1282
|
+
results.push(result)
|
|
1283
|
+
if (!result.stopped) errors.push({ id: cmd.id, error: result.reason || 'unknown service' })
|
|
1284
|
+
} catch (err) {
|
|
1285
|
+
errors.push({ id: cmd.id, error: err.message })
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
return { ok: errors.length === 0, services: results, errors }
|
|
1289
|
+
}
|
|
1290
|
+
}
|