| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154 |
- /**
- * 引擎进程
- * =======
- * 和桌面端 electron/sidecar.js 同一套启动方式:
- *
- * node <dsh>/lib/bin.js --profile web --patch <patch.yml> --port 0 --no-open
- *
- * 端口由系统分配,从输出里抓 `http://127.0.0.1:<port>/`。区别只有三处:
- * · DSH_HOME 指到老师自己的目录(会话、设置互不串);
- * · CC_LLM_KEY 用这个老师自己的 apiKey;
- * · 进程按进程组管理,主服务退出时一起收掉(不留孤儿 node 进程)。
- */
- import { spawn } from 'node:child_process'
- const URL_RE = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)\/\S*/
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
- export class Engine {
- constructor (options) {
- this.entry = options.entry
- this.node = options.node || process.execPath
- this.patchFile = options.patchFile
- this.cwd = options.cwd
- this.env = options.env || {}
- this.bootMs = options.bootMs || 90_000
- this.log = options.log || (() => {})
- this.child = null
- this.port = 0
- this.token = ''
- this.startedAt = 0
- this.tail = []
- this.stopping = false
- }
- get url () {
- return this.port ? `http://127.0.0.1:${this.port}/` : ''
- }
- args () {
- const args = ['--profile', 'web']
- if (this.patchFile) args.push('--patch', this.patchFile)
- args.push('--port', '0', '--no-open')
- return args
- }
- async start () {
- if (this.child) return { port: this.port, url: this.url }
- this.stopping = false
- this.startedAt = Date.now()
- const child = spawn(this.node, [this.entry, ...this.args()], {
- cwd: this.cwd || undefined,
- env: { ...process.env, ...this.env },
- stdio: ['ignore', 'pipe', 'pipe'],
- // POSIX 上单独一个进程组,停止时整组发信号;Windows 走 taskkill /T
- detached: process.platform !== 'win32',
- windowsHide: true
- })
- this.child = child
- const ready = new Promise((resolve, reject) => {
- let settled = false
- const timer = setTimeout(() => {
- if (settled) return
- settled = true
- this.stop().catch(() => {})
- reject(new Error(`引擎 ${Math.round(this.bootMs / 1000)} 秒内没有就绪。最近日志:\n${this.tailText(15)}`))
- }, this.bootMs)
- timer.unref?.()
- const onData = (buf) => {
- const text = buf.toString('utf8')
- for (const line of text.split(/\r?\n/)) {
- if (!line.trim()) continue
- this.log(`[engine] ${line}`)
- this.tail.push(line)
- if (this.tail.length > 200) this.tail.shift()
- if (settled) continue
- const m = line.match(URL_RE)
- if (!m) continue
- settled = true
- clearTimeout(timer)
- this.port = Number(m[1])
- // 引擎启动时会打印带 token 的地址;桌面端直接把整条 URL 交给 BrowserWindow,
- // 第一次访问靠 ?token= 换成 cookie。Web 版必须在代理层补这一步(见 index.js)。
- try { this.token = new URL(m[0]).searchParams.get('token') || '' } catch { this.token = '' }
- this.waitHealthy(`http://127.0.0.1:${this.port}/`)
- .then(() => resolve({ port: this.port, url: this.url }))
- .catch(reject)
- }
- }
- child.stdout.on('data', onData)
- child.stderr.on('data', onData)
- child.on('error', (err) => {
- clearTimeout(timer)
- if (settled) return
- settled = true
- reject(err)
- })
- child.on('exit', (code, signal) => {
- clearTimeout(timer)
- this.child = null
- if (this.stopping) return
- if (settled) {
- this.log(`[engine] 进程退出 code=${code} signal=${signal}`)
- return
- }
- settled = true
- reject(new Error(`引擎启动即退出(code=${code})。最近日志:\n${this.tailText(20)}`))
- })
- })
- return ready
- }
- async waitHealthy (url, attempts = 60) {
- for (let i = 0; i < attempts; i += 1) {
- try {
- const res = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(2000) })
- if (res.status < 500) return true
- } catch { /* 端口刚开,还没人接 */ }
- await sleep(250)
- }
- throw new Error(`引擎端口 ${this.port} 起来了但健康检查一直失败`)
- }
- tailText (n) {
- return this.tail.slice(-n).join('\n')
- }
- async stop () {
- const child = this.child
- if (!child) return
- this.stopping = true
- this.child = null
- const pid = child.pid
- try {
- if (process.platform === 'win32') {
- spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true }).on('error', () => {})
- } else {
- try { process.kill(-pid, 'SIGTERM') } catch { child.kill('SIGTERM') }
- const timer = setTimeout(() => {
- try { process.kill(-pid, 'SIGKILL') } catch { /* 已经退了 */ }
- }, 3000)
- timer.unref?.()
- }
- } catch { /* 进程已经没了 */ }
- this.port = 0
- }
- }
|