@danhachuel/jobfinder 0.1.10 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/package.json +1 -1
- package/scripts/cli.mjs +37 -8
- package/scripts/manual-tests/startup-keepalive.mjs +122 -2
- package/src/server/index.mjs +3 -1
- package/src/server/storage/jsonStore.mjs +55 -1
- package/src/server/worker.mjs +133 -27
- package/src/server/workerRuntime.mjs +15 -2
- package/src/ui/dist/assets/{index-Bm84G2Aa.js → index-Jg7CthP-.js} +1 -1
- package/src/ui/dist/index.html +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,42 @@ All notable changes to JobFinder are documented in this file.
|
|
|
6
6
|
|
|
7
7
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
8
8
|
|
|
9
|
+
## [0.1.12] — 2026-11-18
|
|
10
|
+
|
|
11
|
+
### Security
|
|
12
|
+
|
|
13
|
+
- **Remoção definitiva da senha no terminal**: a linha `Login: <email> / <senha>` foi **deletada** do startup do servidor — o terminal não exibe mais e-mail nem senha (a dica de "troque a senha padrão" continua apenas na UI, em Configurações → Segurança). Verificado em boot real: stdout/stderr sem `123456`, sem e-mail e sem `Login:`.
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- **`EPERM` no `rename` atômico (Windows)**: `JsonStore.write` agora usa `renameAtomic` — em `EPERM`/`EACCES`/`EBUSY` (antivírus, editor ou outro processo segurando o destino) o rename é retentado com backoff (5 × 50 ms) e, se ainda falhar, o destino é removido antes da última tentativa (`unlink` + `rename`); falha definitiva limpa o `.tmp` e propaga o erro. Nenhum `.tmp` órfão em nenhum caminho.
|
|
18
|
+
- **Worker não morre por falha de escrita de estado**: `patchState`/`patchStateSync` envolvem a escrita em try/catch — `EPERM` (ou qualquer erro de I/O) VAI para `worker-error.log` + log + console e a escrita é tentada de novo no próximo tick/heartbeat; `process.exit` não é chamado.
|
|
19
|
+
- **Restart do worker determinístico (fim do falso "outro worker dono")**: (1) detecção de órfão por **pipe** — o supervisor mantém o stdin do worker aberto; quando ele morre (inclusive kill externo), o worker vê EOF e se encerra na hora, sem depender de `ppid` (que o Windows recicla); (2) o launcher passa `JOBFINDER_TAKEOVER=1` em seus spawns — no boot e no restart, uma heartbeat velha de pid reciclado nunca mais bloqueia o worker novo.
|
|
20
|
+
- **Loop do worker à prova de fuga síncrona**: callbacks dos timers (tick e heartbeat) em try/catch, com re-agendamento.
|
|
21
|
+
|
|
22
|
+
### Tests
|
|
23
|
+
|
|
24
|
+
- `tests/test_atomic_write_concurrency.js` (stub → real, node:test): 40 updates concorrentes sem perder registro, mutator que lança preserva o arquivo anterior, `.tmp` restante não quebra o store, **rename travado com EPERM retentado até dar certo** e **EPERM permanente falhando alto sem .tmp órfão**.
|
|
25
|
+
- `startup-keepalive.mjs`: novo cenário **worker direto com rename sabotado (EPERM permanente)** — sobrevive, registra em `worker-error.log`. Suíte: 32 keepalive + 39 fase2-worker + 32 auth + 16 serviços + 22 E2E.
|
|
26
|
+
|
|
27
|
+
## [0.1.11] — 2026-11-16
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- **Crash do Worker (exit `4294967295` / `0xFFFFFFFF`) não encerra mais o processo principal** (Windows/MobaXterm): o launcher passou a **supervisionar** o worker — a saída dele só é registrada (`[jobfinder] worker encerrou (code/signal). O servidor web continua rodando.`) e, com o servidor no ar, um worker novo é iniciado automaticamente (até 5 tentativas, 3 s de intervalo; nunca durante o shutdown — sem órfãos). `process.exit` não é chamado nesse caminho.
|
|
32
|
+
- **Worker não morre mais por falha de I/O no console**: escritas em `stdout`/`stderr` passaram por um helper à prova de throw (`safeWrite`); `unhandledRejection` é registrado e o processo **continua rodando** (antes um EPIPE/escrita quebrada no MobaXterm podia derrubar o worker); `uncaughtException` registra e sai(1) — com o launcher reiniciando o worker.
|
|
33
|
+
- **`worker-error.log`**: falhas inesperadas do worker (rejection, exceção, erro de stdio) agora são gravadas em `<dataDir>/worker-error.log` — o único artefato que sobrevive a um pipe morto, permitindo diagnosticar o crash no terminal hostil.
|
|
34
|
+
- **Heartbeat fresca de pid morto não bloqueia mais um worker novo**: `anotherWorkerOwnsState()` confirma que o pid dono do estado está vivo (`process.kill(pid, 0)`). Sem isso, um worker morto por kill externo (que no Windows pula o handler de exit) deixava a heartbeat "fresca" e o restart seria recusado como duplicado.
|
|
35
|
+
- **Loop do worker à prova de fuga**: os callbacks dos timers (tick e heartbeat) estão envoltos em try/catch — uma falha síncrona é reportada e o loop é re-agendado, nunca abandonado.
|
|
36
|
+
|
|
37
|
+
### Changed
|
|
38
|
+
|
|
39
|
+
- Mensagem de encerramento do worker no launcher agora é em português e explícita sobre a continuidade do servidor.
|
|
40
|
+
|
|
41
|
+
### Tests
|
|
42
|
+
|
|
43
|
+
- `startup-keepalive.mjs` cobre o worker de ponta a ponta: crash do worker com o CLI vivo + **restart automático** (pid novo assumindo a fila), `worker-error.log` com rejection injetada, worker sobrevivendo a EPIPE com heartbeat no disco. Suíte: 29 keepalive + 39 fase2-worker + 32 auth + 16 serviços + 22 E2E.
|
|
44
|
+
|
|
9
45
|
## [0.1.10] — 2026-11-15
|
|
10
46
|
|
|
11
47
|
### Documentation
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@danhachuel/jobfinder",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.12",
|
|
4
4
|
"description": "JobFinder — LinkedIn automation platform (posts, connections/DMs, job matching) with a React + Vite UI. Intelligent workflows, JSON storage.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"linkedin",
|
package/scripts/cli.mjs
CHANGED
|
@@ -209,17 +209,47 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
209
209
|
|
|
210
210
|
// Background worker: a SEPARATE process so the automation queues keep
|
|
211
211
|
// running when the browser is closed (or was never opened). Spawn follows
|
|
212
|
-
//
|
|
213
|
-
//
|
|
212
|
+
// runtime-guard: windowsHide + new process group + piped stdio (never
|
|
213
|
+
// 'inherit'). Disable with JOBFINDER_NO_WORKER=1.
|
|
214
214
|
let worker = null;
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
215
|
+
let workerRestarts = 0;
|
|
216
|
+
let stopping = false;
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Supervise the worker.
|
|
220
|
+
*
|
|
221
|
+
* THE LAUNCHER NEVER DIES BECAUSE OF THE WORKER. An exit here only logs
|
|
222
|
+
* (the server keeps serving) and, while the server is still up, starts a
|
|
223
|
+
* fresh worker so the automation queues never stop silently. process.exit
|
|
224
|
+
* is NEVER called on this path.
|
|
225
|
+
*/
|
|
226
|
+
const startWorker = () => {
|
|
227
|
+
// JOBFINDER_TAKEOVER: the launcher either just booted (any previous
|
|
228
|
+
// worker's supervisor is gone by definition) or observed the previous
|
|
229
|
+
// worker exit — a stale heartbeat must never block this spawn.
|
|
230
|
+
worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: resolved, JOBFINDER_TAKEOVER: '1' } });
|
|
219
231
|
forwardChildOutput(worker, '[worker]');
|
|
220
232
|
worker.on('exit', (code, signal) => {
|
|
221
|
-
|
|
233
|
+
const reason = signal ? `signal ${signal}` : `code ${code}`;
|
|
234
|
+
console.error(`\n[jobfinder] worker encerrou (${reason}). O servidor web continua rodando.`);
|
|
235
|
+
const serverAlive = child.exitCode === null && child.signalCode === null;
|
|
236
|
+
if (!stopping && serverAlive && workerRestarts < 5) {
|
|
237
|
+
workerRestarts += 1;
|
|
238
|
+
console.error(`[jobfinder] reiniciando o worker (tentativa ${workerRestarts}/5)...`);
|
|
239
|
+
// Re-check `stopping`: a shutdown that starts while this timer is
|
|
240
|
+
// pending must never leave an orphan behind.
|
|
241
|
+
setTimeout(() => {
|
|
242
|
+
if (!stopping) startWorker();
|
|
243
|
+
}, 3000);
|
|
244
|
+
}
|
|
222
245
|
});
|
|
246
|
+
return worker;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
if (process.env.JOBFINDER_NO_WORKER === '1') {
|
|
250
|
+
console.log(' Worker : disabled (JOBFINDER_NO_WORKER=1)');
|
|
251
|
+
} else {
|
|
252
|
+
startWorker();
|
|
223
253
|
console.log(` Worker : automação em segundo plano (pid ${worker.pid})`);
|
|
224
254
|
}
|
|
225
255
|
|
|
@@ -240,7 +270,6 @@ async function commandStart({ port, host, dataDir, dryRun }) {
|
|
|
240
270
|
console.error(`[jobfinder] launcher exiting with code ${code}.`);
|
|
241
271
|
});
|
|
242
272
|
|
|
243
|
-
let stopping = false;
|
|
244
273
|
const stopChildren = () => {
|
|
245
274
|
if (worker && worker.exitCode === null && worker.signalCode === null) {
|
|
246
275
|
worker.kill('SIGTERM');
|
|
@@ -10,6 +10,11 @@
|
|
|
10
10
|
* 4. SIGTERM encerra de forma limpa — verificado emitindo o sinal dentro
|
|
11
11
|
* do próprio processo (no Windows, child.kill() sempre vira
|
|
12
12
|
* TerminateProcess e os handlers graceful nunca rodam)
|
|
13
|
+
* 5. worker: sobe com o app, o CLI sobrevive ao crash dele (e o
|
|
14
|
+
* reinicia), modo JOBFINDER_NO_WORKER=1
|
|
15
|
+
* 6. worker direto: rejection injetada -> worker-error.log em disco e o
|
|
16
|
+
* processo continua vivo; pipes quebrados (EPIPE) não o derrubam;
|
|
17
|
+
* rename sempre EPERM (arquivo travado no Windows) não o derruba
|
|
13
18
|
*
|
|
14
19
|
* Uso: node scripts/manual-tests/startup-keepalive.mjs
|
|
15
20
|
*/
|
|
@@ -20,6 +25,8 @@ import os from 'node:os';
|
|
|
20
25
|
import path from 'node:path';
|
|
21
26
|
import process from 'node:process';
|
|
22
27
|
|
|
28
|
+
import { ensureDataDir } from '../../src/server/storage/bootstrap.mjs';
|
|
29
|
+
|
|
23
30
|
const ROOT = process.cwd();
|
|
24
31
|
let passed = 0;
|
|
25
32
|
let failed = 0;
|
|
@@ -190,7 +197,7 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
190
197
|
const pid1 = await workerPid();
|
|
191
198
|
check('worker continua vivo apos os heartbeats (sem falso positivo do guardiao)', pid1 === pid0 && (await getStatus(4185, '/api/health')) === 200, `pid=${pid1}`);
|
|
192
199
|
|
|
193
|
-
// CRASH do worker: o CLI NAO pode morrer — so logar.
|
|
200
|
+
// CRASH do worker: o CLI NAO pode morrer — so logar (e reiniciar o worker).
|
|
194
201
|
try {
|
|
195
202
|
process.kill(Number(pid1), 'SIGTERM');
|
|
196
203
|
} catch {
|
|
@@ -198,13 +205,126 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
198
205
|
}
|
|
199
206
|
await wait(2500);
|
|
200
207
|
check('CLI sobrevive ao crash do worker', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
|
|
201
|
-
check('
|
|
208
|
+
check('saida do worker foi registrada no log', /worker encerrou/i.test(out), out.split('\n').filter((l) => /worker encerrou/i.test(l))[0] ?? '');
|
|
202
209
|
check('servidor continua respondendo apos o crash do worker', (await getStatus(4185, '/api/health')) === 200);
|
|
210
|
+
|
|
211
|
+
// O launcher supervisiona: um worker novo assume a fila.
|
|
212
|
+
await wait(5000);
|
|
213
|
+
const pid2 = await workerPid();
|
|
214
|
+
check('launcher reiniciou o worker automaticamente', pid2 !== null && pid2 !== pid1, `antes=${pid1} depois=${pid2}`);
|
|
215
|
+
check('restart anunciado no log', /reiniciando o worker/i.test(out), out.split('\n').filter((l) => /reiniciando o worker/i.test(l))[0] ?? '');
|
|
216
|
+
check('CLI continua vivo depois do restart', !dead(child) && (await getStatus(4185, '/api/health')) === 200);
|
|
203
217
|
child.kill();
|
|
204
218
|
await wait(800);
|
|
205
219
|
fs.rmSync(tmp, { recursive: true, force: true });
|
|
206
220
|
}
|
|
207
221
|
|
|
222
|
+
// 7) worker direto: rejection injetada -> worker-error.log + processo vivo
|
|
223
|
+
{
|
|
224
|
+
console.log('\n== worker direto: rejection injetada e log em arquivo ==');
|
|
225
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-wrej-'));
|
|
226
|
+
const home = path.join(tmp, 'data');
|
|
227
|
+
ensureDataDir(home); // o worker exige o skeleton (como o launcher faz)
|
|
228
|
+
const fault = path.join(tmp, 'fault.cjs');
|
|
229
|
+
fs.writeFileSync(fault, "setTimeout(() => { Promise.reject(new Error('fault-injection: worker rejection')); }, 1200);\n");
|
|
230
|
+
const worker = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'worker.mjs')], {
|
|
231
|
+
cwd: ROOT,
|
|
232
|
+
env: { ...process.env, JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', JOBFINDER_WORKER_INTERVAL: '4000', NODE_OPTIONS: `--require ${fault}` },
|
|
233
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
234
|
+
});
|
|
235
|
+
let out = '';
|
|
236
|
+
worker.stdout.on('data', (d) => { out += String(d); });
|
|
237
|
+
worker.stderr.on('data', (d) => { out += String(d); });
|
|
238
|
+
await wait(8000);
|
|
239
|
+
check('worker sobrevive a rejection (nao morre silencioso)', !dead(worker), dead(worker) ? `exitCode=${worker.exitCode} signal=${worker.signalCode}` : 'vivo');
|
|
240
|
+
let errorLog = '';
|
|
241
|
+
try {
|
|
242
|
+
errorLog = fs.readFileSync(path.join(home, 'worker-error.log'), 'utf8');
|
|
243
|
+
} catch {
|
|
244
|
+
/* arquivo pode nao existir */
|
|
245
|
+
}
|
|
246
|
+
check('worker-error.log registrou a falha', /fault-injection: worker rejection/.test(errorLog), errorLog.split('\n')[0]?.slice(0, 100) ?? 'vazio');
|
|
247
|
+
check('falha tambem apareceu no console', /unhandled promise rejection ignored/i.test(out));
|
|
248
|
+
worker.kill();
|
|
249
|
+
await wait(800);
|
|
250
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// 8) worker direto: stdout/stderr quebrados (EPIPE) -> worker segue vivo
|
|
254
|
+
{
|
|
255
|
+
console.log('\n== worker direto: EPIPE nos pipes ==');
|
|
256
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-wepipe-'));
|
|
257
|
+
const home = path.join(tmp, 'data');
|
|
258
|
+
ensureDataDir(home); // o worker exige o skeleton (como o launcher faz)
|
|
259
|
+
const worker = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'worker.mjs')], {
|
|
260
|
+
cwd: ROOT,
|
|
261
|
+
env: { ...process.env, JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', JOBFINDER_WORKER_INTERVAL: '4000' },
|
|
262
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
263
|
+
});
|
|
264
|
+
worker.stdout.on('data', () => {});
|
|
265
|
+
worker.stderr.on('data', () => {});
|
|
266
|
+
await wait(3000);
|
|
267
|
+
worker.stdout.destroy();
|
|
268
|
+
worker.stderr.destroy();
|
|
269
|
+
await wait(6000);
|
|
270
|
+
check('worker sobrevive ao EPIPE', !dead(worker), dead(worker) ? `exitCode=${worker.exitCode} signal=${worker.signalCode}` : 'vivo');
|
|
271
|
+
let state = null;
|
|
272
|
+
try {
|
|
273
|
+
state = JSON.parse(fs.readFileSync(path.join(home, 'worker-state.json'), 'utf8'));
|
|
274
|
+
} catch {
|
|
275
|
+
/* arquivo pode nao existir */
|
|
276
|
+
}
|
|
277
|
+
check('heartbeat continua sendo publicado sem o console', Boolean(state?.pid) && state.pid === worker.pid, `pid=${state?.pid}`);
|
|
278
|
+
worker.kill();
|
|
279
|
+
await wait(800);
|
|
280
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// 9) worker direto: rename SEMPRE EPERM (antivirus/arquivo travado no
|
|
284
|
+
// Windows) -> o worker NAO morre; o erro vai para worker-error.log e a
|
|
285
|
+
// escrita é tentada de novo no próximo tick/heartbeat.
|
|
286
|
+
{
|
|
287
|
+
console.log('\n== worker direto: EPERM no rename (arquivo travado) ==');
|
|
288
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-wperm-'));
|
|
289
|
+
const home = path.join(tmp, 'data');
|
|
290
|
+
ensureDataDir(home);
|
|
291
|
+
const sabotage = path.join(tmp, 'eperm.cjs');
|
|
292
|
+
fs.writeFileSync(
|
|
293
|
+
sabotage,
|
|
294
|
+
`const fs = require('node:fs');\n` +
|
|
295
|
+
`const real = fs.renameSync.bind(fs);\n` +
|
|
296
|
+
`fs.renameSync = (from, to) => {\n` +
|
|
297
|
+
` if (String(to).endsWith('worker-state.json')) {\n` +
|
|
298
|
+
` const err = new Error('EPERM: operation not permitted, rename');\n` +
|
|
299
|
+
` err.code = 'EPERM';\n` +
|
|
300
|
+
` throw err;\n` +
|
|
301
|
+
` }\n` +
|
|
302
|
+
` return real(from, to);\n` +
|
|
303
|
+
`};\n`
|
|
304
|
+
);
|
|
305
|
+
const worker = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'worker.mjs')], {
|
|
306
|
+
cwd: ROOT,
|
|
307
|
+
env: { ...process.env, JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', JOBFINDER_WORKER_INTERVAL: '4000', NODE_OPTIONS: `--require ${sabotage}` },
|
|
308
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
309
|
+
});
|
|
310
|
+
let out = '';
|
|
311
|
+
worker.stdout.on('data', (d) => { out += String(d); });
|
|
312
|
+
worker.stderr.on('data', (d) => { out += String(d); });
|
|
313
|
+
await wait(9000);
|
|
314
|
+
check('worker sobrevive ao EPERM no rename', !dead(worker), dead(worker) ? `exitCode=${worker.exitCode} signal=${worker.signalCode}` : 'vivo');
|
|
315
|
+
let errorLog = '';
|
|
316
|
+
try {
|
|
317
|
+
errorLog = fs.readFileSync(path.join(home, 'worker-error.log'), 'utf8');
|
|
318
|
+
} catch {
|
|
319
|
+
/* arquivo pode nao existir */
|
|
320
|
+
}
|
|
321
|
+
check('EPERM registrado em worker-error.log', /EPERM/.test(errorLog), errorLog.split('\n')[0]?.slice(0, 100) ?? 'vazio');
|
|
322
|
+
check('worker-state write failed registrado (não engolido em silêncio)', /worker-state write failed/i.test(errorLog));
|
|
323
|
+
worker.kill();
|
|
324
|
+
await wait(800);
|
|
325
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
326
|
+
}
|
|
327
|
+
|
|
208
328
|
// 6) JOBFINDER_NO_WORKER=1: modo sem worker, CLI continua vivo
|
|
209
329
|
{
|
|
210
330
|
console.log('\n== boot sem worker (JOBFINDER_NO_WORKER=1) ==');
|
package/src/server/index.mjs
CHANGED
|
@@ -127,7 +127,9 @@ export async function start() {
|
|
|
127
127
|
} else {
|
|
128
128
|
console.log('REAL MODE: live LinkedIn actions are enabled (dry-run is OFF).');
|
|
129
129
|
}
|
|
130
|
-
|
|
130
|
+
// Credentials are NEVER printed to the terminal (security): the local
|
|
131
|
+
// account is managed in the UI (Configurações → Segurança). A dangling
|
|
132
|
+
// `Login:` line here leaked the default e-mail/password to every console.
|
|
131
133
|
});
|
|
132
134
|
|
|
133
135
|
// Pin the server handle: the listening socket keeps the event loop (and
|
|
@@ -10,6 +10,60 @@ import fs from 'node:fs';
|
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import { randomUUID } from 'node:crypto';
|
|
12
12
|
|
|
13
|
+
/** Synchronous sleep — the only dependency-free one in Node. */
|
|
14
|
+
function sleepSync(ms) {
|
|
15
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Atomic replace with Windows patience.
|
|
20
|
+
*
|
|
21
|
+
* On Windows, `rename` over a file that ANY process still holds open —
|
|
22
|
+
* antivirus scanning the data dir, an editor, another node process that
|
|
23
|
+
* opened it without FILE_SHARE_DELETE — fails with EPERM/EACCES/EBUSY.
|
|
24
|
+
* The rename is the LAST step of every atomic write, so the write retries
|
|
25
|
+
* with backoff (5 × 50 ms) and, if the destination is still locked, drops
|
|
26
|
+
* it first: Windows allows deleting a locked file far more often than
|
|
27
|
+
* renaming over it.
|
|
28
|
+
*
|
|
29
|
+
* @param {string} tmp temp file holding the new content
|
|
30
|
+
* @param {string} file destination
|
|
31
|
+
* @throws the OS error when every attempt failed (callers decide how bad
|
|
32
|
+
* that is — a heartbeat failure must never kill a process)
|
|
33
|
+
*/
|
|
34
|
+
function renameAtomic(tmp, file) {
|
|
35
|
+
const RETRY_DELAY_MS = 50;
|
|
36
|
+
const MAX_ATTEMPTS = 5;
|
|
37
|
+
let lastErr = null;
|
|
38
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
|
|
39
|
+
try {
|
|
40
|
+
fs.renameSync(tmp, file);
|
|
41
|
+
return;
|
|
42
|
+
} catch (err) {
|
|
43
|
+
const code = err?.code;
|
|
44
|
+
if (code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY') throw err;
|
|
45
|
+
lastErr = err;
|
|
46
|
+
if (attempt < MAX_ATTEMPTS) sleepSync(RETRY_DELAY_MS);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
// Fallback: remove the locked destination (best-effort) and rename once more.
|
|
50
|
+
try {
|
|
51
|
+
fs.unlinkSync(file);
|
|
52
|
+
} catch {
|
|
53
|
+
/* the rename below may still succeed: only it can report failure */
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
fs.renameSync(tmp, file);
|
|
57
|
+
} catch (err) {
|
|
58
|
+
try {
|
|
59
|
+
fs.unlinkSync(tmp); // never leave the .tmp behind
|
|
60
|
+
} catch {
|
|
61
|
+
/* best effort */
|
|
62
|
+
}
|
|
63
|
+
throw err ?? lastErr;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
13
67
|
export function newId(prefix) {
|
|
14
68
|
return `${prefix}_${randomUUID().replace(/-/g, '').slice(0, 12)}`;
|
|
15
69
|
}
|
|
@@ -71,7 +125,7 @@ export class JsonStore {
|
|
|
71
125
|
const tmp = `${file}.tmp.${process.pid}`;
|
|
72
126
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
73
127
|
fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
|
|
74
|
-
|
|
128
|
+
renameAtomic(tmp, file);
|
|
75
129
|
this.cache.set(name, data);
|
|
76
130
|
return data;
|
|
77
131
|
}
|
package/src/server/worker.mjs
CHANGED
|
@@ -22,9 +22,10 @@
|
|
|
22
22
|
* Rules honoured here (see .agents/skills/): only atomic JSON writes through
|
|
23
23
|
* the store, dry-run re-checked on every pass against the live config, spawn
|
|
24
24
|
* flags and stdio handled by the launcher, and no unhandled error can kill
|
|
25
|
-
* this process silently (
|
|
25
|
+
* this process silently (runtime-guard).
|
|
26
26
|
*/
|
|
27
27
|
import fs from 'node:fs';
|
|
28
|
+
import path from 'node:path';
|
|
28
29
|
import process from 'node:process';
|
|
29
30
|
|
|
30
31
|
import { createContext } from './context.mjs';
|
|
@@ -44,26 +45,66 @@ const INTERVAL_MS = Math.max(2_000, Number(process.env.JOBFINDER_WORKER_INTERVAL
|
|
|
44
45
|
const HEARTBEAT_MS = Math.min(5_000, INTERVAL_MS);
|
|
45
46
|
|
|
46
47
|
/* ------------------------------------------------------------------ *
|
|
47
|
-
* Process resilience (
|
|
48
|
+
* Process resilience (runtime-guard): never die silently *
|
|
48
49
|
* ------------------------------------------------------------------ */
|
|
49
50
|
let logger = null;
|
|
51
|
+
let errorLogPath = null;
|
|
50
52
|
|
|
51
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Write that cannot kill the process: a broken stdout/stderr (EPIPE on
|
|
55
|
+
* Windows terminals, MobaXterm, redirection) must never take the worker
|
|
56
|
+
* down — the automation queues would stop for a console line.
|
|
57
|
+
*/
|
|
58
|
+
function safeWrite(stream, text) {
|
|
59
|
+
try {
|
|
60
|
+
stream?.write?.(text);
|
|
61
|
+
} catch {
|
|
62
|
+
/* the pipe is gone: the file log keeps the evidence */
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Append one line to <dataDir>/worker-error.log (best-effort, sync).
|
|
68
|
+
* This file is the ONLY artifact that survives a dead pipe: when the
|
|
69
|
+
* process dies on a hostile terminal, the console output is gone but the
|
|
70
|
+
* crash reason stays on disk for diagnosis.
|
|
71
|
+
*/
|
|
72
|
+
function appendErrorLog(line) {
|
|
73
|
+
if (!errorLogPath) return;
|
|
74
|
+
try {
|
|
75
|
+
fs.appendFileSync(errorLogPath, `${new Date().toISOString()} ${line}\n`, 'utf8');
|
|
76
|
+
} catch {
|
|
77
|
+
/* the data dir may be read-only: the console mirror still has the line */
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Report an unexpected failure: file log + logger + safe console mirror. */
|
|
82
|
+
function reportUnexpected(scope, reason) {
|
|
52
83
|
const message = reason instanceof Error ? reason.message : String(reason);
|
|
53
|
-
|
|
54
|
-
|
|
84
|
+
const stack = reason instanceof Error ? reason.stack : undefined;
|
|
85
|
+
appendErrorLog(`${scope}: ${message}${stack ? `\n${stack}` : ''}`);
|
|
86
|
+
logger?.error('worker', scope, { message, stack });
|
|
87
|
+
safeWrite(process.stderr, `[jobfinder:worker] ${scope}: ${message}\n`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
process.on('unhandledRejection', (reason) => {
|
|
91
|
+
// Keep running: the worker owns the automation queues and must survive a
|
|
92
|
+
// stray async failure instead of exiting silently.
|
|
93
|
+
reportUnexpected('unhandled promise rejection ignored', reason);
|
|
55
94
|
});
|
|
56
95
|
|
|
57
96
|
process.on('uncaughtException', (err) => {
|
|
58
|
-
|
|
59
|
-
|
|
97
|
+
// An uncaught exception leaves the state undefined: record it, then exit(1)
|
|
98
|
+
// — the launcher supervises the worker and starts a fresh one.
|
|
99
|
+
reportUnexpected('uncaught exception - exiting', err);
|
|
60
100
|
process.exit(1);
|
|
61
101
|
});
|
|
62
102
|
|
|
63
103
|
for (const stream of [process.stdout, process.stderr]) {
|
|
64
104
|
stream?.on?.('error', (err) => {
|
|
65
105
|
if (err?.code === 'EPIPE') return; // terminal/pipe closed: keep working
|
|
66
|
-
|
|
106
|
+
appendErrorLog(`stdio error: ${err?.code ?? ''} ${err?.message ?? err}`);
|
|
107
|
+
safeWrite(process.stderr, `[jobfinder:worker] stdio error: ${err?.code ?? ''} ${err?.message ?? err}\n`);
|
|
67
108
|
});
|
|
68
109
|
}
|
|
69
110
|
|
|
@@ -86,11 +127,18 @@ function nowIso() {
|
|
|
86
127
|
* Used for every normal-path write.
|
|
87
128
|
*/
|
|
88
129
|
async function patchState(patch) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
130
|
+
try {
|
|
131
|
+
return await store.update(
|
|
132
|
+
STATE_FILE,
|
|
133
|
+
(current) => ({ ...defaultWorkerState(), ...(current ?? {}), ...patch }),
|
|
134
|
+
{}
|
|
135
|
+
);
|
|
136
|
+
} catch (err) {
|
|
137
|
+
// A locked state file (Windows EPERM/EACCES) must never kill the worker:
|
|
138
|
+
// record it and let the next tick/heartbeat try again.
|
|
139
|
+
reportUnexpected('worker-state write failed', err);
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
94
142
|
}
|
|
95
143
|
|
|
96
144
|
/**
|
|
@@ -98,8 +146,13 @@ async function patchState(patch) {
|
|
|
98
146
|
* handlers, where awaiting is not possible.
|
|
99
147
|
*/
|
|
100
148
|
function patchStateSync(patch) {
|
|
101
|
-
|
|
102
|
-
|
|
149
|
+
try {
|
|
150
|
+
const current = store.read(STATE_FILE, {}) ?? {};
|
|
151
|
+
return store.write(STATE_FILE, { ...defaultWorkerState(), ...current, ...patch });
|
|
152
|
+
} catch (err) {
|
|
153
|
+
reportUnexpected('worker-state write failed (sync)', err);
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
103
156
|
}
|
|
104
157
|
|
|
105
158
|
/** Append an action line and persist it. */
|
|
@@ -108,12 +161,33 @@ async function writeLog(level, message, data) {
|
|
|
108
161
|
await patchState({ logs: appendLog(readWorkerState(store).logs, entry) });
|
|
109
162
|
}
|
|
110
163
|
|
|
111
|
-
/**
|
|
164
|
+
/**
|
|
165
|
+
* Is another live worker already holding the state file?
|
|
166
|
+
*
|
|
167
|
+
* A fresh heartbeat from a DEAD pid is not ownership: on Windows a hard
|
|
168
|
+
* kill (TerminateProcess, exit 0xFFFFFFFF) skips the worker's exit handler,
|
|
169
|
+
* so the heartbeat stays fresh for a few seconds after the process is gone.
|
|
170
|
+
* Without the pid check, a crash-restart would be rejected as a duplicate.
|
|
171
|
+
*
|
|
172
|
+
* JOBFINDER_TAKEOVER=1 is set by a SUPERVISOR that is spawning us after
|
|
173
|
+
* having observed the previous lifecycle end (the launcher's restart path,
|
|
174
|
+
* or its own boot): the supervisor owns the lifecycle — when it dies, its
|
|
175
|
+
* workers die with it (stdin EOF) — so a stale heartbeat must never block
|
|
176
|
+
* its spawn. This is what makes an automatic restart deterministic even
|
|
177
|
+
* when Windows recycled the dead worker's pid.
|
|
178
|
+
*/
|
|
112
179
|
function anotherWorkerOwnsState() {
|
|
180
|
+
if (process.env.JOBFINDER_TAKEOVER === '1') return false;
|
|
113
181
|
const state = readWorkerState(store);
|
|
114
182
|
if (!state.pid || state.pid === process.pid || !state.heartbeatAt) return false;
|
|
115
183
|
const age = Date.now() - new Date(state.heartbeatAt).getTime();
|
|
116
|
-
|
|
184
|
+
if (!(age >= 0 && age < 12_000)) return false;
|
|
185
|
+
try {
|
|
186
|
+
process.kill(state.pid, 0);
|
|
187
|
+
return true; // heartbeat fresh AND the pid is alive: someone owns it
|
|
188
|
+
} catch (err) {
|
|
189
|
+
return err?.code !== 'ESRCH'; // dead pid -> not an owner
|
|
190
|
+
}
|
|
117
191
|
}
|
|
118
192
|
|
|
119
193
|
function beatHeartbeat() {
|
|
@@ -292,7 +366,8 @@ function stop(reason) {
|
|
|
292
366
|
} catch {
|
|
293
367
|
/* state is best-effort during shutdown */
|
|
294
368
|
}
|
|
295
|
-
|
|
369
|
+
appendErrorLog(`stopped (${reason})`);
|
|
370
|
+
safeWrite(process.stderr, `[jobfinder:worker] stopped (${reason}).\n`);
|
|
296
371
|
process.exit(0);
|
|
297
372
|
}
|
|
298
373
|
|
|
@@ -305,18 +380,27 @@ function schedule() {
|
|
|
305
380
|
if (stopping) return;
|
|
306
381
|
beatHeartbeat();
|
|
307
382
|
timer = setTimeout(async () => {
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
383
|
+
// A synchronous failure in this callback must never escape as an
|
|
384
|
+
// uncaughtException: report it and reschedule instead of dying.
|
|
385
|
+
try {
|
|
386
|
+
if (parentIsGone()) {
|
|
387
|
+
stop('parent launcher exited');
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
await tick().catch((err) => reportUnexpected('tick failed', err));
|
|
391
|
+
schedule();
|
|
392
|
+
} catch (err) {
|
|
393
|
+
reportUnexpected('loop failed', err);
|
|
394
|
+
if (!stopping) schedule();
|
|
311
395
|
}
|
|
312
|
-
await tick().catch((err) => {
|
|
313
|
-
logger?.error('worker', 'tick failed', { message: err?.message });
|
|
314
|
-
});
|
|
315
|
-
schedule();
|
|
316
396
|
}, INTERVAL_MS);
|
|
317
397
|
heartbeatTimer = setInterval(() => {
|
|
318
|
-
|
|
319
|
-
|
|
398
|
+
try {
|
|
399
|
+
beatHeartbeat();
|
|
400
|
+
if (parentIsGone()) stop('parent launcher exited');
|
|
401
|
+
} catch (err) {
|
|
402
|
+
reportUnexpected('heartbeat failed', err);
|
|
403
|
+
}
|
|
320
404
|
}, HEARTBEAT_MS);
|
|
321
405
|
}
|
|
322
406
|
|
|
@@ -326,6 +410,28 @@ async function main() {
|
|
|
326
410
|
console.error(`[jobfinder:worker] data directory not found: ${dataDir}`);
|
|
327
411
|
process.exit(1);
|
|
328
412
|
}
|
|
413
|
+
// Crash/forensic log: the only artifact that survives a dead pipe.
|
|
414
|
+
errorLogPath = path.join(dataDir, 'worker-error.log');
|
|
415
|
+
|
|
416
|
+
// Orphan detection by PIPE (primary). The supervisor keeps our stdin pipe
|
|
417
|
+
// open for as long as it lives; when it dies (any reason, hard kill
|
|
418
|
+
// included) the pipe closes and stdin reaches EOF — immediately and
|
|
419
|
+
// without depending on pids, which Windows recycles. `parentIsGone()`
|
|
420
|
+
// stays as the heartbeat backstop.
|
|
421
|
+
//
|
|
422
|
+
// Armed ONLY when the supervisor said so (JOBFINDER_SUPERVISED_STDIN):
|
|
423
|
+
// a manual run's fd 0 may be the NUL device, which EOFs instantly.
|
|
424
|
+
if (process.env.JOBFINDER_SUPERVISED_STDIN === '1') {
|
|
425
|
+
try {
|
|
426
|
+
process.stdin?.resume?.();
|
|
427
|
+
process.stdin?.on?.('end', () => stop('parent launcher closed the pipe (EOF)'));
|
|
428
|
+
process.stdin?.on?.('error', (err) => {
|
|
429
|
+
if (err?.code !== 'EPIPE') appendErrorLog(`stdin error: ${err?.code ?? ''} ${err?.message ?? err}`);
|
|
430
|
+
});
|
|
431
|
+
} catch {
|
|
432
|
+
/* no pipe to watch: the heartbeat backstop still applies */
|
|
433
|
+
}
|
|
434
|
+
}
|
|
329
435
|
|
|
330
436
|
context = createContext(dataDir);
|
|
331
437
|
store = context.store;
|
|
@@ -31,6 +31,12 @@ export const CREATE_NEW_PROCESS_GROUP = 0x00000200;
|
|
|
31
31
|
* independent from the terminal: the supervisor forwards the output and its
|
|
32
32
|
* own EPIPE handlers absorb a dead pipe.
|
|
33
33
|
*
|
|
34
|
+
* stdin is a pipe that the supervisor NEVER writes: when the supervisor
|
|
35
|
+
* dies, its end closes and the child sees EOF on stdin — a deterministic
|
|
36
|
+
* "parent is gone" signal that does not depend on pid recycling (which
|
|
37
|
+
* breaks the classic `process.kill(ppid, 0)` check on Windows). The worker
|
|
38
|
+
* uses it to self-terminate; the server ignores it.
|
|
39
|
+
*
|
|
34
40
|
* @param {string} entry absolute path of the child entrypoint
|
|
35
41
|
* @param {{ env?: object, cwd?: string }} [options]
|
|
36
42
|
* @returns {import('node:child_process').ChildProcess}
|
|
@@ -38,8 +44,15 @@ export const CREATE_NEW_PROCESS_GROUP = 0x00000200;
|
|
|
38
44
|
export function spawnSupervised(entry, options = {}) {
|
|
39
45
|
return spawn(process.execPath, [entry], {
|
|
40
46
|
cwd: options.cwd ?? path.resolve(__dirname, '..', '..'),
|
|
41
|
-
env: {
|
|
42
|
-
|
|
47
|
+
env: {
|
|
48
|
+
...process.env,
|
|
49
|
+
// Tells a supervised worker that fd 0 is a REAL pipe to this supervisor
|
|
50
|
+
// (never the NUL device of a manual run): EOF on stdin then means
|
|
51
|
+
// "the supervisor died". A manual run must not arm the detector.
|
|
52
|
+
JOBFINDER_SUPERVISED_STDIN: '1',
|
|
53
|
+
...(options.env ?? {}),
|
|
54
|
+
},
|
|
55
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
43
56
|
windowsHide: true,
|
|
44
57
|
creationFlags: process.platform === 'win32' ? CREATE_NEW_PROCESS_GROUP : 0,
|
|
45
58
|
});
|