@danhachuel/jobfinder 0.1.5 → 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.
- package/CHANGELOG.md +42 -0
- package/README.md +22 -6
- package/package.json +1 -1
- package/scripts/cli.mjs +28 -0
- package/scripts/manual-tests/fase2-worker.mjs +337 -0
- package/src/server/index.mjs +4 -8
- package/src/server/routes/index.mjs +2 -0
- package/src/server/routes/worker.mjs +108 -0
- package/src/server/services/outreach/cascades.mjs +1 -1
- package/src/server/services/posting/publisher.mjs +6 -0
- package/src/server/services/workers.mjs +52 -27
- package/src/server/storage/bootstrap.mjs +7 -0
- package/src/server/storage/configSync.mjs +8 -1
- package/src/server/storage/jsonStore.mjs +9 -2
- package/src/server/storage/workerState.mjs +110 -0
- package/src/server/worker.mjs +373 -0
- package/src/server/workerRuntime.mjs +72 -0
- package/src/ui/dist/assets/index-D_t6FNqH.css +2 -0
- package/src/ui/dist/assets/index-DsPMdx2I.js +13 -0
- package/src/ui/dist/index.html +2 -2
- package/src/ui/dist/assets/index-CT_D8FEQ.css +0 -2
- package/src/ui/dist/assets/index-DF1owmbE.js +0 -13
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JobFinder — worker control routes (protected by the session guard).
|
|
3
|
+
*
|
|
4
|
+
* GET /api/worker/status live status + last actions (polled by the UI)
|
|
5
|
+
* POST /api/worker/start resume (and spawn the worker when it is dead)
|
|
6
|
+
* POST /api/worker/stop pause (the process stays alive, idles)
|
|
7
|
+
* POST /api/worker/tick force one pass now (tests / manual control)
|
|
8
|
+
*
|
|
9
|
+
* The worker is a separate process: the API only reads worker-state.json and
|
|
10
|
+
* writes worker-control.json (see storage/workerState.mjs), so the UI can
|
|
11
|
+
* observe and steer it without owning it.
|
|
12
|
+
*/
|
|
13
|
+
import { Router } from 'express';
|
|
14
|
+
|
|
15
|
+
import { asyncRoute } from '../middleware/errors.mjs';
|
|
16
|
+
import { runWorkerPass } from '../services/workers.mjs';
|
|
17
|
+
import { spawnWorker, forwardChildOutput } from '../workerRuntime.mjs';
|
|
18
|
+
import {
|
|
19
|
+
readWorkerControl,
|
|
20
|
+
readWorkerState,
|
|
21
|
+
isWorkerAlive,
|
|
22
|
+
workerStatusView,
|
|
23
|
+
defaultWorkerControl,
|
|
24
|
+
} from '../storage/workerState.mjs';
|
|
25
|
+
|
|
26
|
+
const CONTROL_FILE = 'worker-control.json';
|
|
27
|
+
|
|
28
|
+
export function workerRoutes({ store, logger, config, rateLimiter }) {
|
|
29
|
+
const router = Router();
|
|
30
|
+
const ctx = { store, logger, config, rateLimiter };
|
|
31
|
+
|
|
32
|
+
router.get(
|
|
33
|
+
'/worker/status',
|
|
34
|
+
asyncRoute((req, res) => {
|
|
35
|
+
const status = workerStatusView(store);
|
|
36
|
+
res.json(status);
|
|
37
|
+
})
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
router.post(
|
|
41
|
+
'/worker/start',
|
|
42
|
+
asyncRoute(async (req, res) => {
|
|
43
|
+
await store.update(
|
|
44
|
+
CONTROL_FILE,
|
|
45
|
+
(current) => ({ ...defaultWorkerControl(), ...(current ?? {}), desired: 'running', requestedAt: new Date().toISOString(), requestedBy: req.user?.email ?? null }),
|
|
46
|
+
{}
|
|
47
|
+
);
|
|
48
|
+
const alive = isWorkerAlive(readWorkerState(store));
|
|
49
|
+
let spawned = false;
|
|
50
|
+
if (!alive) {
|
|
51
|
+
try {
|
|
52
|
+
const child = spawnWorker({ env: { JOBFINDER_DATA_DIR: store.dataDir } });
|
|
53
|
+
forwardChildOutput(child, '[jobfinder:worker]');
|
|
54
|
+
child.on('exit', (code, signal) => {
|
|
55
|
+
logger.info('worker', 'worker process exited', { reason: signal ? `signal ${signal}` : `code ${code}` });
|
|
56
|
+
});
|
|
57
|
+
spawned = true;
|
|
58
|
+
logger.info('worker', 'worker spawned by the API', { pid: child.pid });
|
|
59
|
+
} catch (err) {
|
|
60
|
+
logger.error('worker', 'failed to spawn the worker', { message: err?.message });
|
|
61
|
+
throw err;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
logger.info('worker', 'worker start requested', { spawned, by: req.user?.email ?? null });
|
|
65
|
+
res.json({ ...workerStatusView(store), spawned });
|
|
66
|
+
})
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
router.post(
|
|
70
|
+
'/worker/stop',
|
|
71
|
+
asyncRoute(async (req, res) => {
|
|
72
|
+
await store.update(
|
|
73
|
+
CONTROL_FILE,
|
|
74
|
+
(current) => ({ ...defaultWorkerControl(), ...(current ?? {}), desired: 'paused', requestedAt: new Date().toISOString(), requestedBy: req.user?.email ?? null }),
|
|
75
|
+
{}
|
|
76
|
+
);
|
|
77
|
+
logger.info('worker', 'worker pause requested', { by: req.user?.email ?? null });
|
|
78
|
+
res.json(workerStatusView(store));
|
|
79
|
+
})
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
router.post(
|
|
83
|
+
'/worker/tick',
|
|
84
|
+
asyncRoute(async (req, res) => {
|
|
85
|
+
// Runs in the API process: same services, same store, atomic writes.
|
|
86
|
+
const control = readWorkerControl(store);
|
|
87
|
+
if (control.desired === 'paused') {
|
|
88
|
+
return res.json({ ok: false, message: 'Worker pausado — inicie-o antes de forçar um passe.', status: workerStatusView(store) });
|
|
89
|
+
}
|
|
90
|
+
const result = await runWorkerPass(ctx, { now: new Date() });
|
|
91
|
+
logger.info('worker', 'manual tick', { posts: (result.posts ?? []).length, sent: result.cascades?.sent ?? 0 });
|
|
92
|
+
res.json({ ok: true, result: summarize(result), status: workerStatusView(store) });
|
|
93
|
+
})
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
return router;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Compact view of a pass for the API response. */
|
|
100
|
+
function summarize(result) {
|
|
101
|
+
return {
|
|
102
|
+
posts: (result.posts ?? []).map((p) => ({ id: p.id, status: p.status, error: p.error ?? null })),
|
|
103
|
+
sent: result.cascades?.sent ?? 0,
|
|
104
|
+
skipped: result.cascades?.skipped ?? 0,
|
|
105
|
+
paused: (result.replies?.paused ?? []).map((p) => p.contactName),
|
|
106
|
+
error: result.cascades?.error ?? null,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
@@ -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 —
|
|
2
|
+
* JobFinder — worker pass (one automation cycle).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
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
|
-
*
|
|
9
|
-
*
|
|
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
|
-
|
|
15
|
-
const REPLIES_EVERY = 10;
|
|
20
|
+
/** Inbox monitoring runs every N passes. */
|
|
21
|
+
export const REPLIES_EVERY = 10;
|
|
16
22
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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
|
|
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
|
-
/**
|
|
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
|
+
}
|