@danhachuel/jobfinder 0.1.16 → 0.1.18
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 +34 -0
- package/README.md +59 -42
- package/ecosystem.config.cjs +22 -12
- package/package.json +1 -1
- package/scripts/cli.mjs +542 -380
- package/scripts/manual-tests/fase1-auth-dryrun.mjs +1 -1
- package/scripts/manual-tests/fase1-dryrun-services.mjs +1 -1
- package/scripts/manual-tests/fase1-screens.mjs +1 -1
- package/scripts/manual-tests/fase1-ui-e2e.mjs +1 -1
- package/scripts/manual-tests/fase2-worker.mjs +2 -2
- package/scripts/manual-tests/fase3-seed-env.mjs +1 -0
- package/scripts/manual-tests/fase4-npx-start.mjs +13 -4
- package/scripts/manual-tests/fase5-daemon.mjs +34 -38
- package/scripts/manual-tests/fase6-runtime-daemon.mjs +274 -0
- package/scripts/manual-tests/startup-keepalive.mjs +84 -41
- package/scripts/start-windows.ps1 +31 -30
- package/src/server/app.mjs +4 -1
- package/src/server/index.mjs +43 -4
- package/src/ui/dist/assets/{index-BIl6BJNG.js → index-Bc84TxuK.js} +1 -1
- package/src/ui/dist/index.html +1 -1
|
@@ -57,13 +57,27 @@ function getStatus(port, urlPath) {
|
|
|
57
57
|
});
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
// Home compartilhado: o runtime permanente (~/.jobfinder/runtime) é instalado
|
|
61
|
+
// uma única vez e reaproveitado por todas as seções — cada home novo pagaria
|
|
62
|
+
// ~20s de npm install e o teste mediria o instalador, não o keep-alive.
|
|
63
|
+
const SHARED_HOME = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'jobfinder-keepalive-')), 'data');
|
|
64
|
+
// Diretório dos arquivos de injeção (preloads) das seções de falha.
|
|
65
|
+
const PRELOAD_DIR = path.join(SHARED_HOME, 'preloads');
|
|
66
|
+
fs.mkdirSync(PRELOAD_DIR, { recursive: true });
|
|
67
|
+
|
|
60
68
|
const dead = (child) => child.exitCode !== null || child.signalCode !== null;
|
|
61
69
|
|
|
70
|
+
/** Texto do log JSONL diário de um home (onde o logger escreve). */
|
|
71
|
+
const jsonlNow = (home) => {
|
|
72
|
+
const day = new Date().toISOString().slice(0, 10);
|
|
73
|
+
const file = path.join(home, 'logs', `${day}.jsonl`);
|
|
74
|
+
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
|
|
75
|
+
};
|
|
76
|
+
|
|
62
77
|
/** Sobe o app e observa por `observeMs` sem enviar nenhum sinal. */
|
|
63
78
|
async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
64
79
|
console.log(`\n== ${label} ==`);
|
|
65
|
-
const
|
|
66
|
-
const home = path.join(tmp, 'data');
|
|
80
|
+
const home = SHARED_HOME;
|
|
67
81
|
const child = spawn(process.execPath, args, {
|
|
68
82
|
cwd: ROOT,
|
|
69
83
|
env: { ...process.env, JOBFINDER_PORT: String(port), JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', ...env },
|
|
@@ -79,12 +93,39 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
79
93
|
return { child, out, home };
|
|
80
94
|
}
|
|
81
95
|
|
|
96
|
+
// 0) AQUECIMENTO: o runtime permanente é preparado uma vez. Desde a 0.1.17 o
|
|
97
|
+
// launcher copia o código e instala as dependências antes de subir o servidor
|
|
98
|
+
// — sem este passo cada seção pagaria ~20s de npm install e o teste mediria o
|
|
99
|
+
// instalador, não o keep-alive.
|
|
100
|
+
{
|
|
101
|
+
console.log('\n== aquecimento do runtime permanente ==');
|
|
102
|
+
const warm = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), '--daemon'], {
|
|
103
|
+
cwd: ROOT,
|
|
104
|
+
env: { ...process.env, JOBFINDER_HOME: SHARED_HOME, JOBFINDER_NO_WORKER: '1' },
|
|
105
|
+
stdio: ['ignore', 'ignore', 'ignore'],
|
|
106
|
+
});
|
|
107
|
+
await new Promise((resolve) => {
|
|
108
|
+
warm.on('exit', () => resolve());
|
|
109
|
+
setTimeout(resolve, 120000);
|
|
110
|
+
});
|
|
111
|
+
const warmSrv = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'stop'], {
|
|
112
|
+
cwd: ROOT,
|
|
113
|
+
env: { ...process.env, JOBFINDER_HOME: SHARED_HOME },
|
|
114
|
+
stdio: 'ignore',
|
|
115
|
+
});
|
|
116
|
+
await new Promise((resolve) => {
|
|
117
|
+
warmSrv.on('exit', () => resolve());
|
|
118
|
+
setTimeout(resolve, 30000);
|
|
119
|
+
});
|
|
120
|
+
console.log(` OK runtime preparado em ${path.join(SHARED_HOME, 'runtime')}`);
|
|
121
|
+
}
|
|
122
|
+
|
|
82
123
|
// 1) launcher: o terminal precisa ficar preso rodando o servidor
|
|
83
124
|
{
|
|
84
|
-
const { child } = await bootAndObserve('boot via launcher (node scripts/cli.mjs
|
|
85
|
-
args: [path.join(ROOT, 'scripts', 'cli.mjs'), '
|
|
125
|
+
const { child } = await bootAndObserve('boot via launcher (node scripts/cli.mjs --foreground)', {
|
|
126
|
+
args: [path.join(ROOT, 'scripts', 'cli.mjs'), '--foreground'],
|
|
86
127
|
port: 4181,
|
|
87
|
-
observeMs:
|
|
128
|
+
observeMs: 12000,
|
|
88
129
|
});
|
|
89
130
|
child.kill();
|
|
90
131
|
await wait(5000);
|
|
@@ -103,8 +144,8 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
103
144
|
|
|
104
145
|
// Sinal emitido dentro do processo (preload): os handlers graceful rodam
|
|
105
146
|
// em qualquer plataforma — no Windows, child.kill() vira TerminateProcess.
|
|
106
|
-
const
|
|
107
|
-
|
|
147
|
+
const home = SHARED_HOME;
|
|
148
|
+
const tmp = PRELOAD_DIR;
|
|
108
149
|
const preload = path.join(tmp, 'sigterm.cjs');
|
|
109
150
|
fs.writeFileSync(preload, "setTimeout(() => process.emit('SIGTERM'), 8000);\n");
|
|
110
151
|
const second = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'index.mjs')], {
|
|
@@ -119,17 +160,17 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
119
160
|
: '';
|
|
120
161
|
check('shutdown gracioso registrado no log', /"shutdown"/.test(logs), logs.split('\n').filter((l) => /shutdown/.test(l))[0] ?? '');
|
|
121
162
|
if (second.exitCode === null && second.signalCode === null) second.kill();
|
|
122
|
-
|
|
163
|
+
/* preloads vivem em PRELOAD_DIR (compartilhado entre as seções) */
|
|
123
164
|
}
|
|
124
165
|
|
|
125
166
|
// 3) injeção de falha: unhandledRejection após o boot não pode matar o processo
|
|
126
167
|
{
|
|
127
168
|
console.log('\n== boot com unhandledRejection injetado (killer silencioso) ==');
|
|
128
|
-
const
|
|
129
|
-
|
|
169
|
+
const home = SHARED_HOME;
|
|
170
|
+
const tmp = PRELOAD_DIR;
|
|
130
171
|
const fault = path.join(tmp, 'fault.cjs');
|
|
131
172
|
fs.writeFileSync(fault, "setTimeout(() => { Promise.reject(new Error('fault-injection: unhandled rejection')); }, 1200);\n");
|
|
132
|
-
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), '
|
|
173
|
+
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), '--foreground', '--no-open'], {
|
|
133
174
|
cwd: ROOT,
|
|
134
175
|
env: { ...process.env, JOBFINDER_PORT: '4183', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', NODE_OPTIONS: `--require ${fault}` },
|
|
135
176
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
@@ -142,16 +183,15 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
142
183
|
check('API responde em localhost', (await getStatus(4183, '/api/health')) === 200);
|
|
143
184
|
check('rejeição foi registrada no log (não engolida em silêncio)', /unhandled promise rejection ignored/i.test(out), out.split('\n').filter((l) => /rejection/i.test(l))[0] ?? '');
|
|
144
185
|
child.kill();
|
|
145
|
-
|
|
186
|
+
/* preloads vivem em PRELOAD_DIR (compartilhado entre as seções) */
|
|
146
187
|
}
|
|
147
188
|
|
|
148
189
|
// 4) stdout quebrado (EPIPE) — ex.: pipe fechado, terminal que some,
|
|
149
190
|
// redirecionamento no Windows/MobaXterm. Não pode matar o processo.
|
|
150
191
|
{
|
|
151
192
|
console.log('\n== boot com stdout fechado (EPIPE) ==');
|
|
152
|
-
const
|
|
153
|
-
const
|
|
154
|
-
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
|
|
193
|
+
const home = SHARED_HOME;
|
|
194
|
+
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), '--foreground', '--no-open'], {
|
|
155
195
|
cwd: ROOT,
|
|
156
196
|
env: { ...process.env, JOBFINDER_PORT: '4184', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1' },
|
|
157
197
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
@@ -166,16 +206,15 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
166
206
|
check('processo sobrevive ao stdout quebrado', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
|
|
167
207
|
check('API responde em localhost', (await getStatus(4184, '/api/health')) === 200);
|
|
168
208
|
child.kill();
|
|
169
|
-
|
|
209
|
+
/* preloads vivem em PRELOAD_DIR (compartilhado entre as seções) */
|
|
170
210
|
}
|
|
171
211
|
|
|
172
212
|
// 5) o worker sobe junto, bate heartbeat e o CLI continua vivo depois
|
|
173
213
|
// dele (regressao 0.1.7: event loop vazio matava o launcher).
|
|
174
214
|
{
|
|
175
215
|
console.log('\n== boot com worker: heartbeat + CLI independente do worker ==');
|
|
176
|
-
const
|
|
177
|
-
const
|
|
178
|
-
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
|
|
216
|
+
const home = SHARED_HOME;
|
|
217
|
+
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), '--foreground', '--no-open'], {
|
|
179
218
|
cwd: ROOT,
|
|
180
219
|
env: { ...process.env, JOBFINDER_PORT: '4185', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1' },
|
|
181
220
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
@@ -195,7 +234,14 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
195
234
|
await wait(3000);
|
|
196
235
|
const pid0 = await workerPid();
|
|
197
236
|
check('worker spawnado publicou o pid no estado', Boolean(pid0), `pid=${pid0}`);
|
|
198
|
-
|
|
237
|
+
// Desde a 0.1.17 os eventos do worker são registrados pelo SERVIDOR no
|
|
238
|
+
// log diário (logs/YYYY-MM-DD.jsonl), não no stdout do launcher.
|
|
239
|
+
const jsonl = () => {
|
|
240
|
+
const day = new Date().toISOString().slice(0, 10);
|
|
241
|
+
const file = path.join(home, 'logs', `${day}.jsonl`);
|
|
242
|
+
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
|
|
243
|
+
};
|
|
244
|
+
check('servidor registrou o início do worker', /worker iniciado pelo servidor/.test(jsonl()));
|
|
199
245
|
|
|
200
246
|
await wait(4000); // passa de 1 heartbeat (5s): o guardiao de orfaos rodou
|
|
201
247
|
const pid1 = await workerPid();
|
|
@@ -209,26 +255,26 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
209
255
|
}
|
|
210
256
|
await wait(2500);
|
|
211
257
|
check('CLI sobrevive ao crash do worker', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
|
|
212
|
-
check('saida do worker foi registrada no log', /worker encerrou/i.test(
|
|
258
|
+
check('saida do worker foi registrada no log', /worker encerrou/i.test(jsonl()), jsonl().split('\n').filter((l) => /worker encerrou/i.test(l))[0]?.slice(0, 120) ?? '');
|
|
213
259
|
check('servidor continua respondendo apos o crash do worker', (await getStatus(4185, '/api/health')) === 200);
|
|
214
260
|
|
|
215
261
|
// O launcher supervisiona: um worker novo assume a fila.
|
|
216
262
|
await wait(5000);
|
|
217
263
|
const pid2 = await workerPid();
|
|
218
264
|
check('launcher reiniciou o worker automaticamente', pid2 !== null && pid2 !== pid1, `antes=${pid1} depois=${pid2}`);
|
|
219
|
-
check('restart
|
|
265
|
+
check('restart do worker registrado no log', /worker iniciado pelo servidor/.test(jsonl()) && pid2 !== pid1);
|
|
220
266
|
check('CLI continua vivo depois do restart', !dead(child) && (await getStatus(4185, '/api/health')) === 200);
|
|
221
267
|
child.kill();
|
|
222
268
|
await wait(800);
|
|
223
|
-
|
|
269
|
+
/* preloads vivem em PRELOAD_DIR (compartilhado entre as seções) */
|
|
224
270
|
}
|
|
225
271
|
|
|
226
272
|
// 7) worker direto: rejection injetada -> worker-error.log + processo vivo
|
|
227
273
|
{
|
|
228
274
|
console.log('\n== worker direto: rejection injetada e log em arquivo ==');
|
|
229
|
-
const
|
|
230
|
-
const home = path.join(tmp, 'data');
|
|
275
|
+
const home = SHARED_HOME;
|
|
231
276
|
ensureDataDir(home); // o worker exige o skeleton (como o launcher faz)
|
|
277
|
+
const tmp = PRELOAD_DIR;
|
|
232
278
|
const fault = path.join(tmp, 'fault.cjs');
|
|
233
279
|
fs.writeFileSync(fault, "setTimeout(() => { Promise.reject(new Error('fault-injection: worker rejection')); }, 1200);\n");
|
|
234
280
|
const worker = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'worker.mjs')], {
|
|
@@ -251,14 +297,13 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
251
297
|
check('falha tambem apareceu no console', /unhandled promise rejection ignored/i.test(out));
|
|
252
298
|
worker.kill();
|
|
253
299
|
await wait(800);
|
|
254
|
-
|
|
300
|
+
/* preloads vivem em PRELOAD_DIR (compartilhado entre as seções) */
|
|
255
301
|
}
|
|
256
302
|
|
|
257
303
|
// 8) worker direto: stdout/stderr quebrados (EPIPE) -> worker segue vivo
|
|
258
304
|
{
|
|
259
305
|
console.log('\n== worker direto: EPIPE nos pipes ==');
|
|
260
|
-
const
|
|
261
|
-
const home = path.join(tmp, 'data');
|
|
306
|
+
const home = SHARED_HOME;
|
|
262
307
|
ensureDataDir(home); // o worker exige o skeleton (como o launcher faz)
|
|
263
308
|
const worker = spawn(process.execPath, [path.join(ROOT, 'src', 'server', 'worker.mjs')], {
|
|
264
309
|
cwd: ROOT,
|
|
@@ -281,7 +326,7 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
281
326
|
check('heartbeat continua sendo publicado sem o console', Boolean(state?.pid) && state.pid === worker.pid, `pid=${state?.pid}`);
|
|
282
327
|
worker.kill();
|
|
283
328
|
await wait(800);
|
|
284
|
-
|
|
329
|
+
/* preloads vivem em PRELOAD_DIR (compartilhado entre as seções) */
|
|
285
330
|
}
|
|
286
331
|
|
|
287
332
|
// 9) worker direto: rename SEMPRE EPERM (antivirus/arquivo travado no
|
|
@@ -289,9 +334,9 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
289
334
|
// escrita é tentada de novo no próximo tick/heartbeat.
|
|
290
335
|
{
|
|
291
336
|
console.log('\n== worker direto: EPERM no rename (arquivo travado) ==');
|
|
292
|
-
const
|
|
293
|
-
const home = path.join(tmp, 'data');
|
|
337
|
+
const home = SHARED_HOME;
|
|
294
338
|
ensureDataDir(home);
|
|
339
|
+
const tmp = PRELOAD_DIR;
|
|
295
340
|
const sabotage = path.join(tmp, 'eperm.cjs');
|
|
296
341
|
fs.writeFileSync(
|
|
297
342
|
sabotage,
|
|
@@ -326,15 +371,14 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
326
371
|
check('worker-state write failed registrado (não engolido em silêncio)', /worker-state write failed/i.test(errorLog));
|
|
327
372
|
worker.kill();
|
|
328
373
|
await wait(800);
|
|
329
|
-
|
|
374
|
+
/* preloads vivem em PRELOAD_DIR (compartilhado entre as seções) */
|
|
330
375
|
}
|
|
331
376
|
|
|
332
377
|
// 6) JOBFINDER_NO_WORKER=1: modo sem worker, CLI continua vivo
|
|
333
378
|
{
|
|
334
379
|
console.log('\n== boot sem worker (JOBFINDER_NO_WORKER=1) ==');
|
|
335
|
-
const
|
|
336
|
-
const
|
|
337
|
-
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
|
|
380
|
+
const home = SHARED_HOME;
|
|
381
|
+
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), '--foreground', '--no-open'], {
|
|
338
382
|
cwd: ROOT,
|
|
339
383
|
env: { ...process.env, JOBFINDER_PORT: '4187', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1', JOBFINDER_NO_WORKER: '1' },
|
|
340
384
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
@@ -344,11 +388,11 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
344
388
|
child.stderr.on('data', (d) => { out += String(d); });
|
|
345
389
|
await wait(6000);
|
|
346
390
|
check('CLI continua rodando sem worker', !dead(child), dead(child) ? `exitCode=${child.exitCode} signal=${child.signalCode}` : 'vivo');
|
|
347
|
-
check('nenhum worker foi spawnado', /
|
|
391
|
+
check('nenhum worker foi spawnado (desativado no log do servidor)', /desativado por JOBFINDER_NO_WORKER/.test(jsonlNow(home)), jsonlNow(home).split('\n').filter((l) => /JOBFINDER_NO_WORKER/.test(l))[0]?.slice(0, 120) ?? '');
|
|
348
392
|
check('API responde em localhost', (await getStatus(4187, '/api/health')) === 200);
|
|
349
393
|
child.kill();
|
|
350
394
|
await wait(800);
|
|
351
|
-
|
|
395
|
+
/* preloads vivem em PRELOAD_DIR (compartilhado entre as seções) */
|
|
352
396
|
}
|
|
353
397
|
|
|
354
398
|
// 10) ARQUITETURA 0.1.13: servidor DENTRO do processo do CLI + ambiente
|
|
@@ -357,9 +401,8 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
357
401
|
// o processo vivo e respondendo HTTP 200 — e o worker é reiniciado.
|
|
358
402
|
{
|
|
359
403
|
console.log('\n== ambiente hostil: stdout destruído + worker morto (servidor embutido) ==');
|
|
360
|
-
const
|
|
361
|
-
const
|
|
362
|
-
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), 'start', '--no-open'], {
|
|
404
|
+
const home = SHARED_HOME;
|
|
405
|
+
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'cli.mjs'), '--foreground', '--no-open'], {
|
|
363
406
|
cwd: ROOT,
|
|
364
407
|
env: { ...process.env, JOBFINDER_PORT: '4190', JOBFINDER_DATA_DIR: home, JOBFINDER_NO_OPEN: '1' },
|
|
365
408
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
@@ -400,7 +443,7 @@ async function bootAndObserve(label, { args, port, observeMs, env = {} }) {
|
|
|
400
443
|
check('worker foi reiniciado pelo launcher', pid1 !== null && pid1 !== pid0, `antes=${pid0} depois=${pid1}`);
|
|
401
444
|
child.kill();
|
|
402
445
|
await wait(800);
|
|
403
|
-
|
|
446
|
+
/* preloads vivem em PRELOAD_DIR (compartilhado entre as seções) */
|
|
404
447
|
}
|
|
405
448
|
|
|
406
449
|
console.log(`\nResultado: ${passed} passaram, ${failed} falharam.`);
|
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
<#
|
|
2
2
|
.SYNOPSIS
|
|
3
|
-
Inicia o JobFinder em background (
|
|
3
|
+
Inicia o JobFinder em background (runtime permanente + daemon) no Windows.
|
|
4
4
|
|
|
5
5
|
.DESCRIPTION
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
Delega ao CLI (@danhachuel/jobfinder), que desde a 0.1.17:
|
|
7
|
+
1. copia o código do servidor para o runtime permanente ~/.jobfinder/runtime
|
|
8
|
+
2. sobe o Express DESTACADO (detached), com stdio no arquivo de log —
|
|
9
|
+
imune ao terminal (MobaXterm, wrapper do npx, PowerShell) e ao EBUSY
|
|
10
|
+
que o Windows devolvia quando um processo vivo segurava o cache do npx
|
|
11
|
+
3. registra o PID em ~/.jobfinder/jobfinder.pid
|
|
12
|
+
|
|
13
|
+
O script apenas orquestra: detecta porta em uso, dispara o CLI, confere o
|
|
14
|
+
/api/health e informa PID, log e como parar. Nada de `&`/`Start-Process
|
|
15
|
+
-Wait` aqui — o PowerShell ficava pendurado esperando handles do filho.
|
|
10
16
|
|
|
11
17
|
Uso:
|
|
12
|
-
.\start-windows.ps1 #
|
|
13
|
-
.\start-windows.ps1 -Version 0.1.
|
|
18
|
+
.\start-windows.ps1 # versão latest do npm
|
|
19
|
+
.\start-windows.ps1 -Version 0.1.17 # versão fixa
|
|
14
20
|
.\start-windows.ps1 -Local # working copy (desenvolvimento)
|
|
15
21
|
.\start-windows.ps1 -Stop # encerra o daemon
|
|
16
|
-
|
|
17
|
-
.NOTES
|
|
18
|
-
O app grava seu próprio log em %USERPROFILE%\.jobfinder\jobfinder.log —
|
|
19
|
-
por isso o script NÃO redireciona a saída do processo. `Start-Process`
|
|
20
|
-
com redireção (ou `&`) faz o PowerShell esperar handles do processo
|
|
21
|
-
nativo, e um daemon que herdou qualquer handle travaria o script.
|
|
22
22
|
#>
|
|
23
23
|
[CmdletBinding()]
|
|
24
24
|
param(
|
|
@@ -53,15 +53,6 @@ function Test-JobFinderUp {
|
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
function Wait-JobFinderUp {
|
|
57
|
-
param([int]$Port, [int]$Seconds = 30)
|
|
58
|
-
for ($i = 0; $i -lt $Seconds; $i++) {
|
|
59
|
-
if (Test-JobFinderUp -Port $Port) { return $true }
|
|
60
|
-
Start-Sleep -Seconds 1
|
|
61
|
-
}
|
|
62
|
-
return $false
|
|
63
|
-
}
|
|
64
|
-
|
|
65
56
|
# Data dir: mesma precedência do CLI (JOBFINDER_HOME > JOBFINDER_DATA_DIR > ~/.jobfinder).
|
|
66
57
|
if ($env:JOBFINDER_HOME) { $dataDir = $env:JOBFINDER_HOME }
|
|
67
58
|
elseif ($env:JOBFINDER_DATA_DIR) { $dataDir = $env:JOBFINDER_DATA_DIR }
|
|
@@ -71,9 +62,8 @@ $logFile = Join-Path $dataDir "jobfinder.log"
|
|
|
71
62
|
if ($Stop) {
|
|
72
63
|
Write-Host "Parando o JobFinder ($label)..." -ForegroundColor Cyan
|
|
73
64
|
Start-Process -FilePath $exe -ArgumentList ($cliArgs + @("stop")) -WindowStyle Hidden
|
|
74
|
-
# Confirma que a porta deixou de responder.
|
|
75
65
|
$down = $false
|
|
76
|
-
for ($i = 0; $i -lt
|
|
66
|
+
for ($i = 0; $i -lt 20; $i++) {
|
|
77
67
|
if (-not (Test-JobFinderUp -Port $Port)) { $down = $true; break }
|
|
78
68
|
Start-Sleep -Seconds 1
|
|
79
69
|
}
|
|
@@ -92,14 +82,25 @@ if (Test-JobFinderUp -Port $Port) {
|
|
|
92
82
|
|
|
93
83
|
Write-Host "Iniciando o JobFinder em background ($label, porta $Port)..." -ForegroundColor Cyan
|
|
94
84
|
$env:JOBFINDER_MODE = "daemon"
|
|
85
|
+
# Sem -Wait e sem redirecionamento: o CLI copia o runtime, sobe o daemon e
|
|
86
|
+
# retorna. Qualquer espera por handles do processo nativo travaria o script.
|
|
95
87
|
Start-Process -FilePath $exe -ArgumentList ($cliArgs + @("--daemon", "--port", "$Port")) -WindowStyle Hidden
|
|
96
88
|
|
|
97
|
-
if (
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
89
|
+
if (Test-JobFinderUp -Port $Port) {
|
|
90
|
+
Start-Sleep -Seconds 1
|
|
91
|
+
if (Test-JobFinderUp -Port $Port) {
|
|
92
|
+
$pidInfo = ""
|
|
93
|
+
$lockFile = Join-Path $dataDir "jobfinder.pid"
|
|
94
|
+
if (Test-Path $lockFile) {
|
|
95
|
+
try { $pidInfo = " (PID $((Get-Content $lockFile -Raw | ConvertFrom-Json).pid))" } catch { }
|
|
96
|
+
}
|
|
97
|
+
Write-Host ""
|
|
98
|
+
Write-Host "JobFinder rodando em background$pidInfo`: http://127.0.0.1:$Port" -ForegroundColor Green
|
|
99
|
+
Write-Host "Runtime: $(Join-Path $dataDir 'runtime')" -ForegroundColor Gray
|
|
100
|
+
Write-Host "Log : $logFile" -ForegroundColor Gray
|
|
101
|
+
Write-Host "Parar : .\start-windows.ps1 -Stop (ou: taskkill /F /IM node.exe)" -ForegroundColor Gray
|
|
102
|
+
exit 0
|
|
103
|
+
}
|
|
103
104
|
}
|
|
104
105
|
|
|
105
106
|
Write-Host ""
|
package/src/server/app.mjs
CHANGED
|
@@ -52,9 +52,12 @@ export function createApp({ store, logger, config, rateLimiter, dataDir }) {
|
|
|
52
52
|
if (fs.existsSync(UI_DIST)) {
|
|
53
53
|
app.use(express.static(UI_DIST, { index: false, maxAge: '1h' }));
|
|
54
54
|
// SPA fallback: any other GET serves index.html.
|
|
55
|
+
// Express 5 EXIGE a opção `root`: um caminho absoluto "puro" falha com
|
|
56
|
+
// 404 "Not Found" — foi a regressão que devolvia JSON na raiz da URL
|
|
57
|
+
// enquanto os assets (servidos pelo static) funcionavam.
|
|
55
58
|
app.use((req, res, next) => {
|
|
56
59
|
if (req.method !== 'GET') return next();
|
|
57
|
-
res.sendFile(
|
|
60
|
+
res.sendFile('index.html', { root: UI_DIST });
|
|
58
61
|
});
|
|
59
62
|
} else {
|
|
60
63
|
app.get('/', (req, res) => {
|
package/src/server/index.mjs
CHANGED
|
@@ -18,6 +18,7 @@ import { createRequire } from 'node:module';
|
|
|
18
18
|
import { createApp } from './app.mjs';
|
|
19
19
|
import { createContext } from './context.mjs';
|
|
20
20
|
import { resolveDataDir, UI_DIST } from './paths.mjs';
|
|
21
|
+
import { spawnWorker } from './workerRuntime.mjs';
|
|
21
22
|
|
|
22
23
|
/** ESM-safe package.json reader: resolved from THIS file, never from cwd. */
|
|
23
24
|
const require = createRequire(import.meta.url);
|
|
@@ -169,11 +170,43 @@ export async function start() {
|
|
|
169
170
|
});
|
|
170
171
|
|
|
171
172
|
// Time-based automation (scheduled posts, DM cascades, inbox monitoring)
|
|
172
|
-
// runs in the standalone background worker process (src/server/worker.mjs)
|
|
173
|
-
//
|
|
174
|
-
//
|
|
175
|
-
|
|
173
|
+
// runs in the standalone background worker process (src/server/worker.mjs).
|
|
174
|
+
// Desde a 0.1.17 o servidor É o daemon: o launcher já morreu, então quem
|
|
175
|
+
// spawna e supervisiona o worker é este processo.
|
|
176
176
|
let shuttingDown = false;
|
|
177
|
+
let worker = null;
|
|
178
|
+
let workerRestarts = 0;
|
|
179
|
+
|
|
180
|
+
const startWorker = () => {
|
|
181
|
+
// JOBFINDER_TAKEOVER: o servidor acabou de subir — heartbeat velha de pid
|
|
182
|
+
// reciclado não pode bloquear este spawn.
|
|
183
|
+
worker = spawnWorker({ env: { JOBFINDER_DATA_DIR: dataDir, JOBFINDER_TAKEOVER: '1' } });
|
|
184
|
+
worker.on('exit', (code, signal) => {
|
|
185
|
+
const reason = signal ? `signal ${signal}` : `code ${code}`;
|
|
186
|
+
logger.warn('worker', `worker encerrou (${reason})`, { restarts: workerRestarts });
|
|
187
|
+
// Worker morto NUNCA derruba o servidor: só reinicia (com teto).
|
|
188
|
+
if (!shuttingDown && workerRestarts < 5) {
|
|
189
|
+
workerRestarts += 1;
|
|
190
|
+
setTimeout(startWorker, 3000).unref();
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
logger.info('worker', 'worker iniciado pelo servidor', { pid: worker.pid });
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const stopWorker = () => {
|
|
197
|
+
if (worker && worker.exitCode === null && worker.signalCode === null) {
|
|
198
|
+
worker.kill('SIGTERM');
|
|
199
|
+
setTimeout(() => {
|
|
200
|
+
if (worker.exitCode === null && worker.signalCode === null) worker.kill('SIGKILL');
|
|
201
|
+
}, 2000).unref();
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
if (process.env.JOBFINDER_NO_WORKER === '1') {
|
|
206
|
+
logger.info('worker', 'worker desativado por JOBFINDER_NO_WORKER=1');
|
|
207
|
+
} else {
|
|
208
|
+
startWorker();
|
|
209
|
+
}
|
|
177
210
|
|
|
178
211
|
/**
|
|
179
212
|
* ULTIMATE keep-alive guard (0.1.15).
|
|
@@ -209,6 +242,12 @@ export async function start() {
|
|
|
209
242
|
if (shuttingDown) return;
|
|
210
243
|
shuttingDown = true;
|
|
211
244
|
logger.info('shutdown', `received ${signal}`);
|
|
245
|
+
// O worker morre com o servidor — nunca fica órfão.
|
|
246
|
+
try {
|
|
247
|
+
stopWorker();
|
|
248
|
+
} catch {
|
|
249
|
+
/* parar o worker é melhor esforço */
|
|
250
|
+
}
|
|
212
251
|
server.close(() => process.exit(0));
|
|
213
252
|
// Never hang on a stuck keep-alive connection: force the exit.
|
|
214
253
|
setTimeout(() => process.exit(0), 3000).unref();
|