@danhachuel/jobfinder 0.1.6 → 0.1.7

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.
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import { HttpError } from '../../middleware/errors.mjs';
14
14
  import { countToday } from '../../middleware/rateLimiter.mjs';
15
- import { requireLiveLinkedInClient } from '../linkedin/index.mjs';
15
+ import { createLinkedInClient, requireLiveLinkedInClient } from '../linkedin/index.mjs';
16
16
 
17
17
  export const MAX_STEPS = 5; // hard limit from the PRD (dmsPorDia)
18
18
 
@@ -41,10 +41,16 @@ export function assertPublishable(post) {
41
41
  */
42
42
  export async function publishPost(ctx, postId) {
43
43
  const { store, logger, config, rateLimiter } = ctx;
44
+ // The API and the background worker are separate processes writing the
45
+ // same posts.json: drop the local cache first so a post created by the UI
46
+ // while the worker publishes is never lost (documented "external writer"
47
+ // case of atomic-write-guard).
48
+ store.invalidate('posts.json');
44
49
  const post = store.find('posts.json', postId);
45
50
  const text = assertPublishable(post);
46
51
 
47
52
  await store.patch('posts.json', postId, { status: 'publishing', error: null, updatedAt: new Date().toISOString() });
53
+ store.invalidate('posts.json');
48
54
 
49
55
  let mode = 'dry-run';
50
56
  try {
@@ -1,36 +1,61 @@
1
1
  /**
2
- * JobFinder — background workers.
2
+ * JobFinder — worker pass (one automation cycle).
3
3
  *
4
- * One internal cron drives every time-based feature (§5.1.2, §5.2.2):
5
- * every minute -> publish due scheduled posts, run the DM cascade engine
6
- * every 10 minutes -> inbox monitoring (pause cascades when a contact replies)
4
+ * The ticks that used to run on an internal interval inside the API process
5
+ * now live in the standalone background worker (src/server/worker.mjs), so
6
+ * scheduled posts and DM cascades keep running when the browser is closed.
7
+ * This module holds the actual work of one pass and is shared by the worker
8
+ * process and by the manual "tick now" route (used by tests).
7
9
  *
8
- * No external scheduler dependency (no node-cron): a plain unref'd interval
9
- * loop is enough for a single-user local app.
10
+ * posts + cascades -> every pass
11
+ * inbox monitoring -> every REPLIES_EVERY passes (pause on reply)
12
+ *
13
+ * No `setInterval` here on purpose: the loop belongs to the worker process
14
+ * (windows-runtime-guard rule 5). Errors never escape: each engine reports
15
+ * its own failures so one bad queue item cannot kill the worker.
10
16
  */
11
17
  import { tick as postsTick } from './posting/scheduler.mjs';
12
18
  import { cascadeTick, checkReplies } from './outreach/cascades.mjs';
13
19
 
14
- const INTERVAL_MS = 60 * 1000; // one minute
15
- const REPLIES_EVERY = 10; // inbox monitoring every 10 minutes
20
+ /** Inbox monitoring runs every N passes. */
21
+ export const REPLIES_EVERY = 10;
16
22
 
17
- export function startWorkers(ctx) {
18
- const { logger } = ctx;
19
- let runs = 0;
20
- const timer = setInterval(() => {
21
- runs += 1;
22
- postsTick(ctx).catch((err) => logger.error('workers', 'posts tick failed', { message: err.message }));
23
- cascadeTick(ctx).catch((err) => logger.error('workers', 'cascade tick failed', { message: err.message }));
24
- if (runs % REPLIES_EVERY === 0) {
25
- checkReplies(ctx).catch((err) => logger.error('workers', 'reply check failed', { message: err.message }));
26
- }
27
- }, INTERVAL_MS);
28
- timer.unref();
29
- logger.info('workers', 'background workers started', { intervalMs: INTERVAL_MS });
30
- return {
31
- stop() {
32
- clearInterval(timer);
33
- logger.info('workers', 'background workers stopped');
34
- },
35
- };
23
+ /**
24
+ * Queue files shared between the API process and the worker process.
25
+ * Each process keeps its own JsonStore cache, so a pass must always read
26
+ * the CURRENT disk state (the API/UI wrote those files in another process).
27
+ * This invalidation is the documented "external writer" case, not a casual
28
+ * cache drop (atomic-write-guard).
29
+ */
30
+ const SHARED_QUEUE_FILES = ['posts.json', 'dm-cascades.json', 'connections.json'];
31
+
32
+ /**
33
+ * Run one worker pass.
34
+ * @param {object} ctx server context (store, logger, config, rateLimiter)
35
+ * @param {{ pass?: number, now?: Date }} [options]
36
+ * @returns {Promise<{ posts: object[], cascades: object, replies?: object }>}
37
+ */
38
+ export async function runWorkerPass(ctx, options = {}) {
39
+ const pass = Number(options.pass) || 1;
40
+ const now = options.now instanceof Date ? options.now : new Date();
41
+
42
+ for (const name of SHARED_QUEUE_FILES) ctx.store.invalidate(name);
43
+
44
+ const posts = await safeTick(ctx, 'posts', () => postsTick(ctx, now));
45
+ const cascades = await safeTick(ctx, 'cascades', () => cascadeTick(ctx, now));
46
+ let replies = null;
47
+ if (pass % REPLIES_EVERY === 0) {
48
+ replies = await safeTick(ctx, 'replies', () => checkReplies(ctx));
49
+ }
50
+ return { posts, cascades, replies };
36
51
  }
52
+
53
+ /** Run one engine, converting a throw into a logged, non-fatal result. */
54
+ async function safeTick(ctx, name, run) {
55
+ try {
56
+ return await run();
57
+ } catch (err) {
58
+ ctx.logger?.error('workers', `${name} tick failed`, { message: err?.message });
59
+ return { error: err?.message ?? 'unknown error' };
60
+ }
61
+ }
@@ -10,6 +10,7 @@ import path from 'node:path';
10
10
 
11
11
  import { resolveDataDir as resolveDataDirPath } from '../paths.mjs';
12
12
  import { defaultAuthPayload } from './authStore.mjs';
13
+ import { defaultWorkerState, defaultWorkerControl } from './workerState.mjs';
13
14
 
14
15
  /** Files created on first run, in creation order. */
15
16
  export const DATA_FILES = [
@@ -23,6 +24,8 @@ export const DATA_FILES = [
23
24
  'jobs.json',
24
25
  'applications.json',
25
26
  'resume.json',
27
+ 'worker-state.json',
28
+ 'worker-control.json',
26
29
  ];
27
30
 
28
31
  /** Default configuration written to config.json on first run. */
@@ -119,6 +122,10 @@ function initialPayload(file) {
119
122
  return SEED_TOPICS.map((t) => ({ ...t, createdAt: new Date().toISOString() }));
120
123
  case 'resume.json':
121
124
  return DEFAULT_RESUME;
125
+ case 'worker-state.json':
126
+ return defaultWorkerState();
127
+ case 'worker-control.json':
128
+ return defaultWorkerControl();
122
129
  default:
123
130
  return [];
124
131
  }
@@ -12,16 +12,23 @@
12
12
  * object, keeping every reference in sync.
13
13
  */
14
14
 
15
- /** Read config.json from the store (cached, always current). */
15
+ /** Read config.json from the store. */
16
16
  export function readLiveConfig(store, fallback = {}) {
17
17
  return store.read('config.json', fallback);
18
18
  }
19
19
 
20
20
  /**
21
21
  * Merge the persisted config into the live context object in place.
22
+ *
23
+ * The cache is invalidated first: in the worker process the API is an
24
+ * external writer (the user toggled dry-run in the UI), so a cached read
25
+ * would keep the worker on a stale dry-run value until a restart. This is
26
+ * the documented "external writer" case of atomic-write-guard.
27
+ *
22
28
  * @returns the fresh config object
23
29
  */
24
30
  export function syncLiveConfig(store, liveConfig) {
31
+ store.invalidate('config.json');
25
32
  const latest = readLiveConfig(store, {});
26
33
  if (liveConfig && typeof liveConfig === 'object') {
27
34
  Object.assign(liveConfig, latest);
@@ -58,10 +58,17 @@ export class JsonStore {
58
58
  }
59
59
  }
60
60
 
61
- /** Atomically write a JSON file (pretty-printed, trailing newline). */
61
+ /**
62
+ * Atomically write a JSON file (pretty-printed, trailing newline).
63
+ *
64
+ * The temp file name carries the pid: the API process and the background
65
+ * worker process share the same data directory, and a fixed
66
+ * `<file>.tmp` would make both rename into each other (EPERM / lost
67
+ * updates on Windows).
68
+ */
62
69
  write(name, data) {
63
70
  const file = this.path(name);
64
- const tmp = `${file}.tmp`;
71
+ const tmp = `${file}.tmp.${process.pid}`;
65
72
  fs.mkdirSync(path.dirname(file), { recursive: true });
66
73
  fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
67
74
  fs.renameSync(tmp, file);
@@ -0,0 +1,110 @@
1
+ /**
2
+ * JobFinder — worker state/control files (cross-process coordination).
3
+ *
4
+ * The background worker (src/server/worker.mjs) is a SEPARATE process from
5
+ * the API. They exchange information through two JSON files in the data
6
+ * directory, always written through the JsonStore (atomic tmp + rename):
7
+ *
8
+ * worker-state.json written by the WORKER: heartbeat, status, active
9
+ * task, next tick, recent actions, counters.
10
+ * worker-control.json written by the API: the desired state
11
+ * ('running' | 'paused') requested from the UI.
12
+ *
13
+ * Each process keeps its own JsonStore cache, so both sides invalidate the
14
+ * cache before reading the shared file (the "external editor" case — here
15
+ * the external editor is simply the other process). Writes never race: the
16
+ * worker only writes state, the API only writes control.
17
+ */
18
+
19
+ const STATE_FILE = 'worker-state.json';
20
+ const CONTROL_FILE = 'worker-control.json';
21
+
22
+ /** Age after which a heartbeat is considered stale (worker presumed dead). */
23
+ export const HEARTBEAT_STALE_MS = 20_000;
24
+
25
+ /** How many action lines the worker keeps in the state file. */
26
+ export const LOG_LIMIT = 50;
27
+
28
+ export function defaultWorkerState() {
29
+ return {
30
+ schemaVersion: 1,
31
+ pid: null,
32
+ status: 'stopped', // running | paused | stopped
33
+ startedAt: null,
34
+ stoppedAt: null,
35
+ heartbeatAt: null,
36
+ lastTickAt: null,
37
+ nextTickAt: null,
38
+ intervalMs: null,
39
+ activeTask: null,
40
+ lastError: null,
41
+ stats: { ticks: 0, postsPublished: 0, dmsSent: 0, cascadesPaused: 0, skipped: 0, failed: 0 },
42
+ logs: [],
43
+ };
44
+ }
45
+
46
+ export function defaultWorkerControl() {
47
+ return {
48
+ schemaVersion: 1,
49
+ desired: 'running', // running | paused
50
+ requestedAt: null,
51
+ requestedBy: null,
52
+ };
53
+ }
54
+
55
+ /** Fresh read of a shared file (cache invalidated: the other process owns it). */
56
+ function readShared(store, name, fallback) {
57
+ store.invalidate(name);
58
+ return store.read(name, fallback);
59
+ }
60
+
61
+ export function readWorkerState(store) {
62
+ return { ...defaultWorkerState(), ...(readShared(store, STATE_FILE, null) ?? {}) };
63
+ }
64
+
65
+ export function readWorkerControl(store) {
66
+ return { ...defaultWorkerControl(), ...(readShared(store, CONTROL_FILE, null) ?? {}) };
67
+ }
68
+
69
+ /** Append an action line (kept in memory order, newest last). */
70
+ export function appendLog(logs, entry) {
71
+ const line = { ts: new Date().toISOString(), ...entry };
72
+ return [...(Array.isArray(logs) ? logs : []), line].slice(-LOG_LIMIT);
73
+ }
74
+
75
+ /** True when the worker heartbeat is recent enough to consider it alive. */
76
+ export function isWorkerAlive(state, now = Date.now()) {
77
+ if (!state?.heartbeatAt) return false;
78
+ const age = now - new Date(state.heartbeatAt).getTime();
79
+ return Number.isFinite(age) && age >= 0 && age < HEARTBEAT_STALE_MS;
80
+ }
81
+
82
+ /**
83
+ * Status consumed by the UI.
84
+ *
85
+ * `desired` (control file, written by the UI) is the source of truth for
86
+ * running/paused: the state file is only refreshed by the worker on its next
87
+ * tick, so trusting `state.status` would show a stale "paused" right after
88
+ * the user pressed start. The worker being alive (heartbeat) is what
89
+ * distinguishes "running/paused" from "stopped".
90
+ */
91
+ export function workerStatusView(store, now = Date.now()) {
92
+ const state = readWorkerState(store);
93
+ const control = readWorkerControl(store);
94
+ const alive = isWorkerAlive(state, now);
95
+ const desired = control.desired === 'paused' ? 'paused' : 'running';
96
+ const status = !alive ? 'stopped' : desired;
97
+ return {
98
+ isRunning: status === 'running',
99
+ status,
100
+ desired,
101
+ pid: alive ? state.pid : null,
102
+ activeTask: status === 'running' ? state.activeTask ?? null : null,
103
+ lastTickAt: state.lastTickAt ?? null,
104
+ nextTickAt: state.nextTickAt ?? null,
105
+ intervalMs: state.intervalMs ?? null,
106
+ lastError: state.lastError ?? null,
107
+ stats: state.stats ?? defaultWorkerState().stats,
108
+ logs: (state.logs ?? []).slice(-10).reverse(),
109
+ };
110
+ }
@@ -0,0 +1,373 @@
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
+ /** True when the parent launcher disappeared (orphan guard on Windows). */
128
+ function parentIsGone() {
129
+ const ppid = process.ppid;
130
+ if (!ppid || ppid <= 1) return false;
131
+ try {
132
+ process.kill(ppid, 0);
133
+ return false;
134
+ } catch (err) {
135
+ return err?.code === 'EPERM' ? false : true;
136
+ }
137
+ }
138
+
139
+ /** Human description of what this pass is about (UI "activeTask"). */
140
+ function describeQueue(now) {
141
+ const parts = [];
142
+ const duePosts = store
143
+ .list('posts.json')
144
+ .filter((post) => post.status === 'scheduled' && new Date(post.scheduledAt ?? 0).getTime() <= now.getTime());
145
+ const activeCascades = store.list('dm-cascades.json').filter((c) => c.status === 'active');
146
+ if (duePosts.length) parts.push(`publicando ${duePosts.length} post(s) agendado(s)`);
147
+ if (activeCascades.length) parts.push(`processando ${activeCascades.length} cascata(s) de DM`);
148
+ return parts.length ? parts.join(' · ') : null;
149
+ }
150
+
151
+ /** stats increment without losing the sibling counters. */
152
+ async function bumpStat(key) {
153
+ const current = (await readWorkerStateAsync()).stats ?? {};
154
+ await patchState({ stats: { ...current, [key]: Number(current[key] ?? 0) + 1 } });
155
+ }
156
+
157
+ /** Fresh (cross-process safe) state read. */
158
+ async function readWorkerStateAsync() {
159
+ return readWorkerState(store);
160
+ }
161
+
162
+ /** One automation pass over the queues. */
163
+ async function tick() {
164
+ const control = readWorkerControl(store);
165
+ const startedAt = new Date();
166
+
167
+ if (control.desired === 'paused') {
168
+ await patchState({
169
+ status: 'paused',
170
+ activeTask: null,
171
+ heartbeatAt: nowIso(),
172
+ nextTickAt: new Date(Date.now() + INTERVAL_MS).toISOString(),
173
+ });
174
+ return;
175
+ }
176
+
177
+ pass += 1;
178
+ const activeTask = describeQueue(startedAt);
179
+ await patchState({
180
+ status: 'running',
181
+ heartbeatAt: nowIso(),
182
+ activeTask,
183
+ lastTickAt: nowIso(),
184
+ nextTickAt: new Date(startedAt.getTime() + INTERVAL_MS).toISOString(),
185
+ });
186
+
187
+ // Always re-read the live config: the user may toggle dry-run in the UI
188
+ // while the worker runs (configSync keeps ctx.config current).
189
+ syncLiveConfig(store, context.config);
190
+ const dryRun = context.config.dryRun !== false;
191
+
192
+ try {
193
+ const { posts, cascades, replies } = await runWorkerPass(context, { pass, now: startedAt });
194
+
195
+ // ---- scheduled posts ---------------------------------------------
196
+ for (const result of posts ?? []) {
197
+ if (result.error) {
198
+ await bumpStat('failed');
199
+ await writeLog('error', `falha ao publicar post: ${result.error}`, { postId: result.id ?? null });
200
+ continue;
201
+ }
202
+ const record = store.find('posts.json', result.id);
203
+ const simulated = Boolean(record?.simulated) || dryRun;
204
+ await bumpStat('postsPublished');
205
+ await writeLog(
206
+ simulated ? 'info' : 'success',
207
+ `${simulated ? '[dry-run] ' : ''}post publicado (${result.status})`,
208
+ { postId: result.id ?? null, simulated }
209
+ );
210
+ }
211
+
212
+ // ---- DM cascades -------------------------------------------------
213
+ for (const result of cascades?.results ?? []) {
214
+ if (result.status === 'sent') {
215
+ const cascade = store.find('dm-cascades.json', result.id);
216
+ await bumpStat('dmsSent');
217
+ await writeLog(
218
+ result.simulated ? 'info' : 'success',
219
+ `${result.simulated ? '[dry-run] ' : ''}DM enviada para ${cascade?.contactName ?? result.id}`,
220
+ { cascadeId: result.id ?? null, simulated: Boolean(result.simulated) }
221
+ );
222
+ } else if (result.status === 'skipped') {
223
+ await bumpStat('skipped');
224
+ await writeLog('warn', `DM nao enviada (${result.reason})`, { cascadeId: result.id ?? null });
225
+ } else if (result.status === 'failed') {
226
+ await bumpStat('failed');
227
+ await writeLog('error', `falha ao enviar DM: ${result.error ?? 'erro desconhecido'}`, { cascadeId: result.id ?? null });
228
+ }
229
+ }
230
+
231
+ // ---- inbox monitoring --------------------------------------------
232
+ for (const paused of replies?.paused ?? []) {
233
+ await bumpStat('cascadesPaused');
234
+ await writeLog('info', `cascata pausada (contato respondeu): ${paused.contactName}`, { cascadeId: paused.id });
235
+ }
236
+ if (replies?.error) {
237
+ await writeLog('warn', `checagem de respostas falhou: ${replies.error}`);
238
+ }
239
+
240
+ await bumpStat('ticks');
241
+ await patchState({
242
+ status: control.desired === 'paused' ? 'paused' : 'running',
243
+ activeTask: null,
244
+ lastError: null,
245
+ nextTickAt: new Date(Date.now() + INTERVAL_MS).toISOString(),
246
+ });
247
+ logger?.info('worker', `pass #${pass} done (dryRun=${dryRun})`, {
248
+ pass,
249
+ dryRun,
250
+ posts: (posts ?? []).length,
251
+ sent: cascades?.sent ?? 0,
252
+ skipped: cascades?.skipped ?? 0,
253
+ });
254
+ } catch (err) {
255
+ const message = err?.message ?? 'unknown error';
256
+ await bumpStat('failed');
257
+ await patchState({ status: 'running', activeTask: null, lastError: message, nextTickAt: new Date(Date.now() + INTERVAL_MS).toISOString() });
258
+ await writeLog('error', `pass #${pass} falhou: ${message}`, { pass });
259
+ logger?.error('worker', 'pass failed', { pass, message });
260
+ }
261
+ }
262
+
263
+ function clearTimers() {
264
+ if (timer) clearTimeout(timer);
265
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
266
+ timer = null;
267
+ heartbeatTimer = null;
268
+ }
269
+
270
+ function stop(reason) {
271
+ if (stopping) return;
272
+ stopping = true;
273
+ clearTimers();
274
+ try {
275
+ patchStateSync({
276
+ status: 'stopped',
277
+ pid: null,
278
+ activeTask: null,
279
+ stoppedAt: nowIso(),
280
+ heartbeatAt: null,
281
+ nextTickAt: null,
282
+ });
283
+ } catch {
284
+ /* state is best-effort during shutdown */
285
+ }
286
+ console.error(`[jobfinder:worker] stopped (${reason}).`);
287
+ process.exit(0);
288
+ }
289
+
290
+ /**
291
+ * The tick/heartbeat timers are the KEEP-ALIVE of this process (unlike the
292
+ * internal cron inside the server, they must NOT be unref'd: an unref'd
293
+ * timer lets Node exit immediately with code 0).
294
+ */
295
+ function schedule() {
296
+ if (stopping) return;
297
+ beatHeartbeat();
298
+ timer = setTimeout(async () => {
299
+ if (parentIsGone()) {
300
+ stop('parent launcher exited');
301
+ return;
302
+ }
303
+ await tick().catch((err) => {
304
+ logger?.error('worker', 'tick failed', { message: err?.message });
305
+ });
306
+ schedule();
307
+ }, INTERVAL_MS);
308
+ heartbeatTimer = setInterval(() => {
309
+ beatHeartbeat();
310
+ if (parentIsGone()) stop('parent launcher exited');
311
+ }, HEARTBEAT_MS);
312
+ }
313
+
314
+ async function main() {
315
+ const dataDir = resolveDataDir();
316
+ if (!fs.existsSync(dataDir)) {
317
+ console.error(`[jobfinder:worker] data directory not found: ${dataDir}`);
318
+ process.exit(1);
319
+ }
320
+
321
+ context = createContext(dataDir);
322
+ store = context.store;
323
+ logger = context.logger;
324
+
325
+ if (anotherWorkerOwnsState()) {
326
+ console.error('[jobfinder:worker] another worker is already running - exiting.');
327
+ process.exit(0);
328
+ }
329
+
330
+ patchStateSync({
331
+ pid: process.pid,
332
+ status: 'running',
333
+ startedAt: nowIso(),
334
+ stoppedAt: null,
335
+ heartbeatAt: nowIso(),
336
+ lastTickAt: null,
337
+ nextTickAt: new Date(Date.now() + INTERVAL_MS).toISOString(),
338
+ intervalMs: INTERVAL_MS,
339
+ activeTask: null,
340
+ lastError: null,
341
+ stats: { ticks: 0, postsPublished: 0, dmsSent: 0, cascadesPaused: 0, skipped: 0, failed: 0 },
342
+ logs: [],
343
+ });
344
+ logger?.info('worker', 'worker started', { pid: process.pid, intervalMs: INTERVAL_MS, dataDir });
345
+ console.log(
346
+ `[jobfinder:worker] running (pid ${process.pid}, every ${Math.round(INTERVAL_MS / 1000)}s) - data: ${dataDir}`
347
+ );
348
+
349
+ // Idempotent signals: only the first one triggers the graceful stop.
350
+ const onSignal = (signal) => () => stop(`received ${signal}`);
351
+ process.on('SIGINT', onSignal('SIGINT'));
352
+ process.on('SIGTERM', onSignal('SIGTERM'));
353
+ process.on('SIGBREAK', onSignal('SIGBREAK'));
354
+
355
+ // Close the state file even on a forced exit path. The heartbeat is
356
+ // cleared so a dead worker is never reported as alive.
357
+ process.on('exit', () => {
358
+ try {
359
+ patchStateSync({ status: 'stopped', pid: null, heartbeatAt: null, nextTickAt: null, activeTask: null });
360
+ } catch {
361
+ /* best effort */
362
+ }
363
+ });
364
+
365
+ schedule();
366
+ // First pass shortly after boot so a fresh start does not wait a full
367
+ // interval to process the queue.
368
+ setTimeout(() => {
369
+ tick().catch(() => {});
370
+ }, 1_500);
371
+ }
372
+
373
+ await main();