@danhachuel/jobfinder 0.1.11 → 0.1.13

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.
@@ -78,6 +78,22 @@ function appendErrorLog(line) {
78
78
  }
79
79
  }
80
80
 
81
+ /**
82
+ * Append one line to <dataDir>/worker.log — the worker's lifecycle log
83
+ * (boot, passes, stops). The worker runs with stdio all-'ignore': the FILE
84
+ * is the log, the console (a NUL device or a dying MobaXterm pipe) is not
85
+ * a channel anything may depend on.
86
+ */
87
+ let logFilePath = null;
88
+ function appendLogFile(line) {
89
+ if (!logFilePath) return;
90
+ try {
91
+ fs.appendFileSync(logFilePath, `${new Date().toISOString()} ${line}\n`, 'utf8');
92
+ } catch {
93
+ /* read-only data dir: worker-error.log may still have the failures */
94
+ }
95
+ }
96
+
81
97
  /** Report an unexpected failure: file log + logger + safe console mirror. */
82
98
  function reportUnexpected(scope, reason) {
83
99
  const message = reason instanceof Error ? reason.message : String(reason);
@@ -127,11 +143,18 @@ function nowIso() {
127
143
  * Used for every normal-path write.
128
144
  */
129
145
  async function patchState(patch) {
130
- return store.update(
131
- STATE_FILE,
132
- (current) => ({ ...defaultWorkerState(), ...(current ?? {}), ...patch }),
133
- {}
134
- );
146
+ try {
147
+ return await store.update(
148
+ STATE_FILE,
149
+ (current) => ({ ...defaultWorkerState(), ...(current ?? {}), ...patch }),
150
+ {}
151
+ );
152
+ } catch (err) {
153
+ // A locked state file (Windows EPERM/EACCES) must never kill the worker:
154
+ // record it and let the next tick/heartbeat try again.
155
+ reportUnexpected('worker-state write failed', err);
156
+ return null;
157
+ }
135
158
  }
136
159
 
137
160
  /**
@@ -139,8 +162,13 @@ async function patchState(patch) {
139
162
  * handlers, where awaiting is not possible.
140
163
  */
141
164
  function patchStateSync(patch) {
142
- const current = store.read(STATE_FILE, {}) ?? {};
143
- return store.write(STATE_FILE, { ...defaultWorkerState(), ...current, ...patch });
165
+ try {
166
+ const current = store.read(STATE_FILE, {}) ?? {};
167
+ return store.write(STATE_FILE, { ...defaultWorkerState(), ...current, ...patch });
168
+ } catch (err) {
169
+ reportUnexpected('worker-state write failed (sync)', err);
170
+ return null;
171
+ }
144
172
  }
145
173
 
146
174
  /** Append an action line and persist it. */
@@ -156,8 +184,16 @@ async function writeLog(level, message, data) {
156
184
  * kill (TerminateProcess, exit 0xFFFFFFFF) skips the worker's exit handler,
157
185
  * so the heartbeat stays fresh for a few seconds after the process is gone.
158
186
  * Without the pid check, a crash-restart would be rejected as a duplicate.
187
+ *
188
+ * JOBFINDER_TAKEOVER=1 is set by a SUPERVISOR that is spawning us after
189
+ * having observed the previous lifecycle end (the launcher's restart path,
190
+ * or its own boot): the supervisor owns the lifecycle — when it dies, its
191
+ * workers die with it (stdin EOF) — so a stale heartbeat must never block
192
+ * its spawn. This is what makes an automatic restart deterministic even
193
+ * when Windows recycled the dead worker's pid.
159
194
  */
160
195
  function anotherWorkerOwnsState() {
196
+ if (process.env.JOBFINDER_TAKEOVER === '1') return false;
161
197
  const state = readWorkerState(store);
162
198
  if (!state.pid || state.pid === process.pid || !state.heartbeatAt) return false;
163
199
  const age = Date.now() - new Date(state.heartbeatAt).getTime();
@@ -346,7 +382,7 @@ function stop(reason) {
346
382
  } catch {
347
383
  /* state is best-effort during shutdown */
348
384
  }
349
- appendErrorLog(`stopped (${reason})`);
385
+ appendLogFile(`stopped (${reason})`);
350
386
  safeWrite(process.stderr, `[jobfinder:worker] stopped (${reason}).\n`);
351
387
  process.exit(0);
352
388
  }
@@ -386,19 +422,43 @@ function schedule() {
386
422
 
387
423
  async function main() {
388
424
  const dataDir = resolveDataDir();
425
+ // Log paths first: even the boot checks below must leave a file trace.
426
+ errorLogPath = path.join(dataDir, 'worker-error.log');
427
+ // Lifecycle log (boot/passes/stops): stdio is 'ignore', the file IS the log.
428
+ logFilePath = path.join(dataDir, 'worker.log');
389
429
  if (!fs.existsSync(dataDir)) {
390
- console.error(`[jobfinder:worker] data directory not found: ${dataDir}`);
430
+ appendErrorLog(`data directory not found: ${dataDir}`);
431
+ safeWrite(process.stderr, `[jobfinder:worker] data directory not found: ${dataDir}\n`);
391
432
  process.exit(1);
392
433
  }
393
- // Crash/forensic log: the only artifact that survives a dead pipe.
394
- errorLogPath = path.join(dataDir, 'worker-error.log');
434
+
435
+ // Orphan detection by PIPE (primary). The supervisor keeps our stdin pipe
436
+ // open for as long as it lives; when it dies (any reason, hard kill
437
+ // included) the pipe closes and stdin reaches EOF — immediately and
438
+ // without depending on pids, which Windows recycles. `parentIsGone()`
439
+ // stays as the heartbeat backstop.
440
+ //
441
+ // Armed ONLY when the supervisor said so (JOBFINDER_SUPERVISED_STDIN):
442
+ // a manual run's fd 0 may be the NUL device, which EOFs instantly.
443
+ if (process.env.JOBFINDER_SUPERVISED_STDIN === '1') {
444
+ try {
445
+ process.stdin?.resume?.();
446
+ process.stdin?.on?.('end', () => stop('parent launcher closed the pipe (EOF)'));
447
+ process.stdin?.on?.('error', (err) => {
448
+ if (err?.code !== 'EPIPE') appendErrorLog(`stdin error: ${err?.code ?? ''} ${err?.message ?? err}`);
449
+ });
450
+ } catch {
451
+ /* no pipe to watch: the heartbeat backstop still applies */
452
+ }
453
+ }
395
454
 
396
455
  context = createContext(dataDir);
397
456
  store = context.store;
398
457
  logger = context.logger;
399
458
 
400
459
  if (anotherWorkerOwnsState()) {
401
- console.error('[jobfinder:worker] another worker is already running - exiting.');
460
+ appendLogFile('another worker is already running - exiting.');
461
+ safeWrite(process.stderr, '[jobfinder:worker] another worker is already running - exiting.\n');
402
462
  process.exit(0);
403
463
  }
404
464
 
@@ -417,9 +477,8 @@ async function main() {
417
477
  logs: [],
418
478
  });
419
479
  logger?.info('worker', 'worker started', { pid: process.pid, intervalMs: INTERVAL_MS, dataDir });
420
- console.log(
421
- `[jobfinder:worker] running (pid ${process.pid}, every ${Math.round(INTERVAL_MS / 1000)}s) - data: ${dataDir}`
422
- );
480
+ appendLogFile(`running (pid ${process.pid}, every ${Math.round(INTERVAL_MS / 1000)}s) - data: ${dataDir}`);
481
+ safeWrite(process.stdout, `[jobfinder:worker] running (pid ${process.pid}, every ${Math.round(INTERVAL_MS / 1000)}s)\n`);
423
482
 
424
483
  // Idempotent signals: only the first one triggers the graceful stop.
425
484
  const onSignal = (signal) => () => stop(`received ${signal}`);
@@ -7,9 +7,15 @@
7
7
  * fresh heartbeat from a different pid exits immediately instead of
8
8
  * creating a duplicate.
9
9
  *
10
- * Spawn flags follow windows-runtime-guard: never `stdio: 'inherit'`
11
- * (a broken terminal would kill the child with EPIPE), `windowsHide: true`
12
- * and CREATE_NEW_PROCESS_GROUP (0x00000200) on Windows.
10
+ * Spawn flags follow runtime-guard: `windowsHide: true` and
11
+ * CREATE_NEW_PROCESS_GROUP (0x00000200) on Windows.
12
+ *
13
+ * stdio is ALL 'ignore' on purpose: the worker never writes to the
14
+ * launcher's pipes. A hostile terminal (MobaXterm, npx wrappers, output
15
+ * redirection) that chokes on — or closes — those pipes can no longer
16
+ * disturb either process. The worker records everything in files inside
17
+ * the data dir (worker.log, worker-error.log, logs/*.jsonl); its stdin
18
+ * stays a pipe only to carry the "supervisor died" EOF signal.
13
19
  */
14
20
  import { spawn } from 'node:child_process';
15
21
  import path from 'node:path';
@@ -23,67 +29,25 @@ export const WORKER_ENTRY = path.join(__dirname, 'worker.mjs');
23
29
  export const CREATE_NEW_PROCESS_GROUP = 0x00000200;
24
30
 
25
31
  /**
26
- * Spawn a long-lived child that the caller supervises (server or worker).
27
- *
28
- * windows-runtime-guard: NEVER `stdio: 'inherit'` — a child that writes
29
- * straight to the terminal dies with EPIPE when the terminal/pipe breaks
30
- * (MobaXterm, redirection, closed SSH session). Piped stdio keeps the child
31
- * independent from the terminal: the supervisor forwards the output and its
32
- * own EPIPE handlers absorb a dead pipe.
33
- *
34
- * @param {string} entry absolute path of the child entrypoint
32
+ * Spawn the worker as a detached-enough child of the caller.
35
33
  * @param {{ env?: object, cwd?: string }} [options]
36
34
  * @returns {import('node:child_process').ChildProcess}
37
35
  */
38
- export function spawnSupervised(entry, options = {}) {
39
- return spawn(process.execPath, [entry], {
36
+ export function spawnWorker(options = {}) {
37
+ return spawn(process.execPath, [WORKER_ENTRY], {
40
38
  cwd: options.cwd ?? path.resolve(__dirname, '..', '..'),
41
- env: { ...process.env, ...(options.env ?? {}) },
42
- stdio: ['ignore', 'pipe', 'pipe'],
39
+ env: {
40
+ ...process.env,
41
+ // Tells the worker that fd 0 is a REAL pipe to this supervisor (never
42
+ // the NUL device of a manual run): EOF on stdin then means "the
43
+ // supervisor died". A manual run must not arm the detector.
44
+ JOBFINDER_SUPERVISED_STDIN: '1',
45
+ ...(options.env ?? {}),
46
+ },
47
+ // stdin stays a pipe (the EOF orphan signal); stdout/stderr are ignored
48
+ // so a broken terminal can never choke the worker — it logs to files.
49
+ stdio: ['pipe', 'ignore', 'ignore'],
43
50
  windowsHide: true,
44
51
  creationFlags: process.platform === 'win32' ? CREATE_NEW_PROCESS_GROUP : 0,
45
52
  });
46
- }
47
-
48
- /**
49
- * Spawn the worker as a detached-enough child of the caller.
50
- * @param {{ env?: object, cwd?: string }} [options]
51
- * @returns {import('node:child_process').ChildProcess}
52
- */
53
- export function spawnWorker(options = {}) {
54
- return spawnSupervised(WORKER_ENTRY, options);
55
- }
56
-
57
- /** Pipe a child's output to the console with a prefix (never inherit). */
58
- export function forwardChildOutput(child, prefix, { onLine } = {}) {
59
- const label = prefix ? `${prefix} ` : '';
60
- const emit = (stream) => (chunk) => {
61
- const text = String(chunk);
62
- if (onLine) {
63
- for (const line of text.split('\n')) {
64
- if (line.trim()) onLine(line);
65
- }
66
- } else {
67
- process.stdout.write(`${label}${text}`);
68
- }
69
- void stream;
70
- };
71
- child.stdout?.on('data', emit('stdout'));
72
- child.stderr?.on('data', (chunk) => {
73
- const text = String(chunk);
74
- if (onLine) {
75
- for (const line of text.split('\n')) {
76
- if (line.trim()) onLine(line);
77
- }
78
- } else {
79
- process.stderr.write(`${prefix} ${text}`);
80
- }
81
- });
82
- // A dead pipe must never kill the launcher.
83
- child.stdout?.on?.('error', (err) => {
84
- if (err?.code !== 'EPIPE') console.error(`${prefix} stdout error: ${err?.code ?? ''}`);
85
- });
86
- child.stderr?.on?.('error', (err) => {
87
- if (err?.code !== 'EPIPE') console.error(`${prefix} stderr error: ${err?.code ?? ''}`);
88
- });
89
53
  }