dsh-seal-scripts 0.4.10 → 0.4.12

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.
@@ -1,32 +1,40 @@
1
1
  /**
2
- * 工具脚本执行(0.3.0):把一套里的某个脚本按 argv 数组跑起来。
2
+ * 工具脚本执行(0.3.0;0.4.11 起两处硬改)。
3
3
  *
4
- * 三条硬规矩:
4
+ * 三条硬规矩(一条没动):
5
5
  * 1. 不经过 shell 拼字符串 —— 参数是数组,模型给的 args 改不了命令行结构;
6
6
  * 2. 只跑工具脚本目录里的文件,越界直接抛(resolveInside);
7
7
  * 3. 跑之前对一遍 toolScript.json 里的 sha256,不一致就拒绝(除非调用方显式 allowDrift)。
8
8
  *
9
- * 输出:单条超过上限就溢写进 _runs/(写全量,不是写截断后的),返回前一段 + 溢写路径。
10
- * 超时:先 SIGTERM,2 秒后 SIGKILL;Windows 上走 taskkill /T 把整棵进程树带走
11
- * (cygwin 的 bash 会留一个 sleep 孙进程攥着管道,只杀父进程会白等到它自己结束)。
9
+ * 0.4.11 改的两处:
10
+ *
11
+ * 超时:不再「到点杀进程」。spawn 时 detached,stdout/stderr 直接重定向进 _runs/ 下的
12
+ * 两个日志文件(不经管道,父进程走了子进程也不会 EPIPE),到点只把「还在跑」的
13
+ * 现场交回去:pid、日志路径、已经写出来的前一段。进程继续跑,输出继续往文件里写。
14
+ * 这就是 DSH 自己的 promoteOnTimeout 行为,只是这里不依赖宿主的 jobs 服务。
15
+ * 要停它:killRun(pid)(SIGTERM,KILL_GRACE_MS 后 SIGKILL)。
16
+ *
17
+ * 上限:默认超时、超时天花板、单流输出上限全部来自宿主的终端设置(host-limits.js)。
18
+ * 读不到就退回 DSH 自己的默认值并注明原因——绝不退回一个更小的数。
19
+ * 输出超出上限时仍然不丢:完整内容就在日志文件里。
12
20
  */
13
21
 
14
22
  import { spawn } from 'node:child_process'
15
23
  import fs from 'node:fs'
16
24
  import path from 'node:path'
17
25
  import { resolveInside, sha256OfFile, runsDir } from './schema.js'
26
+ import { readHostLimits, clampTimeoutToHost, clampOutputToHost } from './host-limits.js'
18
27
 
19
- /** 默认超时 120 秒,上限 600 秒(和 ops_bash 的上限对齐)。 */
20
- export const DEFAULT_TIMEOUT_MS = 120000
21
- export const MAX_TIMEOUT_MS = 600000
22
-
23
- /** 单条输出上限 64 KB。 */
24
- export const DEFAULT_MAX_OUTPUT = 64 * 1024
28
+ /*
29
+ * 0.4.10 的三个死数(120000 / 600000 / 64 KB)在这个文件里**不再存在**。
30
+ * 读不到宿主设置时的兜底值只有一处:lib/core/host-limits.js 的 DSH_DEFAULTS,
31
+ * 与 DSH bash-local 的 Config 默认值一致,且绝不比它更小。
32
+ */
25
33
 
26
- /** TERM 之后等多久再 KILL。 */
27
- const KILL_GRACE_MS = 2000
34
+ /** TERM 之后等多久再 KILL:0.4.11 起只给显式的 killRun() 用(超时不再杀进程)。 */
35
+ export const KILL_GRACE_MS = 2000
28
36
 
29
- /** 子进程退出后,等管道关闭的上限(孙进程攥着管道时不陪它等)。 */
37
+ /** 子进程退出后等日志落盘的上限。 */
30
38
  const CLOSE_GRACE_MS = 600
31
39
 
32
40
  /**
@@ -59,7 +67,7 @@ export function interpreterOf(run) {
59
67
  }
60
68
 
61
69
  /**
62
- * 跑一条。顺序、退出码、超时、截断都在这里收口。
70
+ * 跑一条。顺序、退出码、超时、输出都在这里收口。
63
71
  * @param {object} p
64
72
  * @param {string} p.dshHome
65
73
  * @param {string} p.toolScriptId
@@ -72,11 +80,12 @@ export function interpreterOf(run) {
72
80
  * @param {number} [p.timeoutMs]
73
81
  * @param {number} [p.maxOutputBytes]
74
82
  * @param {boolean} [p.allowDrift]
83
+ * @param {object} [p.limits] 宿主限制(默认现读)
75
84
  * @returns {Promise<object>}
76
85
  */
77
86
  export async function runScript({
78
87
  dshHome, toolScriptId, dir, manifest, step, args = [], stdin,
79
- cwd, timeoutMs, maxOutputBytes, allowDrift = false
88
+ cwd, timeoutMs, maxOutputBytes, allowDrift = false, limits
80
89
  }) {
81
90
  const name = String(step ?? '').trim()
82
91
  const file = resolveInside(dir, name)
@@ -93,8 +102,9 @@ export async function runScript({
93
102
  '如果你刚手动改过它,重装这个工具脚本(session_tool_create_write + replace),或者这次显式传 allowDrift: true。')
94
103
  }
95
104
 
96
- const timeout = normalizeTimeout(timeoutMs === undefined ? (manifest?.timeoutMs ?? DEFAULT_TIMEOUT_MS) : timeoutMs)
97
- const cap = normalizeMaxOutput(maxOutputBytes)
105
+ const host = limits ?? readHostLimits()
106
+ const timeout = normalizeTimeout(timeoutMs === undefined ? (manifest?.timeoutMs ?? host.timeoutMs) : timeoutMs, host)
107
+ const cap = normalizeMaxOutput(maxOutputBytes, host)
98
108
  const interp = interpreterOf(meta.run)
99
109
  const argv = [...interp.args, file, ...args.map((a) => String(a))]
100
110
  const runCwd = cwd || path.resolve(dir)
@@ -108,7 +118,12 @@ export async function runScript({
108
118
  }
109
119
 
110
120
  const startedAt = Date.now()
111
- const result = await spawnCollect({ cmd: interp.cmd, argv, cwd: runCwd, env, timeout, cap, stdin })
121
+ const result = await spawnCollect({
122
+ cmd: interp.cmd, argv, cwd: runCwd, env, timeout, cap, stdin,
123
+ dshHome: String(dshHome ?? process.env.DSH_HOME ?? ''),
124
+ label: String(toolScriptId) + ':' + name,
125
+ meta: { toolScript: String(toolScriptId), step: name, run: meta.run, cwd: runCwd, timeoutMs: timeout, maxOutputBytes: cap, limits: { source: host.source, note: host.note } }
126
+ })
112
127
  return {
113
128
  toolScript: String(toolScriptId),
114
129
  step: name,
@@ -121,161 +136,248 @@ export async function runScript({
121
136
  }
122
137
  }
123
138
 
124
- /** 时间收口:非数字给默认,越界夹到上限。 */
125
- export function normalizeTimeout(value) {
126
- const n = Number(value)
127
- if (!Number.isFinite(n) || n <= 0) return DEFAULT_TIMEOUT_MS
128
- return Math.min(Math.max(Math.trunc(n), 1000), MAX_TIMEOUT_MS)
139
+ /**
140
+ * 时间收口:默认值与天花板都来自宿主设置(0.4.11)。
141
+ * 非数字 → 宿主默认超时;越界 → 夹到宿主 maxTimeoutMs(绝不夹到一个插件自己写的数)。
142
+ * @param {unknown} value
143
+ * @param {object} [limits]
144
+ * @returns {number}
145
+ */
146
+ export function normalizeTimeout(value, limits = readHostLimits()) {
147
+ return clampTimeoutToHost(value, limits)
129
148
  }
130
149
 
131
- /** 输出上限收口。 */
132
- export function normalizeMaxOutput(value) {
133
- const n = Number(value)
134
- if (!Number.isFinite(n) || n <= 0) return DEFAULT_MAX_OUTPUT
135
- return Math.min(Math.trunc(n), 1024 * 1024)
150
+ /**
151
+ * 输出上限收口:默认值来自宿主 maxOutputBytes;0.4.10 的 1MB 封顶删掉。
152
+ * @param {unknown} value
153
+ * @param {object} [limits]
154
+ * @returns {number}
155
+ */
156
+ export function normalizeMaxOutput(value, limits = readHostLimits()) {
157
+ return clampOutputToHost(value, limits)
158
+ }
159
+
160
+ /** 名字里不许有目录分隔符(它要进文件名)。 */
161
+ function safeTag(text) {
162
+ return String(text).replace(/[^A-Za-z0-9._-]+/g, '-').slice(0, 80) || 'run'
163
+ }
164
+
165
+ /** 一条运行的三个落点:stdout 日志、stderr 日志、可追溯的 meta。 */
166
+ export function runLogPaths(dshHome, label, startedAt = Date.now()) {
167
+ const dir = runsDir(dshHome)
168
+ const base = path.join(dir, String(startedAt) + '-' + safeTag(label) + '-' + process.pid)
169
+ return { dir, base, stdoutFile: base + '.stdout.log', stderrFile: base + '.stderr.log', metaFile: base + '.run.json' }
136
170
  }
137
171
 
138
172
  /**
139
- * 真正跑一次子进程:收集 stdout/stderr,超上限就溢写。
140
- * 不 resolve 成「成功」,只如实回 exitCode / signal / timedOut。
141
- * @returns {Promise<{exitCode:number|null, signal:string|null, timedOut:boolean, stdout:string, stderr:string, truncated:boolean, spill:string}>}
173
+ * 从文件头读一段(同步,进程还在写也照读)。多大就是多大,不做别的解释。
174
+ * @param {string} file
175
+ * @param {number} cap
176
+ * @returns {{text:string, size:number, truncated:boolean}}
142
177
  */
143
- function spawnCollect({ cmd, argv, cwd, env, timeout, cap, stdin }) {
178
+ function readHead(file, cap) {
179
+ let size = 0
180
+ try { size = fs.statSync(file).size } catch { return { text: '', size: 0, truncated: false } }
181
+ if (size <= 0) return { text: '', size: 0, truncated: false }
182
+ const want = Math.min(size, cap)
183
+ const buf = Buffer.allocUnsafe(want)
184
+ let fd
185
+ try {
186
+ fd = fs.openSync(file, 'r')
187
+ const got = fs.readSync(fd, buf, 0, want, 0)
188
+ return { text: buf.subarray(0, got).toString('utf8'), size, truncated: size > cap }
189
+ } catch {
190
+ return { text: '', size, truncated: size > cap }
191
+ } finally {
192
+ if (fd !== undefined) { try { fs.closeSync(fd) } catch { /* 已经关了 */ } }
193
+ }
194
+ }
195
+
196
+ /**
197
+ * 真正跑一次子进程:stdout/stderr 直接进日志文件,到点不杀、转后台。
198
+ * 不 resolve 成「成功」,只如实回 exitCode / signal / timedOut / background。
199
+ *
200
+ * @returns {Promise<object>}
201
+ */
202
+ function spawnCollect({ cmd, argv, cwd, env, timeout, cap, stdin, dshHome, label, meta }) {
144
203
  return new Promise((resolve, reject) => {
145
- const detached = process.platform !== 'win32'
204
+ const paths = runLogPaths(dshHome, label)
205
+ let outFd
206
+ let errFd
207
+ try {
208
+ fs.mkdirSync(paths.dir, { recursive: true })
209
+ outFd = fs.openSync(paths.stdoutFile, 'w')
210
+ errFd = fs.openSync(paths.stderrFile, 'w')
211
+ } catch (err) {
212
+ for (const fd of [outFd, errFd]) if (typeof fd === 'number') { try { fs.closeSync(fd) } catch { /* 忽略 */ } }
213
+ reject(new Error('建运行日志失败:' + (err && err.message ? err.message : String(err))))
214
+ return
215
+ }
216
+
146
217
  let child
147
218
  try {
148
- child = spawn(cmd, argv, { cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], detached })
219
+ child = spawn(cmd, argv, {
220
+ cwd,
221
+ env,
222
+ windowsHide: true,
223
+ // 0.4.11:detached 才不会被父进程的退出带走;输出直接进文件,不走管道。
224
+ detached: process.platform !== 'win32',
225
+ stdio: ['pipe', outFd, errFd]
226
+ })
149
227
  } catch (err) {
150
- reject(new Error('起不来解释器 ' + cmd + ':' + (err?.message ?? err)))
228
+ reject(new Error('起不来解释器 ' + cmd + ':' + (err && err.message ? err.message : String(err))))
151
229
  return
230
+ } finally {
231
+ // 子进程已经 dup 了自己的那一份,父进程这边立刻关掉,免得句柄泄漏。
232
+ for (const fd of [outFd, errFd]) if (typeof fd === 'number') { try { fs.closeSync(fd) } catch { /* 忽略 */ } }
152
233
  }
153
234
 
154
- const out = { stdout: [], stderr: [], bytes: 0, truncated: false }
155
- let spillFile = ''
156
- let spillFd = null
157
- let killedByTimeout = false
235
+ // 可追溯记录:这次跑的是什么、pid 几、什么时候开始。
236
+ try {
237
+ fs.writeFileSync(paths.metaFile, JSON.stringify({
238
+ ...meta, pid: child.pid ?? null, startedAt: new Date().toISOString(),
239
+ stdoutFile: paths.stdoutFile, stderrFile: paths.stderrFile
240
+ }, null, 2) + '\n', 'utf8')
241
+ } catch { /* 记不下来不影响跑 */ }
242
+
158
243
  let done = false
159
- let exited = false
244
+ let promoted = false
160
245
  let code = null
161
246
  let sig = null
162
247
 
163
- // 溢写:第一次超限时把已经收到的头一段写进去,之后按到达顺序追加。
164
- const openSpill = () => {
165
- if (spillFile !== '') return
166
- try {
167
- const dir = runsDir(env.DSH_HOME || '')
168
- fs.mkdirSync(dir, { recursive: true })
169
- spillFile = path.join(dir, Date.now() + '-' + String(env.TOOL_SCRIPT || 'toolScript') + '-' +
170
- String(env.TOOL_NAME || 'step') + '.log')
171
- spillFd = fs.openSync(spillFile, 'w')
172
- if (out.stdout.length > 0) fs.writeSync(spillFd, Buffer.concat(out.stdout))
173
- fs.writeSync(spillFd, '\n----- stderr -----\n')
174
- if (out.stderr.length > 0) fs.writeSync(spillFd, Buffer.concat(out.stderr))
175
- fs.writeSync(spillFd, '\n----- 之后的内容按到达顺序 -----\n')
176
- } catch {
177
- spillFile = ''
178
- spillFd = null
179
- }
180
- }
181
-
182
- const take = (which, chunk) => {
183
- if (spillFd !== null) {
184
- try { fs.writeSync(spillFd, chunk) } catch { /* 盘满之类:算了,返回值还在 */ }
185
- return
186
- }
187
- if (out.truncated) return
188
- const room = cap - out.bytes
189
- if (chunk.length <= room) {
190
- out[which].push(chunk)
191
- out.bytes += chunk.length
192
- return
193
- }
194
- if (room > 0) out[which].push(chunk.subarray(0, room))
195
- out.bytes = cap
196
- out.truncated = true
197
- openSpill()
198
- const rest = room > 0 ? chunk.subarray(room) : chunk
199
- if (spillFd !== null) {
200
- try { fs.writeSync(spillFd, rest) } catch { /* 同上 */ }
201
- }
202
- }
203
-
204
- const killTree = (signal) => {
205
- if (!child.pid) return
206
- try {
207
- if (process.platform === 'win32') {
208
- const k = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
209
- k.on('error', () => {})
210
- } else if (detached) {
211
- try { process.kill(-child.pid, signal) } catch { child.kill(signal) }
212
- } else {
213
- child.kill(signal)
214
- }
215
- } catch { /* 进程已经没了 */ }
216
- }
217
-
218
- const timer = setTimeout(() => {
219
- killedByTimeout = true
220
- killTree('SIGTERM')
221
- const graceTimer = setTimeout(() => killTree('SIGKILL'), KILL_GRACE_MS)
222
- if (typeof graceTimer.unref === 'function') graceTimer.unref()
223
- }, timeout)
224
-
225
- const finish = () => {
248
+ const settle = (fields) => {
226
249
  if (done) return
227
250
  done = true
251
+ resolve(fields)
252
+ }
253
+
254
+ /** 正常结束时的回报:从日志文件头读两段,超出上限就指向完整文件。 */
255
+ const finishNormal = () => {
256
+ if (done || promoted) return
257
+ // 必须清:这个定时器的默认寿命是宿主的 timeoutMs(12 万毫秒),留着会把事件循环吊住。
228
258
  clearTimeout(timer)
229
- if (spillFd !== null) {
230
- try { fs.closeSync(spillFd) } catch { /* 已经关了 */ }
231
- spillFd = null
232
- }
233
- const stdout = Buffer.concat(out.stdout).toString('utf8')
234
- const stderr = Buffer.concat(out.stderr).toString('utf8')
235
- resolve({
259
+ const out = readHead(paths.stdoutFile, cap)
260
+ const errOut = readHead(paths.stderrFile, cap)
261
+ settle({
236
262
  exitCode: typeof code === 'number' ? code : null,
237
263
  signal: sig ?? null,
238
- timedOut: killedByTimeout,
239
- stdout: out.truncated
240
- ? stdout + '\n[输出超过单条上限(' + cap + ' 字节),完整内容在 ' + (spillFile || '(溢写失败,已丢)') + ']'
241
- : stdout,
242
- stderr,
243
- truncated: out.truncated,
244
- spill: spillFile
264
+ timedOut: false,
265
+ background: false,
266
+ stdout: out.text,
267
+ stderr: errOut.text,
268
+ truncated: out.truncated || errOut.truncated,
269
+ spill: out.truncated ? paths.stdoutFile : '',
270
+ stderrSpill: errOut.truncated ? paths.stderrFile : '',
271
+ logFile: paths.stdoutFile,
272
+ stderrFile: paths.stderrFile
245
273
  })
246
274
  }
247
275
 
248
- child.stdout?.on('data', (c) => take('stdout', c))
249
- child.stderr?.on('data', (c) => take('stderr', c))
276
+ // 到点:不杀,交回现场。
277
+ const timer = setTimeout(() => {
278
+ if (done) return
279
+ promoted = true
280
+ const out = readHead(paths.stdoutFile, cap)
281
+ const errOut = readHead(paths.stderrFile, cap)
282
+ // 让出事件循环,DSH 不被这个子进程攥着(它已经 detached,会自己跑完)。
283
+ try { child.unref() } catch { /* 老 node 没有也就算了 */ }
284
+ settle({
285
+ exitCode: null,
286
+ signal: null,
287
+ timedOut: true,
288
+ background: true,
289
+ pid: child.pid ?? null,
290
+ stdout: out.text,
291
+ stderr: errOut.text,
292
+ truncated: out.truncated || errOut.truncated,
293
+ spill: out.truncated ? paths.stdoutFile : '',
294
+ stderrSpill: errOut.truncated ? paths.stderrFile : '',
295
+ logFile: paths.stdoutFile,
296
+ stderrFile: paths.stderrFile,
297
+ metaFile: paths.metaFile
298
+ })
299
+ }, timeout)
300
+
301
+ // unref:跑着呢,是子进程的 handle 在撑事件循环;定时器不该单独把进程吊着。
302
+ if (typeof timer.unref === 'function') timer.unref()
250
303
 
251
304
  child.on('error', (err) => {
305
+ clearTimeout(timer)
252
306
  if (done) return
253
307
  done = true
254
- clearTimeout(timer)
255
- if (spillFd !== null) { try { fs.closeSync(spillFd) } catch { /* 忽略 */ } }
256
308
  const message = err && err.code === 'ENOENT'
257
309
  ? '找不到解释器:' + cmd + (cmd === 'bash' ? '(这个工具脚本用 bash 写的;这台机器上 bash 不在 PATH 里,改写 node 脚本或先装 bash)' : '')
258
- : '起不来:' + (err?.message ?? err)
310
+ : '起不来:' + (err && err.message ? err.message : String(err))
259
311
  reject(new Error(message))
260
312
  })
261
313
 
262
- // 子进程自己退了:最多再等 CLOSE_GRACE_MS 让管道收完,孙进程攥着管道也不陪它等。
314
+ // 退出了就等日志落盘(CLOSE_GRACE_MS 兜底)。已经转后台的不用管,结果早交回去了。
263
315
  child.on('exit', (c, s) => {
264
316
  code = c
265
317
  sig = s
266
- exited = true
267
- const finalTimer = setTimeout(finish, CLOSE_GRACE_MS)
318
+ if (promoted || done) return
319
+ const finalTimer = setTimeout(finishNormal, CLOSE_GRACE_MS)
268
320
  if (typeof finalTimer.unref === 'function') finalTimer.unref()
269
321
  })
270
322
  child.on('close', (c, s) => {
271
- if (!exited) { code = c; sig = s }
272
- finish()
323
+ if (typeof code !== 'number' && code === null) { code = c; sig = s }
324
+ finishNormal()
273
325
  })
274
326
 
275
327
  if (stdin !== undefined && stdin !== null) {
276
328
  try { child.stdin?.end(String(stdin)) } catch { /* 子进程可能不看 stdin */ }
277
329
  } else {
330
+ // 不保留 stdin:后台化的进程不能攥着父进程的管道。
278
331
  try { child.stdin?.end() } catch { /* 同上 */ }
279
332
  }
280
333
  })
281
334
  }
335
+
336
+ /** 进程还活着吗(pid 存在且不是自己)。 */
337
+ export function isAlive(pid) {
338
+ const n = Number(pid)
339
+ if (!Number.isInteger(n) || n <= 0) return false
340
+ try {
341
+ process.kill(n, 0)
342
+ return true
343
+ } catch (err) {
344
+ return err && err.code === 'EPERM'
345
+ }
346
+ }
347
+
348
+ /** 睡一会儿(只给 killRun 的宽限期用)。 */
349
+ function sleep(ms) {
350
+ return new Promise((done) => {
351
+ const t = setTimeout(done, ms)
352
+ if (typeof t.unref === 'function') t.unref()
353
+ })
354
+ }
355
+
356
+ /**
357
+ * 停掉一条转后台的运行:SIGTERM,KILL_GRACE_MS 内没走就 SIGKILL。
358
+ * 0.4.11 之前这段逻辑在超时里;现在超时不杀,这里是**显式**停它的唯一入口。
359
+ *
360
+ * @param {number} pid
361
+ * @param {{graceMs?:number}} [p]
362
+ * @returns {Promise<{pid:number, term:boolean, sigkill:boolean, exited:boolean, waitedMs:number}>}
363
+ */
364
+ export async function killRun(pid, { graceMs = KILL_GRACE_MS } = {}) {
365
+ const n = Number(pid)
366
+ if (!Number.isInteger(n) || n <= 0) throw new Error('killRun 要一个正的 pid:' + String(pid))
367
+ const signal = (s) => {
368
+ try { process.kill(-n, s); return true } catch { /* 进程组可能已经没了 */ }
369
+ try { process.kill(n, s); return true } catch { return false }
370
+ }
371
+ const startedAt = Date.now()
372
+ const term = signal('SIGTERM')
373
+ const limit = Date.now() + Math.max(0, Number(graceMs) || 0)
374
+ while (Date.now() < limit) {
375
+ if (!isAlive(n)) return { pid: n, term, sigkill: false, exited: true, waitedMs: Date.now() - startedAt }
376
+ await sleep(50)
377
+ }
378
+ const stillAlive = isAlive(n)
379
+ const sigkill = stillAlive ? signal('SIGKILL') : false
380
+ // SIGKILL 之后给一点点时间让内核回收
381
+ for (let i = 0; i < 20 && isAlive(n); i++) await sleep(25)
382
+ return { pid: n, term, sigkill, exited: !isAlive(n), waitedMs: Date.now() - startedAt }
383
+ }