@animastor/installer 0.1.1 → 0.2.9
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/README.md +153 -1
- package/ai/install-manifests/audio/qwen-tts.json +6 -7
- package/ai/install-manifests/image/qwen-image.json +3 -3
- package/ai/install-manifests/video/ltx-2.3.json +9 -9
- package/package.json +3 -3
- package/src/installer/cli.js +1493 -214
- package/src/installer/compatibility-resolver.js +58 -11
- package/src/installer/engine/comfy-owner.js +385 -0
- package/src/installer/engine/downloader.js +26 -0
- package/src/installer/engine/engine.js +600 -61
- package/src/installer/engine/fixes.js +96 -0
- package/src/installer/engine/io.js +33 -2
- package/src/installer/engine/node-deps.js +560 -0
- package/src/installer/engine/overrides.js +375 -0
- package/src/installer/engine/prereq.js +176 -0
- package/src/installer/engine/probe.js +265 -8
- package/src/installer/engine/pydeps.js +204 -0
- package/src/installer/engine/summary.js +124 -0
- package/src/installer/engine/tty.js +214 -0
- package/src/installer/engine/worker.js +736 -52
- package/src/installer/install-plan.js +99 -15
- package/src/installer/management.js +342 -13
- package/src/installer/platform/linux.js +17 -0
- package/src/installer/setup-contract.js +35 -23
- package/src/installer/verification-report.js +21 -5
|
@@ -45,7 +45,65 @@ function findWorkerManifest(manifests, workerEntryId) {
|
|
|
45
45
|
* already on disk and were kept (files_kept).
|
|
46
46
|
* @returns {{ status, files, files_installed, files_kept, dir_created, reason? }}
|
|
47
47
|
*/
|
|
48
|
-
function
|
|
48
|
+
function readPkgVersion(io, dir) {
|
|
49
|
+
try {
|
|
50
|
+
const pkg = JSON.parse(io.fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
|
|
51
|
+
return typeof pkg.version === 'string' ? pkg.version : null;
|
|
52
|
+
} catch (_) {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Runtime dependencies declared by a bundle's package.json ({} when none). */
|
|
58
|
+
function declaredDependencies(io, dir) {
|
|
59
|
+
try {
|
|
60
|
+
const pkg = JSON.parse(io.fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
|
|
61
|
+
return pkg && pkg.dependencies && typeof pkg.dependencies === 'object' ? pkg.dependencies : {};
|
|
62
|
+
} catch (_) {
|
|
63
|
+
return {};
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Install the bundle's runtime dependencies with `npm ci` — ONLY when the
|
|
69
|
+
* bundle declares any. The canonical worker bundle is zero-dependency (Node
|
|
70
|
+
* 20 global fetch), so this is normally a no-op; it exists so a future
|
|
71
|
+
* bundle with dependencies can never be deployed half-installed. npm next to
|
|
72
|
+
* the chosen node binary is preferred (same runtime the worker runs with).
|
|
73
|
+
* Throws with the npm output tail on failure — never a silent warning.
|
|
74
|
+
* @returns {{ ran: boolean, deps: string[] }}
|
|
75
|
+
*/
|
|
76
|
+
function ensureWorkerDependencies(io, { workerDir, nodeBin = null }) {
|
|
77
|
+
const deps = Object.keys(declaredDependencies(io, workerDir));
|
|
78
|
+
if (deps.length === 0) return { ran: false, deps };
|
|
79
|
+
const npmNextToNode = nodeBin && path.isAbsolute(nodeBin) ? path.join(path.dirname(nodeBin), 'npm') : null;
|
|
80
|
+
const npm = npmNextToNode && io.fs.existsSync(npmNextToNode) ? npmNextToNode : 'npm';
|
|
81
|
+
const args = io.fs.existsSync(path.join(workerDir, 'package-lock.json'))
|
|
82
|
+
? ['ci', '--omit=dev', '--no-audit', '--no-fund']
|
|
83
|
+
: ['install', '--omit=dev', '--no-audit', '--no-fund'];
|
|
84
|
+
const r = io.exec(npm, args, { cwd: workerDir, timeout: 10 * 60 * 1000 });
|
|
85
|
+
if (r.code !== 0) {
|
|
86
|
+
throw new Error(`${npm} ${args[0]} in ${workerDir} failed: ${String(r.stderr || r.stdout || '').trim().slice(-300)}`);
|
|
87
|
+
}
|
|
88
|
+
return { ran: true, deps };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Deploy the worker bundle into workerDir.
|
|
93
|
+
* Source order (never invented): a repo checkout bundle first — canonical
|
|
94
|
+
* `packages/animastor-worker/worker/`, legacy `worker/worker/` (pre-
|
|
95
|
+
* relocation checkouts; see installer/worker-bundle-source.js) — then an
|
|
96
|
+
* explicit `bundleDir` (a verified hub worker-bundle tarball the engine
|
|
97
|
+
* extracted beforehand). If both fail, the install returns status 'failed'.
|
|
98
|
+
* A bundle whose version differs from the source is UPDATED (bundle files
|
|
99
|
+
* only — .env and logs are never touched) when `update` is true; otherwise
|
|
100
|
+
* present files are kept.
|
|
101
|
+
* Ownership details are returned for the uninstall manifest: dir_created,
|
|
102
|
+
* files the installer actually copied (files_installed) vs files that were
|
|
103
|
+
* already on disk and were kept (files_kept).
|
|
104
|
+
* @returns {{ status, files, files_installed, files_kept, dir_created, updated_from?, reason? }}
|
|
105
|
+
*/
|
|
106
|
+
function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleDir = null, hubUrl = null, httpFetchText = null, log = null, update = true, nodeBin = null }) {
|
|
49
107
|
const wb = manifest.worker_bundle || {};
|
|
50
108
|
const files = wb.files || [];
|
|
51
109
|
const dirCreated = !io.fs.existsSync(workerDir);
|
|
@@ -53,13 +111,17 @@ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleD
|
|
|
53
111
|
|
|
54
112
|
const repoBundleDir = resolveRepoBundleDir(io.fs, repoRoot);
|
|
55
113
|
const fromRepo = !!repoBundleDir;
|
|
114
|
+
const sourceDir = fromRepo ? repoBundleDir : bundleDir;
|
|
115
|
+
const installedVersion = readPkgVersion(io, workerDir);
|
|
116
|
+
const sourceVersion = sourceDir ? readPkgVersion(io, sourceDir) : null;
|
|
117
|
+
const outdated = !dirCreated && update && !!installedVersion && !!sourceVersion && installedVersion !== sourceVersion;
|
|
56
118
|
const installed = [];
|
|
57
119
|
const kept = [];
|
|
58
120
|
const failed = [];
|
|
59
121
|
|
|
60
122
|
for (const f of files) {
|
|
61
123
|
const dest = path.join(workerDir, f);
|
|
62
|
-
if (io.fs.existsSync(dest)) { kept.push(f); continue; }
|
|
124
|
+
if (io.fs.existsSync(dest) && !outdated) { kept.push(f); continue; }
|
|
63
125
|
if (fromRepo && io.fs.existsSync(path.join(repoBundleDir, f))) {
|
|
64
126
|
io.fs.copyFileSync(path.join(repoBundleDir, f), dest);
|
|
65
127
|
installed.push(f);
|
|
@@ -70,6 +132,7 @@ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleD
|
|
|
70
132
|
installed.push(f);
|
|
71
133
|
continue;
|
|
72
134
|
}
|
|
135
|
+
if (io.fs.existsSync(dest)) { kept.push(f); continue; }
|
|
73
136
|
failed.push(f);
|
|
74
137
|
}
|
|
75
138
|
|
|
@@ -77,16 +140,18 @@ function installWorkerBundle(io, { workerDir, manifest, repoRoot = null, bundleD
|
|
|
77
140
|
return { status: 'failed', files: installed, files_installed: installed, files_kept: kept, dir_created: dirCreated, reason: `could not obtain bundle files: ${failed.join(', ')} (no repo checkout, no hub bundle)` };
|
|
78
141
|
}
|
|
79
142
|
|
|
80
|
-
|
|
81
|
-
if (installed.
|
|
82
|
-
const r = io.exec('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], { cwd: workerDir, timeout: 10 * 60 * 1000 });
|
|
83
|
-
if (r.code !== 0 && log) {
|
|
84
|
-
log.warn(`npm install in ${workerDir} failed (worker may still run if deps are cached): ${String(r.stderr).slice(-300)}`);
|
|
85
|
-
}
|
|
86
|
-
}
|
|
143
|
+
const deps = ensureWorkerDependencies(io, { workerDir, nodeBin });
|
|
144
|
+
if (deps.ran && log) log.info(`worker dependencies installed (${deps.deps.join(', ')})`);
|
|
87
145
|
|
|
88
|
-
if (log)
|
|
89
|
-
|
|
146
|
+
if (log) {
|
|
147
|
+
if (outdated) log.info(`worker bundle updated ${installedVersion} → ${sourceVersion} at ${workerDir} (.env kept)`);
|
|
148
|
+
else log.info(`worker bundle deployed at ${workerDir} (${installed.length} files)`);
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
status: 'installed', files: installed, files_installed: installed, files_kept: kept, dir_created: dirCreated,
|
|
152
|
+
version: readPkgVersion(io, workerDir),
|
|
153
|
+
...(outdated ? { updated_from: installedVersion } : {}),
|
|
154
|
+
};
|
|
90
155
|
}
|
|
91
156
|
|
|
92
157
|
/** Serialize KEY=value lines. Values are written as given — never logged. */
|
|
@@ -98,14 +163,20 @@ function renderEnvLines(values) {
|
|
|
98
163
|
* Create or update `.env` with merge semantics:
|
|
99
164
|
* - existing keys are preserved (a valid token is never overwritten);
|
|
100
165
|
* - missing required keys are appended;
|
|
166
|
+
* - `overrides` REPLACE the value of existing non-secret keys (installer-
|
|
167
|
+
* owned wiring the user agreed to fix: WORKER_TYPE, COMFY_URL, NODE_BIN…)
|
|
168
|
+
* and are appended when absent. Secret keys are only overridden through
|
|
169
|
+
* an explicit `secretOverrides` (a new Worker Key typed by the user after
|
|
170
|
+
* the old one was rejected);
|
|
101
171
|
* - chmod 600.
|
|
102
172
|
* @param {object} opts { workerDir, manifest, values: {KEY: value} candidate
|
|
103
|
-
* values for MISSING keys only, log }
|
|
104
|
-
* @returns {{ status, missing_after: string[], preserved: string[] }}
|
|
173
|
+
* values for MISSING keys only, overrides, secretOverrides, log }
|
|
174
|
+
* @returns {{ status, missing_after: string[], preserved: string[], changed: string[] }}
|
|
105
175
|
*/
|
|
106
|
-
function configureEnv(io, { workerDir, manifest, values = {}, log = null }) {
|
|
176
|
+
function configureEnv(io, { workerDir, manifest, values = {}, overrides = {}, secretOverrides = {}, log = null }) {
|
|
107
177
|
const wb = manifest.worker_bundle || {};
|
|
108
178
|
const required = (wb.env && wb.env.required) || [];
|
|
179
|
+
const secretKeys = (wb.env && wb.env.secrets) || ['ANIMASTOR_WORKER_TOKEN'];
|
|
109
180
|
const envPath = path.join(workerDir, '.env');
|
|
110
181
|
|
|
111
182
|
let existingText = '';
|
|
@@ -115,34 +186,101 @@ function configureEnv(io, { workerDir, manifest, values = {}, log = null }) {
|
|
|
115
186
|
existingKeys = parseEnvKeys(existingText);
|
|
116
187
|
}
|
|
117
188
|
|
|
118
|
-
const
|
|
189
|
+
const replace = {};
|
|
190
|
+
for (const [k, v] of Object.entries(overrides || {})) {
|
|
191
|
+
if (v === undefined || v === null || secretKeys.includes(k)) continue;
|
|
192
|
+
replace[k] = String(v);
|
|
193
|
+
}
|
|
194
|
+
for (const [k, v] of Object.entries(secretOverrides || {})) {
|
|
195
|
+
if (v) replace[k] = String(v);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const changed = [];
|
|
199
|
+
let text = existingText;
|
|
200
|
+
if (Object.keys(replace).length > 0 && text) {
|
|
201
|
+
text = text.split('\n').map((line) => {
|
|
202
|
+
const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
|
|
203
|
+
if (!m || replace[m[1]] === undefined) return line;
|
|
204
|
+
const current = m[2].trim().replace(/^["']|["']$/g, '');
|
|
205
|
+
if (current === replace[m[1]]) return line;
|
|
206
|
+
changed.push(m[1]);
|
|
207
|
+
return `${m[1]}=${replace[m[1]]}`;
|
|
208
|
+
}).join('\n');
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// Merge semantics: EVERY key of the existing .env that this run did not
|
|
212
|
+
// change is preserved — the log line must show the real numbers (a re-run
|
|
213
|
+
// over a configured worker used to report "0 key(s) preserved" because
|
|
214
|
+
// only manifest-required keys were counted).
|
|
215
|
+
const preserved = existingKeys.filter((k) => !changed.includes(k));
|
|
119
216
|
const additions = [];
|
|
217
|
+
const added = new Set();
|
|
218
|
+
const add = (key, val) => { if (!added.has(key)) { additions.push(`${key}=${val}`); added.add(key); } };
|
|
120
219
|
for (const key of required) {
|
|
121
220
|
if (existingKeys.includes(key)) {
|
|
122
|
-
preserved
|
|
221
|
+
// already preserved above (merge semantics: never overwrite)
|
|
222
|
+
} else if (replace[key] !== undefined) {
|
|
223
|
+
add(key, replace[key]);
|
|
123
224
|
} else if (values[key] !== undefined) {
|
|
124
|
-
|
|
225
|
+
add(key, values[key]);
|
|
125
226
|
}
|
|
126
227
|
}
|
|
127
228
|
for (const [key, val] of Object.entries(values)) {
|
|
128
|
-
if (!required.includes(key) && !existingKeys.includes(key))
|
|
129
|
-
|
|
130
|
-
|
|
229
|
+
if (!required.includes(key) && !existingKeys.includes(key) && replace[key] === undefined) add(key, val);
|
|
230
|
+
}
|
|
231
|
+
for (const [key, val] of Object.entries(replace)) {
|
|
232
|
+
if (!existingKeys.includes(key)) add(key, val);
|
|
131
233
|
}
|
|
132
234
|
|
|
133
|
-
const missingAfter = required.filter((k) => !existingKeys.includes(k) &&
|
|
235
|
+
const missingAfter = required.filter((k) => !existingKeys.includes(k) && !added.has(k));
|
|
134
236
|
|
|
135
237
|
const envCreated = !io.fs.existsSync(envPath);
|
|
136
|
-
let text = existingText;
|
|
137
238
|
if (additions.length > 0) {
|
|
138
239
|
if (text && !text.endsWith('\n')) text += '\n';
|
|
139
240
|
text += additions.join('\n') + '\n';
|
|
140
241
|
}
|
|
141
|
-
|
|
242
|
+
// Installer 0.2.8: an unchanged .env is NOT rewritten. Its mtime is the
|
|
243
|
+
// "configuration changed after the worker started" marker
|
|
244
|
+
// (workerConfigNewer) — rewriting identical content made every doctor
|
|
245
|
+
// run restart a running (even busy) worker (04.11, 13:55/13:58 UTC).
|
|
246
|
+
if (envCreated || text !== existingText) io.fs.writeFileSync(envPath, text);
|
|
142
247
|
io.fs.chmodSync(envPath, 0o600);
|
|
143
248
|
|
|
144
|
-
if (log) log.info(`.env configured: ${preserved.length} key(s) preserved, ${additions.length} added, ${missingAfter.length} still missing`);
|
|
145
|
-
return { status: missingAfter.length === 0 ? 'configured' : 'incomplete', missing_after: missingAfter, preserved, created: envCreated };
|
|
249
|
+
if (log) log.info(`.env configured: ${preserved.length} key(s) preserved, ${additions.length} added, ${changed.length} updated${changed.length ? ` (${changed.join(', ')})` : ''}, ${missingAfter.length} still missing`);
|
|
250
|
+
return { status: missingAfter.length === 0 ? 'configured' : 'incomplete', missing_after: missingAfter, preserved, changed, added: Array.from(added), created: envCreated };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* True when the worker .env already holds a NON-EMPTY value for `key`.
|
|
255
|
+
* Only a boolean is returned — the value itself is never read out of .env,
|
|
256
|
+
* so a Worker Key can never leak through this check (re-installs therefore
|
|
257
|
+
* never ask for a key that is already there).
|
|
258
|
+
*/
|
|
259
|
+
function hasEnvKey(io, workerDir, key) {
|
|
260
|
+
try {
|
|
261
|
+
const text = String(io.fs.readFileSync(path.join(workerDir, '.env'), 'utf8'));
|
|
262
|
+
for (const raw of text.split('\n')) {
|
|
263
|
+
const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(raw);
|
|
264
|
+
if (!m || m[1] !== key) continue;
|
|
265
|
+
const value = m[2].trim().replace(/^["']|[\"']$/g, '');
|
|
266
|
+
if (value) return true;
|
|
267
|
+
}
|
|
268
|
+
} catch (_) { /* no .env */ }
|
|
269
|
+
return false;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Read non-secret KEY=value pairs from the worker .env (secret keys skipped). */
|
|
273
|
+
function readEnvValues(io, workerDir, { skip = ['ANIMASTOR_WORKER_TOKEN'] } = {}) {
|
|
274
|
+
const out = {};
|
|
275
|
+
try {
|
|
276
|
+
const text = io.fs.readFileSync(path.join(workerDir, '.env'), 'utf8');
|
|
277
|
+
for (const raw of text.split('\n')) {
|
|
278
|
+
const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(raw);
|
|
279
|
+
if (!m || skip.includes(m[1])) continue;
|
|
280
|
+
out[m[1]] = m[2].trim().replace(/^["']|["']$/g, '');
|
|
281
|
+
}
|
|
282
|
+
} catch (_) { /* no .env */ }
|
|
283
|
+
return out;
|
|
146
284
|
}
|
|
147
285
|
|
|
148
286
|
/** Derive the backend API base from HUB_URL (…/gpu → …/api/v1). */
|
|
@@ -188,18 +326,22 @@ async function verifyRegistration(io, { hubUrl, token, expectedType = null }) {
|
|
|
188
326
|
}
|
|
189
327
|
|
|
190
328
|
/**
|
|
191
|
-
* Local sanity check that the worker CAN start: syntax check
|
|
192
|
-
*
|
|
193
|
-
*
|
|
329
|
+
* Local sanity check that the worker CAN start: syntax check with the node
|
|
330
|
+
* binary that will run it + resolution of the dependencies the bundle
|
|
331
|
+
* DECLARES (the canonical bundle declares none — the old hard-coded
|
|
332
|
+
* node-fetch probe made every zero-dependency install "unstartable").
|
|
194
333
|
*/
|
|
195
|
-
function checkWorkerCanStart(io, { workerDir }) {
|
|
334
|
+
function checkWorkerCanStart(io, { workerDir, nodeBin = 'node' }) {
|
|
196
335
|
const workerCjs = path.join(workerDir, 'worker.cjs');
|
|
197
336
|
if (!io.fs.existsSync(workerCjs)) return { ok: false, reason: 'worker.cjs missing' };
|
|
198
|
-
const syntax = io.exec(
|
|
337
|
+
const syntax = io.exec(nodeBin, ['--check', workerCjs]);
|
|
199
338
|
if (syntax.code !== 0) return { ok: false, reason: `worker.cjs failed syntax check: ${String(syntax.stderr).slice(-200)}` };
|
|
200
|
-
const deps =
|
|
201
|
-
if (deps.
|
|
202
|
-
|
|
339
|
+
const deps = Object.keys(declaredDependencies(io, workerDir));
|
|
340
|
+
if (deps.length > 0) {
|
|
341
|
+
const r = io.exec(nodeBin, ['-e', 'for (const d of process.argv.slice(2)) require.resolve(d, { paths: [process.cwd()] })', ...deps], { cwd: workerDir });
|
|
342
|
+
if (r.code !== 0) {
|
|
343
|
+
return { ok: false, reason: `worker dependencies missing (${deps.join(', ')}) — run: cd ${workerDir} && npm ci --omit=dev` };
|
|
344
|
+
}
|
|
203
345
|
}
|
|
204
346
|
return { ok: true };
|
|
205
347
|
}
|
|
@@ -276,12 +418,8 @@ function findRunningWorkerPid(io, workerDir, opts = {}) {
|
|
|
276
418
|
*/
|
|
277
419
|
function workerEnvIsNewer(io, { workerDir, pid, platformAdapter = null }) {
|
|
278
420
|
try {
|
|
279
|
-
const adapter = platformAdapter || adapterOf({});
|
|
280
421
|
const envM = io.fs.statSync(path.join(workerDir, '.env')).mtimeMs;
|
|
281
|
-
|
|
282
|
-
if (procM == null && typeof adapter.workerStartMarkerMs === 'function') {
|
|
283
|
-
procM = adapter.workerStartMarkerMs(io, workerDir);
|
|
284
|
-
}
|
|
422
|
+
const procM = workerProcessStartMs(io, { workerDir, pid, platformAdapter });
|
|
285
423
|
if (procM == null) return false;
|
|
286
424
|
return envM > procM + 1000; // 1s tolerance for same-second writes
|
|
287
425
|
} catch (_) {
|
|
@@ -290,21 +428,139 @@ function workerEnvIsNewer(io, { workerDir, pid, platformAdapter = null }) {
|
|
|
290
428
|
}
|
|
291
429
|
|
|
292
430
|
/**
|
|
293
|
-
* Start the
|
|
294
|
-
*
|
|
431
|
+
* Start time of the running worker `pid` (ms) or null when unknown.
|
|
432
|
+
* Most reliable marker: logs/worker.pid written at start (by this installer
|
|
433
|
+
* and by start-worker.sh) — its mtime IS the start time; then the platform
|
|
434
|
+
* adapter (/proc/<pid> on Linux, the pid marker on Windows).
|
|
435
|
+
*/
|
|
436
|
+
function workerProcessStartMs(io, { workerDir, pid, platformAdapter = null }) {
|
|
437
|
+
try {
|
|
438
|
+
const adapter = platformAdapter || adapterOf({});
|
|
439
|
+
let procM = pidFileStartMs(io, workerDir, pid);
|
|
440
|
+
if (procM == null) procM = adapter.processStartMs(io, pid);
|
|
441
|
+
if (procM == null && typeof adapter.workerStartMarkerMs === 'function') {
|
|
442
|
+
procM = adapter.workerStartMarkerMs(io, workerDir);
|
|
443
|
+
}
|
|
444
|
+
return procM == null ? null : procM;
|
|
445
|
+
} catch (_) {
|
|
446
|
+
return null;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Files whose change requires a worker restart: .env and the bundle (installer 0.2.8). */
|
|
451
|
+
const WORKER_CONFIG_FILES = Object.freeze(['.env', 'package.json', 'worker.cjs', 'worker-env.cjs',
|
|
452
|
+
'job-protocol-v2.cjs', 'worker-cleanup.cjs', 'worker-cleanup-journal.cjs']);
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Configuration files (.env, bundle files) modified AFTER the worker `pid`
|
|
456
|
+
* started — the running process holds the old configuration (env and code
|
|
457
|
+
* are fixed at process start). Persistent across runs: a restart deferred
|
|
458
|
+
* because the worker was busy is still required on the next run. Unknown
|
|
459
|
+
* start time → [] (never restart on a guess).
|
|
460
|
+
* @returns {string[]} changed file names
|
|
461
|
+
*/
|
|
462
|
+
function workerConfigNewer(io, { workerDir, pid, platformAdapter = null, files = WORKER_CONFIG_FILES }) {
|
|
463
|
+
const procM = workerProcessStartMs(io, { workerDir, pid, platformAdapter });
|
|
464
|
+
if (procM == null) return [];
|
|
465
|
+
const out = [];
|
|
466
|
+
for (const f of files) {
|
|
467
|
+
try {
|
|
468
|
+
const p = path.join(workerDir, f);
|
|
469
|
+
if (!io.fs.existsSync(p)) continue;
|
|
470
|
+
if (io.fs.statSync(p).mtimeMs > procM + 1000) out.push(f);
|
|
471
|
+
} catch (_) { /* unreadable → not counted */ }
|
|
472
|
+
}
|
|
473
|
+
return out;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** Default worker log: <install base>/logs/worker.log (same file start-worker.sh uses). */
|
|
477
|
+
function workerLogPath(workerDir) {
|
|
478
|
+
return path.join(path.dirname(workerDir), 'logs', 'worker.log');
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Node binary for the worker: NODE_BIN from .env when it exists and is >= 20,
|
|
483
|
+
* else the node running this installer (>= 20, verified by the bootstrap).
|
|
484
|
+
*/
|
|
485
|
+
function resolveWorkerNode(io, workerDir) {
|
|
486
|
+
const fromEnv = readEnvValues(io, workerDir).NODE_BIN || null;
|
|
487
|
+
if (fromEnv && io.fs.existsSync(fromEnv)) {
|
|
488
|
+
const r = io.exec(fromEnv, ['--version']);
|
|
489
|
+
const m = /^v?(\d+)/.exec(String(r.stdout || '').trim());
|
|
490
|
+
if (r.code === 0 && m && Number(m[1]) >= 20) return fromEnv;
|
|
491
|
+
}
|
|
492
|
+
return process.execPath;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* Environment for the spawned worker: the installer's own environment minus
|
|
497
|
+
* the worker configuration keys — the worker reads them from its .env, and a
|
|
498
|
+
* stray exported WORKER_TYPE/HUB_URL/COMFY_PORT in the installer's shell must
|
|
499
|
+
* never override the configuration that was just written (real env wins
|
|
500
|
+
* over .env inside the worker).
|
|
501
|
+
*/
|
|
502
|
+
const WORKER_ENV_KEYS = Object.freeze([
|
|
503
|
+
'HUB_URL', 'WORKER_TYPE', 'WORKER_ID', 'COMFY_PORT', 'COMFY_URL', 'NOTEBOOK_PATH',
|
|
504
|
+
'COMFY_INPUT_DIR', 'ANIMASTOR_WORKER_TOKEN', 'ANIMASTOR_API_URL', 'NODE_BIN',
|
|
505
|
+
]);
|
|
506
|
+
function workerSpawnEnv(base = process.env) {
|
|
507
|
+
const env = { ...base };
|
|
508
|
+
for (const k of WORKER_ENV_KEYS) delete env[k];
|
|
509
|
+
return env;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** <base>/logs/worker.pid — written on every worker start. */
|
|
513
|
+
function workerPidFile(workerDir) {
|
|
514
|
+
return path.join(path.dirname(workerDir), 'logs', 'worker.pid');
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Start time (pid file mtime) when the pid file names `pid`, else null. */
|
|
518
|
+
function pidFileStartMs(io, workerDir, pid) {
|
|
519
|
+
try {
|
|
520
|
+
const f = workerPidFile(workerDir);
|
|
521
|
+
if (!io.fs.existsSync(f)) return null;
|
|
522
|
+
if (Number(String(io.fs.readFileSync(f, 'utf8')).trim()) !== Number(pid)) return null;
|
|
523
|
+
const st = io.fs.statSync(f);
|
|
524
|
+
return typeof st.mtimeMs === 'number' ? st.mtimeMs : null;
|
|
525
|
+
} catch (_) {
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Start the installed worker as a detached daemon (<NODE_BIN> worker.cjs).
|
|
532
|
+
* The worker loads its own .env (worker-env.cjs), so no secrets pass through
|
|
295
533
|
* the environment or argv here. Returns whether the process is still alive
|
|
296
|
-
* after a short grace period
|
|
297
|
-
*
|
|
298
|
-
*
|
|
299
|
-
*
|
|
534
|
+
* after a short grace period, plus the log file and the byte offset where
|
|
535
|
+
* THIS start's output begins (readiness is judged from there).
|
|
536
|
+
* Idempotent: a worker already running for this directory is left alone
|
|
537
|
+
* (re-runs must never spawn a second instance) unless .env changed after it
|
|
538
|
+
* started. Platform specifics (kill/sleep/alive commands, pid marker) come
|
|
539
|
+
* from the platform adapter — the flow itself is universal.
|
|
300
540
|
*/
|
|
301
|
-
function startWorker(io, { workerDir, logFile = null, graceMs = 3000, sleep = null, platformAdapter = null }) {
|
|
541
|
+
function startWorker(io, { workerDir, nodeBin = null, logFile = null, graceMs = 3000, sleep = null, platformAdapter = null, forceRestart = false }) {
|
|
302
542
|
const adapter = platformAdapter || adapterOf({});
|
|
303
|
-
const
|
|
304
|
-
|
|
543
|
+
const node = nodeBin || resolveWorkerNode(io, workerDir);
|
|
544
|
+
const log = logFile || workerLogPath(workerDir);
|
|
545
|
+
const can = checkWorkerCanStart(io, { workerDir, nodeBin: node });
|
|
546
|
+
if (!can.ok) return { started: false, alive: false, reason: can.reason, logFile: log };
|
|
305
547
|
const existing = findRunningWorkerPid(io, workerDir, { platformAdapter: adapter });
|
|
306
|
-
|
|
307
|
-
|
|
548
|
+
// forceRestart: the caller just changed .env/the bundle — a running worker
|
|
549
|
+
// holds the OLD configuration (process env is fixed at start).
|
|
550
|
+
if (existing && !forceRestart && !workerEnvIsNewer(io, { workerDir, pid: existing, platformAdapter: adapter })) {
|
|
551
|
+
return { started: true, already_running: true, pid: existing, alive: true, reason: null, logFile: log, logOffset: null };
|
|
552
|
+
}
|
|
553
|
+
if (existing && !forceRestart) {
|
|
554
|
+
// Installer 0.2.8: a stale-config restart never kills a task in
|
|
555
|
+
// progress (`animastor start` path; doctor/install decide in
|
|
556
|
+
// ensureWorker, which waits for the task).
|
|
557
|
+
const act = readWorkerActivity(io, { workerDir, pid: existing, logFile: log });
|
|
558
|
+
if (act.known && act.current_job_id) {
|
|
559
|
+
return {
|
|
560
|
+
started: true, already_running: true, pid: existing, alive: true, reason: null, logFile: log, logOffset: null,
|
|
561
|
+
restart_pending: ['.env'], busy_job: act.current_job_id,
|
|
562
|
+
};
|
|
563
|
+
}
|
|
308
564
|
}
|
|
309
565
|
if (existing) {
|
|
310
566
|
// .env changed after this worker started — it is running on the OLD
|
|
@@ -314,14 +570,19 @@ function startWorker(io, { workerDir, logFile = null, graceMs = 3000, sleep = nu
|
|
|
314
570
|
io.exec(kc.cmd, kc.args);
|
|
315
571
|
runSleep(io, adapter, sleep, 1);
|
|
316
572
|
}
|
|
317
|
-
|
|
573
|
+
try { io.fs.mkdirSync(path.dirname(log), { recursive: true }); } catch (_) { /* exists */ }
|
|
574
|
+
let logOffset = 0;
|
|
575
|
+
try { logOffset = io.fs.existsSync(log) ? io.fs.statSync(log).size : 0; } catch (_) { logOffset = 0; }
|
|
576
|
+
const pid = io.spawnDaemon(node, ['worker.cjs'], {
|
|
318
577
|
cwd: workerDir,
|
|
319
|
-
logFile:
|
|
578
|
+
logFile: log,
|
|
579
|
+
env: workerSpawnEnv(),
|
|
320
580
|
});
|
|
321
581
|
// Platform post-start bookkeeping (Windows: write the managed pid marker)
|
|
322
582
|
if (typeof adapter.onWorkerSpawned === 'function') {
|
|
323
583
|
try { adapter.onWorkerSpawned(io, { workerDir, pid }); } catch (_) { /* best effort */ }
|
|
324
584
|
}
|
|
585
|
+
try { io.fs.writeFileSync(workerPidFile(workerDir), `${pid}\n`); } catch (_) { /* best effort */ }
|
|
325
586
|
// sync grace pause (installer is already a synchronous-step CLI)
|
|
326
587
|
runSleep(io, adapter, sleep, Math.max(1, Math.ceil(graceMs / 1000)));
|
|
327
588
|
let alive;
|
|
@@ -332,7 +593,214 @@ function startWorker(io, { workerDir, logFile = null, graceMs = 3000, sleep = nu
|
|
|
332
593
|
const chk = io.exec(chkCmd.cmd, chkCmd.args);
|
|
333
594
|
alive = chk.code === 0 && /worker\.cjs/.test(chk.stdout);
|
|
334
595
|
}
|
|
335
|
-
return { started: true, pid, alive, reason: alive ? null :
|
|
596
|
+
return { started: true, pid, alive, reason: alive ? null : `worker exited immediately — see ${log}`, logFile: log, logOffset };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Classify a worker log excerpt (the output of ONE worker start: everything
|
|
601
|
+
* after the last "Worker <type> started" line). Pure — shared by the
|
|
602
|
+
* installer, `animastor start/status/doctor` and tests.
|
|
603
|
+
* Markers (worker.cjs >= 2.2.0; "ComfyUI ready" exists in every version):
|
|
604
|
+
* comfy_ready — "ComfyUI ready"
|
|
605
|
+
* heartbeat — "Hub heartbeat accepted"
|
|
606
|
+
* auth_failed — "Worker authentication failed"
|
|
607
|
+
* @returns {{ comfy_ready, heartbeat, auth_failed, crashed, last_comfy_error, last_beacon_error, last_lines }}
|
|
608
|
+
*/
|
|
609
|
+
function scanWorkerLog(text) {
|
|
610
|
+
const all = String(text || '').split('\n');
|
|
611
|
+
let start = 0;
|
|
612
|
+
all.forEach((l, i) => { if (/\] Worker \S+ started/.test(l)) start = i; });
|
|
613
|
+
const lines = all.slice(start);
|
|
614
|
+
const find = (re) => lines.some((l) => re.test(l));
|
|
615
|
+
const last = (re) => {
|
|
616
|
+
for (let i = lines.length - 1; i >= 0; i--) if (re.test(lines[i])) return lines[i];
|
|
617
|
+
return null;
|
|
618
|
+
};
|
|
619
|
+
const comfyErr = last(/ComfyUI not ready/);
|
|
620
|
+
const lastIdx = (re) => { for (let i = lines.length - 1; i >= 0; i--) if (re.test(lines[i])) return i; return -1; };
|
|
621
|
+
const beaconErrIdx = lastIdx(/Beacon failed/);
|
|
622
|
+
return {
|
|
623
|
+
comfy_ready: find(/ComfyUI ready/),
|
|
624
|
+
// ONLINE now = the latest heartbeat marker is newer than the latest
|
|
625
|
+
// beacon failure (the worker re-logs the marker after a recovery).
|
|
626
|
+
heartbeat: lastIdx(/Hub heartbeat accepted/) > beaconErrIdx,
|
|
627
|
+
auth_failed: find(/Worker authentication failed/),
|
|
628
|
+
crashed: find(/Worker crashed/),
|
|
629
|
+
last_comfy_error: comfyErr ? comfyErr.replace(/^\[[^\]]*\]\s*\[[^\]]*\]\s*/, '') : null,
|
|
630
|
+
last_beacon_error: beaconErrIdx >= 0 ? (lines[beaconErrIdx + 1] || lines[beaconErrIdx]).trim() : null,
|
|
631
|
+
last_lines: lines.filter(Boolean).slice(-8),
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// ── Worker activity (installer 0.2.8) ─────────────────────────────────────────
|
|
636
|
+
// The hub's heartbeat record (current_job_id) lives in the hub's Redis and is
|
|
637
|
+
// not readable from the node; the worker's OWN log carries the same facts:
|
|
638
|
+
// "[ts] [info] Task <job_id> (type=…" — a task was taken
|
|
639
|
+
// "[ts] [info] Done <job_id>" — result delivered
|
|
640
|
+
// "[ts] [error] Failed <job_id>" — task failed (error sent)
|
|
641
|
+
// "[ts] [error] Rejecting incompatible task…" — the taken task was refused
|
|
642
|
+
// Only the output of the CURRENT process counts (after its last
|
|
643
|
+
// "Worker <type> started"). "Hub heartbeat accepted" is logged on the first
|
|
644
|
+
// accepted beacon and again after every recovery; every failed beacon logs
|
|
645
|
+
// "Beacon failed" — so "heartbeat fresh" = the latest beacon marker of this
|
|
646
|
+
// process is an accepted one.
|
|
647
|
+
const TASK_START_RE = /\] Task (\S+) \(type=/;
|
|
648
|
+
const TASK_END_RE = /\] (?:Done|Failed) (\S+)\s*$/;
|
|
649
|
+
const TASK_REJECT_RE = /\] Rejecting incompatible task/;
|
|
650
|
+
const WORKER_LOG_TAIL_BYTES = 4 * 1024 * 1024;
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Pure: classify the worker log (text of one or more runs).
|
|
654
|
+
* @returns {{ started: boolean, current_job_id: string|null, last_job_id: string|null,
|
|
655
|
+
* comfy_ready: boolean, heartbeat: boolean, healthy: boolean, last_beacon_error: string|null }}
|
|
656
|
+
*/
|
|
657
|
+
function parseWorkerActivity(text) {
|
|
658
|
+
const all = String(text || '').split('\n');
|
|
659
|
+
let start = -1;
|
|
660
|
+
all.forEach((l, i) => { if (/\] Worker \S+ started/.test(l)) start = i; });
|
|
661
|
+
const lines = start >= 0 ? all.slice(start) : all;
|
|
662
|
+
let current = null;
|
|
663
|
+
let last = null;
|
|
664
|
+
for (const l of lines) {
|
|
665
|
+
let m = TASK_START_RE.exec(l);
|
|
666
|
+
if (m) { current = m[1]; last = m[1]; continue; }
|
|
667
|
+
m = TASK_END_RE.exec(l);
|
|
668
|
+
if (m) { if (current === m[1]) current = null; continue; }
|
|
669
|
+
if (TASK_REJECT_RE.test(l)) current = null;
|
|
670
|
+
}
|
|
671
|
+
const scan = scanWorkerLog(lines.join('\n'));
|
|
672
|
+
return {
|
|
673
|
+
started: start >= 0,
|
|
674
|
+
current_job_id: current,
|
|
675
|
+
last_job_id: last,
|
|
676
|
+
comfy_ready: scan.comfy_ready,
|
|
677
|
+
heartbeat: scan.heartbeat,
|
|
678
|
+
healthy: start >= 0 && scan.comfy_ready && scan.heartbeat && !scan.crashed && !scan.auth_failed,
|
|
679
|
+
last_beacon_error: scan.last_beacon_error,
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* Activity of the running worker `pid` from its log (tail of at most
|
|
685
|
+
* WORKER_LOG_TAIL_BYTES). known=false when there is no log, or the log was
|
|
686
|
+
* last written BEFORE this process started (it is some other process's log —
|
|
687
|
+
* busy/idle cannot be told).
|
|
688
|
+
* @returns {{ known: boolean, reason: string|null, current_job_id, last_job_id, comfy_ready, heartbeat, healthy, last_beacon_error, log_file }}
|
|
689
|
+
*/
|
|
690
|
+
function readWorkerActivity(io, { workerDir, pid = null, logFile = null, tailBytes = WORKER_LOG_TAIL_BYTES }) {
|
|
691
|
+
const log = logFile || workerLogPath(workerDir);
|
|
692
|
+
const unknown = (reason) => ({
|
|
693
|
+
known: false, reason, current_job_id: null, last_job_id: null, comfy_ready: false, heartbeat: false,
|
|
694
|
+
healthy: false, last_beacon_error: null, log_file: log,
|
|
695
|
+
});
|
|
696
|
+
let text;
|
|
697
|
+
try {
|
|
698
|
+
if (!io.fs.existsSync(log)) return unknown(`no worker log at ${log}`);
|
|
699
|
+
text = String(io.fs.readFileSync(log, 'utf8'));
|
|
700
|
+
} catch (err) {
|
|
701
|
+
return unknown(`worker log ${log} unreadable: ${err.message}`);
|
|
702
|
+
}
|
|
703
|
+
if (pid) {
|
|
704
|
+
// Only the pid file is a precise start marker here (/proc/<pid> mtime
|
|
705
|
+
// on Linux is the procfs inode time, not the start time).
|
|
706
|
+
const procM = pidFileStartMs(io, workerDir, pid);
|
|
707
|
+
let logM = null;
|
|
708
|
+
try { logM = io.fs.statSync(log).mtimeMs; } catch (_) { logM = null; }
|
|
709
|
+
if (procM != null && typeof logM === 'number' && logM + 1000 < procM) {
|
|
710
|
+
return unknown(`worker log ${log} was not written by the running worker (pid ${pid})`);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
if (text.length > tailBytes) text = text.slice(text.length - tailBytes);
|
|
714
|
+
const a = parseWorkerActivity(text);
|
|
715
|
+
return { known: true, reason: null, ...a, log_file: log };
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** "none" | "<job_id>" | "unknown" for the `current job:` line of doctor/status. */
|
|
719
|
+
function currentJobLabel(io, { workerDir, pid = undefined, platformAdapter = null, logFile = null }) {
|
|
720
|
+
const p = pid === undefined ? findRunningWorkerPid(io, workerDir, { platformAdapter }) : pid;
|
|
721
|
+
if (!p) return 'none';
|
|
722
|
+
const a = readWorkerActivity(io, { workerDir, pid: p, logFile });
|
|
723
|
+
if (!a.known) return 'unknown';
|
|
724
|
+
return a.current_job_id || 'none';
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function readLogFrom(io, logFile, offset) {
|
|
728
|
+
try {
|
|
729
|
+
const text = String(io.fs.readFileSync(logFile, 'utf8'));
|
|
730
|
+
return offset ? Buffer.from(text).subarray(offset).toString('utf8') : text;
|
|
731
|
+
} catch (_) {
|
|
732
|
+
return '';
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* Wait until the worker proves it is serving, judged from ITS OWN log:
|
|
738
|
+
* 1. "ComfyUI ready" (worker reached the ComfyUI API) — within comfyTimeoutMs
|
|
739
|
+
* 2. "Hub heartbeat accepted" (the hub recorded the heartbeat → Animastor
|
|
740
|
+
* shows ONLINE) — within heartbeatTimeoutMs after 1
|
|
741
|
+
* Stops early when the process died or authentication failed.
|
|
742
|
+
* @returns {Promise<{ comfy_ready, heartbeat, auth_failed, exited, reason, logFile, scan }>}
|
|
743
|
+
*/
|
|
744
|
+
async function waitForWorkerReady(io, { workerDir, pid = null, logFile = null, logOffset = 0, comfyTimeoutMs = 90000, heartbeatTimeoutMs = 45000, pollMs = 1000, requireHeartbeat = true, platformAdapter = null, comfyUp = null, comfyUpTimeoutMs = 0 }) {
|
|
745
|
+
const log = logFile || workerLogPath(workerDir);
|
|
746
|
+
const adapter = platformAdapter || adapterOf({});
|
|
747
|
+
const now = () => (io.now ? io.now() : Date.now());
|
|
748
|
+
const alive = () => {
|
|
749
|
+
if (!pid) return true;
|
|
750
|
+
try {
|
|
751
|
+
if (typeof adapter.checkDaemonAlive === 'function') return adapter.checkDaemonAlive(io, { pid, workerDir });
|
|
752
|
+
const chk = adapter.psCheckCommand(pid);
|
|
753
|
+
const r = io.exec(chk.cmd, chk.args);
|
|
754
|
+
return r.code === 0 && /worker\.cjs/.test(r.stdout);
|
|
755
|
+
} catch (_) { return false; }
|
|
756
|
+
};
|
|
757
|
+
let scan = scanWorkerLog(readLogFrom(io, log, logOffset));
|
|
758
|
+
let deadline = now() + comfyTimeoutMs;
|
|
759
|
+
let phase = scan.comfy_ready ? 'heartbeat' : 'comfy';
|
|
760
|
+
if (phase === 'heartbeat') deadline = now() + heartbeatTimeoutMs;
|
|
761
|
+
// comfyUp (installer 0.2.3): the comfyTimeoutMs window opens only once
|
|
762
|
+
// ComfyUI itself answers — up to comfyUpTimeoutMs are spent waiting for
|
|
763
|
+
// that first (0 = check once, then count as before).
|
|
764
|
+
if (phase === 'comfy' && typeof comfyUp === 'function') {
|
|
765
|
+
const upDeadline = now() + Math.max(0, comfyUpTimeoutMs);
|
|
766
|
+
for (;;) {
|
|
767
|
+
let up = false;
|
|
768
|
+
try { up = await comfyUp(); } catch (_) { up = false; }
|
|
769
|
+
if (up) break;
|
|
770
|
+
scan = scanWorkerLog(readLogFrom(io, log, logOffset));
|
|
771
|
+
if (scan.comfy_ready || scan.auth_failed || !alive() || now() >= upDeadline) break;
|
|
772
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
773
|
+
}
|
|
774
|
+
deadline = now() + comfyTimeoutMs;
|
|
775
|
+
}
|
|
776
|
+
for (;;) {
|
|
777
|
+
scan = scanWorkerLog(readLogFrom(io, log, logOffset));
|
|
778
|
+
if (scan.auth_failed) {
|
|
779
|
+
return { ...flags(scan), exited: !alive(), reason: 'the Worker Key was rejected (Worker authentication failed)', logFile: log, scan };
|
|
780
|
+
}
|
|
781
|
+
if (phase === 'comfy' && scan.comfy_ready) {
|
|
782
|
+
if (!requireHeartbeat) return { ...flags(scan), exited: false, reason: null, logFile: log, scan };
|
|
783
|
+
phase = 'heartbeat';
|
|
784
|
+
deadline = now() + heartbeatTimeoutMs;
|
|
785
|
+
}
|
|
786
|
+
if (phase === 'heartbeat' && scan.heartbeat) {
|
|
787
|
+
return { ...flags(scan), exited: false, reason: null, logFile: log, scan };
|
|
788
|
+
}
|
|
789
|
+
if (!alive()) {
|
|
790
|
+
return { ...flags(scan), exited: true, reason: `worker process exited${scan.crashed ? ' (Worker crashed)' : ''} — see ${log}`, logFile: log, scan };
|
|
791
|
+
}
|
|
792
|
+
if (now() > deadline) {
|
|
793
|
+
const reason = phase === 'comfy'
|
|
794
|
+
? `worker did not log "ComfyUI ready" within ${Math.round(comfyTimeoutMs / 1000)} s${scan.last_comfy_error ? ` (${scan.last_comfy_error})` : ''} — see ${log}`
|
|
795
|
+
: `the hub did not confirm a heartbeat within ${Math.round(heartbeatTimeoutMs / 1000)} s${scan.last_beacon_error ? ` (${scan.last_beacon_error})` : ''} — see ${log}`;
|
|
796
|
+
return { ...flags(scan), exited: false, reason, logFile: log, scan };
|
|
797
|
+
}
|
|
798
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
function flags(scan) {
|
|
803
|
+
return { comfy_ready: scan.comfy_ready, heartbeat: scan.heartbeat, auth_failed: scan.auth_failed };
|
|
336
804
|
}
|
|
337
805
|
|
|
338
806
|
/** Grace sleep through the adapter (test-injectable `sleep` command wins). */
|
|
@@ -414,17 +882,233 @@ async function restartManagedWorker(io, { workerDir, log = null, stopTimeoutMs =
|
|
|
414
882
|
return { restarted: true, previously_running: previouslyRunning, pid: start.pid, alive: start.alive, reason: start.reason };
|
|
415
883
|
}
|
|
416
884
|
|
|
885
|
+
// ── ensureWorker (installer 0.2.8) ──────────────────────────────────────────
|
|
886
|
+
// install/doctor/boot no longer restart a running worker by default
|
|
887
|
+
// (04.11: doctor restarted the audio/image workers at 13:55:15 and 13:58:52,
|
|
888
|
+
// between tasks only by chance — a result in flight would have been lost).
|
|
889
|
+
//
|
|
890
|
+
// not running → start
|
|
891
|
+
// running, configuration unchanged → left as is
|
|
892
|
+
// running, .env/bundle changed:
|
|
893
|
+
// boot (doctor --yes, no TTY) → left as is, restart pending (warn)
|
|
894
|
+
// --force → restart now
|
|
895
|
+
// idle → restart
|
|
896
|
+
// busy (a task in progress) → wait up to waitJobMs for the task
|
|
897
|
+
// to finish, then restart; still
|
|
898
|
+
// busy → DEFERRED (FAILED, exit ≠ 0)
|
|
899
|
+
// busy state unknown (no log of this
|
|
900
|
+
// process) → DEFERRED (FAILED; --force restarts)
|
|
901
|
+
const DEFAULT_WAIT_JOB_MS = 600000;
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* Pure decision for a running worker.
|
|
905
|
+
* @returns {{ action: 'start'|'leave'|'restart'|'wait'|'defer', reasons: string[] }}
|
|
906
|
+
*/
|
|
907
|
+
function decideWorkerAction({ pid = null, reasons = [], activity = null, force = false, boot = false }) {
|
|
908
|
+
if (!pid) return { action: 'start', reasons: [] };
|
|
909
|
+
if (reasons.length === 0) return { action: 'leave', reasons: [] };
|
|
910
|
+
if (force) return { action: 'restart', reasons };
|
|
911
|
+
if (boot) return { action: 'leave', reasons };
|
|
912
|
+
if (!activity || !activity.known) return { action: 'defer', reasons };
|
|
913
|
+
if (activity.current_job_id) return { action: 'wait', reasons };
|
|
914
|
+
return { action: 'restart', reasons };
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* Bring the worker of this installation up without ever killing a task in
|
|
919
|
+
* progress (see the table above). Returns the startWorker() shape plus
|
|
920
|
+
* { action, restart_reasons, current_job, busy_job, deferred, restart_pending }.
|
|
921
|
+
* @param {object} o
|
|
922
|
+
* @param {string[]} [o.configChanged] what THIS run changed (".env", "worker bundle 2.2.2 → 2.2.3")
|
|
923
|
+
*/
|
|
924
|
+
async function ensureWorker(io, {
|
|
925
|
+
workerDir, nodeBin = null, graceMs = 3000, platformAdapter = null, logFile = null,
|
|
926
|
+
configChanged = [], force = false, boot = false, waitJobMs = DEFAULT_WAIT_JOB_MS,
|
|
927
|
+
pollMs = 5000, progressMs = 30000, sleep = null, log = null, startFn = startWorker, tool = 'animastor',
|
|
928
|
+
}) {
|
|
929
|
+
const adapter = platformAdapter || adapterOf({});
|
|
930
|
+
const lf = logFile || workerLogPath(workerDir);
|
|
931
|
+
const now = () => (io.now ? io.now() : Date.now());
|
|
932
|
+
const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
933
|
+
const info = (m) => { if (log) log.info(m); };
|
|
934
|
+
const warn = (m) => { if (log) log.warn(m); };
|
|
935
|
+
const start = (forceRestart) => startFn(io, { workerDir, nodeBin, graceMs, platformAdapter: adapter, logFile: lf, forceRestart });
|
|
936
|
+
|
|
937
|
+
let pid = findRunningWorkerPid(io, workerDir, { platformAdapter: adapter });
|
|
938
|
+
if (!pid) {
|
|
939
|
+
const res = start(false);
|
|
940
|
+
return { ...res, action: 'started', restart_reasons: [], current_job: 'none' };
|
|
941
|
+
}
|
|
942
|
+
// What this run changed explains itself; otherwise the persistent marker
|
|
943
|
+
// (files newer than the process — e.g. a restart deferred by an earlier run).
|
|
944
|
+
const reasons = (configChanged || []).length > 0
|
|
945
|
+
? Array.from(new Set(configChanged))
|
|
946
|
+
: workerConfigNewer(io, { workerDir, pid, platformAdapter: adapter }).map((f) => `${f} changed after the worker started`);
|
|
947
|
+
let activity = readWorkerActivity(io, { workerDir, pid, logFile: lf });
|
|
948
|
+
const decision = decideWorkerAction({ pid, reasons, activity, force, boot });
|
|
949
|
+
const jobOf = (a) => (a.known ? (a.current_job_id || 'none') : 'unknown');
|
|
950
|
+
const left = (extra = {}) => ({
|
|
951
|
+
started: true, already_running: true, pid, alive: true, reason: null, logFile: lf, logOffset: null,
|
|
952
|
+
action: 'left', restart_reasons: reasons, current_job: jobOf(activity), ...extra,
|
|
953
|
+
});
|
|
954
|
+
const deferred = (why) => ({
|
|
955
|
+
started: false, already_running: true, pid, alive: true, deferred: true, reason: why, logFile: lf, logOffset: null,
|
|
956
|
+
action: 'deferred', restart_reasons: reasons, current_job: jobOf(activity), busy_job: activity.current_job_id || null,
|
|
957
|
+
});
|
|
958
|
+
|
|
959
|
+
if (decision.action === 'leave' && reasons.length === 0) {
|
|
960
|
+
const health = activity.known && !activity.healthy
|
|
961
|
+
? ` — ${activity.comfy_ready ? (activity.last_beacon_error ? `last beacon failed: ${activity.last_beacon_error}` : 'no heartbeat accepted yet') : 'it has not reached ComfyUI yet'}`
|
|
962
|
+
: '';
|
|
963
|
+
info(`worker already running (pid ${pid}), left as is${health}`);
|
|
964
|
+
return left();
|
|
965
|
+
}
|
|
966
|
+
if (decision.action === 'leave') {
|
|
967
|
+
warn(`worker already running (pid ${pid}), left as is — restart pending (${reasons.join('; ')}); the boot path never restarts a running worker: run \`${tool} doctor\``);
|
|
968
|
+
return left({ restart_pending: reasons });
|
|
969
|
+
}
|
|
970
|
+
if (decision.action === 'defer') {
|
|
971
|
+
const why = `cannot tell whether the worker (pid ${pid}) is busy (${activity.reason}) — restart for ${reasons.join('; ')} deferred; to restart anyway: ${tool} doctor --force`;
|
|
972
|
+
warn(why);
|
|
973
|
+
return deferred(why);
|
|
974
|
+
}
|
|
975
|
+
if (decision.action === 'wait') {
|
|
976
|
+
const deadline = now() + Math.max(0, Number(waitJobMs) || 0);
|
|
977
|
+
let nextProgress = now();
|
|
978
|
+
while (activity.known && activity.current_job_id && now() < deadline) {
|
|
979
|
+
if (now() >= nextProgress) {
|
|
980
|
+
info(`worker is busy with ${activity.current_job_id} (pid ${pid}) — waiting up to ${Math.round((deadline - now()) / 1000)} s for the task to finish before the restart (${reasons.join('; ')})`);
|
|
981
|
+
nextProgress = now() + progressMs;
|
|
982
|
+
}
|
|
983
|
+
await wait(Math.min(pollMs, Math.max(1, deadline - now())));
|
|
984
|
+
const still = findRunningWorkerPid(io, workerDir, { platformAdapter: adapter });
|
|
985
|
+
if (still !== pid) { pid = still; break; }
|
|
986
|
+
activity = readWorkerActivity(io, { workerDir, pid, logFile: lf });
|
|
987
|
+
}
|
|
988
|
+
if (!pid) {
|
|
989
|
+
info('the worker exited while waiting — starting it');
|
|
990
|
+
const res = start(false);
|
|
991
|
+
return { ...res, action: 'started', restart_reasons: reasons, current_job: 'none' };
|
|
992
|
+
}
|
|
993
|
+
if (!activity.known) {
|
|
994
|
+
const why = `cannot tell whether the worker (pid ${pid}) is busy (${activity.reason}) — restart for ${reasons.join('; ')} deferred; to restart anyway: ${tool} doctor --force`;
|
|
995
|
+
warn(why);
|
|
996
|
+
return deferred(why);
|
|
997
|
+
}
|
|
998
|
+
if (activity.current_job_id) {
|
|
999
|
+
const why = `worker is busy with ${activity.current_job_id} (pid ${pid}) — restart deferred (waited ${Math.round((Number(waitJobMs) || 0) / 1000)} s; needed for: ${reasons.join('; ')}); re-run \`${tool} doctor\` when the task finishes, or \`${tool} doctor --force\` to restart now (the task's result is lost)`;
|
|
1000
|
+
warn(why);
|
|
1001
|
+
return deferred(why);
|
|
1002
|
+
}
|
|
1003
|
+
info(`the worker (pid ${pid}) finished ${activity.last_job_id || 'its task'}`);
|
|
1004
|
+
}
|
|
1005
|
+
// restart: idle (or --force)
|
|
1006
|
+
if (force && activity.current_job_id) warn(`--force: restarting the worker (pid ${pid}) while it is busy with ${activity.current_job_id} — the task's result is lost`);
|
|
1007
|
+
info(`restarting the worker (pid ${pid}): ${reasons.join('; ')}`);
|
|
1008
|
+
const res = start(true);
|
|
1009
|
+
return { ...res, action: 'restarted', restarted_from: pid, restart_reasons: reasons, current_job: 'none' };
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// ── node-classes.json (installer 0.2.7, worker bundle >= 2.2.2) ─────────────
|
|
1013
|
+
// GPU E2E 2026-11-02: a worker took tasks from a ComfyUI without its
|
|
1014
|
+
// profile's nodes. Bundle 2.2.2 asks for tasks only after ComfyUI's
|
|
1015
|
+
// /object_info lists every class of this file; without the file it keeps the
|
|
1016
|
+
// old behaviour (ComfyUI API only) and logs one warning. The installer writes
|
|
1017
|
+
// it from the manifests' `provides_classes` (required dependencies only) on a
|
|
1018
|
+
// fresh install, on a bundle update and on every doctor/boot run — so a node
|
|
1019
|
+
// installed by an older installer gets it on its next doctor/boot.
|
|
1020
|
+
//
|
|
1021
|
+
// { "generated_by": "animastor-installer <v>",
|
|
1022
|
+
// "profiles": { "audio/qwen-tts": ["Qwen3TTSLoader", …] } }
|
|
1023
|
+
const NODE_CLASSES_FILE = 'node-classes.json';
|
|
1024
|
+
|
|
1025
|
+
/** {profileId: [classes]} of the given manifests (required deps only, sorted, unique). */
|
|
1026
|
+
function nodeClassesOfManifests(manifests) {
|
|
1027
|
+
const profiles = {};
|
|
1028
|
+
for (const m of manifests || []) {
|
|
1029
|
+
const id = m && m.profile && m.profile.id;
|
|
1030
|
+
if (!id) continue;
|
|
1031
|
+
const set = new Set(profiles[id] || []);
|
|
1032
|
+
for (const dep of m.dependencies || []) {
|
|
1033
|
+
if (dep && dep.requirement && dep.requirement !== 'required') continue;
|
|
1034
|
+
for (const cls of (dep && dep.provides_classes) || []) {
|
|
1035
|
+
if (typeof cls === 'string' && cls.trim()) set.add(cls.trim());
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
profiles[id] = Array.from(set).sort();
|
|
1039
|
+
}
|
|
1040
|
+
return profiles;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
/**
|
|
1044
|
+
* Write <workerDir>/node-classes.json for the profiles of this run. Only when
|
|
1045
|
+
* a worker bundle is installed there (worker.cjs present). Atomic (temp +
|
|
1046
|
+
* rename); an identical file is left untouched.
|
|
1047
|
+
* @returns {{ status: 'written'|'current'|'absent'|'skipped'|'failed', path?: string, profiles?: object, reason?: string }}
|
|
1048
|
+
*/
|
|
1049
|
+
function writeNodeClasses(io, { workerDir, manifests, log = null, version = null }) {
|
|
1050
|
+
if (!workerDir || !io.fs.existsSync(path.join(workerDir, 'worker.cjs'))) return { status: 'absent' };
|
|
1051
|
+
const profiles = nodeClassesOfManifests(manifests);
|
|
1052
|
+
if (Object.keys(profiles).length === 0) return { status: 'skipped', reason: 'no profile manifests' };
|
|
1053
|
+
const file = path.join(workerDir, NODE_CLASSES_FILE);
|
|
1054
|
+
let v = version;
|
|
1055
|
+
if (!v) { try { v = require('../../../package.json').version || null; } catch (_) { v = null; } }
|
|
1056
|
+
const doc = { generated_by: `animastor-installer${v ? ` ${v}` : ''}`, profiles };
|
|
1057
|
+
const text = JSON.stringify(doc, null, 2) + '\n';
|
|
1058
|
+
try {
|
|
1059
|
+
if (io.fs.existsSync(file)) {
|
|
1060
|
+
let current = null;
|
|
1061
|
+
try { current = JSON.parse(String(io.fs.readFileSync(file, 'utf8'))); } catch (_) { current = null; }
|
|
1062
|
+
if (current && JSON.stringify(current.profiles || null) === JSON.stringify(profiles)) {
|
|
1063
|
+
return { status: 'current', path: file, profiles };
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
1067
|
+
io.fs.writeFileSync(tmp, text);
|
|
1068
|
+
io.fs.renameSync(tmp, file);
|
|
1069
|
+
const n = Object.values(profiles).reduce((a, l) => a + l.length, 0);
|
|
1070
|
+
if (log) log.info(`${NODE_CLASSES_FILE} written: ${Object.keys(profiles).join(', ')} (${n} node class(es)) — the worker takes tasks only when ComfyUI lists them`);
|
|
1071
|
+
return { status: 'written', path: file, profiles };
|
|
1072
|
+
} catch (err) {
|
|
1073
|
+
if (log) log.warn(`${NODE_CLASSES_FILE} could not be written: ${err.message} — the worker falls back to the ComfyUI-API-only readiness`);
|
|
1074
|
+
return { status: 'failed', path: file, reason: err.message };
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
|
|
417
1078
|
module.exports = {
|
|
418
1079
|
installWorkerBundle,
|
|
1080
|
+
ensureWorkerDependencies,
|
|
1081
|
+
declaredDependencies,
|
|
1082
|
+
readPkgVersion,
|
|
1083
|
+
readEnvValues,
|
|
1084
|
+
hasEnvKey,
|
|
1085
|
+
resolveWorkerNode,
|
|
1086
|
+
workerLogPath,
|
|
1087
|
+
workerSpawnEnv,
|
|
1088
|
+
scanWorkerLog,
|
|
1089
|
+
readLogFrom,
|
|
1090
|
+
waitForWorkerReady,
|
|
419
1091
|
fetchHubWorkerBundle,
|
|
420
1092
|
startWorker,
|
|
421
1093
|
stopManagedWorker,
|
|
422
1094
|
restartManagedWorker,
|
|
423
1095
|
findRunningWorkerPid,
|
|
424
1096
|
workerEnvIsNewer,
|
|
1097
|
+
workerProcessStartMs,
|
|
1098
|
+
workerConfigNewer,
|
|
1099
|
+
WORKER_CONFIG_FILES,
|
|
1100
|
+
parseWorkerActivity,
|
|
1101
|
+
readWorkerActivity,
|
|
1102
|
+
currentJobLabel,
|
|
1103
|
+
decideWorkerAction,
|
|
1104
|
+
ensureWorker,
|
|
1105
|
+
DEFAULT_WAIT_JOB_MS,
|
|
425
1106
|
configureEnv,
|
|
426
1107
|
apiBaseFromHubUrl,
|
|
427
1108
|
verifyRegistration,
|
|
428
1109
|
checkWorkerCanStart,
|
|
429
1110
|
renderEnvLines,
|
|
1111
|
+
NODE_CLASSES_FILE,
|
|
1112
|
+
nodeClassesOfManifests,
|
|
1113
|
+
writeNodeClasses,
|
|
430
1114
|
};
|