@danhachuel/jobfinder 0.1.6 → 0.1.8

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.
@@ -0,0 +1,382 @@
1
+ /**
2
+ * JobFinder — background worker (separate process).
3
+ *
4
+ * Spawned by the launcher (scripts/cli.mjs) or on demand by the API
5
+ * (POST /api/worker/start). It keeps processing the automation queues even
6
+ * when the browser tab is closed or the UI is not open at all:
7
+ *
8
+ * scheduled posts (posts.json) -> publishPost()
9
+ * DM cascades (dm-cascades.json) -> cascadeTick()
10
+ *
11
+ * Coordination with the API happens through two JSON files in the data
12
+ * directory (see storage/workerState.mjs), always written through the
13
+ * JsonStore (atomic tmp + rename — atomic-write-guard):
14
+ *
15
+ * worker-state.json heartbeat, status, active task, next tick, actions
16
+ * worker-control.json desired state ('running' | 'paused') from the UI
17
+ *
18
+ * Environment:
19
+ * JOBFINDER_DATA_DIR data directory (default ~/.jobfinder)
20
+ * JOBFINDER_WORKER_INTERVAL tick interval in ms (default 30000)
21
+ *
22
+ * Rules honoured here (see .agents/skills/): only atomic JSON writes through
23
+ * the store, dry-run re-checked on every pass against the live config, spawn
24
+ * flags and stdio handled by the launcher, and no unhandled error can kill
25
+ * this process silently (windows-runtime-guard).
26
+ */
27
+ import fs from 'node:fs';
28
+ import process from 'node:process';
29
+
30
+ import { createContext } from './context.mjs';
31
+ import { resolveDataDir } from './paths.mjs';
32
+ import { runWorkerPass } from './services/workers.mjs';
33
+ import { syncLiveConfig } from './storage/configSync.mjs';
34
+ import {
35
+ appendLog,
36
+ defaultWorkerState,
37
+ readWorkerControl,
38
+ readWorkerState,
39
+ } from './storage/workerState.mjs';
40
+
41
+ const STATE_FILE = 'worker-state.json';
42
+
43
+ const INTERVAL_MS = Math.max(2_000, Number(process.env.JOBFINDER_WORKER_INTERVAL) || 30_000);
44
+ const HEARTBEAT_MS = Math.min(5_000, INTERVAL_MS);
45
+
46
+ /* ------------------------------------------------------------------ *
47
+ * Process resilience (windows-runtime-guard): never die silently *
48
+ * ------------------------------------------------------------------ */
49
+ let logger = null;
50
+
51
+ process.on('unhandledRejection', (reason) => {
52
+ const message = reason instanceof Error ? reason.message : String(reason);
53
+ logger?.error('worker', 'unhandled promise rejection ignored', { message });
54
+ console.error(`[jobfinder:worker] unhandled promise rejection ignored: ${message}`);
55
+ });
56
+
57
+ process.on('uncaughtException', (err) => {
58
+ logger?.error('worker', 'uncaught exception - shutting down', { message: err?.message });
59
+ console.error('[jobfinder:worker] uncaught exception:', err);
60
+ process.exit(1);
61
+ });
62
+
63
+ for (const stream of [process.stdout, process.stderr]) {
64
+ stream?.on?.('error', (err) => {
65
+ if (err?.code === 'EPIPE') return; // terminal/pipe closed: keep working
66
+ console.error(`[jobfinder:worker] stdio error: ${err?.code ?? ''} ${err?.message ?? err}`);
67
+ });
68
+ }
69
+
70
+ /* ------------------------------------------------------------------ *
71
+ * Worker *
72
+ * ------------------------------------------------------------------ */
73
+ let store = null;
74
+ let context = null;
75
+ let stopping = false;
76
+ let timer = null;
77
+ let heartbeatTimer = null;
78
+ let pass = 0;
79
+
80
+ function nowIso() {
81
+ return new Date().toISOString();
82
+ }
83
+
84
+ /**
85
+ * Patch worker-state.json. Serialized + atomic (store.update).
86
+ * Used for every normal-path write.
87
+ */
88
+ async function patchState(patch) {
89
+ return store.update(
90
+ STATE_FILE,
91
+ (current) => ({ ...defaultWorkerState(), ...(current ?? {}), ...patch }),
92
+ {}
93
+ );
94
+ }
95
+
96
+ /**
97
+ * Synchronous variant (store.write, still tmp + rename) for signal/exit
98
+ * handlers, where awaiting is not possible.
99
+ */
100
+ function patchStateSync(patch) {
101
+ const current = store.read(STATE_FILE, {}) ?? {};
102
+ return store.write(STATE_FILE, { ...defaultWorkerState(), ...current, ...patch });
103
+ }
104
+
105
+ /** Append an action line and persist it. */
106
+ async function writeLog(level, message, data) {
107
+ const entry = { level, message, ...(data && Object.keys(data).length ? { ...data } : {}) };
108
+ await patchState({ logs: appendLog(readWorkerState(store).logs, entry) });
109
+ }
110
+
111
+ /** Is another live worker already holding the state file? */
112
+ function anotherWorkerOwnsState() {
113
+ const state = readWorkerState(store);
114
+ if (!state.pid || state.pid === process.pid || !state.heartbeatAt) return false;
115
+ const age = Date.now() - new Date(state.heartbeatAt).getTime();
116
+ return age >= 0 && age < 12_000;
117
+ }
118
+
119
+ function beatHeartbeat() {
120
+ try {
121
+ patchStateSync({ heartbeatAt: nowIso(), pid: process.pid });
122
+ } catch {
123
+ /* heartbeat is best-effort */
124
+ }
125
+ }
126
+
127
+ /**
128
+ * True when the parent launcher disappeared (orphan guard on Windows).
129
+ *
130
+ * Only ESRCH (the pid does not exist) means the parent is gone. ANY other
131
+ * error — EPERM, EINVAL, anything the host decides to return — means
132
+ * "unknown", and an unknown parent must be treated as ALIVE: on Windows the
133
+ * liveness probe is not a POSIX kill (MobaXterm/npx wrap the real parent),
134
+ * and the previous "any error = gone" rule made the worker suicide for no
135
+ * reason whenever the host answered with an unexpected code.
136
+ */
137
+ function parentIsGone() {
138
+ const ppid = process.ppid;
139
+ if (!ppid || ppid <= 1) return false;
140
+ try {
141
+ process.kill(ppid, 0);
142
+ return false;
143
+ } catch (err) {
144
+ return err?.code === 'ESRCH';
145
+ }
146
+ }
147
+
148
+ /** Human description of what this pass is about (UI "activeTask"). */
149
+ function describeQueue(now) {
150
+ const parts = [];
151
+ const duePosts = store
152
+ .list('posts.json')
153
+ .filter((post) => post.status === 'scheduled' && new Date(post.scheduledAt ?? 0).getTime() <= now.getTime());
154
+ const activeCascades = store.list('dm-cascades.json').filter((c) => c.status === 'active');
155
+ if (duePosts.length) parts.push(`publicando ${duePosts.length} post(s) agendado(s)`);
156
+ if (activeCascades.length) parts.push(`processando ${activeCascades.length} cascata(s) de DM`);
157
+ return parts.length ? parts.join(' · ') : null;
158
+ }
159
+
160
+ /** stats increment without losing the sibling counters. */
161
+ async function bumpStat(key) {
162
+ const current = (await readWorkerStateAsync()).stats ?? {};
163
+ await patchState({ stats: { ...current, [key]: Number(current[key] ?? 0) + 1 } });
164
+ }
165
+
166
+ /** Fresh (cross-process safe) state read. */
167
+ async function readWorkerStateAsync() {
168
+ return readWorkerState(store);
169
+ }
170
+
171
+ /** One automation pass over the queues. */
172
+ async function tick() {
173
+ const control = readWorkerControl(store);
174
+ const startedAt = new Date();
175
+
176
+ if (control.desired === 'paused') {
177
+ await patchState({
178
+ status: 'paused',
179
+ activeTask: null,
180
+ heartbeatAt: nowIso(),
181
+ nextTickAt: new Date(Date.now() + INTERVAL_MS).toISOString(),
182
+ });
183
+ return;
184
+ }
185
+
186
+ pass += 1;
187
+ const activeTask = describeQueue(startedAt);
188
+ await patchState({
189
+ status: 'running',
190
+ heartbeatAt: nowIso(),
191
+ activeTask,
192
+ lastTickAt: nowIso(),
193
+ nextTickAt: new Date(startedAt.getTime() + INTERVAL_MS).toISOString(),
194
+ });
195
+
196
+ // Always re-read the live config: the user may toggle dry-run in the UI
197
+ // while the worker runs (configSync keeps ctx.config current).
198
+ syncLiveConfig(store, context.config);
199
+ const dryRun = context.config.dryRun !== false;
200
+
201
+ try {
202
+ const { posts, cascades, replies } = await runWorkerPass(context, { pass, now: startedAt });
203
+
204
+ // ---- scheduled posts ---------------------------------------------
205
+ for (const result of posts ?? []) {
206
+ if (result.error) {
207
+ await bumpStat('failed');
208
+ await writeLog('error', `falha ao publicar post: ${result.error}`, { postId: result.id ?? null });
209
+ continue;
210
+ }
211
+ const record = store.find('posts.json', result.id);
212
+ const simulated = Boolean(record?.simulated) || dryRun;
213
+ await bumpStat('postsPublished');
214
+ await writeLog(
215
+ simulated ? 'info' : 'success',
216
+ `${simulated ? '[dry-run] ' : ''}post publicado (${result.status})`,
217
+ { postId: result.id ?? null, simulated }
218
+ );
219
+ }
220
+
221
+ // ---- DM cascades -------------------------------------------------
222
+ for (const result of cascades?.results ?? []) {
223
+ if (result.status === 'sent') {
224
+ const cascade = store.find('dm-cascades.json', result.id);
225
+ await bumpStat('dmsSent');
226
+ await writeLog(
227
+ result.simulated ? 'info' : 'success',
228
+ `${result.simulated ? '[dry-run] ' : ''}DM enviada para ${cascade?.contactName ?? result.id}`,
229
+ { cascadeId: result.id ?? null, simulated: Boolean(result.simulated) }
230
+ );
231
+ } else if (result.status === 'skipped') {
232
+ await bumpStat('skipped');
233
+ await writeLog('warn', `DM nao enviada (${result.reason})`, { cascadeId: result.id ?? null });
234
+ } else if (result.status === 'failed') {
235
+ await bumpStat('failed');
236
+ await writeLog('error', `falha ao enviar DM: ${result.error ?? 'erro desconhecido'}`, { cascadeId: result.id ?? null });
237
+ }
238
+ }
239
+
240
+ // ---- inbox monitoring --------------------------------------------
241
+ for (const paused of replies?.paused ?? []) {
242
+ await bumpStat('cascadesPaused');
243
+ await writeLog('info', `cascata pausada (contato respondeu): ${paused.contactName}`, { cascadeId: paused.id });
244
+ }
245
+ if (replies?.error) {
246
+ await writeLog('warn', `checagem de respostas falhou: ${replies.error}`);
247
+ }
248
+
249
+ await bumpStat('ticks');
250
+ await patchState({
251
+ status: control.desired === 'paused' ? 'paused' : 'running',
252
+ activeTask: null,
253
+ lastError: null,
254
+ nextTickAt: new Date(Date.now() + INTERVAL_MS).toISOString(),
255
+ });
256
+ logger?.info('worker', `pass #${pass} done (dryRun=${dryRun})`, {
257
+ pass,
258
+ dryRun,
259
+ posts: (posts ?? []).length,
260
+ sent: cascades?.sent ?? 0,
261
+ skipped: cascades?.skipped ?? 0,
262
+ });
263
+ } catch (err) {
264
+ const message = err?.message ?? 'unknown error';
265
+ await bumpStat('failed');
266
+ await patchState({ status: 'running', activeTask: null, lastError: message, nextTickAt: new Date(Date.now() + INTERVAL_MS).toISOString() });
267
+ await writeLog('error', `pass #${pass} falhou: ${message}`, { pass });
268
+ logger?.error('worker', 'pass failed', { pass, message });
269
+ }
270
+ }
271
+
272
+ function clearTimers() {
273
+ if (timer) clearTimeout(timer);
274
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
275
+ timer = null;
276
+ heartbeatTimer = null;
277
+ }
278
+
279
+ function stop(reason) {
280
+ if (stopping) return;
281
+ stopping = true;
282
+ clearTimers();
283
+ try {
284
+ patchStateSync({
285
+ status: 'stopped',
286
+ pid: null,
287
+ activeTask: null,
288
+ stoppedAt: nowIso(),
289
+ heartbeatAt: null,
290
+ nextTickAt: null,
291
+ });
292
+ } catch {
293
+ /* state is best-effort during shutdown */
294
+ }
295
+ console.error(`[jobfinder:worker] stopped (${reason}).`);
296
+ process.exit(0);
297
+ }
298
+
299
+ /**
300
+ * The tick/heartbeat timers are the KEEP-ALIVE of this process (unlike the
301
+ * internal cron inside the server, they must NOT be unref'd: an unref'd
302
+ * timer lets Node exit immediately with code 0).
303
+ */
304
+ function schedule() {
305
+ if (stopping) return;
306
+ beatHeartbeat();
307
+ timer = setTimeout(async () => {
308
+ if (parentIsGone()) {
309
+ stop('parent launcher exited');
310
+ return;
311
+ }
312
+ await tick().catch((err) => {
313
+ logger?.error('worker', 'tick failed', { message: err?.message });
314
+ });
315
+ schedule();
316
+ }, INTERVAL_MS);
317
+ heartbeatTimer = setInterval(() => {
318
+ beatHeartbeat();
319
+ if (parentIsGone()) stop('parent launcher exited');
320
+ }, HEARTBEAT_MS);
321
+ }
322
+
323
+ async function main() {
324
+ const dataDir = resolveDataDir();
325
+ if (!fs.existsSync(dataDir)) {
326
+ console.error(`[jobfinder:worker] data directory not found: ${dataDir}`);
327
+ process.exit(1);
328
+ }
329
+
330
+ context = createContext(dataDir);
331
+ store = context.store;
332
+ logger = context.logger;
333
+
334
+ if (anotherWorkerOwnsState()) {
335
+ console.error('[jobfinder:worker] another worker is already running - exiting.');
336
+ process.exit(0);
337
+ }
338
+
339
+ patchStateSync({
340
+ pid: process.pid,
341
+ status: 'running',
342
+ startedAt: nowIso(),
343
+ stoppedAt: null,
344
+ heartbeatAt: nowIso(),
345
+ lastTickAt: null,
346
+ nextTickAt: new Date(Date.now() + INTERVAL_MS).toISOString(),
347
+ intervalMs: INTERVAL_MS,
348
+ activeTask: null,
349
+ lastError: null,
350
+ stats: { ticks: 0, postsPublished: 0, dmsSent: 0, cascadesPaused: 0, skipped: 0, failed: 0 },
351
+ logs: [],
352
+ });
353
+ logger?.info('worker', 'worker started', { pid: process.pid, intervalMs: INTERVAL_MS, dataDir });
354
+ console.log(
355
+ `[jobfinder:worker] running (pid ${process.pid}, every ${Math.round(INTERVAL_MS / 1000)}s) - data: ${dataDir}`
356
+ );
357
+
358
+ // Idempotent signals: only the first one triggers the graceful stop.
359
+ const onSignal = (signal) => () => stop(`received ${signal}`);
360
+ process.on('SIGINT', onSignal('SIGINT'));
361
+ process.on('SIGTERM', onSignal('SIGTERM'));
362
+ process.on('SIGBREAK', onSignal('SIGBREAK'));
363
+
364
+ // Close the state file even on a forced exit path. The heartbeat is
365
+ // cleared so a dead worker is never reported as alive.
366
+ process.on('exit', () => {
367
+ try {
368
+ patchStateSync({ status: 'stopped', pid: null, heartbeatAt: null, nextTickAt: null, activeTask: null });
369
+ } catch {
370
+ /* best effort */
371
+ }
372
+ });
373
+
374
+ schedule();
375
+ // First pass shortly after boot so a fresh start does not wait a full
376
+ // interval to process the queue.
377
+ setTimeout(() => {
378
+ tick().catch(() => {});
379
+ }, 1_500);
380
+ }
381
+
382
+ await main();
@@ -0,0 +1,89 @@
1
+ /**
2
+ * JobFinder — worker process runtime (spawn / ownership).
3
+ *
4
+ * Shared by the launcher (scripts/cli.mjs) and the API (so the UI can start
5
+ * the worker on demand). Both sides must agree on ONE running worker: the
6
+ * state file heartbeat is the ownership token — a new process that finds a
7
+ * fresh heartbeat from a different pid exits immediately instead of
8
+ * creating a duplicate.
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.
13
+ */
14
+ import { spawn } from 'node:child_process';
15
+ import path from 'node:path';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
+
20
+ /** Absolute path of the worker entrypoint. */
21
+ export const WORKER_ENTRY = path.join(__dirname, 'worker.mjs');
22
+
23
+ export const CREATE_NEW_PROCESS_GROUP = 0x00000200;
24
+
25
+ /**
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
35
+ * @param {{ env?: object, cwd?: string }} [options]
36
+ * @returns {import('node:child_process').ChildProcess}
37
+ */
38
+ export function spawnSupervised(entry, options = {}) {
39
+ return spawn(process.execPath, [entry], {
40
+ cwd: options.cwd ?? path.resolve(__dirname, '..', '..'),
41
+ env: { ...process.env, ...(options.env ?? {}) },
42
+ stdio: ['ignore', 'pipe', 'pipe'],
43
+ windowsHide: true,
44
+ creationFlags: process.platform === 'win32' ? CREATE_NEW_PROCESS_GROUP : 0,
45
+ });
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
+ }