opencode-supertask 0.1.41 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +77 -0
- package/README.md +66 -39
- package/README.zh-CN.md +66 -39
- package/dist/cli/chunk-3PIYMBV3.js +45 -0
- package/dist/cli/chunk-3PIYMBV3.js.map +1 -0
- package/dist/cli/chunk-4FK5KE6G.js +111 -0
- package/dist/cli/chunk-4FK5KE6G.js.map +1 -0
- package/dist/cli/chunk-5VKFECHP.js +412 -0
- package/dist/cli/chunk-5VKFECHP.js.map +1 -0
- package/dist/cli/chunk-AZM76ISG.js +143 -0
- package/dist/cli/chunk-AZM76ISG.js.map +1 -0
- package/dist/cli/chunk-CMEP6IB4.js +9379 -0
- package/dist/cli/chunk-CMEP6IB4.js.map +1 -0
- package/dist/cli/chunk-DF56RPNL.js +65 -0
- package/dist/cli/chunk-DF56RPNL.js.map +1 -0
- package/dist/cli/chunk-DIJEKFBV.js +486 -0
- package/dist/cli/chunk-DIJEKFBV.js.map +1 -0
- package/dist/cli/chunk-DYXFSX5J.js +28 -0
- package/dist/cli/chunk-DYXFSX5J.js.map +1 -0
- package/dist/cli/chunk-EQWICVCJ.js +1701 -0
- package/dist/cli/chunk-EQWICVCJ.js.map +1 -0
- package/dist/cli/chunk-GHXFMJTS.js +42 -0
- package/dist/cli/chunk-GHXFMJTS.js.map +1 -0
- package/dist/cli/chunk-IYYBJHZF.js +28 -0
- package/dist/cli/chunk-IYYBJHZF.js.map +1 -0
- package/dist/cli/chunk-J34FWHQU.js +376 -0
- package/dist/cli/chunk-J34FWHQU.js.map +1 -0
- package/dist/cli/chunk-LX5CBJLP.js +121 -0
- package/dist/cli/chunk-LX5CBJLP.js.map +1 -0
- package/dist/cli/chunk-MVQ2XONT.js +139 -0
- package/dist/cli/chunk-MVQ2XONT.js.map +1 -0
- package/dist/cli/chunk-NCT3ETTK.js +1332 -0
- package/dist/cli/chunk-NCT3ETTK.js.map +1 -0
- package/dist/cli/chunk-YB7MYTE5.js +34 -0
- package/dist/cli/chunk-YB7MYTE5.js.map +1 -0
- package/dist/cli/chunk-YGELD2E5.js +5464 -0
- package/dist/cli/chunk-YGELD2E5.js.map +1 -0
- package/dist/cli/chunk-ZBH7YWXF.js +314 -0
- package/dist/cli/chunk-ZBH7YWXF.js.map +1 -0
- package/dist/cli/config-ED56ZLHY.js +20 -0
- package/dist/cli/config-ED56ZLHY.js.map +1 -0
- package/dist/cli/database-maintenance.service-F3IZU52F.js +16 -0
- package/dist/cli/database-maintenance.service-F3IZU52F.js.map +1 -0
- package/dist/cli/database-output-GH7F6X6D.js +165 -0
- package/dist/cli/database-output-GH7F6X6D.js.map +1 -0
- package/dist/cli/db-H7GIFWS2.js +26 -0
- package/dist/cli/db-H7GIFWS2.js.map +1 -0
- package/dist/cli/doctor-smoke-QXHF7UNN.js +150 -0
- package/dist/cli/doctor-smoke-QXHF7UNN.js.map +1 -0
- package/dist/cli/duration-Q3UMLO6F.js +10 -0
- package/dist/cli/duration-Q3UMLO6F.js.map +1 -0
- package/dist/cli/gateway-HNMX5ZTO.js +1738 -0
- package/dist/cli/gateway-HNMX5ZTO.js.map +1 -0
- package/dist/cli/gateway-wake-U4HTV56Q.js +14 -0
- package/dist/cli/gateway-wake-U4HTV56Q.js.map +1 -0
- package/dist/cli/index.js +626 -26583
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/job-templates-RPQJ4XXW.js +21 -0
- package/dist/cli/job-templates-RPQJ4XXW.js.map +1 -0
- package/dist/cli/logs-QD2N62KK.js +316 -0
- package/dist/cli/logs-QD2N62KK.js.map +1 -0
- package/dist/cli/output-2INTEUFQ.js +19 -0
- package/dist/cli/output-2INTEUFQ.js.map +1 -0
- package/dist/cli/pm2-WY644BUO.js +49 -0
- package/dist/cli/pm2-WY644BUO.js.map +1 -0
- package/dist/cli/task-run.service-QMDINJKG.js +15 -0
- package/dist/cli/task-run.service-QMDINJKG.js.map +1 -0
- package/dist/cli/task-template.service-SZBKGLCB.js +12 -0
- package/dist/cli/task-template.service-SZBKGLCB.js.map +1 -0
- package/dist/cli/task.service-ZVDJ6VSQ.js +19 -0
- package/dist/cli/task.service-ZVDJ6VSQ.js.map +1 -0
- package/dist/cli/update-FYD546I2.js +2058 -0
- package/dist/cli/update-FYD546I2.js.map +1 -0
- package/dist/cli/web-2S7DW7XA.js +9403 -0
- package/dist/cli/web-2S7DW7XA.js.map +1 -0
- package/dist/daemon/gateway-diagnostic-runner.js +280 -238
- package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
- package/dist/gateway/index.d.ts +82 -1
- package/dist/gateway/index.js +9154 -2577
- package/dist/gateway/index.js.map +1 -1
- package/dist/plugin/supertask.d.ts +157 -1
- package/dist/plugin/supertask.js +5056 -1550
- package/dist/plugin/supertask.js.map +1 -1
- package/dist/pm2-cli-CEDhULjk.d.ts +40 -0
- package/dist/web/index.d.ts +36 -34
- package/dist/web/index.js +9951 -4006
- package/dist/web/index.js.map +1 -1
- package/dist/worker/index.d.ts +5 -0
- package/dist/worker/index.js +1989 -331
- package/dist/worker/index.js.map +1 -1
- package/dist/worker/launcher.d.ts +46 -1
- package/dist/worker/launcher.js +218 -68
- package/dist/worker/launcher.js.map +1 -1
- package/drizzle/0009_little_weapon_omega.sql +7 -0
- package/drizzle/meta/0009_snapshot.json +681 -0
- package/drizzle/meta/_journal.json +7 -0
- package/package.json +4 -4
|
@@ -0,0 +1,1738 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
gatewayEvents,
|
|
5
|
+
initializeGatewayHealth,
|
|
6
|
+
markGatewayActivity,
|
|
7
|
+
markGatewayFailure,
|
|
8
|
+
markGatewaySuccess,
|
|
9
|
+
resetGatewayHealth
|
|
10
|
+
} from "./chunk-J34FWHQU.js";
|
|
11
|
+
import {
|
|
12
|
+
OpenCodeInvocationError,
|
|
13
|
+
buildOpenCodeRunArgs,
|
|
14
|
+
detectOpenCodeVersion,
|
|
15
|
+
openCodeExecutable
|
|
16
|
+
} from "./chunk-LX5CBJLP.js";
|
|
17
|
+
import {
|
|
18
|
+
TaskRunService
|
|
19
|
+
} from "./chunk-5VKFECHP.js";
|
|
20
|
+
import {
|
|
21
|
+
DUE_TEMPLATE_BATCH_SIZE,
|
|
22
|
+
cloneTaskFromTemplate,
|
|
23
|
+
getDueTemplates,
|
|
24
|
+
initializeNextRunAt
|
|
25
|
+
} from "./chunk-AZM76ISG.js";
|
|
26
|
+
import {
|
|
27
|
+
TaskTemplateService
|
|
28
|
+
} from "./chunk-CMEP6IB4.js";
|
|
29
|
+
import {
|
|
30
|
+
identifyGatewayProcess,
|
|
31
|
+
inspectSpawnedProcessTreePresence,
|
|
32
|
+
isProcessAlive,
|
|
33
|
+
signalRecordedProcessTreeWithResult,
|
|
34
|
+
waitForSpawnedProcessTreeExit
|
|
35
|
+
} from "./chunk-ZBH7YWXF.js";
|
|
36
|
+
import {
|
|
37
|
+
LAUNCH_IDENTITY_ARGUMENT,
|
|
38
|
+
LEGACY_GUARDIAN_LAUNCH_PROTOCOL,
|
|
39
|
+
MANAGED_RUN_ENV,
|
|
40
|
+
MANAGED_RUN_ENV_VALUE,
|
|
41
|
+
TOKEN_GUARDIAN_LAUNCH_PROTOCOL,
|
|
42
|
+
drainProofAckForIdentity,
|
|
43
|
+
isMatchingDrainProof
|
|
44
|
+
} from "./chunk-YB7MYTE5.js";
|
|
45
|
+
import {
|
|
46
|
+
TaskService,
|
|
47
|
+
normalizeTaskBatchId,
|
|
48
|
+
validateTaskWorkingDirectory
|
|
49
|
+
} from "./chunk-EQWICVCJ.js";
|
|
50
|
+
import {
|
|
51
|
+
and,
|
|
52
|
+
asc,
|
|
53
|
+
closeDb,
|
|
54
|
+
db,
|
|
55
|
+
eq,
|
|
56
|
+
gt,
|
|
57
|
+
isNull,
|
|
58
|
+
schema_exports,
|
|
59
|
+
sqlite
|
|
60
|
+
} from "./chunk-YGELD2E5.js";
|
|
61
|
+
import {
|
|
62
|
+
getPackageVersion
|
|
63
|
+
} from "./chunk-DYXFSX5J.js";
|
|
64
|
+
import {
|
|
65
|
+
loadConfig
|
|
66
|
+
} from "./chunk-MVQ2XONT.js";
|
|
67
|
+
import "./chunk-3PIYMBV3.js";
|
|
68
|
+
|
|
69
|
+
// src/worker/index.ts
|
|
70
|
+
import { spawn } from "child_process";
|
|
71
|
+
import { fileURLToPath } from "url";
|
|
72
|
+
import { existsSync } from "fs";
|
|
73
|
+
import { dirname, join } from "path";
|
|
74
|
+
import { randomUUID } from "crypto";
|
|
75
|
+
|
|
76
|
+
// src/worker/run-output.ts
|
|
77
|
+
var SESSION_ID_PATTERN = /^ses_[A-Za-z0-9_]+$/;
|
|
78
|
+
var RunOutput = class {
|
|
79
|
+
constructor(maxChars, onSessionId, onLine) {
|
|
80
|
+
this.maxChars = maxChars;
|
|
81
|
+
this.onSessionId = onSessionId;
|
|
82
|
+
this.onLine = onLine;
|
|
83
|
+
}
|
|
84
|
+
maxChars;
|
|
85
|
+
onSessionId;
|
|
86
|
+
onLine;
|
|
87
|
+
lines = [];
|
|
88
|
+
head = 0;
|
|
89
|
+
totalChars = 0;
|
|
90
|
+
partial = { stdout: "", stderr: "" };
|
|
91
|
+
sessionId = null;
|
|
92
|
+
push(stream, chunk) {
|
|
93
|
+
const lines = (this.partial[stream] + chunk).split("\n");
|
|
94
|
+
let rest = lines.pop() ?? "";
|
|
95
|
+
if (rest.length > this.maxChars) {
|
|
96
|
+
lines.push(rest);
|
|
97
|
+
rest = "";
|
|
98
|
+
}
|
|
99
|
+
this.partial[stream] = rest;
|
|
100
|
+
for (const line of lines) this.appendLine(stream, line);
|
|
101
|
+
}
|
|
102
|
+
flush() {
|
|
103
|
+
for (const stream of ["stdout", "stderr"]) {
|
|
104
|
+
const rest = this.partial[stream];
|
|
105
|
+
this.partial[stream] = "";
|
|
106
|
+
if (rest) this.appendLine(stream, rest);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
text() {
|
|
110
|
+
if (this.head >= this.lines.length) return "";
|
|
111
|
+
return this.head === 0 ? this.lines.join("") : this.lines.slice(this.head).join("");
|
|
112
|
+
}
|
|
113
|
+
appendLine(stream, line) {
|
|
114
|
+
const clean = line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
115
|
+
this.pushBoundedLine(`${clean}
|
|
116
|
+
`);
|
|
117
|
+
if (this.onLine) {
|
|
118
|
+
try {
|
|
119
|
+
this.onLine(stream, clean);
|
|
120
|
+
} catch {
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (stream === "stdout" && this.sessionId === null) this.detectSessionId(clean);
|
|
124
|
+
}
|
|
125
|
+
pushBoundedLine(entry) {
|
|
126
|
+
if (this.maxChars <= 0) return;
|
|
127
|
+
if (entry.length >= this.maxChars) {
|
|
128
|
+
const truncated = entry.slice(-this.maxChars);
|
|
129
|
+
this.lines = [truncated];
|
|
130
|
+
this.head = 0;
|
|
131
|
+
this.totalChars = truncated.length;
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
this.lines.push(entry);
|
|
135
|
+
this.totalChars += entry.length;
|
|
136
|
+
while (this.totalChars > this.maxChars && this.head < this.lines.length) {
|
|
137
|
+
const first = this.lines[this.head];
|
|
138
|
+
if (this.totalChars - first.length >= this.maxChars) {
|
|
139
|
+
this.totalChars -= first.length;
|
|
140
|
+
this.lines[this.head] = "";
|
|
141
|
+
this.head += 1;
|
|
142
|
+
} else {
|
|
143
|
+
const overflow = this.totalChars - this.maxChars;
|
|
144
|
+
this.lines[this.head] = first.slice(overflow);
|
|
145
|
+
this.totalChars = this.maxChars;
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (this.head >= 1024 && this.head * 2 >= this.lines.length) {
|
|
150
|
+
this.lines = this.lines.slice(this.head);
|
|
151
|
+
this.head = 0;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
detectSessionId(line) {
|
|
155
|
+
if (!line.startsWith("{") || !line.includes("ses_")) return;
|
|
156
|
+
let event;
|
|
157
|
+
try {
|
|
158
|
+
event = JSON.parse(line);
|
|
159
|
+
} catch {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const sessionId = topLevelSessionId(event);
|
|
163
|
+
if (!sessionId) return;
|
|
164
|
+
this.sessionId = sessionId;
|
|
165
|
+
this.onSessionId(sessionId);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
function topLevelSessionId(event) {
|
|
169
|
+
if (event === null || typeof event !== "object" || Array.isArray(event)) return null;
|
|
170
|
+
const record = event;
|
|
171
|
+
const value = record.sessionID ?? record.sessionId;
|
|
172
|
+
return typeof value === "string" && SESSION_ID_PATTERN.test(value) ? value : null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/worker/index.ts
|
|
176
|
+
var DEFAULT_MAX_OUTPUT_CHARS = 64 * 1024;
|
|
177
|
+
var FORBIDDEN_AGENT = "supertask-runner";
|
|
178
|
+
function runCommandContext(executable, args, cwd) {
|
|
179
|
+
return JSON.stringify({
|
|
180
|
+
type: "supertask_command",
|
|
181
|
+
executable,
|
|
182
|
+
args,
|
|
183
|
+
cwd
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
function assertWorkerProcessIsolationSupported(platform = process.platform) {
|
|
187
|
+
if (platform === "win32") {
|
|
188
|
+
throw new Error(
|
|
189
|
+
"Windows Worker \u5DF2\u5B89\u5168\u7981\u7528\uFF1A\u5F53\u524D\u8FD0\u884C\u65F6\u65E0\u6CD5\u7528 Job Object \u63D0\u4F9B\u7B49\u4EF7\u7684\u53D7\u7BA1\u8FDB\u7A0B\u9694\u79BB\u4E0E\u6392\u7A7A\u8BC1\u660E"
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
var WorkerEngine = class {
|
|
194
|
+
activeBatchIds = /* @__PURE__ */ new Set();
|
|
195
|
+
runningTasks = /* @__PURE__ */ new Map();
|
|
196
|
+
stopped = false;
|
|
197
|
+
wakePending = false;
|
|
198
|
+
consecutiveIdlePolls = 0;
|
|
199
|
+
unsubscribeWake = null;
|
|
200
|
+
pollTimer = null;
|
|
201
|
+
heartbeatTimer = null;
|
|
202
|
+
pollCyclePromise = null;
|
|
203
|
+
shutdownDeadlineMs = null;
|
|
204
|
+
settlementRetryWakeups = /* @__PURE__ */ new Set();
|
|
205
|
+
cfg;
|
|
206
|
+
opencodeBin;
|
|
207
|
+
maxOutputChars;
|
|
208
|
+
settlementRetryDelaysMs;
|
|
209
|
+
settlementRetryIntervalMs;
|
|
210
|
+
constructor(cfg, options = {}) {
|
|
211
|
+
this.cfg = cfg.worker;
|
|
212
|
+
this.opencodeBin = options.opencodeBin ?? openCodeExecutable();
|
|
213
|
+
this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
|
|
214
|
+
this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1e3, 4e3];
|
|
215
|
+
this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5e3;
|
|
216
|
+
}
|
|
217
|
+
start() {
|
|
218
|
+
assertWorkerProcessIsolationSupported();
|
|
219
|
+
this.stopped = false;
|
|
220
|
+
this.wakePending = false;
|
|
221
|
+
this.consecutiveIdlePolls = 0;
|
|
222
|
+
this.shutdownDeadlineMs = null;
|
|
223
|
+
this.unsubscribeWake?.();
|
|
224
|
+
this.unsubscribeWake = gatewayEvents.registerWakeHandler((reason) => this.wake(reason));
|
|
225
|
+
markGatewayActivity("worker");
|
|
226
|
+
this.poll();
|
|
227
|
+
this.heartbeatTimer = setInterval(() => {
|
|
228
|
+
this.runDetached(this.updateHeartbeats(), "worker heartbeat cycle failed");
|
|
229
|
+
}, this.cfg.heartbeatIntervalMs);
|
|
230
|
+
}
|
|
231
|
+
wake(_reason) {
|
|
232
|
+
if (this.stopped) return;
|
|
233
|
+
this.consecutiveIdlePolls = 0;
|
|
234
|
+
if (this.pollCyclePromise) {
|
|
235
|
+
this.wakePending = true;
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (this.pollTimer) {
|
|
239
|
+
clearTimeout(this.pollTimer);
|
|
240
|
+
this.pollTimer = null;
|
|
241
|
+
}
|
|
242
|
+
this.pollTimer = setTimeout(() => {
|
|
243
|
+
this.pollTimer = null;
|
|
244
|
+
this.poll();
|
|
245
|
+
}, 0);
|
|
246
|
+
}
|
|
247
|
+
async stop(gracePeriodMs = 0) {
|
|
248
|
+
this.stopped = true;
|
|
249
|
+
this.wakePending = false;
|
|
250
|
+
this.unsubscribeWake?.();
|
|
251
|
+
this.unsubscribeWake = null;
|
|
252
|
+
this.shutdownDeadlineMs = Date.now() + Math.max(0, gracePeriodMs);
|
|
253
|
+
for (const wake of [...this.settlementRetryWakeups]) wake();
|
|
254
|
+
if (this.pollTimer) {
|
|
255
|
+
clearTimeout(this.pollTimer);
|
|
256
|
+
this.pollTimer = null;
|
|
257
|
+
}
|
|
258
|
+
if (this.pollCyclePromise) await this.pollCyclePromise;
|
|
259
|
+
if (gracePeriodMs > 0 && this.runningTasks.size > 0) {
|
|
260
|
+
const deadline = Date.now() + gracePeriodMs;
|
|
261
|
+
while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
|
|
262
|
+
await Bun.sleep(Math.min(50, deadline - Date.now()));
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (this.heartbeatTimer) {
|
|
266
|
+
clearInterval(this.heartbeatTimer);
|
|
267
|
+
this.heartbeatTimer = null;
|
|
268
|
+
}
|
|
269
|
+
const interrupted = [];
|
|
270
|
+
const entries = [...this.runningTasks.values()];
|
|
271
|
+
await Promise.all(entries.map(async (entry) => {
|
|
272
|
+
if (entry.settled) {
|
|
273
|
+
if (entry.settlementPromise) await entry.settlementPromise;
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const termination = entry.termination ?? {
|
|
277
|
+
kind: "shutdown",
|
|
278
|
+
message: "Gateway shutdown"
|
|
279
|
+
};
|
|
280
|
+
const terminated = await this.terminateEntry(entry, termination);
|
|
281
|
+
if (terminated && termination.kind === "shutdown") {
|
|
282
|
+
interrupted.push({ taskId: entry.task.id, runId: entry.runId });
|
|
283
|
+
}
|
|
284
|
+
}));
|
|
285
|
+
return interrupted;
|
|
286
|
+
}
|
|
287
|
+
getRunningTaskIds() {
|
|
288
|
+
return [...this.runningTasks.keys()];
|
|
289
|
+
}
|
|
290
|
+
getRunningCount() {
|
|
291
|
+
return this.runningTasks.size;
|
|
292
|
+
}
|
|
293
|
+
ownsRun(taskId, runId) {
|
|
294
|
+
return this.runningTasks.get(taskId)?.runId === runId;
|
|
295
|
+
}
|
|
296
|
+
nextPollDelayMs() {
|
|
297
|
+
const base = this.cfg.pollIntervalMs;
|
|
298
|
+
if (base < 500 || this.consecutiveIdlePolls <= 1 || this.runningTasks.size > 0) {
|
|
299
|
+
return base;
|
|
300
|
+
}
|
|
301
|
+
const maxIdleMs = Math.max(base, Math.min(base * 2, 2500));
|
|
302
|
+
const step = Math.min(this.consecutiveIdlePolls - 1, 3);
|
|
303
|
+
return Math.max(base, Math.min(maxIdleMs, Math.round(base * (1 + step * 0.5))));
|
|
304
|
+
}
|
|
305
|
+
poll() {
|
|
306
|
+
if (this.stopped) return;
|
|
307
|
+
if (this.pollTimer) {
|
|
308
|
+
clearTimeout(this.pollTimer);
|
|
309
|
+
this.pollTimer = null;
|
|
310
|
+
}
|
|
311
|
+
this.wakePending = false;
|
|
312
|
+
markGatewayActivity("worker");
|
|
313
|
+
this.pollCyclePromise = this.tryDispatch().then(({ healthy, dispatched }) => {
|
|
314
|
+
if (dispatched > 0) this.consecutiveIdlePolls = 0;
|
|
315
|
+
else this.consecutiveIdlePolls += 1;
|
|
316
|
+
if (healthy) markGatewaySuccess("worker");
|
|
317
|
+
}).catch((err) => {
|
|
318
|
+
this.consecutiveIdlePolls = 0;
|
|
319
|
+
markGatewayFailure("worker", err);
|
|
320
|
+
this.logError("worker poll failed", err);
|
|
321
|
+
}).finally(() => {
|
|
322
|
+
this.pollCyclePromise = null;
|
|
323
|
+
if (this.stopped) return;
|
|
324
|
+
if (this.wakePending) {
|
|
325
|
+
this.wakePending = false;
|
|
326
|
+
this.pollTimer = setTimeout(() => {
|
|
327
|
+
this.pollTimer = null;
|
|
328
|
+
this.poll();
|
|
329
|
+
}, 0);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
this.pollTimer = setTimeout(() => {
|
|
333
|
+
this.pollTimer = null;
|
|
334
|
+
this.poll();
|
|
335
|
+
}, this.nextPollDelayMs());
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
async tryDispatch() {
|
|
339
|
+
await TaskService.resetOrphanRunningToPending();
|
|
340
|
+
await this.reconcileCancelledTasks();
|
|
341
|
+
await this.reconcileQuarantinedTasks();
|
|
342
|
+
let dispatched = 0;
|
|
343
|
+
while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {
|
|
344
|
+
const databaseRunningCount = await TaskService.countRunning();
|
|
345
|
+
if (databaseRunningCount >= this.cfg.maxConcurrency) break;
|
|
346
|
+
const openCode = await detectOpenCodeVersion(this.opencodeBin);
|
|
347
|
+
if (this.stopped) break;
|
|
348
|
+
let task;
|
|
349
|
+
try {
|
|
350
|
+
task = await TaskService.claimNext({ excludedBatchIds: [...this.activeBatchIds] });
|
|
351
|
+
} catch (err) {
|
|
352
|
+
this.logError("task claim failed", err);
|
|
353
|
+
throw err;
|
|
354
|
+
}
|
|
355
|
+
if (!task) break;
|
|
356
|
+
if (this.stopped) {
|
|
357
|
+
await TaskService.resetRunningToPending([task.id]);
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
dispatched += 1;
|
|
361
|
+
const batchId = normalizeTaskBatchId(task.batchId);
|
|
362
|
+
if (batchId) this.activeBatchIds.add(batchId);
|
|
363
|
+
gatewayEvents.emitTaskChanged({
|
|
364
|
+
taskId: task.id,
|
|
365
|
+
cwd: task.cwd,
|
|
366
|
+
status: "running",
|
|
367
|
+
reason: "task-claimed"
|
|
368
|
+
});
|
|
369
|
+
let runId = null;
|
|
370
|
+
try {
|
|
371
|
+
const launchIdentity = `gateway-${process.pid}:launch:${randomUUID()}`;
|
|
372
|
+
const run = await TaskRunService.create({
|
|
373
|
+
taskId: task.id,
|
|
374
|
+
model: this.resolveModel(task.model),
|
|
375
|
+
variant: this.resolveVariant(task.variant),
|
|
376
|
+
status: "running",
|
|
377
|
+
workerPid: process.pid,
|
|
378
|
+
lockedAt: Date.now(),
|
|
379
|
+
lockedBy: launchIdentity,
|
|
380
|
+
launchProtocol: TOKEN_GUARDIAN_LAUNCH_PROTOCOL
|
|
381
|
+
});
|
|
382
|
+
runId = run.id;
|
|
383
|
+
if (this.stopped) {
|
|
384
|
+
await TaskRunService.fail(run.id, "Gateway shutdown before spawn");
|
|
385
|
+
await TaskService.resetRunningToPending([task.id]);
|
|
386
|
+
this.releaseBatch(task);
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
if (task.agent === FORBIDDEN_AGENT) {
|
|
390
|
+
const message = `\u7981\u6B62\u6267\u884C\u9012\u5F52 Agent: ${FORBIDDEN_AGENT}`;
|
|
391
|
+
await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });
|
|
392
|
+
this.releaseBatch(task);
|
|
393
|
+
continue;
|
|
394
|
+
}
|
|
395
|
+
try {
|
|
396
|
+
validateTaskWorkingDirectory(task.cwd);
|
|
397
|
+
} catch (error) {
|
|
398
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
399
|
+
await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });
|
|
400
|
+
this.releaseBatch(task);
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
let args;
|
|
404
|
+
try {
|
|
405
|
+
args = buildOpenCodeRunArgs(openCode.major, {
|
|
406
|
+
agent: task.agent,
|
|
407
|
+
model: this.resolveModel(task.model),
|
|
408
|
+
variant: this.resolveVariant(task.variant),
|
|
409
|
+
prompt: task.prompt,
|
|
410
|
+
title: task.name
|
|
411
|
+
});
|
|
412
|
+
} catch (error) {
|
|
413
|
+
if (!(error instanceof OpenCodeInvocationError)) throw error;
|
|
414
|
+
await TaskService.failRun(task.id, run.id, `${error.message}\uFF08OpenCode ${openCode.version}\uFF09`, { setDeadLetter: true });
|
|
415
|
+
this.releaseBatch(task);
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
await this.spawnTask(task, run.id, launchIdentity, args);
|
|
419
|
+
} catch (err) {
|
|
420
|
+
this.releaseBatch(task);
|
|
421
|
+
const message = `Worker \u542F\u52A8\u4EFB\u52A1\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}`;
|
|
422
|
+
try {
|
|
423
|
+
if (runId == null) {
|
|
424
|
+
await TaskService.fail(task.id, message);
|
|
425
|
+
} else {
|
|
426
|
+
const failed = await TaskService.failRun(task.id, runId, message);
|
|
427
|
+
if (!failed) {
|
|
428
|
+
await TaskRunService.fail(runId, `${message}
|
|
429
|
+
\u4EFB\u52A1\u72B6\u6001\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u6539\u53D8`);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
} catch (failErr) {
|
|
433
|
+
this.logError("failed to compensate task startup", failErr, task.id);
|
|
434
|
+
}
|
|
435
|
+
this.logError("task dispatch failed", err, task.id);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return {
|
|
439
|
+
healthy: ![...this.runningTasks.values()].some((entry) => entry.quarantined),
|
|
440
|
+
dispatched
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
launcherEntry() {
|
|
444
|
+
const extension = import.meta.url.endsWith(".ts") ? "ts" : "js";
|
|
445
|
+
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
446
|
+
const candidates = [
|
|
447
|
+
join(moduleDir, `launcher.${extension}`),
|
|
448
|
+
join(moduleDir, `../worker/launcher.${extension}`)
|
|
449
|
+
];
|
|
450
|
+
const entry = candidates.find((candidate) => existsSync(candidate));
|
|
451
|
+
if (!entry) throw new Error(`Worker launcher \u4E0D\u5B58\u5728\uFF1A${candidates.join(", ")}`);
|
|
452
|
+
return entry;
|
|
453
|
+
}
|
|
454
|
+
async spawnTask(task, runId, launchIdentity, args) {
|
|
455
|
+
const cwd = task.cwd || process.cwd();
|
|
456
|
+
const child = spawn(process.execPath, [
|
|
457
|
+
this.launcherEntry(),
|
|
458
|
+
LAUNCH_IDENTITY_ARGUMENT,
|
|
459
|
+
launchIdentity,
|
|
460
|
+
this.opencodeBin,
|
|
461
|
+
...args
|
|
462
|
+
], {
|
|
463
|
+
cwd,
|
|
464
|
+
env: {
|
|
465
|
+
...process.env,
|
|
466
|
+
PWD: cwd,
|
|
467
|
+
[MANAGED_RUN_ENV]: MANAGED_RUN_ENV_VALUE
|
|
468
|
+
},
|
|
469
|
+
stdio: ["pipe", "pipe", "pipe", "ipc"],
|
|
470
|
+
detached: process.platform !== "win32"
|
|
471
|
+
});
|
|
472
|
+
const entry = {
|
|
473
|
+
task,
|
|
474
|
+
runId,
|
|
475
|
+
launchIdentity,
|
|
476
|
+
child,
|
|
477
|
+
commandContext: runCommandContext(this.opencodeBin, args, cwd),
|
|
478
|
+
output: new RunOutput(
|
|
479
|
+
this.maxOutputChars,
|
|
480
|
+
(sessionId) => {
|
|
481
|
+
TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
|
|
482
|
+
this.logError("sessionId update failed", err, task.id);
|
|
483
|
+
});
|
|
484
|
+
},
|
|
485
|
+
(stream, line) => {
|
|
486
|
+
gatewayEvents.emitRunLog(runId, task.id, stream, line);
|
|
487
|
+
}
|
|
488
|
+
),
|
|
489
|
+
timeoutTimer: null,
|
|
490
|
+
termination: null,
|
|
491
|
+
terminationPromise: null,
|
|
492
|
+
settlementPromise: null,
|
|
493
|
+
guardianDrained: false,
|
|
494
|
+
quarantined: false,
|
|
495
|
+
settled: false
|
|
496
|
+
};
|
|
497
|
+
this.runningTasks.set(task.id, entry);
|
|
498
|
+
child.stdout?.setEncoding("utf8");
|
|
499
|
+
child.stderr?.setEncoding("utf8");
|
|
500
|
+
child.stdout?.on("data", (chunk) => entry.output.push("stdout", chunk));
|
|
501
|
+
child.stderr?.on("data", (chunk) => entry.output.push("stderr", chunk));
|
|
502
|
+
child.on("message", (message) => {
|
|
503
|
+
if (isMatchingDrainProof(message, entry.launchIdentity)) {
|
|
504
|
+
entry.guardianDrained = true;
|
|
505
|
+
try {
|
|
506
|
+
child.send(drainProofAckForIdentity(entry.launchIdentity));
|
|
507
|
+
} catch (error) {
|
|
508
|
+
this.logError("drain proof acknowledgment failed", error, task.id);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
let spawnError = null;
|
|
513
|
+
let started = false;
|
|
514
|
+
const spawned = new Promise((resolve, reject) => {
|
|
515
|
+
child.once("spawn", () => {
|
|
516
|
+
started = true;
|
|
517
|
+
resolve();
|
|
518
|
+
});
|
|
519
|
+
child.on("error", (error) => {
|
|
520
|
+
if (started) {
|
|
521
|
+
this.logError("launcher process error", error, task.id);
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
spawnError = error;
|
|
525
|
+
reject(error);
|
|
526
|
+
});
|
|
527
|
+
});
|
|
528
|
+
child.once("close", (code, signal) => {
|
|
529
|
+
this.handleChildClose(entry, code, signal, spawnError);
|
|
530
|
+
});
|
|
531
|
+
try {
|
|
532
|
+
await spawned;
|
|
533
|
+
} catch (error) {
|
|
534
|
+
entry.settled = true;
|
|
535
|
+
this.runningTasks.delete(task.id);
|
|
536
|
+
this.releaseBatch(task);
|
|
537
|
+
throw error;
|
|
538
|
+
}
|
|
539
|
+
const childPid = child.pid;
|
|
540
|
+
if (!childPid) {
|
|
541
|
+
entry.settled = true;
|
|
542
|
+
this.runningTasks.delete(task.id);
|
|
543
|
+
this.releaseBatch(task);
|
|
544
|
+
throw new Error("launcher \u672A\u8FD4\u56DE PID");
|
|
545
|
+
}
|
|
546
|
+
let pidRecorded = false;
|
|
547
|
+
try {
|
|
548
|
+
pidRecorded = await TaskRunService.updatePid(
|
|
549
|
+
runId,
|
|
550
|
+
process.pid,
|
|
551
|
+
childPid,
|
|
552
|
+
launchIdentity
|
|
553
|
+
) !== null;
|
|
554
|
+
} catch (error) {
|
|
555
|
+
await this.terminateForFailure(
|
|
556
|
+
entry,
|
|
557
|
+
`\u8BB0\u5F55 Worker PID \u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
558
|
+
);
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
if (!pidRecorded) {
|
|
562
|
+
await this.terminateForFailure(entry, "\u8BB0\u5F55 Worker PID \u5931\u8D25\uFF1Arun \u5DF2\u4E0D\u518D\u5904\u4E8E running \u72B6\u6001");
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
if (this.stopped) {
|
|
566
|
+
entry.termination = { kind: "shutdown", message: "Gateway shutdown" };
|
|
567
|
+
try {
|
|
568
|
+
child.stdin?.end();
|
|
569
|
+
} catch {
|
|
570
|
+
}
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
if (!child.stdin) {
|
|
574
|
+
await this.terminateForFailure(entry, "\u653E\u884C OpenCode \u5931\u8D25\uFF1Alauncher stdin \u4E0D\u53EF\u7528");
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
gatewayEvents.emitRunStarted({
|
|
578
|
+
runId,
|
|
579
|
+
taskId: task.id,
|
|
580
|
+
cwd: task.cwd,
|
|
581
|
+
model: this.resolveModel(task.model),
|
|
582
|
+
variant: this.resolveVariant(task.variant)
|
|
583
|
+
});
|
|
584
|
+
try {
|
|
585
|
+
await new Promise((resolve, reject) => {
|
|
586
|
+
child.stdin.end("START\n", (error) => {
|
|
587
|
+
if (error) reject(error);
|
|
588
|
+
else resolve();
|
|
589
|
+
});
|
|
590
|
+
});
|
|
591
|
+
} catch (error) {
|
|
592
|
+
await this.terminateForFailure(
|
|
593
|
+
entry,
|
|
594
|
+
`\u653E\u884C OpenCode \u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
595
|
+
);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
if (entry.settled || entry.termination) return;
|
|
599
|
+
const timeoutMs = task.timeoutMs ?? this.cfg.taskTimeoutMs;
|
|
600
|
+
if (timeoutMs > 0) {
|
|
601
|
+
entry.timeoutTimer = setTimeout(() => {
|
|
602
|
+
this.runDetached(
|
|
603
|
+
this.terminateForFailure(entry, `\u4EFB\u52A1\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09`, "SIGKILL"),
|
|
604
|
+
"timeout termination failed",
|
|
605
|
+
entry.task.id
|
|
606
|
+
);
|
|
607
|
+
}, timeoutMs);
|
|
608
|
+
entry.timeoutTimer.unref?.();
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
handleChildClose(entry, code, signal, spawnError) {
|
|
612
|
+
if (entry.settled || entry.termination) return;
|
|
613
|
+
if (!entry.guardianDrained) {
|
|
614
|
+
const pid2 = entry.child.pid;
|
|
615
|
+
const presence = pid2 == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid2);
|
|
616
|
+
const message = "guardian \u672A\u63D0\u4F9B\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A\u8BC1\u660E";
|
|
617
|
+
if (presence !== "not-running") {
|
|
618
|
+
if (entry.timeoutTimer) {
|
|
619
|
+
clearTimeout(entry.timeoutTimer);
|
|
620
|
+
entry.timeoutTimer = null;
|
|
621
|
+
}
|
|
622
|
+
entry.termination = { kind: "failure", message };
|
|
623
|
+
entry.quarantined = true;
|
|
624
|
+
markGatewayFailure(
|
|
625
|
+
"worker",
|
|
626
|
+
new Error(`${message}\uFF1B\u4EFB\u52A1 #${entry.task.id} \u4FDD\u6301\u9694\u79BB`)
|
|
627
|
+
);
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
this.runDetached(
|
|
631
|
+
this.settleEntry(entry, null, message),
|
|
632
|
+
"task settlement failed",
|
|
633
|
+
entry.task.id
|
|
634
|
+
);
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
const pid = entry.child.pid;
|
|
638
|
+
if (pid != null && inspectSpawnedProcessTreePresence(pid) !== "not-running") {
|
|
639
|
+
if (entry.timeoutTimer) {
|
|
640
|
+
clearTimeout(entry.timeoutTimer);
|
|
641
|
+
entry.timeoutTimer = null;
|
|
642
|
+
}
|
|
643
|
+
const message = "guardian \u9000\u51FA\u540E\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u4ECD\u5B58\u6D3B\u6216\u72B6\u6001\u4E0D\u660E";
|
|
644
|
+
entry.guardianDrained = false;
|
|
645
|
+
entry.termination = { kind: "failure", message };
|
|
646
|
+
entry.quarantined = true;
|
|
647
|
+
markGatewayFailure(
|
|
648
|
+
"worker",
|
|
649
|
+
new Error(`${message}\uFF1B\u4EFB\u52A1 #${entry.task.id} \u4FDD\u6301\u9694\u79BB`)
|
|
650
|
+
);
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
const failure = code === 0 ? void 0 : `${spawnError ? "\u65E0\u6CD5\u542F\u52A8 opencode" : "opencode \u9000\u51FA\u7801"} ${spawnError?.message ?? code ?? "null"}${signal ? `\uFF0C\u4FE1\u53F7 ${signal}` : ""}\uFF08agent=${entry.task.agent}\uFF0Cmodel=${this.resolveModel(entry.task.model) ?? "Agent/\u9ED8\u8BA4\u914D\u7F6E"}\uFF0Cvariant=${this.resolveVariant(entry.task.variant) ?? "Agent/\u6A21\u578B\u9ED8\u8BA4\u914D\u7F6E"}\uFF0Ccwd=${entry.task.cwd ?? process.cwd()}\uFF09`;
|
|
654
|
+
this.runDetached(
|
|
655
|
+
this.settleEntry(entry, code, failure),
|
|
656
|
+
"task settlement failed",
|
|
657
|
+
entry.task.id
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
settleEntry(entry, code, failure) {
|
|
661
|
+
if (entry.settlementPromise) return entry.settlementPromise;
|
|
662
|
+
if (entry.settled) return Promise.resolve(false);
|
|
663
|
+
entry.settled = true;
|
|
664
|
+
if (entry.timeoutTimer) {
|
|
665
|
+
clearTimeout(entry.timeoutTimer);
|
|
666
|
+
entry.timeoutTimer = null;
|
|
667
|
+
}
|
|
668
|
+
const settlement = this.commitEntryWithRetry(entry, code, failure).finally(() => {
|
|
669
|
+
this.runningTasks.delete(entry.task.id);
|
|
670
|
+
this.releaseBatch(entry.task);
|
|
671
|
+
if (!this.stopped) this.wake("task-settled");
|
|
672
|
+
});
|
|
673
|
+
entry.settlementPromise = settlement;
|
|
674
|
+
return settlement;
|
|
675
|
+
}
|
|
676
|
+
async commitEntryWithRetry(entry, code, failure) {
|
|
677
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
678
|
+
try {
|
|
679
|
+
await this.commitEntry(entry, code, failure);
|
|
680
|
+
return true;
|
|
681
|
+
} catch (error) {
|
|
682
|
+
markGatewayFailure("worker", error);
|
|
683
|
+
const shortRetryDelayMs = this.settlementRetryDelaysMs[attempt];
|
|
684
|
+
let retryDelayMs = shortRetryDelayMs ?? this.settlementRetryIntervalMs;
|
|
685
|
+
if (this.stopped) {
|
|
686
|
+
const remainingMs = Math.max(0, (this.shutdownDeadlineMs ?? 0) - Date.now());
|
|
687
|
+
if (remainingMs === 0) return false;
|
|
688
|
+
retryDelayMs = Math.min(retryDelayMs, remainingMs);
|
|
689
|
+
}
|
|
690
|
+
this.logError(
|
|
691
|
+
`task settlement failed; retrying in ${retryDelayMs}ms`,
|
|
692
|
+
error,
|
|
693
|
+
entry.task.id
|
|
694
|
+
);
|
|
695
|
+
await this.waitForSettlementRetry(retryDelayMs);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
waitForSettlementRetry(delayMs) {
|
|
700
|
+
return new Promise((resolve) => {
|
|
701
|
+
let timer;
|
|
702
|
+
const finish = () => {
|
|
703
|
+
clearTimeout(timer);
|
|
704
|
+
this.settlementRetryWakeups.delete(finish);
|
|
705
|
+
resolve();
|
|
706
|
+
};
|
|
707
|
+
timer = setTimeout(finish, delayMs);
|
|
708
|
+
this.settlementRetryWakeups.add(finish);
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
async commitEntry(entry, code, failure) {
|
|
712
|
+
const termination = entry.termination;
|
|
713
|
+
if (termination?.kind === "shutdown") return;
|
|
714
|
+
if (termination?.kind === "cancel") {
|
|
715
|
+
const output2 = this.outputWithCommand(entry);
|
|
716
|
+
const log2 = `${termination.message}${output2 ? `
|
|
717
|
+
${output2}` : ""}`;
|
|
718
|
+
await TaskRunService.fail(entry.runId, log2);
|
|
719
|
+
gatewayEvents.emitRunFinished({
|
|
720
|
+
runId: entry.runId,
|
|
721
|
+
taskId: entry.task.id,
|
|
722
|
+
status: "failed",
|
|
723
|
+
taskStatus: "cancelled",
|
|
724
|
+
cwd: entry.task.cwd
|
|
725
|
+
});
|
|
726
|
+
gatewayEvents.emitTaskChanged({
|
|
727
|
+
taskId: entry.task.id,
|
|
728
|
+
cwd: entry.task.cwd,
|
|
729
|
+
status: "cancelled",
|
|
730
|
+
reason: "run-cancelled"
|
|
731
|
+
});
|
|
732
|
+
console.log(JSON.stringify({
|
|
733
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
734
|
+
level: "info",
|
|
735
|
+
msg: "running task cancelled",
|
|
736
|
+
taskId: entry.task.id
|
|
737
|
+
}));
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
const currentRun = await TaskRunService.getById(entry.runId);
|
|
741
|
+
if (!currentRun || currentRun.status !== "running") return;
|
|
742
|
+
const output = this.outputWithCommand(entry);
|
|
743
|
+
const log = failure ? `${failure}${output ? `
|
|
744
|
+
${output}` : ""}` : output;
|
|
745
|
+
if (code === 0 && !failure) {
|
|
746
|
+
const completed = await TaskService.completeRun(entry.task.id, entry.runId, log);
|
|
747
|
+
if (completed) {
|
|
748
|
+
gatewayEvents.emitRunFinished({
|
|
749
|
+
runId: entry.runId,
|
|
750
|
+
taskId: entry.task.id,
|
|
751
|
+
status: "done",
|
|
752
|
+
taskStatus: "done",
|
|
753
|
+
cwd: entry.task.cwd
|
|
754
|
+
});
|
|
755
|
+
gatewayEvents.emitTaskChanged({
|
|
756
|
+
taskId: entry.task.id,
|
|
757
|
+
cwd: entry.task.cwd,
|
|
758
|
+
status: "done",
|
|
759
|
+
reason: "run-done"
|
|
760
|
+
});
|
|
761
|
+
console.log(JSON.stringify({
|
|
762
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
763
|
+
level: "info",
|
|
764
|
+
msg: "task done",
|
|
765
|
+
taskId: entry.task.id
|
|
766
|
+
}));
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
await TaskRunService.fail(entry.runId, "\u4EFB\u52A1\u6216\u6267\u884C\u8BB0\u5F55\u72B6\u6001\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u6539\u53D8");
|
|
770
|
+
gatewayEvents.emitRunFinished({
|
|
771
|
+
runId: entry.runId,
|
|
772
|
+
taskId: entry.task.id,
|
|
773
|
+
status: "failed",
|
|
774
|
+
cwd: entry.task.cwd
|
|
775
|
+
});
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
const failed = await TaskService.failRun(entry.task.id, entry.runId, log);
|
|
779
|
+
if (!failed) {
|
|
780
|
+
await TaskRunService.fail(
|
|
781
|
+
entry.runId,
|
|
782
|
+
`${log}${log ? "\n" : ""}\u4EFB\u52A1\u72B6\u6001\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u6539\u53D8`
|
|
783
|
+
);
|
|
784
|
+
this.logError("task failure state transition rejected", failure ?? "unknown failure", entry.task.id);
|
|
785
|
+
gatewayEvents.emitRunFinished({
|
|
786
|
+
runId: entry.runId,
|
|
787
|
+
taskId: entry.task.id,
|
|
788
|
+
status: "failed",
|
|
789
|
+
cwd: entry.task.cwd
|
|
790
|
+
});
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
gatewayEvents.emitRunFinished({
|
|
794
|
+
runId: entry.runId,
|
|
795
|
+
taskId: entry.task.id,
|
|
796
|
+
status: "failed",
|
|
797
|
+
taskStatus: failed.status,
|
|
798
|
+
cwd: entry.task.cwd
|
|
799
|
+
});
|
|
800
|
+
gatewayEvents.emitTaskChanged({
|
|
801
|
+
taskId: entry.task.id,
|
|
802
|
+
cwd: entry.task.cwd,
|
|
803
|
+
status: failed.status,
|
|
804
|
+
reason: "run-failed"
|
|
805
|
+
});
|
|
806
|
+
console.error(JSON.stringify({
|
|
807
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
808
|
+
level: "error",
|
|
809
|
+
msg: "task failed",
|
|
810
|
+
taskId: entry.task.id,
|
|
811
|
+
error: failure
|
|
812
|
+
}));
|
|
813
|
+
}
|
|
814
|
+
async reconcileCancelledTasks() {
|
|
815
|
+
for (const entry of [...this.runningTasks.values()]) {
|
|
816
|
+
try {
|
|
817
|
+
const task = await TaskService.getById(entry.task.id);
|
|
818
|
+
if (task?.status === "cancelled") await this.cancelEntry(entry);
|
|
819
|
+
} catch (err) {
|
|
820
|
+
this.logError("cancel reconciliation failed", err, entry.task.id);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
async reconcileQuarantinedTasks() {
|
|
825
|
+
for (const entry of [...this.runningTasks.values()]) {
|
|
826
|
+
if (!entry.quarantined || !entry.termination) continue;
|
|
827
|
+
await this.terminateEntry(entry, entry.termination);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
async cancelEntry(entry) {
|
|
831
|
+
await this.terminateEntry(entry, { kind: "cancel", message: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" });
|
|
832
|
+
}
|
|
833
|
+
async updateHeartbeats() {
|
|
834
|
+
for (const entry of this.runningTasks.values()) {
|
|
835
|
+
if (entry.quarantined) continue;
|
|
836
|
+
try {
|
|
837
|
+
await TaskRunService.heartbeat(entry.runId);
|
|
838
|
+
} catch (err) {
|
|
839
|
+
this.logError("heartbeat update failed", err, entry.task.id);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
async terminateForFailure(entry, message, initialSignal = "SIGTERM") {
|
|
844
|
+
return this.terminateEntry(entry, { kind: "failure", message }, initialSignal);
|
|
845
|
+
}
|
|
846
|
+
terminateEntry(entry, termination, initialSignal = "SIGTERM") {
|
|
847
|
+
if (entry.terminationPromise) return entry.terminationPromise;
|
|
848
|
+
if (entry.settled) return entry.settlementPromise ?? Promise.resolve(false);
|
|
849
|
+
entry.termination ??= termination;
|
|
850
|
+
if (entry.timeoutTimer) {
|
|
851
|
+
clearTimeout(entry.timeoutTimer);
|
|
852
|
+
entry.timeoutTimer = null;
|
|
853
|
+
}
|
|
854
|
+
entry.quarantined = true;
|
|
855
|
+
const terminationPromise = this.completeTermination(entry, initialSignal).finally(() => {
|
|
856
|
+
if (!entry.settled && entry.terminationPromise === terminationPromise) {
|
|
857
|
+
entry.terminationPromise = null;
|
|
858
|
+
}
|
|
859
|
+
});
|
|
860
|
+
entry.terminationPromise = terminationPromise;
|
|
861
|
+
return terminationPromise;
|
|
862
|
+
}
|
|
863
|
+
async completeTermination(entry, initialSignal) {
|
|
864
|
+
const termination = entry.termination;
|
|
865
|
+
if (!termination) return false;
|
|
866
|
+
try {
|
|
867
|
+
const exited = await this.killEntry(entry, initialSignal);
|
|
868
|
+
if (!exited) {
|
|
869
|
+
markGatewayFailure(
|
|
870
|
+
"worker",
|
|
871
|
+
new Error(`${termination.message}\uFF1B\u4EFB\u52A1 #${entry.task.id} \u7684\u8FDB\u7A0B\u65E0\u6CD5\u786E\u8BA4\u9000\u51FA`)
|
|
872
|
+
);
|
|
873
|
+
return false;
|
|
874
|
+
}
|
|
875
|
+
entry.quarantined = false;
|
|
876
|
+
return await this.settleEntry(
|
|
877
|
+
entry,
|
|
878
|
+
null,
|
|
879
|
+
termination.kind === "failure" ? termination.message : void 0
|
|
880
|
+
);
|
|
881
|
+
} catch (error) {
|
|
882
|
+
markGatewayFailure("worker", error);
|
|
883
|
+
this.logError("task termination failed", error, entry.task.id);
|
|
884
|
+
return false;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
async killEntry(entry, initialSignal = "SIGTERM") {
|
|
888
|
+
const pid = entry.child.pid;
|
|
889
|
+
if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && (!pid || inspectSpawnedProcessTreePresence(pid) === "not-running")) return true;
|
|
890
|
+
if (!pid) return false;
|
|
891
|
+
const initialResult = this.signalEntry(entry, initialSignal);
|
|
892
|
+
if (initialResult === "not-running") return true;
|
|
893
|
+
if (initialResult !== "signalled") return false;
|
|
894
|
+
if (await waitForSpawnedProcessTreeExit(pid, 2500)) return true;
|
|
895
|
+
if (initialSignal === "SIGKILL") return false;
|
|
896
|
+
if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && inspectSpawnedProcessTreePresence(pid) === "not-running") return true;
|
|
897
|
+
const forcedResult = this.signalEntry(entry, "SIGKILL");
|
|
898
|
+
if (forcedResult === "not-running") return true;
|
|
899
|
+
if (forcedResult !== "signalled") return false;
|
|
900
|
+
return waitForSpawnedProcessTreeExit(pid, 2500);
|
|
901
|
+
}
|
|
902
|
+
signalEntry(entry, signal) {
|
|
903
|
+
const pid = entry.child.pid;
|
|
904
|
+
if (!pid) return "not-running";
|
|
905
|
+
return signalRecordedProcessTreeWithResult(
|
|
906
|
+
pid,
|
|
907
|
+
signal,
|
|
908
|
+
this.opencodeBin,
|
|
909
|
+
TOKEN_GUARDIAN_LAUNCH_PROTOCOL,
|
|
910
|
+
entry.launchIdentity
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
releaseBatch(task) {
|
|
914
|
+
const batchId = normalizeTaskBatchId(task.batchId);
|
|
915
|
+
if (batchId) this.activeBatchIds.delete(batchId);
|
|
916
|
+
}
|
|
917
|
+
outputWithCommand(entry) {
|
|
918
|
+
entry.output.flush();
|
|
919
|
+
const output = entry.output.text().trim();
|
|
920
|
+
return `${entry.commandContext}${output ? `
|
|
921
|
+
${output}` : ""}`;
|
|
922
|
+
}
|
|
923
|
+
resolveModel(taskModel) {
|
|
924
|
+
const normalized = taskModel?.trim();
|
|
925
|
+
if (!normalized || normalized === "default") return null;
|
|
926
|
+
return normalized;
|
|
927
|
+
}
|
|
928
|
+
resolveVariant(taskVariant) {
|
|
929
|
+
return taskVariant?.trim() || null;
|
|
930
|
+
}
|
|
931
|
+
runDetached(operation, message, taskId) {
|
|
932
|
+
operation.catch((error) => {
|
|
933
|
+
markGatewayFailure("worker", error);
|
|
934
|
+
this.logError(message, error, taskId);
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
logError(message, error, taskId) {
|
|
938
|
+
console.error(JSON.stringify({
|
|
939
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
940
|
+
level: "error",
|
|
941
|
+
msg: message,
|
|
942
|
+
taskId,
|
|
943
|
+
error: error instanceof Error ? error.message : String(error)
|
|
944
|
+
}));
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
|
|
948
|
+
// src/gateway/watchdog/heartbeat.ts
|
|
949
|
+
async function checkHeartbeats(heartbeatTimeoutMs, isOwnedRun = () => false, shouldStop = () => false) {
|
|
950
|
+
const staleRuns = await TaskRunService.getStaleRuns(heartbeatTimeoutMs);
|
|
951
|
+
const result = {
|
|
952
|
+
staleRuns: staleRuns.length,
|
|
953
|
+
recoveredRuns: 0,
|
|
954
|
+
quarantinedRuns: 0,
|
|
955
|
+
failedRuns: 0
|
|
956
|
+
};
|
|
957
|
+
if (staleRuns.length === 0) return result;
|
|
958
|
+
for (const run of staleRuns) {
|
|
959
|
+
await Bun.sleep(1);
|
|
960
|
+
if (shouldStop()) break;
|
|
961
|
+
if (isOwnedRun(run.taskId, run.runId)) continue;
|
|
962
|
+
try {
|
|
963
|
+
if (run.launchProtocol != null && run.launchProtocol !== LEGACY_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
|
|
964
|
+
console.warn(JSON.stringify({
|
|
965
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
966
|
+
level: "warn",
|
|
967
|
+
msg: "unknown launch protocol remains quarantined",
|
|
968
|
+
taskId: run.taskId,
|
|
969
|
+
runId: run.runId,
|
|
970
|
+
launchProtocol: run.launchProtocol,
|
|
971
|
+
remediation: "\u5347\u7EA7\u5230\u652F\u6301\u8BE5\u534F\u8BAE\u7684 SuperTask \u7248\u672C\uFF1B\u7981\u6B62\u4F7F\u7528 run abandon \u7ED5\u8FC7\u672A\u77E5\u534F\u8BAE"
|
|
972
|
+
}));
|
|
973
|
+
result.quarantinedRuns += 1;
|
|
974
|
+
continue;
|
|
975
|
+
}
|
|
976
|
+
if (run.childPid != null && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
|
|
977
|
+
if (run.childPid > 0 && !isProcessAlive(run.childPid) && inspectSpawnedProcessTreePresence(run.childPid) === "not-running") {
|
|
978
|
+
} else {
|
|
979
|
+
console.warn(JSON.stringify({
|
|
980
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
981
|
+
level: "warn",
|
|
982
|
+
msg: "stale run has no per-run process identity; run remains quarantined",
|
|
983
|
+
taskId: run.taskId,
|
|
984
|
+
runId: run.runId,
|
|
985
|
+
childPid: run.childPid,
|
|
986
|
+
launchProtocol: run.launchProtocol,
|
|
987
|
+
remediation: "\u65E7\u542F\u52A8\u534F\u8BAE\u4E0D\u80FD\u6392\u9664 PID \u590D\u7528\uFF0C\u7981\u6B62\u81EA\u52A8\u7EC8\u6B62\uFF1B\u8BF7\u4EBA\u5DE5\u786E\u8BA4\u8FDB\u7A0B\u4E0E\u6570\u636E\u72B6\u6001"
|
|
988
|
+
}));
|
|
989
|
+
result.quarantinedRuns += 1;
|
|
990
|
+
continue;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
if (run.childPid == null && run.launchProtocol == null) {
|
|
994
|
+
console.warn(JSON.stringify({
|
|
995
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
996
|
+
level: "warn",
|
|
997
|
+
msg: "legacy stale run has no recorded child pid; run remains quarantined",
|
|
998
|
+
taskId: run.taskId,
|
|
999
|
+
runId: run.runId,
|
|
1000
|
+
remediation: {
|
|
1001
|
+
taskCwd: run.taskCwd,
|
|
1002
|
+
owner: run.ownerAlive ? `owner PID ${run.workerPid} \u4ECD\u5B58\u6D3B\uFF0C\u5FC5\u987B\u5148\u786E\u8BA4\u5E76\u505C\u6B62\u5BF9\u5E94\u8FDB\u7A0B` : "owner PID \u5DF2\u9000\u51FA\u6216\u672A\u8BB0\u5F55",
|
|
1003
|
+
cancelCommand: run.taskStatus === "cancelled" ? null : run.taskCwd == null ? `\u4EFB\u52A1\u6CA1\u6709\u8BB0\u5F55 cwd\uFF0C\u8BF7\u5728 Dashboard \u53D6\u6D88\u4EFB\u52A1 #${run.taskId}` : `\u5728 ${run.taskCwd} \u6267\u884C: supertask cancel --id ${run.taskId}`,
|
|
1004
|
+
abandonCommand: `\u786E\u8BA4\u6CA1\u6709\u9057\u7559 OpenCode \u8FDB\u7A0B\u540E\u6267\u884C: supertask run abandon --id ${run.runId} --confirm ABANDON`
|
|
1005
|
+
}
|
|
1006
|
+
}));
|
|
1007
|
+
result.quarantinedRuns += 1;
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
1010
|
+
if (run.childPid != null && run.childPid > 0 && run.launchProtocol === TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
|
|
1011
|
+
const expectedExecutable = openCodeExecutable();
|
|
1012
|
+
const signalResult = signalRecordedProcessTreeWithResult(
|
|
1013
|
+
run.childPid,
|
|
1014
|
+
"SIGKILL",
|
|
1015
|
+
expectedExecutable,
|
|
1016
|
+
run.launchProtocol,
|
|
1017
|
+
run.lockedBy
|
|
1018
|
+
);
|
|
1019
|
+
if (signalResult === "signalled") {
|
|
1020
|
+
const exited = await waitForSpawnedProcessTreeExit(run.childPid);
|
|
1021
|
+
if (!exited) {
|
|
1022
|
+
console.warn(JSON.stringify({
|
|
1023
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1024
|
+
level: "warn",
|
|
1025
|
+
msg: "stale child process did not exit; task remains quarantined",
|
|
1026
|
+
taskId: run.taskId,
|
|
1027
|
+
runId: run.runId,
|
|
1028
|
+
childPid: run.childPid
|
|
1029
|
+
}));
|
|
1030
|
+
result.quarantinedRuns += 1;
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
} else if (signalResult !== "not-running") {
|
|
1034
|
+
console.warn(JSON.stringify({
|
|
1035
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1036
|
+
level: "warn",
|
|
1037
|
+
msg: "stale child process could not be safely terminated; task remains quarantined",
|
|
1038
|
+
taskId: run.taskId,
|
|
1039
|
+
runId: run.runId,
|
|
1040
|
+
childPid: run.childPid,
|
|
1041
|
+
reason: signalResult
|
|
1042
|
+
}));
|
|
1043
|
+
result.quarantinedRuns += 1;
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
const recovery = await TaskService.recoverRun(
|
|
1048
|
+
run.taskId,
|
|
1049
|
+
run.runId,
|
|
1050
|
+
`\u6267\u884C\u6240\u6709\u8005\u9000\u51FA\u6216\u5FC3\u8DF3\u8D85\u65F6 (${heartbeatTimeoutMs / 1e3}s)\uFF0CWatchdog \u5DF2\u786E\u8BA4\u5B50\u8FDB\u7A0B\u7ED3\u675F`
|
|
1051
|
+
);
|
|
1052
|
+
if (!recovery) continue;
|
|
1053
|
+
result.recoveredRuns += 1;
|
|
1054
|
+
gatewayEvents.emitRunFinished({
|
|
1055
|
+
runId: run.runId,
|
|
1056
|
+
taskId: run.taskId,
|
|
1057
|
+
status: "failed",
|
|
1058
|
+
taskStatus: recovery.status,
|
|
1059
|
+
cwd: run.taskCwd
|
|
1060
|
+
});
|
|
1061
|
+
gatewayEvents.emitTaskChanged({
|
|
1062
|
+
taskId: run.taskId,
|
|
1063
|
+
cwd: run.taskCwd,
|
|
1064
|
+
status: recovery.status,
|
|
1065
|
+
reason: "watchdog-recover"
|
|
1066
|
+
});
|
|
1067
|
+
if (recovery.status === "pending" && (recovery.retryAfterMs == null || recovery.retryAfterMs <= Date.now())) {
|
|
1068
|
+
gatewayEvents.requestWake("watchdog-recover");
|
|
1069
|
+
}
|
|
1070
|
+
if (recovery.status === "dead_letter") {
|
|
1071
|
+
console.log(JSON.stringify({
|
|
1072
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1073
|
+
level: "warn",
|
|
1074
|
+
msg: "task dead_letter",
|
|
1075
|
+
taskId: run.taskId,
|
|
1076
|
+
runId: run.runId,
|
|
1077
|
+
retryCount: recovery.retryCount,
|
|
1078
|
+
maxRetries: run.taskMaxRetries
|
|
1079
|
+
}));
|
|
1080
|
+
} else {
|
|
1081
|
+
console.log(JSON.stringify({
|
|
1082
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1083
|
+
level: "warn",
|
|
1084
|
+
msg: "task retry scheduled",
|
|
1085
|
+
taskId: run.taskId,
|
|
1086
|
+
runId: run.runId,
|
|
1087
|
+
retryCount: recovery.retryCount,
|
|
1088
|
+
retryAfterMs: recovery.retryAfterMs == null ? null : Math.max(0, recovery.retryAfterMs - Date.now())
|
|
1089
|
+
}));
|
|
1090
|
+
}
|
|
1091
|
+
} catch (err) {
|
|
1092
|
+
result.failedRuns += 1;
|
|
1093
|
+
console.error(JSON.stringify({
|
|
1094
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1095
|
+
level: "error",
|
|
1096
|
+
msg: "failed to process stale run",
|
|
1097
|
+
runId: run.runId,
|
|
1098
|
+
taskId: run.taskId,
|
|
1099
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1100
|
+
}));
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
return result;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
// src/gateway/watchdog/cleanup.ts
|
|
1107
|
+
async function cleanupOldRecords(retentionDays, shouldStop = () => false) {
|
|
1108
|
+
const deletedTasks = await TaskService.deleteOlderThan(retentionDays, shouldStop);
|
|
1109
|
+
const deletedDelayedTemplates = await TaskTemplateService.deleteExpiredDelayed(
|
|
1110
|
+
retentionDays,
|
|
1111
|
+
shouldStop
|
|
1112
|
+
);
|
|
1113
|
+
if (deletedTasks > 0 || deletedDelayedTemplates > 0) {
|
|
1114
|
+
console.log(JSON.stringify({
|
|
1115
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1116
|
+
level: "info",
|
|
1117
|
+
msg: "cleanup completed",
|
|
1118
|
+
deletedTasks,
|
|
1119
|
+
deletedDelayedTemplates
|
|
1120
|
+
}));
|
|
1121
|
+
}
|
|
1122
|
+
return deletedTasks;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// src/gateway/watchdog/index.ts
|
|
1126
|
+
var Watchdog = class {
|
|
1127
|
+
constructor(cfg, isOwnedRun = () => false) {
|
|
1128
|
+
this.cfg = cfg;
|
|
1129
|
+
this.isOwnedRun = isOwnedRun;
|
|
1130
|
+
}
|
|
1131
|
+
cfg;
|
|
1132
|
+
isOwnedRun;
|
|
1133
|
+
stopped = false;
|
|
1134
|
+
heartbeatTimer = null;
|
|
1135
|
+
cleanupTimer = null;
|
|
1136
|
+
checkingHeartbeats = false;
|
|
1137
|
+
cleaning = false;
|
|
1138
|
+
heartbeatCheckPromise = null;
|
|
1139
|
+
cleanupPromise = null;
|
|
1140
|
+
start() {
|
|
1141
|
+
this.stopped = false;
|
|
1142
|
+
markGatewayActivity("watchdog");
|
|
1143
|
+
this.heartbeatTimer = setInterval(
|
|
1144
|
+
() => this.runHeartbeatCheck(),
|
|
1145
|
+
this.cfg.watchdog.checkIntervalMs
|
|
1146
|
+
);
|
|
1147
|
+
this.cleanupTimer = setInterval(
|
|
1148
|
+
() => this.runCleanup(),
|
|
1149
|
+
this.cfg.watchdog.cleanupIntervalMs
|
|
1150
|
+
);
|
|
1151
|
+
void this.runHeartbeatCheck();
|
|
1152
|
+
}
|
|
1153
|
+
async stop() {
|
|
1154
|
+
this.stopped = true;
|
|
1155
|
+
if (this.heartbeatTimer) {
|
|
1156
|
+
clearInterval(this.heartbeatTimer);
|
|
1157
|
+
this.heartbeatTimer = null;
|
|
1158
|
+
}
|
|
1159
|
+
if (this.cleanupTimer) {
|
|
1160
|
+
clearInterval(this.cleanupTimer);
|
|
1161
|
+
this.cleanupTimer = null;
|
|
1162
|
+
}
|
|
1163
|
+
await Promise.all([
|
|
1164
|
+
this.heartbeatCheckPromise,
|
|
1165
|
+
this.cleanupPromise
|
|
1166
|
+
]);
|
|
1167
|
+
}
|
|
1168
|
+
runHeartbeatCheck() {
|
|
1169
|
+
if (this.stopped) return Promise.resolve();
|
|
1170
|
+
if (this.heartbeatCheckPromise) return this.heartbeatCheckPromise;
|
|
1171
|
+
this.checkingHeartbeats = true;
|
|
1172
|
+
markGatewayActivity("watchdog");
|
|
1173
|
+
const operation = (async () => {
|
|
1174
|
+
try {
|
|
1175
|
+
const result = await checkHeartbeats(
|
|
1176
|
+
this.cfg.watchdog.heartbeatTimeoutMs,
|
|
1177
|
+
this.isOwnedRun,
|
|
1178
|
+
() => this.stopped
|
|
1179
|
+
);
|
|
1180
|
+
if (result.quarantinedRuns > 0 || result.failedRuns > 0) {
|
|
1181
|
+
throw new Error(
|
|
1182
|
+
`Watchdog \u6709 ${result.quarantinedRuns} \u4E2A\u9694\u79BB run\u3001${result.failedRuns} \u4E2A\u6062\u590D\u5931\u8D25 run`
|
|
1183
|
+
);
|
|
1184
|
+
}
|
|
1185
|
+
markGatewaySuccess("watchdog");
|
|
1186
|
+
} catch (err) {
|
|
1187
|
+
markGatewayFailure("watchdog", err);
|
|
1188
|
+
console.error(JSON.stringify({
|
|
1189
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1190
|
+
level: "error",
|
|
1191
|
+
msg: "watchdog heartbeat check failed",
|
|
1192
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1193
|
+
}));
|
|
1194
|
+
} finally {
|
|
1195
|
+
this.checkingHeartbeats = false;
|
|
1196
|
+
}
|
|
1197
|
+
})();
|
|
1198
|
+
this.heartbeatCheckPromise = operation.finally(() => {
|
|
1199
|
+
this.heartbeatCheckPromise = null;
|
|
1200
|
+
});
|
|
1201
|
+
return this.heartbeatCheckPromise;
|
|
1202
|
+
}
|
|
1203
|
+
runCleanup() {
|
|
1204
|
+
if (this.stopped) return Promise.resolve();
|
|
1205
|
+
if (this.cleanupPromise) return this.cleanupPromise;
|
|
1206
|
+
this.cleaning = true;
|
|
1207
|
+
markGatewayActivity("watchdogCleanup");
|
|
1208
|
+
const operation = (async () => {
|
|
1209
|
+
try {
|
|
1210
|
+
await cleanupOldRecords(
|
|
1211
|
+
this.cfg.watchdog.retentionDays,
|
|
1212
|
+
() => this.stopped
|
|
1213
|
+
);
|
|
1214
|
+
markGatewaySuccess("watchdogCleanup");
|
|
1215
|
+
} catch (err) {
|
|
1216
|
+
markGatewayFailure("watchdogCleanup", err);
|
|
1217
|
+
console.error(JSON.stringify({
|
|
1218
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1219
|
+
level: "error",
|
|
1220
|
+
msg: "watchdog cleanup failed",
|
|
1221
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1222
|
+
}));
|
|
1223
|
+
} finally {
|
|
1224
|
+
this.cleaning = false;
|
|
1225
|
+
}
|
|
1226
|
+
})();
|
|
1227
|
+
this.cleanupPromise = operation.finally(() => {
|
|
1228
|
+
this.cleanupPromise = null;
|
|
1229
|
+
});
|
|
1230
|
+
return this.cleanupPromise;
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
|
|
1234
|
+
// src/gateway/scheduler/index.ts
|
|
1235
|
+
var Scheduler = class {
|
|
1236
|
+
constructor(cfg) {
|
|
1237
|
+
this.cfg = cfg;
|
|
1238
|
+
}
|
|
1239
|
+
cfg;
|
|
1240
|
+
stopped = false;
|
|
1241
|
+
ticking = false;
|
|
1242
|
+
tickPromise = null;
|
|
1243
|
+
timer = null;
|
|
1244
|
+
dueSweep = null;
|
|
1245
|
+
async start() {
|
|
1246
|
+
if (!this.cfg.scheduler.enabled) return;
|
|
1247
|
+
this.stopped = false;
|
|
1248
|
+
markGatewayActivity("scheduler");
|
|
1249
|
+
await this.initializeTemplates();
|
|
1250
|
+
if (this.stopped) return;
|
|
1251
|
+
markGatewaySuccess("scheduler");
|
|
1252
|
+
this.timer = setInterval(() => {
|
|
1253
|
+
void this.tick();
|
|
1254
|
+
}, this.cfg.scheduler.checkIntervalMs);
|
|
1255
|
+
}
|
|
1256
|
+
async stop() {
|
|
1257
|
+
this.stopped = true;
|
|
1258
|
+
if (this.timer) {
|
|
1259
|
+
clearInterval(this.timer);
|
|
1260
|
+
this.timer = null;
|
|
1261
|
+
}
|
|
1262
|
+
if (this.tickPromise) {
|
|
1263
|
+
await this.tickPromise;
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
tick() {
|
|
1267
|
+
if (this.stopped || this.ticking) return this.tickPromise ?? Promise.resolve();
|
|
1268
|
+
const run = this.runTick().finally(() => {
|
|
1269
|
+
if (this.tickPromise === run) this.tickPromise = null;
|
|
1270
|
+
});
|
|
1271
|
+
this.tickPromise = run;
|
|
1272
|
+
return run;
|
|
1273
|
+
}
|
|
1274
|
+
async runTick() {
|
|
1275
|
+
if (this.stopped || this.ticking) return;
|
|
1276
|
+
markGatewayActivity("scheduler");
|
|
1277
|
+
this.ticking = true;
|
|
1278
|
+
let hadFailure = false;
|
|
1279
|
+
try {
|
|
1280
|
+
const sweep = this.dueSweep ?? { cutoffNow: Date.now(), cursor: null };
|
|
1281
|
+
const dueTemplates = await getDueTemplates(sweep.cursor, sweep.cutoffNow);
|
|
1282
|
+
const lastTemplate = dueTemplates.at(-1);
|
|
1283
|
+
for (const tmpl of dueTemplates) {
|
|
1284
|
+
if (this.stopped) break;
|
|
1285
|
+
try {
|
|
1286
|
+
const task = await cloneTaskFromTemplate(tmpl.id, tmpl.nextRunAt);
|
|
1287
|
+
if (task) {
|
|
1288
|
+
gatewayEvents.emitTaskChanged({
|
|
1289
|
+
taskId: task.id,
|
|
1290
|
+
cwd: task.cwd,
|
|
1291
|
+
status: task.status,
|
|
1292
|
+
reason: "scheduler-clone"
|
|
1293
|
+
});
|
|
1294
|
+
gatewayEvents.emitTemplateChanged({
|
|
1295
|
+
templateId: tmpl.id,
|
|
1296
|
+
reason: "scheduler-clone"
|
|
1297
|
+
});
|
|
1298
|
+
gatewayEvents.requestWake("scheduler-clone");
|
|
1299
|
+
console.log(JSON.stringify({
|
|
1300
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1301
|
+
level: "info",
|
|
1302
|
+
msg: "scheduled task created",
|
|
1303
|
+
templateId: tmpl.id,
|
|
1304
|
+
taskId: task.id
|
|
1305
|
+
}));
|
|
1306
|
+
}
|
|
1307
|
+
} catch (err) {
|
|
1308
|
+
hadFailure = true;
|
|
1309
|
+
markGatewayFailure("scheduler", err);
|
|
1310
|
+
console.error(JSON.stringify({
|
|
1311
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1312
|
+
level: "error",
|
|
1313
|
+
msg: "failed to clone from template",
|
|
1314
|
+
templateId: tmpl.id,
|
|
1315
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1316
|
+
}));
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
if (!this.stopped) {
|
|
1320
|
+
this.dueSweep = dueTemplates.length < DUE_TEMPLATE_BATCH_SIZE || lastTemplate?.nextRunAt == null ? null : {
|
|
1321
|
+
cutoffNow: sweep.cutoffNow,
|
|
1322
|
+
cursor: { nextRunAt: lastTemplate.nextRunAt, id: lastTemplate.id }
|
|
1323
|
+
};
|
|
1324
|
+
if (!hadFailure) markGatewaySuccess("scheduler");
|
|
1325
|
+
}
|
|
1326
|
+
} catch (err) {
|
|
1327
|
+
markGatewayFailure("scheduler", err);
|
|
1328
|
+
console.error(JSON.stringify({
|
|
1329
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1330
|
+
level: "error",
|
|
1331
|
+
msg: "scheduler tick failed",
|
|
1332
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1333
|
+
}));
|
|
1334
|
+
} finally {
|
|
1335
|
+
this.ticking = false;
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
async initializeTemplates() {
|
|
1339
|
+
const { taskTemplates } = schema_exports;
|
|
1340
|
+
const batchSize = 100;
|
|
1341
|
+
let cursor = 0;
|
|
1342
|
+
while (!this.stopped) {
|
|
1343
|
+
const templates = await db.select({ id: taskTemplates.id }).from(taskTemplates).where(and(
|
|
1344
|
+
eq(taskTemplates.enabled, true),
|
|
1345
|
+
isNull(taskTemplates.nextRunAt),
|
|
1346
|
+
gt(taskTemplates.id, cursor)
|
|
1347
|
+
)).orderBy(asc(taskTemplates.id)).limit(batchSize);
|
|
1348
|
+
if (templates.length === 0) break;
|
|
1349
|
+
for (const tmpl of templates) {
|
|
1350
|
+
if (this.stopped) break;
|
|
1351
|
+
await initializeNextRunAt(tmpl.id);
|
|
1352
|
+
}
|
|
1353
|
+
cursor = templates.at(-1).id;
|
|
1354
|
+
if (templates.length < batchSize) break;
|
|
1355
|
+
await Bun.sleep(0);
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
};
|
|
1359
|
+
|
|
1360
|
+
// src/gateway/index.ts
|
|
1361
|
+
var STALE_THRESHOLD_MS = 3e4;
|
|
1362
|
+
var MAX_TRANSIENT_HEARTBEAT_ERRORS = 2;
|
|
1363
|
+
var GATEWAY_DASHBOARD_IDLE_TIMEOUT_SECONDS = 60;
|
|
1364
|
+
function assertNoOrphanRunningTaskRuns() {
|
|
1365
|
+
const orphanRunningRun = sqlite.query(
|
|
1366
|
+
"SELECT 1 AS found FROM task_runs AS r LEFT JOIN tasks AS t ON t.id = r.task_id WHERE r.status = 'running' AND t.id IS NULL LIMIT 1"
|
|
1367
|
+
).get();
|
|
1368
|
+
if (orphanRunningRun) {
|
|
1369
|
+
throw new Error("\u68C0\u6D4B\u5230\u5931\u53BB\u7236\u4EFB\u52A1\u7684\u5B64\u7ACB running \u6267\u884C\u8BB0\u5F55\uFF0C\u8BF7\u5148\u4FEE\u590D\u6570\u636E\u5E93\u518D\u542F\u52A8 Gateway");
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
async function runGatewayShutdownStep(failures, step, operation) {
|
|
1373
|
+
try {
|
|
1374
|
+
await operation();
|
|
1375
|
+
} catch (error) {
|
|
1376
|
+
failures.push({
|
|
1377
|
+
step,
|
|
1378
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1379
|
+
});
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
function resolveGatewayShutdownExitCode(requestedExitCode, failures) {
|
|
1383
|
+
return failures.length > 0 ? 1 : requestedExitCode;
|
|
1384
|
+
}
|
|
1385
|
+
function acquireLock() {
|
|
1386
|
+
const now = Date.now();
|
|
1387
|
+
const pid = process.pid;
|
|
1388
|
+
try {
|
|
1389
|
+
sqlite.exec("BEGIN IMMEDIATE");
|
|
1390
|
+
const existing = sqlite.prepare("SELECT id, pid, heartbeat_at FROM gateway_lock WHERE id = 1").get();
|
|
1391
|
+
if (existing) {
|
|
1392
|
+
const lockHolderAlive = existing.pid !== pid && isProcessAlive(existing.pid);
|
|
1393
|
+
if (lockHolderAlive) {
|
|
1394
|
+
const identity = identifyGatewayProcess(existing.pid);
|
|
1395
|
+
const lockIsFresh = now - existing.heartbeat_at < STALE_THRESHOLD_MS;
|
|
1396
|
+
if (lockIsFresh || identity !== "mismatch") {
|
|
1397
|
+
sqlite.exec("ROLLBACK");
|
|
1398
|
+
console.error(JSON.stringify({
|
|
1399
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1400
|
+
level: "fatal",
|
|
1401
|
+
msg: "another Gateway instance is already running",
|
|
1402
|
+
existingPid: existing.pid,
|
|
1403
|
+
identity
|
|
1404
|
+
}));
|
|
1405
|
+
return false;
|
|
1406
|
+
}
|
|
1407
|
+
console.warn(JSON.stringify({
|
|
1408
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1409
|
+
level: "warn",
|
|
1410
|
+
msg: "taking over stale Gateway lock from a reused PID",
|
|
1411
|
+
existingPid: existing.pid
|
|
1412
|
+
}));
|
|
1413
|
+
}
|
|
1414
|
+
sqlite.exec("DELETE FROM gateway_lock WHERE id = 1");
|
|
1415
|
+
}
|
|
1416
|
+
sqlite.exec(
|
|
1417
|
+
"INSERT INTO gateway_lock (id, pid, acquired_at, heartbeat_at, ready_at) VALUES (1, ?, ?, ?, NULL)",
|
|
1418
|
+
[pid, now, now]
|
|
1419
|
+
);
|
|
1420
|
+
sqlite.exec("COMMIT");
|
|
1421
|
+
return true;
|
|
1422
|
+
} catch (err) {
|
|
1423
|
+
try {
|
|
1424
|
+
sqlite.exec("ROLLBACK");
|
|
1425
|
+
} catch {
|
|
1426
|
+
}
|
|
1427
|
+
console.error(JSON.stringify({
|
|
1428
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1429
|
+
level: "fatal",
|
|
1430
|
+
msg: "failed to acquire lock",
|
|
1431
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1432
|
+
}));
|
|
1433
|
+
return false;
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
function releaseLock() {
|
|
1437
|
+
try {
|
|
1438
|
+
sqlite.exec("DELETE FROM gateway_lock WHERE pid = ?", [process.pid]);
|
|
1439
|
+
} catch {
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
function updateLockHeartbeatResult() {
|
|
1443
|
+
try {
|
|
1444
|
+
const result = sqlite.query(
|
|
1445
|
+
"UPDATE gateway_lock SET heartbeat_at = ? WHERE id = 1 AND pid = ?"
|
|
1446
|
+
).run(Date.now(), process.pid);
|
|
1447
|
+
return result.changes === 1 ? { status: "ok" } : { status: "lost" };
|
|
1448
|
+
} catch (error) {
|
|
1449
|
+
return {
|
|
1450
|
+
status: "error",
|
|
1451
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1452
|
+
};
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
function updateLockHeartbeat() {
|
|
1456
|
+
return updateLockHeartbeatResult().status === "ok";
|
|
1457
|
+
}
|
|
1458
|
+
var TRANSIENT_LOCK_HEARTBEAT_ERROR_PATTERN = /\b(SQLITE_BUSY|SQLITE_LOCKED)\b|database is locked|database table is locked/i;
|
|
1459
|
+
function isTransientLockHeartbeatError(error) {
|
|
1460
|
+
return typeof error === "string" && TRANSIENT_LOCK_HEARTBEAT_ERROR_PATTERN.test(error);
|
|
1461
|
+
}
|
|
1462
|
+
function createLockHeartbeatTracker(options = {}) {
|
|
1463
|
+
const maxTransientErrors = options.maxTransientErrors ?? MAX_TRANSIENT_HEARTBEAT_ERRORS;
|
|
1464
|
+
const staleThresholdMs = options.staleThresholdMs ?? STALE_THRESHOLD_MS;
|
|
1465
|
+
let consecutiveTransientErrors = 0;
|
|
1466
|
+
let lastOkAt = options.now ?? Date.now();
|
|
1467
|
+
return {
|
|
1468
|
+
record(result, now = Date.now()) {
|
|
1469
|
+
if (result.status === "ok") {
|
|
1470
|
+
consecutiveTransientErrors = 0;
|
|
1471
|
+
lastOkAt = now;
|
|
1472
|
+
return "ok";
|
|
1473
|
+
}
|
|
1474
|
+
if (result.status === "lost") {
|
|
1475
|
+
return "lost";
|
|
1476
|
+
}
|
|
1477
|
+
if (!isTransientLockHeartbeatError(result.error)) {
|
|
1478
|
+
return "lost";
|
|
1479
|
+
}
|
|
1480
|
+
consecutiveTransientErrors += 1;
|
|
1481
|
+
if (consecutiveTransientErrors <= maxTransientErrors && now - lastOkAt < staleThresholdMs) {
|
|
1482
|
+
return "retry";
|
|
1483
|
+
}
|
|
1484
|
+
return "lost";
|
|
1485
|
+
}
|
|
1486
|
+
};
|
|
1487
|
+
}
|
|
1488
|
+
function markGatewayReady() {
|
|
1489
|
+
const now = Date.now();
|
|
1490
|
+
const result = sqlite.query(
|
|
1491
|
+
"UPDATE gateway_lock SET heartbeat_at = ?, ready_at = ?, version = ? WHERE id = 1 AND pid = ?"
|
|
1492
|
+
).run(now, now, getPackageVersion(), process.pid);
|
|
1493
|
+
if (result.changes !== 1) {
|
|
1494
|
+
throw new Error("Gateway \u5728\u5C31\u7EEA\u524D\u5931\u53BB\u4E86\u6570\u636E\u5E93\u5355\u5B9E\u4F8B\u9501");
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
function markGatewayNotReady() {
|
|
1498
|
+
try {
|
|
1499
|
+
sqlite.exec("UPDATE gateway_lock SET ready_at = NULL WHERE pid = ?", [process.pid]);
|
|
1500
|
+
} catch {
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
async function runGatewayMain(deps = {}) {
|
|
1504
|
+
const assertIsolation = deps.assertIsolationSupported ?? assertWorkerProcessIsolationSupported;
|
|
1505
|
+
const loadGatewayConfig = deps.loadConfig ?? loadConfig;
|
|
1506
|
+
const acquireGatewayLock = deps.acquireLock ?? acquireLock;
|
|
1507
|
+
const releaseGatewayLock = deps.releaseLock ?? releaseLock;
|
|
1508
|
+
const checkLockHeartbeat = deps.updateLockHeartbeatResult ?? updateLockHeartbeatResult;
|
|
1509
|
+
const markReady = deps.markGatewayReady ?? markGatewayReady;
|
|
1510
|
+
const markNotReady = deps.markGatewayNotReady ?? markGatewayNotReady;
|
|
1511
|
+
const checkOrphanRuns = deps.assertNoOrphanRunningTaskRuns ?? assertNoOrphanRunningTaskRuns;
|
|
1512
|
+
const resetOrphans = deps.resetOrphanRunningToPending ?? (() => TaskService.resetOrphanRunningToPending());
|
|
1513
|
+
const resolveDeps = deps.resolveBlockedDependencies ?? (() => TaskService.resolveBlockedDependencies());
|
|
1514
|
+
const interruptRun = deps.interruptRun ?? ((taskId, runId, reason) => TaskService.interruptRun(taskId, runId, reason));
|
|
1515
|
+
const closeDatabase = deps.closeDb ?? closeDb;
|
|
1516
|
+
const createWorker = deps.createWorker ?? ((cfg2) => new WorkerEngine(cfg2));
|
|
1517
|
+
const createWatchdog = deps.createWatchdog ?? ((cfg2, ownsRun) => new Watchdog(cfg2, ownsRun));
|
|
1518
|
+
const createScheduler = deps.createScheduler ?? ((cfg2) => new Scheduler(cfg2));
|
|
1519
|
+
const exitProcess = deps.exit ?? ((code) => {
|
|
1520
|
+
process.exit(code);
|
|
1521
|
+
});
|
|
1522
|
+
const heartbeatIntervalMs = deps.heartbeatIntervalMs ?? 1e4;
|
|
1523
|
+
const registerProcessHandlers = deps.registerProcessHandlers ?? true;
|
|
1524
|
+
console.log(JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), level: "info", msg: "SuperTask Gateway starting", pid: process.pid }));
|
|
1525
|
+
assertIsolation();
|
|
1526
|
+
const cfg = loadGatewayConfig();
|
|
1527
|
+
if (!acquireGatewayLock()) {
|
|
1528
|
+
exitProcess(1);
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
const worker = createWorker(cfg);
|
|
1532
|
+
const watchdog = createWatchdog(cfg, (taskId, runId) => worker.ownsRun(taskId, runId));
|
|
1533
|
+
const scheduler = createScheduler(cfg);
|
|
1534
|
+
let heartbeatTimer = null;
|
|
1535
|
+
let dashboardServer = null;
|
|
1536
|
+
let shuttingDown = false;
|
|
1537
|
+
const heartbeatTracker = createLockHeartbeatTracker();
|
|
1538
|
+
const shutdown = async (signal, exitCode = 0) => {
|
|
1539
|
+
if (shuttingDown) return;
|
|
1540
|
+
shuttingDown = true;
|
|
1541
|
+
const failures = [];
|
|
1542
|
+
try {
|
|
1543
|
+
console.log(JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), level: "info", msg: `received ${signal}, shutting down...` }));
|
|
1544
|
+
if (heartbeatTimer) {
|
|
1545
|
+
clearInterval(heartbeatTimer);
|
|
1546
|
+
heartbeatTimer = null;
|
|
1547
|
+
}
|
|
1548
|
+
markNotReady();
|
|
1549
|
+
await runGatewayShutdownStep(failures, "dashboard.stop", () => {
|
|
1550
|
+
const server = dashboardServer;
|
|
1551
|
+
dashboardServer = null;
|
|
1552
|
+
return server?.stop(true);
|
|
1553
|
+
});
|
|
1554
|
+
await runGatewayShutdownStep(failures, "scheduler.stop", () => scheduler.stop());
|
|
1555
|
+
await runGatewayShutdownStep(failures, "watchdog.stop", () => watchdog.stop());
|
|
1556
|
+
let interruptedRuns = [];
|
|
1557
|
+
await runGatewayShutdownStep(failures, "worker.stop", async () => {
|
|
1558
|
+
interruptedRuns = await worker.stop(cfg.worker.shutdownGracePeriodMs);
|
|
1559
|
+
});
|
|
1560
|
+
let resetCount = 0;
|
|
1561
|
+
for (const run of interruptedRuns) {
|
|
1562
|
+
await runGatewayShutdownStep(
|
|
1563
|
+
failures,
|
|
1564
|
+
`task.interrupt:${run.taskId}:${run.runId}`,
|
|
1565
|
+
async () => {
|
|
1566
|
+
if (await interruptRun(
|
|
1567
|
+
run.taskId,
|
|
1568
|
+
run.runId,
|
|
1569
|
+
"Gateway shutdown after child exit"
|
|
1570
|
+
)) {
|
|
1571
|
+
resetCount += 1;
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
);
|
|
1575
|
+
}
|
|
1576
|
+
if (resetCount > 0) {
|
|
1577
|
+
console.log(JSON.stringify({
|
|
1578
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1579
|
+
level: "info",
|
|
1580
|
+
msg: "reset confirmed interrupted tasks to pending",
|
|
1581
|
+
count: resetCount
|
|
1582
|
+
}));
|
|
1583
|
+
}
|
|
1584
|
+
await runGatewayShutdownStep(failures, "lock.release", () => releaseGatewayLock());
|
|
1585
|
+
await runGatewayShutdownStep(failures, "events.reset", () => gatewayEvents.reset());
|
|
1586
|
+
await runGatewayShutdownStep(failures, "health.reset", () => resetGatewayHealth());
|
|
1587
|
+
await runGatewayShutdownStep(failures, "database.close", () => closeDatabase());
|
|
1588
|
+
if (failures.length > 0) {
|
|
1589
|
+
console.error(JSON.stringify({
|
|
1590
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1591
|
+
level: "error",
|
|
1592
|
+
msg: "Gateway stopped with shutdown failures",
|
|
1593
|
+
failures
|
|
1594
|
+
}));
|
|
1595
|
+
} else {
|
|
1596
|
+
console.log(JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), level: "info", msg: "Gateway stopped" }));
|
|
1597
|
+
}
|
|
1598
|
+
} finally {
|
|
1599
|
+
exitProcess(resolveGatewayShutdownExitCode(exitCode, failures));
|
|
1600
|
+
}
|
|
1601
|
+
};
|
|
1602
|
+
const onSigterm = () => {
|
|
1603
|
+
void shutdown("SIGTERM");
|
|
1604
|
+
};
|
|
1605
|
+
const onSigint = () => {
|
|
1606
|
+
void shutdown("SIGINT");
|
|
1607
|
+
};
|
|
1608
|
+
const onUncaughtException = (err) => {
|
|
1609
|
+
console.error(JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), level: "fatal", msg: "uncaughtException", error: err.message, stack: err.stack }));
|
|
1610
|
+
void shutdown("uncaughtException", 1);
|
|
1611
|
+
};
|
|
1612
|
+
const onUnhandledRejection = (reason) => {
|
|
1613
|
+
console.error(JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), level: "fatal", msg: "unhandledRejection", reason: String(reason) }));
|
|
1614
|
+
void shutdown("unhandledRejection", 1);
|
|
1615
|
+
};
|
|
1616
|
+
if (registerProcessHandlers) {
|
|
1617
|
+
process.on("SIGTERM", onSigterm);
|
|
1618
|
+
process.on("SIGINT", onSigint);
|
|
1619
|
+
process.on("uncaughtException", onUncaughtException);
|
|
1620
|
+
process.on("unhandledRejection", onUnhandledRejection);
|
|
1621
|
+
}
|
|
1622
|
+
const runHeartbeatTick = () => {
|
|
1623
|
+
const result = checkLockHeartbeat();
|
|
1624
|
+
const decision = heartbeatTracker.record(result);
|
|
1625
|
+
if (decision === "ok") return;
|
|
1626
|
+
if (decision === "retry") {
|
|
1627
|
+
console.warn(JSON.stringify({
|
|
1628
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1629
|
+
level: "warn",
|
|
1630
|
+
msg: "transient database lock heartbeat error, will retry within stale threshold",
|
|
1631
|
+
pid: process.pid,
|
|
1632
|
+
error: result.error
|
|
1633
|
+
}));
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
console.error(JSON.stringify({
|
|
1637
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1638
|
+
level: "fatal",
|
|
1639
|
+
msg: "Gateway lost its database lock and will stop",
|
|
1640
|
+
pid: process.pid,
|
|
1641
|
+
error: result.error
|
|
1642
|
+
}));
|
|
1643
|
+
void shutdown("database lock lost", 1);
|
|
1644
|
+
};
|
|
1645
|
+
heartbeatTimer = setInterval(runHeartbeatTick, heartbeatIntervalMs);
|
|
1646
|
+
heartbeatTimer.unref();
|
|
1647
|
+
deps.onReadyForTest?.({ shutdown, runHeartbeatTick });
|
|
1648
|
+
try {
|
|
1649
|
+
checkOrphanRuns();
|
|
1650
|
+
const recoveredOrphans = await resetOrphans();
|
|
1651
|
+
if (shuttingDown) return;
|
|
1652
|
+
if (recoveredOrphans > 0) {
|
|
1653
|
+
console.log(JSON.stringify({
|
|
1654
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1655
|
+
level: "warn",
|
|
1656
|
+
msg: "reset orphan running tasks to pending",
|
|
1657
|
+
count: recoveredOrphans
|
|
1658
|
+
}));
|
|
1659
|
+
}
|
|
1660
|
+
await resolveDeps();
|
|
1661
|
+
if (shuttingDown) return;
|
|
1662
|
+
initializeGatewayHealth({
|
|
1663
|
+
workerPollIntervalMs: cfg.worker.pollIntervalMs,
|
|
1664
|
+
schedulerEnabled: cfg.scheduler.enabled,
|
|
1665
|
+
schedulerCheckIntervalMs: cfg.scheduler.checkIntervalMs,
|
|
1666
|
+
watchdogCheckIntervalMs: cfg.watchdog.checkIntervalMs,
|
|
1667
|
+
watchdogCleanupIntervalMs: cfg.watchdog.cleanupIntervalMs
|
|
1668
|
+
});
|
|
1669
|
+
await scheduler.start();
|
|
1670
|
+
if (shuttingDown) return;
|
|
1671
|
+
if (cfg.dashboard.enabled) {
|
|
1672
|
+
if (deps.startDashboard) {
|
|
1673
|
+
dashboardServer = await deps.startDashboard(cfg);
|
|
1674
|
+
} else {
|
|
1675
|
+
const { dashboardApp, setDashboardRuntimeConfig } = await import("./web-2S7DW7XA.js");
|
|
1676
|
+
if (shuttingDown) return;
|
|
1677
|
+
setDashboardRuntimeConfig(cfg);
|
|
1678
|
+
dashboardServer = Bun.serve({
|
|
1679
|
+
hostname: "127.0.0.1",
|
|
1680
|
+
port: cfg.dashboard.port,
|
|
1681
|
+
fetch: dashboardApp.fetch,
|
|
1682
|
+
idleTimeout: GATEWAY_DASHBOARD_IDLE_TIMEOUT_SECONDS
|
|
1683
|
+
});
|
|
1684
|
+
}
|
|
1685
|
+
if (shuttingDown) {
|
|
1686
|
+
await dashboardServer?.stop(true);
|
|
1687
|
+
dashboardServer = null;
|
|
1688
|
+
return;
|
|
1689
|
+
}
|
|
1690
|
+
console.log(JSON.stringify({
|
|
1691
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1692
|
+
level: "info",
|
|
1693
|
+
msg: "Dashboard started",
|
|
1694
|
+
url: `http://localhost:${cfg.dashboard.port}`
|
|
1695
|
+
}));
|
|
1696
|
+
}
|
|
1697
|
+
if (shuttingDown) return;
|
|
1698
|
+
watchdog.start();
|
|
1699
|
+
worker.start();
|
|
1700
|
+
markReady();
|
|
1701
|
+
console.log(JSON.stringify({
|
|
1702
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1703
|
+
level: "info",
|
|
1704
|
+
msg: "Gateway started",
|
|
1705
|
+
maxConcurrency: cfg.worker.maxConcurrency,
|
|
1706
|
+
schedulerEnabled: cfg.scheduler.enabled
|
|
1707
|
+
}));
|
|
1708
|
+
} catch (error) {
|
|
1709
|
+
console.error(JSON.stringify({
|
|
1710
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1711
|
+
level: "fatal",
|
|
1712
|
+
msg: "Gateway startup failed",
|
|
1713
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1714
|
+
}));
|
|
1715
|
+
await shutdown("startup failure", 1);
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
async function main() {
|
|
1719
|
+
await runGatewayMain();
|
|
1720
|
+
}
|
|
1721
|
+
if (import.meta.main) {
|
|
1722
|
+
main();
|
|
1723
|
+
}
|
|
1724
|
+
export {
|
|
1725
|
+
GATEWAY_DASHBOARD_IDLE_TIMEOUT_SECONDS,
|
|
1726
|
+
acquireLock,
|
|
1727
|
+
assertNoOrphanRunningTaskRuns,
|
|
1728
|
+
createLockHeartbeatTracker,
|
|
1729
|
+
isTransientLockHeartbeatError,
|
|
1730
|
+
main,
|
|
1731
|
+
releaseLock,
|
|
1732
|
+
resolveGatewayShutdownExitCode,
|
|
1733
|
+
runGatewayMain,
|
|
1734
|
+
runGatewayShutdownStep,
|
|
1735
|
+
updateLockHeartbeat,
|
|
1736
|
+
updateLockHeartbeatResult
|
|
1737
|
+
};
|
|
1738
|
+
//# sourceMappingURL=gateway-HNMX5ZTO.js.map
|